Skip to content

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

Per-symbol atomic rendering for Status column (#2067)

Maximilian Roos5d3fd7a0348a
diff --git a/src/commands/list/collect/execution.rs b/src/commands/list/collect/execution.rs
index 943d76b58..d681003bd 100644
--- a/src/commands/list/collect/execution.rs
+++ b/src/commands/list/collect/execution.rs
@@ -5,12 +5,27 @@
//! - `dispatch_task()` - route TaskKind to the correct Task implementation
//! - `work_items_for_worktree()` / `work_items_for_branch()` - generate work items
//! - `ExpectedResults` - track expected results for timeout diagnostics
+//! - `seed_skipped_task_defaults()` - conservative sentinels for skipped tasks
+//!
+//! ## Status field bookkeeping at spawn time
+//!
+//! `compute_status_symbols` refuses to compute until every required field on
+//! `ListItem` / `WorktreeData` is `Some`. Tasks that *will* run are written
+//! by the drain as their results arrive. Tasks that will *not* run (stale
+//! branches skip expensive tasks, unborn branches skip commit-dependent
+//! tasks, `--skip-tasks` filters, branches with no worktree have no
+//! worktree-only tasks) have their fields seeded here via
+//! [`seed_skipped_task_defaults`] with conservative defaults — otherwise
+//! the fields would stay `None` forever and status would never compute.
use std::sync::Arc;
use crossbeam_channel as chan;
use worktrunk::git::{BranchRef, Repository, WorktreeInfo};
+use super::super::model::{
+ ActiveGitOperation, ItemKind, ListItem, UpstreamStatus, WorkingTreeStatus,
+};
use super::CollectOptions;
use super::tasks::{
AheadBehindTask, BranchDiffTask, CiStatusTask, CommitDetailsTask, CommittedTreesMatchTask,
@@ -135,21 +150,172 @@ impl ExpectedResults {
}
}
+// ============================================================================
+// Skipped Task Sentinels
+// ============================================================================
+
+/// Seed conservative defaults for a task that will not run for an item.
+///
+/// `refresh_status_symbols` keeps gates at `None` while their inputs are
+/// unloaded, which renders as the `⋯` placeholder. For tasks that will
+/// *never* run (stale branch, user `--skip-tasks`, unborn item missing
+/// commit-dependent tasks, prunable worktree), seeding a conservative
+/// default up front lets the gate resolve normally instead of showing `⋯`
+/// forever.
+///
+/// **Not seeded by this function:** `item.counts`. The ahead/behind counts
+/// are the only field that leaks directly into JSON output (`JsonMain` at
+/// `json_output.rs:~305`), so seeding them with `(0, 0)` would falsely
+/// claim "in sync" in `wt list --format=json` output. Callers that need to
+/// resolve gate 3 (main_state) for items without counts should instead
+/// pre-seed `status_symbols.main_state` directly — see
+/// [`seed_unborn_main_state`].
+///
+/// Non-status-feeding tasks (`CommitDetails`, `BranchDiff`, `CiStatus`,
+/// `UrlStatus`, `SummaryGenerate`) are rendered by their own columns with
+/// their own placeholders; `refresh_status_symbols` doesn't read them, so
+/// there is nothing to seed.
+pub(super) fn seed_skipped_task_defaults(item: &mut ListItem, kind: TaskKind) {
+ match kind {
+ // Not consumed by refresh_status_symbols — columns handle their own
+ // loading state.
+ TaskKind::CommitDetails
+ | TaskKind::BranchDiff
+ | TaskKind::CiStatus
+ | TaskKind::UrlStatus
+ | TaskKind::SummaryGenerate => {}
+
+ TaskKind::AheadBehind => {
+ // Seed `is_orphan` (safe — not in JSON) but NOT `counts`
+ // (leaks to `JsonMain`). Gate 3 callers that need counts-less
+ // resolution use `seed_unborn_main_state` to pre-seed
+ // `status_symbols.main_state` directly.
+ item.is_orphan = Some(false);
+ }
+ TaskKind::Upstream => {
+ // Safe to seed: `UpstreamStatus::default()` has
+ // `remote: None`, so `active()` returns `None` and
+ // `upstream_to_json` elides the `remote` JSON key. No leak.
+ item.upstream = Some(UpstreamStatus::default());
+ }
+ TaskKind::CommittedTreesMatch => {
+ // Conservative: don't claim integrated if we haven't checked.
+ item.committed_trees_match = Some(false);
+ }
+ TaskKind::HasFileChanges => {
+ // Conservative: assume unique changes exist.
+ item.has_file_changes = Some(true);
+ }
+ TaskKind::WouldMergeAdd => {
+ // Conservative: assume the merge would add changes.
+ item.would_merge_add = Some(true);
+ item.is_patch_id_match = Some(false);
+ }
+ TaskKind::IsAncestor => {
+ // Conservative: don't claim merged if we haven't checked.
+ item.is_ancestor = Some(false);
+ }
+ TaskKind::MergeTreeConflicts => {
+ item.has_merge_tree_conflicts = Some(false);
+ }
+ TaskKind::UserMarker => {
+ item.user_marker = Some(None);
+ }
+ TaskKind::WorkingTreeDiff => {
+ // Do not seed. `working_tree_diff` feeds gate 3's `is_clean`
+ // check and flows into JSON output. Seeding `Some(default())`
+ // would misreport dirty worktrees as clean+removable and
+ // fabricate an empty diff in `--format=json`. Same rule as
+ // `item.counts`: leaks-to-JSON inputs stay `None`; the gate
+ // waits and renders `⋯`.
+ }
+ TaskKind::WorkingTreeConflicts => {
+ if let ItemKind::Worktree(data) = &mut item.kind {
+ // `Some(None)` = "task did not run, fall back to the
+ // committed-HEAD merge-tree check" — matches the semantics
+ // of a clean working tree under `--full`.
+ data.has_working_tree_conflicts = Some(None);
+ }
+ }
+ TaskKind::GitOperation => {
+ if let ItemKind::Worktree(data) = &mut item.kind {
+ data.git_operation = Some(ActiveGitOperation::None);
+ }
+ }
+ }
+}
+
+/// Pre-seed gate 3 (`main_state`) for unborn items whose `AheadBehind`
+/// task will not run.
+///
+/// Gate 3's tier 4 requires `item.counts` to be loaded, but `item.counts`
+/// is a JSON-leaking field we can't safely seed. For unborn items there is
+/// no ahead/behind relationship to compute — the main worktree always
+/// resolves to `MainState::IsMain`, and a linked unborn worktree (rare:
+/// `git worktree add -b new main` before the first commit) resolves to
+/// `MainState::None` (no symbol). Both are known at spawn time without
+/// any task output.
+pub(super) fn seed_unborn_main_state(item: &mut ListItem) {
+ let is_main = matches!(&item.kind, ItemKind::Worktree(data) if data.is_main);
+ item.status_symbols.main_state = Some(if is_main {
+ super::super::model::MainState::IsMain
+ } else {
+ super::super::model::MainState::None
+ });
+}
+
+/// Pre-seed every gate on a prunable worktree so the only visible symbol
+/// is `⊟` (from the metadata `worktree_state`).
+///
+/// Prunable worktrees have their directory missing from disk, so no task
+/// can run for them. Without this seeding, every gate would stay `None`
+/// forever and the cell would render as seven `⋯` placeholders. This
+/// helper replaces the runtime fallback in `refresh_status_symbols`
+/// (introduced as a shim in step 4) with spawn-time seeding.
+pub(super) fn seed_prunable_item(item: &mut ListItem) {
+ use super::super::model::{
+ Divergence, MainState, OperationState, StatusSymbols, WorktreeState,
+ };
+ item.status_symbols = StatusSymbols {
+ working_tree: Some(WorkingTreeStatus::default()),
+ operation_state: Some(OperationState::None),
+ worktree_state: Some(WorktreeState::Prunable),
+ main_state: Some(MainState::None),
+ upstream_divergence: Some(Divergence::None),
+ user_marker: Some(None),
+ };
+}
+
// ============================================================================
// Work Item Generation
// ============================================================================
/// Generate work items for a worktree.
///
-/// Returns a list of work items representing all tasks that should run for this
-/// worktree. Expected results are registered internally as each work item is added.
-/// The caller is responsible for executing the work items.
+/// Returns a list of work items representing all tasks that should run for
+/// this worktree. Expected results are registered internally as each work
+/// item is added. The caller is responsible for executing the work items.
+///
+/// **Side effects on `item`:**
+/// - Seeds conservative sentinels on fields corresponding to tasks that will
+/// *not* run (stale/unborn/skipped). See module docstring.
+///
+/// **Side effects on `tx`:**
+/// - Sends an immediate `TaskResult::UrlStatus { url: Some, active: None }`
+/// for items with a URL template, so the row redraws as soon as the
+/// first drain tick fires (the slower follow-up `UrlStatus` health
+/// check then updates `url_active`). The drain pipeline is the only
+/// path that triggers progressive row redraws, so writing `item.url`
+/// directly here would leave it stuck behind whatever task happens to
+/// complete first.
///
/// Task preconditions (stale branch, unborn branch, missing llm_command) are
-/// enforced here — not in callers. This function is called from both `collect()`
-/// and `populate_item()`, so guards must live here to cover all entry points.
+/// enforced here — not in callers. This function is called from both
+/// `collect()` and `populate_item()`, so guards must live here to cover all
+/// entry points.
///
-/// The `repo` parameter is cloned into each TaskContext, sharing its cache via Arc.
+/// The `repo` parameter is cloned into each TaskContext, sharing its cache
+/// via Arc.
pub fn work_items_for_worktree(
repo: &Repository,
wt: &WorktreeInfo,
@@ -157,9 +323,13 @@ pub fn work_items_for_worktree(
options: &CollectOptions,
expected_results: &Arc<ExpectedResults>,
tx: &chan::Sender<Result<TaskResult, TaskError>>,
+ item: &mut ListItem,
) -> Vec<WorkItem> {
- // Skip git operations for prunable worktrees (directory missing).
+ // Prunable worktrees have their directory missing — no task can run.
+ // Seed every gate directly so the cell shows just the `⊟` metadata
+ // symbol rather than seven `⋯` placeholders.
if wt.is_prunable() {
+ seed_prunable_item(item);
return vec![];
}
@@ -181,8 +351,10 @@ pub fn work_items_for_worktree(
None
};
- // Send URL immediately (before health check) so it appears right away.
- // The UrlStatusTask will later update with active status.
+ // Send the URL through the drain channel so the row redraws as soon as
+ // the result is processed. Without this round trip, the URL would only
+ // appear when *some other* task happens to complete and trigger a
+ // refresh — often the slow `UrlStatusTask` itself.
if include_url && let Some(ref url) = item_url {
expected_results.expect(item_idx, TaskKind::UrlStatus);
let _ = tx.send(Ok(TaskResult::UrlStatus {
@@ -210,15 +382,6 @@ pub fn work_items_for_worktree(
let mut items = Vec::with_capacity(15);
- // Helper to add a work item and register the expected result
- let mut add_item = |kind: TaskKind| {
- expected_results.expect(item_idx, kind);
- items.push(WorkItem {
- ctx: ctx.clone(),
- kind,
- });
- };
-
for kind in [
TaskKind::CommitDetails,
TaskKind::AheadBehind,
@@ -241,27 +404,32 @@ pub fn work_items_for_worktree(
TaskKind::WouldMergeAdd,
TaskKind::SummaryGenerate,
] {
- if skip.contains(&kind) {
- continue;
- }
- // Skip expensive tasks for stale branches (far behind default branch)
- if is_stale && EXPENSIVE_TASKS.contains(&kind) {
+ let will_skip = skip.contains(&kind)
+ || (is_stale && EXPENSIVE_TASKS.contains(&kind))
+ || (!has_commits && COMMIT_TASKS.contains(&kind))
+ || (kind == TaskKind::SummaryGenerate && options.llm_command.is_none());
+ if will_skip {
+ seed_skipped_task_defaults(item, kind);
continue;
}
- // Skip commit-dependent tasks for unborn branches (no commits yet)
- if !has_commits && COMMIT_TASKS.contains(&kind) {
- continue;
- }
- // Skip SummaryGenerate when no LLM command is configured
- if kind == TaskKind::SummaryGenerate && options.llm_command.is_none() {
- continue;
- }
- add_item(kind);
+ expected_results.expect(item_idx, kind);
+ items.push(WorkItem {
+ ctx: ctx.clone(),
+ kind,
+ });
+ }
+
+ // Unborn items: their `AheadBehind` task was skipped in the loop
+ // above, so `item.counts` stays `None` (by design — seeding it would
+ // leak `{ahead:0, behind:0}` into JSON). Pre-seed `main_state`
+ // directly so gate 3 resolves without needing counts.
+ if !has_commits {
+ seed_unborn_main_state(item);
}
- // URL status health check task (if we have a URL).
- // Note: We already registered and sent an immediate UrlStatus above with url + active=None.
- // This work item will send a second UrlStatus with active=Some(bool) after health check.
- // Both results must be registered and expected.
+
+ // URL status health check task (if we have a URL). Only this single
+ // work item is queued per item — `item.url` was set directly above, so
+ // no placeholder send is needed.
if include_url && ctx.item_url.is_some() {
expected_results.expect(item_idx, TaskKind::UrlStatus);
items.push(WorkItem {
@@ -283,15 +451,29 @@ pub fn work_items_for_worktree(
/// The `repo` parameter is cloned into each TaskContext, sharing its cache via Arc.
/// The `is_remote` flag indicates whether this is a remote-tracking branch (e.g., "origin/feature")
/// vs a local branch. This is known definitively at collection time and avoids guessing later.
+/// Identity of a branch item being spawned (grouped to keep
+/// `work_items_for_branch` under the clippy arg-count limit).
+pub struct BranchSpawn<'a> {
+ pub name: &'a str,
+ pub commit_sha: &'a str,
+ pub item_idx: usize,
+ pub is_remote: bool,
+}
+
pub fn work_items_for_branch(
repo: &Repository,
- branch_name: &str,
- commit_sha: &str,
- item_idx: usize,
- is_remote: bool,
+ branch: BranchSpawn<'_>,
options: &CollectOptions,
expected_results: &Arc<ExpectedResults>,
+ item: &mut ListItem,
) -> Vec<WorkItem> {
+ let BranchSpawn {
+ name: branch_name,
+ commit_sha,
+ item_idx,
+ is_remote,
+ } = branch;
+
let skip = &options.skip_tasks;
let branch_ref = if is_remote {
@@ -313,15 +495,6 @@ pub fn work_items_for_branch(
let mut items = Vec::with_capacity(11);
- // Helper to add a work item and register the expected result
- let mut add_item = |kind: TaskKind| {
- expected_results.expect(item_idx, kind);
- items.push(WorkItem {
- ctx: ctx.clone(),
- kind,
- });
- };
-
for kind in [
TaskKind::CommitDetails,
TaskKind::AheadBehind,
@@ -335,18 +508,36 @@ pub fn work_items_for_branch(
TaskKind::WouldMergeAdd,
TaskKind::SummaryGenerate,
] {
- if skip.contains(&kind) {
+ let will_skip = skip.contains(&kind)
+ || (is_stale && EXPENSIVE_TASKS.contains(&kind))
+ || (kind == TaskKind::SummaryGenerate && options.llm_command.is_none());
+ if will_skip {
+ seed_skipped_task_defaults(item, kind);
continue;
}
- // Skip expensive tasks for stale branches (far behind default branch)
- if is_stale && EXPENSIVE_TASKS.contains(&kind) {
- continue;
- }
- // Skip SummaryGenerate when no LLM command is configured
- if kind == TaskKind::SummaryGenerate && options.llm_command.is_none() {
- continue;
- }
- add_item(kind);
+ expected_results.expect(item_idx, kind);
+ items.push(WorkItem {
+ ctx: ctx.clone(),
+ kind,
+ });
+ }
+ // `UserMarker` is never in the branch task list above (it only runs
+ // for worktrees), but the branch arm of `compute_status_symbols`
+ // *does* read `item.user_marker` and will bail while it is `None`.
+ // Seed it here so branches can compute status.
+ seed_skipped_task_defaults(item, TaskKind::UserMarker);
+ // `WorkingTreeDiff` / `WorkingTreeConflicts` / `GitOperation` only
+ // affect the worktree arm of `compute_status_symbols`, which is never
+ // entered for `ItemKind::Branch`. Seeding them is a no-op today (the
+ // seed helper branches on `ItemKind::Worktree` internally) but makes
+ // the per-item task set explicit and keeps this loop forward-compatible
+ // if the branch arm ever starts reading them.
+ for kind in [
+ TaskKind::WorkingTreeDiff,
+ TaskKind::WorkingTreeConflicts,
+ TaskKind::GitOperation,
+ ] {
+ seed_skipped_task_defaults(item, kind);
}
items
@@ -355,6 +546,7 @@ pub fn work_items_for_branch(
#[cfg(test)]
mod tests {
use super::*;
+ use crate::commands::list::collect::build_worktree_item;
use std::collections::HashSet;
#[test]
@@ -381,13 +573,15 @@ mod tests {
let expected_results = Arc::new(ExpectedResults::default());
let (tx, rx) = chan::unbounded::<Result<TaskResult, TaskError>>();
+ let mut item = build_worktree_item(&wt, true, false, false);
- let items = work_items_for_worktree(&repo, &wt, 0, &options, &expected_results, &tx);
+ let items =
+ work_items_for_worktree(&repo, &wt, 0, &options, &expected_results, &tx, &mut item);
- // No placeholder sent
+ // No placeholder UrlStatus result was sent to the channel.
assert!(rx.try_recv().is_err());
// No UrlStatus work item created
- assert!(!items.iter().any(|item| item.kind == TaskKind::UrlStatus));
+ assert!(!items.iter().any(|w| w.kind == TaskKind::UrlStatus));
// No UrlStatus in expected results
assert!(
!expected_results
@@ -395,7 +589,7 @@ mod tests {
.contains(&TaskKind::UrlStatus)
);
// item_url is None for all items
- assert!(items.iter().all(|item| item.ctx.item_url.is_none()));
+ assert!(items.iter().all(|w| w.ctx.item_url.is_none()));
}
#[test]
@@ -422,13 +616,13 @@ mod tests {
let expected_results = Arc::new(ExpectedResults::default());
let (tx, _rx) = chan::unbounded::<Result<TaskResult, TaskError>>();
+ let mut item = build_worktree_item(&wt, true, false, false);
- let items = work_items_for_worktree(&repo, &wt, 0, &options, &expected_results, &tx);
+ let items =
+ work_items_for_worktree(&repo, &wt, 0, &options, &expected_results, &tx, &mut item);
assert!(
- !items
- .iter()
- .any(|item| item.kind == TaskKind::SummaryGenerate),
+ !items.iter().any(|w| w.kind == TaskKind::SummaryGenerate),
"SummaryGenerate should be skipped when llm_command is None"
);
}
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rs
index 326a85802..3fceeeda4 100644
--- a/src/commands/list/collect/mod.rs
+++ b/src/commands/list/collect/mod.rs
@@ -115,7 +115,7 @@ use worktrunk::styling::{
use crate::commands::is_worktree_at_expected_path;
-use super::model::{DisplayFields, ItemKind, ListItem, WorktreeData};
+use super::model::{DisplayFields, ItemKind, ListItem, StatusSymbols, WorktreeData};
use super::progressive_table::ProgressiveTable;
// Re-exports for sibling modules (columns.rs, render.rs, layout.rs)
@@ -126,7 +126,7 @@ pub(crate) use types::TaskKind;
pub(crate) use execution::ExpectedResults;
use execution::{work_items_for_branch, work_items_for_worktree};
use results::drain_results;
-use types::{DrainOutcome, StatusContext};
+use types::DrainOutcome;
use types::{TaskError, TaskResult};
struct TableRenderPlan {
@@ -554,7 +554,9 @@ pub fn collect(
url: None,
url_active: None,
summary: None,
- status_symbols: None,
+ has_merge_tree_conflicts: None,
+ user_marker: None,
+ status_symbols: StatusSymbols::default(),
display: DisplayFields::default(),
kind: ItemKind::Worktree(Box::new(worktree_data)),
}
@@ -769,20 +771,7 @@ pub fn collect(
// Collect errors for display after rendering
let mut errors: Vec<TaskError> = Vec::new();
- // Collect all work items upfront, then execute in a single Rayon pool.
- // This avoids nested parallelism (Rayon par_iter → scope per worktree)
- // which can deadlock when outer tasks block pool threads waiting for inner
- // tasks that can't get scheduled. Instead, we have one flat pool with the
- // configured thread count (default 2x CPU cores unless overridden by
- // RAYON_NUM_THREADS).
- let sorted_worktrees_clone = sorted_worktrees.clone();
- let tx_worker = tx.clone();
- let expected_results_clone = expected_results.clone();
-
- // Clone repo for the worker thread (shares cache via Arc)
- let repo_clone = repo.clone();
-
- // Prepare branch data if needed (before moving into closure)
+ // Prepare branch data if needed.
// Tuple: (item_idx, branch_name, commit_sha, is_remote)
let branch_data: Vec<(usize, String, String, bool)> =
if show_branches || show_remotes {
@@ -802,41 +791,52 @@ pub fn collect(
Vec::new()
};
- worktrunk::shell_exec::trace_instant("Spawning worker thread");
- std::thread::spawn(move || {
- // Phase 1: Generate all work items (sequential, fast)
- // Work items are collected upfront so we can process them all in a single par_iter.
- let mut all_work_items = Vec::new();
-
- // Worktree work items
- for (idx, wt) in sorted_worktrees_clone.iter().enumerate() {
- all_work_items.extend(work_items_for_worktree(
- &repo_clone,
- wt,
- idx,
- &options,
- &expected_results_clone,
- &tx_worker,
- ));
- }
+ // Phase 1: Generate all work items on the main thread. Work item
+ // generation is fast (a fixed-size loop per item) and *must* run here
+ // because it pre-populates per-item status-feeder sentinels directly on
+ // `all_items` — the worker thread can't hold a mutable reference while
+ // the drain loop is also mutating items.
+ let mut all_work_items = Vec::new();
+
+ // Worktree work items
+ for (idx, wt) in sorted_worktrees.iter().enumerate() {
+ all_work_items.extend(work_items_for_worktree(
+ repo,
+ wt,
+ idx,
+ &options,
+ &expected_results,
+ &tx,
+ &mut all_items[idx],
+ ));
+ }
- // Branch work items (local + remote)
- for (item_idx, branch_name, commit_sha, is_remote) in &branch_data {
- all_work_items.extend(work_items_for_branch(
- &repo_clone,
- branch_name,
+ // Branch work items (local + remote)
+ for (item_idx, branch_name, commit_sha, is_remote) in &branch_data {
+ all_work_items.extend(work_items_for_branch(
+ repo,
+ execution::BranchSpawn {
+ name: branch_name,
commit_sha,
- *item_idx,
- *is_remote,
- &options,
- &expected_results_clone,
- ));
- }
+ item_idx: *item_idx,
+ is_remote: *is_remote,
+ },
+ &options,
+ &expected_results,
+ &mut all_items[*item_idx],
+ ));
+ }
- // Sort work items: network tasks last to avoid blocking local operations
- all_work_items.sort_by_key(|item| item.kind.is_network());
+ // Sort work items: network tasks last to avoid blocking local operations
+ all_work_items.sort_by_key(|item| item.kind.is_network());
- // Phase 2: Execute all work items in parallel
+ // Phase 2: Execute all work items in a single Rayon pool on a worker
+ // thread. Flat parallelism avoids nested-Rayon deadlocks, and the
+ // worker-thread split lets the drain loop start consuming results on
+ // the main thread immediately.
+ let tx_worker = tx.clone();
+ worktrunk::shell_exec::trace_instant("Spawning worker thread");
+ std::thread::spawn(move || {
worktrunk::shell_exec::trace_instant("Parallel execution started");
all_work_items.into_par_iter().for_each(|item| {
worktrunk::shell_exec::set_command_timeout(command_timeout);
@@ -862,18 +862,17 @@ pub fn collect(
&mut errors,
&expected_results,
drain_deadline,
- |item_idx, item, ctx| {
+ integration_target.as_deref(),
+ |item_idx, item| {
// Trace first result arrival
if !first_result_traced {
first_result_traced = true;
worktrunk::shell_exec::trace_instant("First result received");
}
- // Compute/recompute status symbols as data arrives (both modes).
- // This is idempotent and updates status as new data (like upstream) arrives.
- ctx.apply_to(item, integration_target.as_deref());
-
- // Progressive mode only: update UI
+ // Progressive mode only: update UI. `status_symbols` is set by
+ // `drain_results` itself (once all status-feeding tasks for this
+ // item have arrived successfully); here we only re-render.
if let Some(ref mut table) = progressive_table {
let dim = Style::new().dimmed();
@@ -933,6 +932,7 @@ pub fn collect(
diag.push_str("\nBlocked tasks:");
let missing_lines: Vec<String> = items_with_missing
.iter()
+ .take(5)
.map(|result| {
let missing_names: Vec<&str> =
result.missing_kinds.iter().map(|k| k.into()).collect();
@@ -955,17 +955,14 @@ pub fn collect(
);
}
- // Compute status symbols for prunable worktrees (skipped during task spawning).
- // They didn't receive any task results, so status_symbols is still None.
- for item in &mut all_items {
- if item.status_symbols.is_none()
- && let Some(data) = item.worktree_data()
- && data.is_prunable()
- {
- // Use default context - no tasks ran, so no conflict/status info
- let ctx = StatusContext::default();
- ctx.apply_to(item, integration_target.as_deref());
- }
+ // The drain calls `refresh_status_symbols` after every *successful*
+ // result, but items with zero successful results (all tasks errored
+ // or timed out) never hit that path. Sweep every item so that
+ // synchronously-derivable gates (worktree_state from metadata,
+ // pre-seeded main_state for unborn/prunable items) still materialize.
+ // The call is idempotent — already-resolved gates are skipped.
+ for item in all_items.iter_mut() {
+ item.refresh_status_symbols(integration_target.as_deref());
}
// Count errors for summary
@@ -1140,7 +1137,9 @@ pub fn build_worktree_item(
url: None,
url_active: None,
summary: None,
- status_symbols: None,
+ has_merge_tree_conflicts: None,
+ user_marker: None,
+ status_symbols: StatusSymbols::default(),
display: DisplayFields::default(),
kind: ItemKind::Worktree(Box::new(WorktreeData::from_worktree(
wt,
@@ -1184,7 +1183,9 @@ pub fn populate_item(
// Collect errors (logged silently for statusline)
let mut errors: Vec<TaskError> = Vec::new();
- // Extract data for background thread (can't send borrows across threads)
+ // Build a minimal WorktreeInfo so the shared work-item generator can
+ // run. The item lives on this (main) thread; the worker thread only
+ // executes prebuilt work items.
let wt = WorktreeInfo {
path: data.path.clone(),
head: item.head.clone(),
@@ -1194,41 +1195,42 @@ pub fn populate_item(
locked: None,
prunable: None,
};
- let repo_clone = repo.clone();
- let expected_results_clone = expected_results.clone();
- // Spawn collection in background thread
- std::thread::spawn(move || {
- // Generate work items for this single worktree
- let mut work_items = work_items_for_worktree(
- &repo_clone,
- &wt,
- 0, // Single item, always index 0
- &options,
- &expected_results_clone,
- &tx,
- );
+ // Generate work items on the main thread so the item can be seeded
+ // with sentinels for skipped tasks (see `work_items_for_worktree`).
+ let mut work_items = work_items_for_worktree(
+ repo,
+ &wt,
+ 0, // Single item, always index 0
+ &options,
+ &expected_results,
+ &tx,
+ item,
+ );
- // Sort: network tasks last
- work_items.sort_by_key(|item| item.kind.is_network());
+ // Sort: network tasks last
+ work_items.sort_by_key(|w| w.kind.is_network());
- // Execute all tasks in parallel
- work_items.into_par_iter().for_each(|item| {
- let result = item.execute();
+ // Spawn collection in background thread (executes only)
+ std::thread::spawn(move || {
+ work_items.into_par_iter().for_each(|w| {
+ let result = w.execute();
let _ = tx.send(result);
});
});
- // Drain task results (blocking until complete)
+ // Drain task results (blocking until complete). `drain_results`
+ // writes each result onto the item and calls `compute_status_symbols`
+ // after every write, so the callback here is just a no-op — there is
+ // no progressive table to refresh on the statusline path.
let drain_outcome = drain_results(
rx,
std::slice::from_mut(item),
&mut errors,
&expected_results,
std::time::Instant::now() + results::DRAIN_TIMEOUT,
- |_item_idx, item, ctx| {
- ctx.apply_to(item, target.as_deref());
- },
+ target.as_deref(),
+ |_item_idx, _item| {},
);
// Handle timeout (silent for statusline - just log it)
@@ -1253,6 +1255,10 @@ pub fn populate_item(
}
}
+ // Ensure status symbols are refreshed even if all tasks errored
+ // (the drain only calls refresh on the success path).
+ item.refresh_status_symbols(target.as_deref());
+
// Populate display fields (including status_line for statusline command)
item.finalize_display();
diff --git a/src/commands/list/collect/results.rs b/src/commands/list/collect/results.rs
index a10d0f9c7..dd778fd1c 100644
--- a/src/commands/list/collect/results.rs
+++ b/src/commands/list/collect/results.rs
@@ -1,115 +1,42 @@
//! Result processing and draining.
//!
-//! Contains the logic for processing task results:
-//! - `drain_results()` - drain channel and apply results to items
-//! - `apply_default()` - apply defaults for failed tasks
+//! The drain consumes task results from the channel and writes them
+//! straight onto `ListItem` / `WorktreeData` fields. There is no parallel
+//! "status context" structure — status-feeding fields flow through the
+//! same `Option<T>` slots as every other column.
+//!
+//! `ListItem::refresh_status_symbols` is called after every successful
+//! result; each gate resolves independently once its inputs arrive.
+//! Callers must also call `refresh_status_symbols` post-drain to cover
+//! items with zero successful results (all tasks errored or timed out),
+//! so that synchronously-derivable gates (e.g. `worktree_state` from
+//! metadata) still materialize.
use std::time::{Duration, Instant};
use crossbeam_channel as chan;
-use worktrunk::git::LineDiff;
/// Deadline for the entire drain operation. Generous to avoid flaky timeouts
/// under CI load where process spawning for ~70 work items can be slow.
pub(super) const DRAIN_TIMEOUT: Duration = Duration::from_secs(120);
-use super::super::model::{CommitDetails, ItemKind, ListItem, UpstreamStatus, WorkingTreeStatus};
+use super::super::model::{ItemKind, ListItem};
use super::execution::ExpectedResults;
-use super::types::{DrainOutcome, MissingResult, StatusContext, TaskError, TaskKind, TaskResult};
-
-/// Apply default values for a failed task.
-///
-/// When a task fails, we still need to populate the item fields with sensible
-/// defaults so the UI can render. This centralizes all default logic in one place.
-pub(super) fn apply_default(
- items: &mut [ListItem],
- status_contexts: &mut [StatusContext],
- error: &TaskError,
-) {
- let idx = error.item_idx;
- match error.kind {
- TaskKind::CommitDetails => {
- items[idx].commit = Some(CommitDetails::default());
- }
- TaskKind::AheadBehind => {
- // Leave as None — UI shows `⋯` for not-loaded tasks
- // Conservative: don't claim orphan if we couldn't check
- items[idx].is_orphan = Some(false);
- }
- TaskKind::CommittedTreesMatch => {
- // Conservative: don't claim integrated if we couldn't check
- items[idx].committed_trees_match = Some(false);
- }
- TaskKind::HasFileChanges => {
- // Conservative: assume has changes if we couldn't check
- items[idx].has_file_changes = Some(true);
- }
- TaskKind::WouldMergeAdd => {
- // Conservative: assume would add changes if we couldn't check
- items[idx].would_merge_add = Some(true);
- items[idx].is_patch_id_match = Some(false);
- }
- TaskKind::IsAncestor => {
- // Conservative: don't claim merged if we couldn't check
- items[idx].is_ancestor = Some(false);
- }
- TaskKind::BranchDiff => {
- // Leave as None — UI shows `…` for skipped/failed tasks
- }
- TaskKind::WorkingTreeDiff => {
- if let ItemKind::Worktree(data) = &mut items[idx].kind {
- data.working_tree_diff = Some(LineDiff::default());
- } else {
- debug_assert!(false, "WorkingTreeDiff task spawned for non-worktree item");
- }
- status_contexts[idx].working_tree_status = Some(WorkingTreeStatus::default());
- status_contexts[idx].has_conflicts = false;
- }
- TaskKind::MergeTreeConflicts => {
- // Don't show conflict symbol if we couldn't check
- status_contexts[idx].has_merge_tree_conflicts = false;
- }
- TaskKind::WorkingTreeConflicts => {
- // Fall back to commit-based check on failure
- status_contexts[idx].has_working_tree_conflicts = None;
- }
- TaskKind::GitOperation => {
- // Already defaults to ActiveGitOperation::None in WorktreeData
- }
- TaskKind::UserMarker => {
- // Already defaults to None
- status_contexts[idx].user_marker = None;
- }
- TaskKind::Upstream => {
- items[idx].upstream = Some(UpstreamStatus::default());
- }
- TaskKind::CiStatus => {
- // Leave as None (not fetched) on error. This allows the hint path
- // in mod.rs to run and show "install gh/glab" when CI tools fail.
- // Some(None) means "CI tool ran successfully but found no PR".
- }
- TaskKind::UrlStatus => {
- // URL is set at item creation, only default url_active
- items[idx].url_active = None;
- }
- TaskKind::SummaryGenerate => {
- // Leave as None — no summary available
- }
- }
-}
+use super::types::{DrainOutcome, MissingResult, TaskError, TaskKind, TaskResult};
/// Drain task results from the channel and apply them to items.
///
/// This is the shared logic between progressive and buffered collection modes.
-/// The `on_result` callback is called after each result is processed with the
-/// item index and a reference to the updated item, allowing progressive mode
-/// to update the live table while buffered mode does nothing.
+/// The `on_result` callback fires after each result so progressive mode can
+/// refresh the live table; buffered mode passes a no-op.
///
/// Uses a caller-provided `deadline` to cap wall-clock time. When the deadline
/// is reached, returns `DrainOutcome::TimedOut` with diagnostic info.
///
-/// Errors are collected in the `errors` vec for display after rendering.
-/// Default values are applied for failed tasks so the UI can still render.
+/// Errors are collected in the `errors` vec for display after rendering. No
+/// defaults are applied — an errored field stays `None`, so the renderer
+/// shows its standard placeholder and `compute_status_symbols` stays a
+/// no-op for that item.
///
/// Callers decide how to handle timeout:
/// - `collect()`: Shows user-facing diagnostic (interactive command)
@@ -120,14 +47,12 @@ pub(super) fn drain_results(
errors: &mut Vec<TaskError>,
expected_results: &ExpectedResults,
deadline: Instant,
- mut on_result: impl FnMut(usize, &mut ListItem, &StatusContext),
+ integration_target: Option<&str>,
+ mut on_result: impl FnMut(usize, &mut ListItem),
) -> DrainOutcome {
// Track which result kinds we've received per item (for timeout diagnostics)
let mut received_by_item: Vec<Vec<TaskKind>> = vec![Vec::new(); items.len()];
- // Temporary storage for data needed by status_symbols computation
- let mut status_contexts = vec![StatusContext::default(); items.len()];
-
// Process task results as they arrive (with deadline)
loop {
let remaining = deadline.saturating_duration_since(Instant::now());
@@ -165,9 +90,9 @@ pub(super) fn drain_results(
}
}
- // Sort by item index and limit to first 5
+ // Sort by item index. The display site in `collect()` truncates
+ // to the first 5 when rendering the warning.
items_with_missing.sort_by_key(|result| result.item_idx);
- items_with_missing.truncate(5);
return DrainOutcome::TimedOut {
received_count,
@@ -190,20 +115,20 @@ pub(super) fn drain_results(
// Track this result for diagnostics (both success and error count as "received")
received_by_item[item_idx].push(kind);
- // Handle error case: apply defaults and collect error
+ // Errors leave the errored task's fields at `None`. The
+ // corresponding gate stays unresolved (renders `⋯`). Callers
+ // must call `refresh_status_symbols` post-drain to cover items
+ // with zero successful results. Still run the callback so the
+ // footer progress counter advances.
if let Err(error) = outcome {
- apply_default(items, &mut status_contexts, &error);
errors.push(error);
- let item = &mut items[item_idx];
- let status_ctx = &status_contexts[item_idx];
- on_result(item_idx, item, status_ctx);
+ on_result(item_idx, &mut items[item_idx]);
continue;
}
// Handle success case
let result = outcome.unwrap();
let item = &mut items[item_idx];
- let status_ctx = &mut status_contexts[item_idx];
match result {
TaskResult::CommitDetails { commit, .. } => {
@@ -248,37 +173,37 @@ pub(super) fn drain_results(
} => {
if let ItemKind::Worktree(data) = &mut item.kind {
data.working_tree_diff = Some(working_tree_diff);
+ data.working_tree_status = Some(working_tree_status);
+ data.has_conflicts = Some(has_conflicts);
} else {
debug_assert!(false, "WorkingTreeDiff result for non-worktree item");
}
- // Store for status_symbols computation
- status_ctx.working_tree_status = Some(working_tree_status);
- status_ctx.has_conflicts = has_conflicts;
}
TaskResult::MergeTreeConflicts {
has_merge_tree_conflicts,
..
} => {
- // Store for status_symbols computation
- status_ctx.has_merge_tree_conflicts = has_merge_tree_conflicts;
+ item.has_merge_tree_conflicts = Some(has_merge_tree_conflicts);
}
TaskResult::WorkingTreeConflicts {
has_working_tree_conflicts,
..
} => {
- // Store for status_symbols computation (takes precedence over commit check)
- status_ctx.has_working_tree_conflicts = has_working_tree_conflicts;
+ if let ItemKind::Worktree(data) = &mut item.kind {
+ data.has_working_tree_conflicts = Some(has_working_tree_conflicts);
+ } else {
+ debug_assert!(false, "WorkingTreeConflicts result for non-worktree item");
+ }
}
TaskResult::GitOperation { git_operation, .. } => {
if let ItemKind::Worktree(data) = &mut item.kind {
- data.git_operation = git_operation;
+ data.git_operation = Some(git_operation);
} else {
debug_assert!(false, "GitOperation result for non-worktree item");
}
}
TaskResult::UserMarker { user_marker, .. } => {
- // Store for status_symbols computation
- status_ctx.user_marker = user_marker;
+ item.user_marker = Some(user_marker);
}
TaskResult::Upstream { upstream, .. } => {
item.upstream = Some(upstream);
@@ -288,10 +213,10 @@ pub(super) fn drain_results(
item.pr_status = Some(pr_status);
}
TaskResult::UrlStatus { url, active, .. } => {
- // Two-phase URL rendering:
- // 1. First result (from spawning code): url=Some, active=None → URL appears in normal styling
- // 2. Second result (from health check): url=None, active=Some → dims if inactive
- // Only update non-None fields to preserve values from earlier results.
+ // The synchronous URL write in `work_items_for_worktree`
+ // already set `item.url`; this result only carries the
+ // health-check outcome. Still guard for older call sites
+ // that may send `url=Some`.
if url.is_some() {
item.url = url;
}
@@ -304,8 +229,12 @@ pub(super) fn drain_results(
}
}
+ // Refresh status symbols. Each gate resolves independently once
+ // its inputs arrive; already-resolved gates are skipped.
+ item.refresh_status_symbols(integration_target);
+
// Invoke callback (progressive mode re-renders rows, buffered mode does nothing)
- on_result(item_idx, item, status_ctx);
+ on_result(item_idx, item);
}
DrainOutcome::Complete
@@ -313,24 +242,79 @@ pub(super) fn drain_results(
#[cfg(test)]
mod tests {
+ use super::super::super::model::{
+ AheadBehind, MainState, UpstreamStatus, WorkingTreeStatus, WorktreeState,
+ };
+ use super::super::execution::seed_skipped_task_defaults;
use super::super::types::ErrorCause;
use super::*;
+ use worktrunk::git::LineDiff;
+
+ /// Seed every status-feeding field on an item so `refresh_status_symbols`
+ /// has no remaining `None` inputs. The values are deliberately
+ /// non-default — counts of (3, 5) means a fully-computed StatusSymbols
+ /// will report `MainState::Diverged`, which is distinguishable from the
+ /// metadata-only fallback's `MainState::None`. Tests use that to assert
+ /// "the full computation ran" vs "only the metadata fallback ran."
+ fn seed_all_fields(item: &mut ListItem) {
+ for kind in [
+ TaskKind::UserMarker,
+ TaskKind::MergeTreeConflicts,
+ TaskKind::IsAncestor,
+ TaskKind::CommittedTreesMatch,
+ TaskKind::HasFileChanges,
+ TaskKind::WouldMergeAdd,
+ TaskKind::WorkingTreeConflicts,
+ TaskKind::GitOperation,
+ ] {
+ seed_skipped_task_defaults(item, kind);
+ }
+ // WorkingTreeDiff is intentionally NOT seeded via
+ // `seed_skipped_task_defaults` (it would fabricate a clean tree).
+ // Simulate a real task result instead.
+ if let ItemKind::Worktree(data) = &mut item.kind {
+ data.working_tree_diff = Some(LineDiff::default());
+ data.working_tree_status = Some(WorkingTreeStatus::default());
+ data.has_conflicts = Some(false);
+ }
+ item.counts = Some(AheadBehind {
+ ahead: 3,
+ behind: 5,
+ });
+ item.is_orphan = Some(false);
+ item.upstream = Some(UpstreamStatus::default());
+ }
- #[test]
- fn test_apply_default_summary_generate() {
- let mut items = vec![ListItem::new_branch("abc123".into(), "feat".into())];
- let mut status_contexts = vec![StatusContext::default()];
+ /// True iff `compute_status_symbols` produced its full output (using
+ /// the seed values from `seed_all_fields`). False iff status is at
+ /// default (nothing computed) or the metadata-only fallback ran.
+ fn full_computation_ran(item: &ListItem) -> bool {
+ item.status_symbols.main_state == Some(MainState::Diverged)
+ }
- let error = TaskError::new(
- 0,
- TaskKind::SummaryGenerate,
- "llm failed",
- ErrorCause::Other,
- );
- apply_default(&mut items, &mut status_contexts, &error);
+ fn fully_seeded_branch_item() -> ListItem {
+ let mut item = ListItem::new_branch("abc123".into(), "feat".into());
+ seed_all_fields(&mut item);
+ item
+ }
- // SummaryGenerate default leaves summary as None
- assert!(items[0].summary.is_none());
+ fn fully_seeded_worktree_item() -> ListItem {
+ use crate::commands::list::collect::build_worktree_item;
+ use worktrunk::git::WorktreeInfo;
+ let wt = WorktreeInfo {
+ path: std::path::PathBuf::from("/tmp/wt"),
+ head: "abc123".into(),
+ branch: Some("feat".into()),
+ bare: false,
+ detached: false,
+ locked: None,
+ prunable: None,
+ };
+ // `is_main: false` so the test exercises the full guard set,
+ // not the main-worktree fast path.
+ let mut item = build_worktree_item(&wt, false, false, false);
+ seed_all_fields(&mut item);
+ item
}
#[test]
@@ -354,12 +338,179 @@ mod tests {
&mut errors,
&expected,
Instant::now() + DRAIN_TIMEOUT,
- |_, _, _| {},
+ None,
+ |_, _| {},
);
assert!(matches!(outcome, DrainOutcome::Complete));
assert_eq!(items[0].summary, Some(Some("Add feature".into())));
}
+ /// Sanity check: a fully-seeded worktree item resolves every gate to
+ /// its expected `Some(...)` value after one `refresh_status_symbols`
+ /// call. Per-gate loading / short-circuit behavior is exercised by
+ /// the dedicated tests in `item.rs`.
+ #[test]
+ fn test_refresh_fully_seeded_worktree_resolves_all_gates() {
+ let mut item = fully_seeded_worktree_item();
+ item.refresh_status_symbols(Some("main"));
+ let s = &item.status_symbols;
+ assert!(s.working_tree.is_some(), "gate 1 (working tree flags)");
+ assert!(s.operation_state.is_some(), "gate 2 (operation state)");
+ assert!(s.worktree_state.is_some(), "gate 2 (metadata)");
+ assert_eq!(
+ s.main_state,
+ Some(MainState::Diverged),
+ "gate 3 — baseline counts (3, 5) produce Diverged"
+ );
+ assert!(
+ s.upstream_divergence.is_some(),
+ "gate 4 (upstream divergence)"
+ );
+ assert!(s.user_marker.is_some(), "gate 5 (user marker)");
+ }
+
+ /// Sanity check: a fully-seeded branch item resolves every gate after
+ /// one `refresh_status_symbols` call.
+ #[test]
+ fn test_refresh_fully_seeded_branch_resolves_all_gates() {
+ let mut item = fully_seeded_branch_item();
+ item.refresh_status_symbols(Some("main"));
+ let s = &item.status_symbols;
+ assert!(s.working_tree.is_some(), "gate 1 (branches are clean)");
+ assert!(s.operation_state.is_some(), "gate 2 (branches have no op)");
+ assert_eq!(s.worktree_state, Some(WorktreeState::Branch));
+ assert_eq!(
+ s.main_state,
+ Some(MainState::Diverged),
+ "gate 3 — baseline counts (3, 5) produce Diverged"
+ );
+ assert!(s.upstream_divergence.is_some());
+ assert!(s.user_marker.is_some());
+ }
+
+ #[test]
+ fn test_drain_results_status_stays_none_while_field_pending() {
+ // A fully-seeded item whose counts are manually reset to None
+ // mirrors the case of an AheadBehind task that has not yet
+ // arrived. The drain must not run the full status computation
+ // for it (the metadata fallback may still mark the item as a
+ // branch — that's fine and expected).
+ let mut item = fully_seeded_branch_item();
+ item.counts = None;
+
+ let (tx, rx) = crossbeam_channel::unbounded();
+ let expected = ExpectedResults::default();
+ expected.expect(0, TaskKind::Upstream);
+
+ tx.send(Ok(TaskResult::Upstream {
+ item_idx: 0,
+ upstream: UpstreamStatus::default(),
+ }))
+ .unwrap();
+ drop(tx);
+
+ let mut errors = Vec::new();
+ let outcome = drain_results(
+ rx,
+ std::slice::from_mut(&mut item),
+ &mut errors,
+ &expected,
+ Instant::now() + DRAIN_TIMEOUT,
+ Some("main"),
+ |_, _| {},
+ );
+
+ assert!(matches!(outcome, DrainOutcome::Complete));
+ assert!(
+ !full_computation_ran(&item),
+ "full status computation should not run while a required field is pending",
+ );
+ }
+
+ #[test]
+ fn test_drain_results_status_snaps_when_final_field_arrives() {
+ // A fully-seeded item whose counts are manually reset to None
+ // starts the drain in the "one field pending" state. Delivering
+ // the AheadBehind result should let the drain run the full
+ // computation.
+ let mut item = fully_seeded_branch_item();
+ item.counts = None;
+ item.is_orphan = None;
+
+ let (tx, rx) = crossbeam_channel::unbounded();
+ let expected = ExpectedResults::default();
+ expected.expect(0, TaskKind::AheadBehind);
+
+ tx.send(Ok(TaskResult::AheadBehind {
+ item_idx: 0,
+ counts: AheadBehind {
+ ahead: 3,
+ behind: 5,
+ },
+ is_orphan: false,
+ }))
+ .unwrap();
+ drop(tx);
+
+ let mut errors = Vec::new();
+ let outcome = drain_results(
+ rx,
+ std::slice::from_mut(&mut item),
+ &mut errors,
+ &expected,
+ Instant::now() + DRAIN_TIMEOUT,
+ Some("main"),
+ |_, _| {},
+ );
+
+ assert!(matches!(outcome, DrainOutcome::Complete));
+ assert!(
+ full_computation_ran(&item),
+ "full status computation should run once the final required field arrives",
+ );
+ }
+
+ #[test]
+ fn test_drain_results_status_stays_none_when_feeder_errors() {
+ // Errors leave fields untouched. A required field that starts
+ // `None` and is errored stays `None`, so the full computation
+ // never runs.
+ let mut item = fully_seeded_branch_item();
+ item.counts = None;
+ item.is_orphan = None;
+
+ let (tx, rx) = crossbeam_channel::unbounded();
+ let expected = ExpectedResults::default();
+ expected.expect(0, TaskKind::AheadBehind);
+
+ tx.send(Err(TaskError::new(
+ 0,
+ TaskKind::AheadBehind,
+ "boom",
+ ErrorCause::Other,
+ )))
+ .unwrap();
+ drop(tx);
+
+ let mut errors = Vec::new();
+ let outcome = drain_results(
+ rx,
+ std::slice::from_mut(&mut item),
+ &mut errors,
+ &expected,
+ Instant::now() + DRAIN_TIMEOUT,
+ Some("main"),
+ |_, _| {},
+ );
+
+ assert!(matches!(outcome, DrainOutcome::Complete));
+ assert!(
+ !full_computation_ran(&item),
+ "full status computation should not run when its sole feeder errored",
+ );
+ assert_eq!(errors.len(), 1);
+ }
+
#[test]
fn test_drain_results_timeout_returns_missing_diagnostics() {
let (_tx, rx) = crossbeam_channel::unbounded();
@@ -378,7 +529,8 @@ mod tests {
&mut errors,
&expected,
Instant::now(),
- |_, _, _| {},
+ None,
+ |_, _| {},
);
let DrainOutcome::TimedOut {
diff --git a/src/commands/list/collect/types.rs b/src/commands/list/collect/types.rs
index b7b3b858b..ccd8215e6 100644
--- a/src/commands/list/collect/types.rs
+++ b/src/commands/list/collect/types.rs
@@ -3,52 +3,16 @@
//! Contains all the type definitions used by the collection system:
//! - `TaskResult` and `TaskKind` - result variants from task computations
//! - `TaskError` and `ErrorCause` - error handling for failed tasks
-//! - `StatusContext` - context for status symbol computation
//! - `DrainOutcome` and `MissingResult` - timeout diagnostic info
use worktrunk::git::LineDiff;
use super::super::ci_status::PrStatus;
use super::super::model::{
- ActiveGitOperation, AheadBehind, BranchDiffTotals, CommitDetails, ListItem, UpstreamStatus,
+ ActiveGitOperation, AheadBehind, BranchDiffTotals, CommitDetails, UpstreamStatus,
WorkingTreeStatus,
};
-/// Context for status symbol computation during result processing
-#[derive(Clone, Default)]
-pub(super) struct StatusContext {
- pub has_merge_tree_conflicts: bool,
- /// Working tree conflict check result (worktrees only).
- /// None = use commit check (task didn't run or working tree clean)
- /// Some(b) = dirty working tree, b is conflict result
- // TODO: If we need to distinguish "task didn't run" from "clean working tree",
- // expand to an enum. Currently both cases fall back to commit-based check.
- pub has_working_tree_conflicts: Option<bool>,
- pub user_marker: Option<String>,
- pub working_tree_status: Option<WorkingTreeStatus>,
- pub has_conflicts: bool,
-}
-
-impl StatusContext {
- pub fn apply_to(&self, item: &mut ListItem, target: Option<&str>) {
- // Main worktree case is handled inside check_integration_state()
- //
- // Prefer working tree conflicts when available.
- // None means task didn't run or working tree was clean - use commit check.
- let has_conflicts = self
- .has_working_tree_conflicts
- .unwrap_or(self.has_merge_tree_conflicts);
-
- item.compute_status_symbols(
- target,
- has_conflicts,
- self.user_marker.clone(),
- self.working_tree_status,
- self.has_conflicts,
- );
- }
-}
-
/// Task results sent as each git operation completes.
/// These enable progressive rendering - update UI as data arrives.
///
@@ -233,7 +197,8 @@ pub enum ErrorCause {
/// Error during task execution.
///
/// Tasks return this instead of swallowing errors. The drain layer
-/// applies defaults and collects errors for display after rendering.
+/// collects errors for display after rendering; errored fields stay
+/// `None` so `compute_status_symbols` naturally skips the item.
#[derive(Debug, Clone)]
pub struct TaskError {
pub item_idx: usize,
diff --git a/src/commands/list/json_output.rs b/src/commands/list/json_output.rs
index 1b7712d1a..b79831e2e 100644
--- a/src/commands/list/json_output.rs
+++ b/src/commands/list/json_output.rs
@@ -263,37 +263,39 @@ impl JsonItem {
timestamp: item.commit.as_ref().map(|c| c.timestamp).unwrap_or(0),
};
- // Working tree (only for worktrees with status symbols)
+ // Working tree: read directly from `WorktreeData`, not from
+ // `status_symbols.working_tree`. `status_symbols` may be set by
+ // the metadata-only fallback in `compute_status_symbols` (locked
+ // / prunable / mismatched worktrees) carrying a default
+ // `WorkingTreeStatus`. The JSON output must reflect whether
+ // `WorkingTreeDiff` actually loaded the field — collapsing
+ // "unknown" into "clean" misleads consumers.
let working_tree = worktree_data.and_then(|data| {
- item.status_symbols.as_ref().map(|symbols| {
- let wt = &symbols.working_tree;
- JsonWorkingTree {
- staged: wt.staged,
- modified: wt.modified,
- untracked: wt.untracked,
- renamed: wt.renamed,
- deleted: wt.deleted,
- diff: data.working_tree_diff.map(JsonDiff::from),
- }
+ data.working_tree_status.map(|wt| JsonWorkingTree {
+ staged: wt.staged,
+ modified: wt.modified,
+ untracked: wt.untracked,
+ renamed: wt.renamed,
+ deleted: wt.deleted,
+ diff: data.working_tree_diff.map(JsonDiff::from),
})
});
- // Main state and integration reason
- let (main_state, integration_reason) = item
+ // Main state and integration reason. Unresolved gate 3 → both
+ // absent from JSON. Resolved → emit as today.
+ let main_state = item.status_symbols.main_state.and_then(|s| s.as_json_str());
+ let integration_reason = item
.status_symbols
- .as_ref()
- .map(|symbols| {
- let state = symbols.main_state.as_json_str();
- let reason = symbols.main_state.integration_reason().map(|r| r.into());
- (state, reason)
- })
- .unwrap_or((None, None));
+ .main_state
+ .and_then(|s| s.integration_reason())
+ .map(|r| r.into());
- // Operation state (conflicts, rebase, merge)
+ // Operation state (conflicts, rebase, merge). Unresolved gate 2
+ // (operation family) → absent from JSON.
let operation_state = item
.status_symbols
- .as_ref()
- .and_then(|symbols| symbols.operation_state.as_json_str());
+ .operation_state
+ .and_then(|s| s.as_json_str());
// Main relationship (absent when is_main)
let main = if is_main {
@@ -314,7 +316,7 @@ impl JsonItem {
// Worktree state
let worktree = worktree_data.map(|data| {
- let (state, reason) = worktree_state_to_json(data, item.status_symbols.as_ref());
+ let (state, reason) = worktree_state_to_json(data, &item.status_symbols);
JsonWorktree {
state,
reason,
@@ -334,11 +336,7 @@ impl JsonItem {
// Statusline and symbols (raw, without ANSI codes)
let statusline = item.display.statusline.clone();
- let symbols = item
- .status_symbols
- .as_ref()
- .map(format_raw_symbols)
- .filter(|s| !s.is_empty());
+ let symbols = Some(format_raw_symbols(&item.status_symbols)).filter(|s| !s.is_empty());
// Per-branch vars data (pre-fetched, moved out to avoid cloning)
let vars = item
@@ -393,25 +391,26 @@ fn upstream_to_json(upstream: &UpstreamStatus, branch: &Option<String>) -> Optio
/// Extract worktree state and reason from WorktreeData
fn worktree_state_to_json(
data: &super::model::WorktreeData,
- status_symbols: Option<&super::model::StatusSymbols>,
+ status_symbols: &super::model::StatusSymbols,
) -> (Option<&'static str>, Option<String>) {
use super::model::WorktreeState;
- // Check status symbols for worktree state
- if let Some(symbols) = status_symbols {
- match symbols.worktree_state {
- WorktreeState::None => {}
- WorktreeState::Branch => return (Some("no_worktree"), None),
- WorktreeState::BranchWorktreeMismatch => {
- return (Some("branch_worktree_mismatch"), None);
- }
- WorktreeState::Prunable => return (Some("prunable"), data.prunable.clone()),
- WorktreeState::Locked => return (Some("locked"), data.locked.clone()),
+ // Check status symbols for worktree state. `None` means gate 2
+ // (metadata family) hasn't been populated yet; fall through to the
+ // direct-field fallback below.
+ match status_symbols.worktree_state {
+ None | Some(WorktreeState::None) => {}
+ Some(WorktreeState::Branch) => return (Some("no_worktree"), None),
+ Some(WorktreeState::BranchWorktreeMismatch) => {
+ return (Some("branch_worktree_mismatch"), None);
}
+ Some(WorktreeState::Prunable) => return (Some("prunable"), data.prunable.clone()),
+ Some(WorktreeState::Locked) => return (Some("locked"), data.locked.clone()),
}
- // Fallback: check direct fields when status_symbols is None
- // This can happen early in progressive rendering before status is computed
+ // Fallback: check direct fields when status_symbols hasn't resolved
+ // worktree_state yet. This can happen early in progressive rendering
+ // before status is computed.
if data.is_prunable() {
return (Some("prunable"), data.prunable.clone());
}
@@ -433,41 +432,54 @@ impl From<&PrStatus> for JsonCi {
}
}
-/// Format status symbols as raw characters (no ANSI codes)
+/// Format status symbols as raw characters (no ANSI codes).
+///
+/// Unresolved gates (`None` fields) contribute nothing — their symbols are
+/// simply absent from the output string, not replaced by a placeholder.
+/// This matches the per-symbol atomic model: machine consumers see only the
+/// symbols that have been computed so far.
fn format_raw_symbols(symbols: &super::model::StatusSymbols) -> String {
let mut result = String::new();
- // Working tree symbols
- let wt_symbols = symbols.working_tree.to_symbols();
- if !wt_symbols.is_empty() {
- result.push_str(&wt_symbols);
+ // Working tree symbols (gate 1)
+ if let Some(wt) = symbols.working_tree {
+ result.push_str(&wt.to_symbols());
}
- // Main state (merged: ^✗_⊂↕↑↓)
- let main_state = symbols.main_state.to_string();
- if !main_state.is_empty() {
- result.push_str(&main_state);
+ // Main state (gate 3) — merged column: ^✗_⊂↕↑↓
+ if let Some(ms) = symbols.main_state {
+ let s = ms.to_string();
+ if !s.is_empty() {
+ result.push_str(&s);
+ }
}
- // Upstream divergence
- let upstream_div = symbols.upstream_divergence.symbol();
- if !upstream_div.is_empty() {
- result.push_str(upstream_div);
+ // Upstream divergence (gate 4)
+ if let Some(div) = symbols.upstream_divergence {
+ let s = div.symbol();
+ if !s.is_empty() {
+ result.push_str(s);
+ }
}
- // Worktree state (operations ✘⤴⤵ take priority over location /⚑⊟⊞)
- let op_state = symbols.operation_state.to_string();
- if !op_state.is_empty() {
- result.push_str(&op_state);
- } else {
- let wt_state = symbols.worktree_state.to_string();
- if !wt_state.is_empty() {
- result.push_str(&wt_state);
+ // Worktree state (gate 2) — operations (✘⤴⤵) take priority over
+ // location (/⚑⊟⊞). Gate 2 is "operation_state is Some"; the metadata
+ // worktree_state is filled synchronously and always Some by the time
+ // the operation family is known.
+ if let Some(op) = symbols.operation_state {
+ let s = op.to_string();
+ if !s.is_empty() {
+ result.push_str(&s);
+ } else if let Some(wt_state) = symbols.worktree_state {
+ let s = wt_state.to_string();
+ if !s.is_empty() {
+ result.push_str(&s);
+ }
}
}
- // User marker
- if let Some(ref marker) = symbols.user_marker {
+ // User marker (gate 5)
+ if let Some(Some(ref marker)) = symbols.user_marker {
result.push_str(marker);
}
@@ -629,7 +641,10 @@ mod tests {
locked: None,
prunable: None,
working_tree_diff: None,
- git_operation: ActiveGitOperation::None,
+ working_tree_status: None,
+ has_conflicts: None,
+ has_working_tree_conflicts: None,
+ git_operation: Some(ActiveGitOperation::None),
branch_worktree_mismatch: false,
working_diff_display: None,
}
@@ -637,12 +652,12 @@ mod tests {
fn make_status_symbols_with_worktree_state(state: WorktreeState) -> StatusSymbols {
StatusSymbols {
- working_tree: WorkingTreeStatus::default(),
- worktree_state: state,
- main_state: MainState::None,
- operation_state: OperationState::None,
- upstream_divergence: Divergence::None,
- user_marker: None,
+ working_tree: Some(WorkingTreeStatus::default()),
+ worktree_state: Some(state),
+ main_state: Some(MainState::None),
+ operation_state: Some(OperationState::None),
+ upstream_divergence: Some(Divergence::None),
+ user_marker: Some(None),
}
}
@@ -650,7 +665,7 @@ mod tests {
fn test_worktree_state_to_json_none() {
let data = make_worktree_data();
let symbols = make_status_symbols_with_worktree_state(WorktreeState::None);
- let (state, reason) = worktree_state_to_json(&data, Some(&symbols));
+ let (state, reason) = worktree_state_to_json(&data, &symbols);
assert!(state.is_none());
assert!(reason.is_none());
}
@@ -659,7 +674,7 @@ mod tests {
fn test_worktree_state_to_json_no_worktree() {
let data = make_worktree_data();
let symbols = make_status_symbols_with_worktree_state(WorktreeState::Branch);
- let (state, reason) = worktree_state_to_json(&data, Some(&symbols));
+ let (state, reason) = worktree_state_to_json(&data, &symbols);
assert_eq!(state, Some("no_worktree"));
assert!(reason.is_none());
}
@@ -669,7 +684,7 @@ mod tests {
let data = make_worktree_data();
let symbols =
make_status_symbols_with_worktree_state(WorktreeState::BranchWorktreeMismatch);
- let (state, reason) = worktree_state_to_json(&data, Some(&symbols));
+ let (state, reason) = worktree_state_to_json(&data, &symbols);
assert_eq!(state, Some("branch_worktree_mismatch"));
assert!(reason.is_none());
}
@@ -679,7 +694,7 @@ mod tests {
let mut data = make_worktree_data();
data.locked = Some("manual lock".to_string());
let symbols = make_status_symbols_with_worktree_state(WorktreeState::Locked);
- let (state, reason) = worktree_state_to_json(&data, Some(&symbols));
+ let (state, reason) = worktree_state_to_json(&data, &symbols);
assert_eq!(state, Some("locked"));
assert_eq!(reason, Some("manual lock".to_string()));
}
@@ -689,7 +704,7 @@ mod tests {
let mut data = make_worktree_data();
data.prunable = Some("gitdir file missing".to_string());
let symbols = make_status_symbols_with_worktree_state(WorktreeState::Prunable);
- let (state, reason) = worktree_state_to_json(&data, Some(&symbols));
+ let (state, reason) = worktree_state_to_json(&data, &symbols);
assert_eq!(state, Some("prunable"));
assert_eq!(reason, Some("gitdir file missing".to_string()));
}
@@ -698,8 +713,9 @@ mod tests {
fn test_worktree_state_to_json_fallback_prunable() {
let mut data = make_worktree_data();
data.prunable = Some("missing gitdir".to_string());
- // No status symbols provided - fallback to data fields
- let (state, reason) = worktree_state_to_json(&data, None);
+ // Default status symbols — fallback to data fields
+ let symbols = StatusSymbols::default();
+ let (state, reason) = worktree_state_to_json(&data, &symbols);
assert_eq!(state, Some("prunable"));
assert_eq!(reason, Some("missing gitdir".to_string()));
}
@@ -708,7 +724,8 @@ mod tests {
fn test_worktree_state_to_json_fallback_locked() {
let mut data = make_worktree_data();
data.locked = Some("in use".to_string());
- let (state, reason) = worktree_state_to_json(&data, None);
+ let symbols = StatusSymbols::default();
+ let (state, reason) = worktree_state_to_json(&data, &symbols);
assert_eq!(state, Some("locked"));
assert_eq!(reason, Some("in use".to_string()));
}
@@ -726,38 +743,43 @@ mod tests {
#[test]
fn test_format_raw_symbols_each_category() {
let working_tree = format_raw_symbols(&StatusSymbols {
- working_tree: WorkingTreeStatus::new(true, true, true, false, false),
+ working_tree: Some(WorkingTreeStatus::new(true, true, true, false, false)),
..Default::default()
});
assert_snapshot!(working_tree, @"+!?");
let main_state = format_raw_symbols(&StatusSymbols {
- main_state: MainState::Ahead,
+ main_state: Some(MainState::Ahead),
..Default::default()
});
assert_snapshot!(main_state, @"↑");
let upstream = format_raw_symbols(&StatusSymbols {
- upstream_divergence: Divergence::Behind,
+ upstream_divergence: Some(Divergence::Behind),
..Default::default()
});
assert_snapshot!(upstream, @"⇣");
// Operation state takes priority over worktree state
let operation = format_raw_symbols(&StatusSymbols {
- operation_state: OperationState::Rebase,
+ operation_state: Some(OperationState::Rebase),
..Default::default()
});
assert_snapshot!(operation, @"⤴");
+ // Worktree metadata renders only once the operation-family gate
+ // has resolved to "no operation" — otherwise we can't rule out
+ // ✘⤴⤵ taking priority. Callers that want just the metadata
+ // symbol must set both `operation_state` and `worktree_state`.
let worktree = format_raw_symbols(&StatusSymbols {
- worktree_state: WorktreeState::Locked,
+ operation_state: Some(OperationState::None),
+ worktree_state: Some(WorktreeState::Locked),
..Default::default()
});
assert_snapshot!(worktree, @"⊞");
let marker = format_raw_symbols(&StatusSymbols {
- user_marker: Some("\u{1f525}".to_string()),
+ user_marker: Some(Some("\u{1f525}".to_string())),
..Default::default()
});
assert_snapshot!(marker, @"🔥");
@@ -766,9 +788,9 @@ mod tests {
#[test]
fn test_format_raw_symbols_combined() {
let result = format_raw_symbols(&StatusSymbols {
- working_tree: WorkingTreeStatus::new(true, false, false, false, false),
- main_state: MainState::Behind,
- upstream_divergence: Divergence::Ahead,
+ working_tree: Some(WorkingTreeStatus::new(true, false, false, false, false)),
+ main_state: Some(MainState::Behind),
+ upstream_divergence: Some(Divergence::Ahead),
..Default::default()
});
assert_snapshot!(result, @"+↓⇡");
diff --git a/src/commands/list/layout.rs b/src/commands/list/layout.rs
index 81c9ec738..75cd8c35f 100644
--- a/src/commands/list/layout.rs
+++ b/src/commands/list/layout.rs
@@ -1330,7 +1330,9 @@ mod tests {
url: None,
url_active: None,
summary: None,
- status_symbols: Some(StatusSymbols::default()),
+ has_merge_tree_conflicts: None,
+ user_marker: None,
+ status_symbols: StatusSymbols::default(),
display: DisplayFields::default(),
kind: ItemKind::Worktree(Box::new(WorktreeData {
path: PathBuf::from("/test/path"),
@@ -1338,7 +1340,10 @@ mod tests {
locked: None,
prunable: None,
working_tree_diff: Some(LineDiff::from((100, 50))),
- git_operation: ActiveGitOperation::None,
+ working_tree_status: None,
+ has_conflicts: None,
+ has_working_tree_conflicts: None,
+ git_operation: Some(ActiveGitOperation::None),
is_main: false,
is_current: false,
is_previous: false,
@@ -1430,7 +1435,9 @@ mod tests {
url: None,
url_active: None,
summary: None,
- status_symbols: Some(StatusSymbols::default()),
+ has_merge_tree_conflicts: None,
+ user_marker: None,
+ status_symbols: StatusSymbols::default(),
display: DisplayFields::default(),
kind: ItemKind::Worktree(Box::new(WorktreeData {
path: PathBuf::from("/test"),
@@ -1438,7 +1445,10 @@ mod tests {
locked: None,
prunable: None,
working_tree_diff: Some(LineDiff::default()),
- git_operation: ActiveGitOperation::None,
+ working_tree_status: None,
+ has_conflicts: None,
+ has_working_tree_conflicts: None,
+ git_operation: Some(ActiveGitOperation::None),
is_main: true, // Primary worktree: no ahead/behind shown
is_current: false,
is_previous: false,
@@ -1525,7 +1535,7 @@ mod tests {
/// Helper: create a minimal ListItem for layout tests.
fn make_test_item(branch: &str) -> super::super::model::ListItem {
use crate::commands::list::model::{
- ActiveGitOperation, DisplayFields, ItemKind, WorktreeData,
+ ActiveGitOperation, DisplayFields, ItemKind, StatusSymbols, WorktreeData,
};
super::super::model::ListItem {
head: "abc12345".to_string(),
@@ -1544,7 +1554,9 @@ mod tests {
url: None,
url_active: None,
summary: None,
- status_symbols: None,
+ has_merge_tree_conflicts: None,
+ user_marker: None,
+ status_symbols: StatusSymbols::default(),
display: DisplayFields::default(),
kind: ItemKind::Worktree(Box::new(WorktreeData {
path: PathBuf::from("/test/wt"),
@@ -1552,7 +1564,10 @@ mod tests {
locked: None,
prunable: None,
working_tree_diff: None,
- git_operation: ActiveGitOperation::None,
+ working_tree_status: None,
+ has_conflicts: None,
+ has_working_tree_conflicts: None,
+ git_operation: Some(ActiveGitOperation::None),
is_main: false,
is_current: false,
is_previous: false,
@@ -1767,7 +1782,7 @@ mod tests {
/// Helper: create a test item with a specific worktree path and no mismatch.
fn make_test_item_at(branch: &str, path: &str) -> super::super::model::ListItem {
use crate::commands::list::model::{
- ActiveGitOperation, DisplayFields, ItemKind, WorktreeData,
+ ActiveGitOperation, DisplayFields, ItemKind, StatusSymbols, WorktreeData,
};
super::super::model::ListItem {
head: "abc12345".to_string(),
@@ -1786,7 +1801,9 @@ mod tests {
url: None,
url_active: None,
summary: None,
- status_symbols: None,
+ has_merge_tree_conflicts: None,
+ user_marker: None,
+ status_symbols: StatusSymbols::default(),
display: DisplayFields::default(),
kind: ItemKind::Worktree(Box::new(WorktreeData {
path: PathBuf::from(path),
@@ -1794,7 +1811,10 @@ mod tests {
locked: None,
prunable: None,
working_tree_diff: None,
- git_operation: ActiveGitOperation::None,
+ working_tree_status: None,
+ has_conflicts: None,
+ has_working_tree_conflicts: None,
+ git_operation: Some(ActiveGitOperation::None),
is_main: false,
is_current: false,
is_previous: false,
@@ -1912,7 +1932,9 @@ mod tests {
url: None,
url_active: None,
summary: Some(summary.map(|s| s.to_string())),
- status_symbols: Some(StatusSymbols::default()),
+ has_merge_tree_conflicts: None,
+ user_marker: None,
+ status_symbols: StatusSymbols::default(),
display: DisplayFields::default(),
kind: ItemKind::Worktree(Box::new(WorktreeData {
path: PathBuf::from(path),
@@ -1920,7 +1942,10 @@ mod tests {
locked: None,
prunable: None,
working_tree_diff: Some(LineDiff::default()),
- git_operation: ActiveGitOperation::None,
+ working_tree_status: None,
+ has_conflicts: None,
+ has_working_tree_conflicts: None,
+ git_operation: Some(ActiveGitOperation::None),
is_main,
is_current,
is_previous: false,
diff --git a/src/commands/list/mod.rs b/src/commands/list/mod.rs
index 076652693..1efdd9ac1 100644
--- a/src/commands/list/mod.rs
+++ b/src/commands/list/mod.rs
@@ -223,11 +223,12 @@ impl SummaryMetrics {
if let Some(_data) = item.worktree_data() {
self.worktrees += 1;
// Use status_symbols.working_tree which includes untracked files,
- // not just working_tree_diff which only has tracked changes
+ // not just working_tree_diff which only has tracked changes.
+ // `None` means gate 1 hasn't resolved yet — don't count.
if item
.status_symbols
- .as_ref()
- .is_some_and(|s| s.working_tree.is_dirty())
+ .working_tree
+ .is_some_and(|wt| wt.is_dirty())
{
self.dirty_worktrees += 1;
}
diff --git a/src/commands/list/model/item.rs b/src/commands/list/model/item.rs
index 36a660baa..815a28b97 100644
--- a/src/commands/list/model/item.rs
+++ b/src/commands/list/model/item.rs
@@ -67,6 +67,38 @@ impl DisplayFields {
}
}
+/// Serde helper: skip `git_operation` when it is absent (unloaded) or an
+/// active `ActiveGitOperation::None` — preserving the original
+/// `skip_serializing_if = "ActiveGitOperation::is_none"` behavior now that
+/// the field is wrapped in `Option`.
+// `clippy::ref_option` fires because we take `&Option<T>` instead of
+// `Option<&T>`, but `skip_serializing_if` calls this with `&field`, so the
+// signature is forced by serde.
+#[allow(clippy::ref_option)]
+fn git_operation_is_none_or_unloaded(op: &Option<ActiveGitOperation>) -> bool {
+ match op {
+ None => true,
+ Some(inner) => inner.is_none(),
+ }
+}
+
+/// Compute the `WorktreeState` from `WorktreeData` metadata alone.
+///
+/// Used by both `compute_status_symbols` (full computation) and the
+/// metadata-only fallback path. The decision priority is:
+/// `branch_worktree_mismatch` > `prunable` > `locked` > `None`.
+fn metadata_worktree_state(data: &WorktreeData) -> WorktreeState {
+ if data.branch_worktree_mismatch {
+ WorktreeState::BranchWorktreeMismatch
+ } else if data.is_prunable() {
+ WorktreeState::Prunable
+ } else if data.locked.is_some() {
+ WorktreeState::Locked
+ } else {
+ WorktreeState::None
+ }
+}
+
/// Type-specific data for worktrees
#[derive(Clone, serde::Serialize, Default)]
pub struct WorktreeData {
@@ -78,9 +110,25 @@ pub struct WorktreeData {
pub prunable: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub working_tree_diff: Option<LineDiff>,
- /// Git operation in progress (rebase/merge)
- #[serde(skip_serializing_if = "ActiveGitOperation::is_none")]
- pub git_operation: ActiveGitOperation,
+ /// Working-tree change flags (tracked/untracked/modified). `None` = not yet
+ /// loaded; `Some` = loaded (possibly empty). Fed by the `WorkingTreeDiff` task.
+ #[serde(skip)]
+ pub working_tree_status: Option<WorkingTreeStatus>,
+ /// Whether the working tree has merge conflicts in tracked files. `None` =
+ /// not yet loaded; `Some` = loaded. Fed by the `WorkingTreeDiff` task.
+ #[serde(skip)]
+ pub has_conflicts: Option<bool>,
+ /// Result of `WorkingTreeConflicts` task (`--full` mode only). Outer `None`
+ /// = task hasn't run yet. Outer `Some(None)` = task ran but working tree
+ /// was clean, so fall back to the committed-HEAD merge-tree check.
+ /// Outer `Some(Some(b))` = dirty working tree, `b` is the conflict result.
+ #[serde(skip)]
+ pub has_working_tree_conflicts: Option<Option<bool>>,
+ /// Git operation in progress (rebase/merge). `None` = not yet loaded;
+ /// `Some(ActiveGitOperation::None)` = loaded, no operation in progress.
+ /// Fed by the `GitOperation` task.
+ #[serde(skip_serializing_if = "git_operation_is_none_or_unloaded")]
+ pub git_operation: Option<ActiveGitOperation>,
pub is_main: bool,
/// Whether this is the current worktree (matches repo discovery path: PWD or `-C`)
#[serde(skip_serializing_if = "std::ops::Not::not")]
@@ -208,10 +256,26 @@ pub struct ListItem {
#[serde(skip)]
pub summary: Option<Option<String>>,
- /// Git status symbols - None until all dependencies are ready.
- /// Note: This field is not serialized directly. JSON output converts to JsonItem first.
+ /// Potential merge conflicts with the integration target, computed from
+ /// the committed HEAD via `git merge-tree`. `None` = not yet loaded;
+ /// `Some` = loaded. Fed by the `MergeTreeConflicts` task.
+ #[serde(skip)]
+ pub has_merge_tree_conflicts: Option<bool>,
+ /// User-defined status marker from git config. Outer `None` = task
+ /// hasn't run yet; `Some(None)` = task ran, no marker configured;
+ /// `Some(Some(s))` = task ran, marker is `s`. Fed by the `UserMarker` task.
+ #[serde(skip)]
+ pub user_marker: Option<Option<String>>,
+
+ /// Git status symbols — one `StatusSymbols` struct per item, always
+ /// present after construction. Each *field inside* `StatusSymbols` is an
+ /// `Option` that progresses from `None` (loading, renders `⋯`) to `Some`
+ /// as task results arrive. See the `status_symbols` module docstring for
+ /// the per-gate rendering rules.
+ ///
+ /// Not serialized directly — JSON output converts to `JsonItem` first.
#[serde(skip)]
- pub status_symbols: Option<StatusSymbols>,
+ pub status_symbols: StatusSymbols,
// Display fields for json-pretty format (with ANSI colors)
#[serde(flatten)]
@@ -255,7 +319,9 @@ impl ListItem {
url: None,
url_active: None,
summary: None,
- status_symbols: None,
+ has_merge_tree_conflicts: None,
+ user_marker: None,
+ status_symbols: StatusSymbols::default(),
display: DisplayFields::default(),
kind: ItemKind::Branch,
}
@@ -314,8 +380,9 @@ impl ListItem {
/// 5. **Working tree matches default branch** (worktrees only) - uncommitted changes
/// don't diverge from the default branch.
pub(crate) fn is_potentially_removable(&self) -> Option<bool> {
- // Use already-computed status_symbols if available
- let main_state = self.status_symbols.as_ref()?.main_state;
+ // Gate 3 (`main_state`) is `None` until its inputs land. Until
+ // then, we don't know whether the item is removable.
+ let main_state = self.status_symbols.main_state?;
// SameCommit excluded: has uncommitted work that would be lost
Some(matches!(
main_state,
@@ -367,11 +434,9 @@ impl ListItem {
));
// 2. Status symbols (priority 2)
- if let Some(ref symbols) = self.status_symbols {
- let status = symbols.format_compact();
- if !status.is_empty() {
- segments.push(StatuslineSegment::from_column(status, ColumnKind::Status));
- }
+ let status = self.status_symbols.format_compact();
+ if !status.is_empty() {
+ segments.push(StatuslineSegment::from_column(status, ColumnKind::Status));
}
// 3. Working diff (priority 3)
@@ -454,135 +519,182 @@ impl ListItem {
}
}
- /// Compute status symbols for this item.
+ /// Refresh status symbols for this item, populating any gates whose
+ /// inputs have newly become available.
///
- /// This is idempotent and can be called multiple times as new data arrives.
- /// It will recompute with the latest available data.
+ /// Idempotent: safe to call repeatedly as task results arrive. Each
+ /// gate is resolved independently; a gate once resolved is never
+ /// unresolved. Gates whose inputs aren't ready yet are left at
+ /// `None`, and the renderer emits the position-level `⋯` placeholder
+ /// for them (step 5).
///
- /// Branches get a subset of status symbols (no working tree changes or worktree attrs).
- pub(crate) fn compute_status_symbols(
- &mut self,
- default_branch: Option<&str>,
- has_merge_tree_conflicts: bool,
- user_marker: Option<String>,
- working_tree_status: Option<WorkingTreeStatus>,
- has_conflicts: bool,
- ) {
- // Common fields for both worktrees and branches
- let default_counts = AheadBehind::default();
- let default_upstream = UpstreamStatus::default();
- let counts = self.counts.as_ref().unwrap_or(&default_counts);
- let upstream = self.upstream.as_ref().unwrap_or(&default_upstream);
- let upstream_divergence = match upstream.active() {
- None => Divergence::None,
- Some(active) => Divergence::from_counts_with_remote(active.ahead, active.behind),
+ /// See the `status_symbols` module docstring for the full per-gate
+ /// spec including priority short-circuit rules.
+ pub(crate) fn refresh_status_symbols(&mut self, default_branch: Option<&str>) {
+ // Gate 2 (metadata family — position 3). Metadata-only, so it
+ // resolves synchronously on the first refresh call. After this
+ // line, `status_symbols.worktree_state` is always `Some`.
+ // (Prunable worktrees are pre-seeded at spawn time and have
+ // `worktree_state = Some(Prunable)` by the time this runs.)
+ let metadata_state = match &self.kind {
+ ItemKind::Worktree(data) => metadata_worktree_state(data),
+ ItemKind::Branch => WorktreeState::Branch,
};
+ if self.status_symbols.worktree_state.is_none() {
+ self.status_symbols.worktree_state = Some(metadata_state);
+ }
+
+ // Gate 1 (working tree flags — positions 0-2).
+ if self.status_symbols.working_tree.is_none()
+ && let Some(wt) = self.try_gate_working_tree()
+ {
+ self.status_symbols.working_tree = Some(wt);
+ }
+
+ // Gate 2 (operation family — position 3).
+ if self.status_symbols.operation_state.is_none()
+ && let Some(op) = self.try_gate_operation_state()
+ {
+ self.status_symbols.operation_state = Some(op);
+ }
+
+ // Gate 3 (main state — position 4).
+ // Gate 3 is re-evaluable: unlike other gates, its answer can
+ // become more specific as later signals arrive. Integration
+ // signals are not hard-gated, so the first pass may see only
+ // counts and produce `Ahead`; a later pass with `has_file_changes`
+ // loaded can refine to `Integrated(NoAddedChanges)`. The
+ // progression is strictly refinement (never wrong, just less
+ // specific), so re-evaluation is safe.
+ if let Some(ms) = self.try_gate_main_state(default_branch) {
+ self.status_symbols.main_state = Some(ms);
+ }
+
+ // Gate 4 (upstream divergence — position 5).
+ if self.status_symbols.upstream_divergence.is_none()
+ && let Some(d) = self.try_gate_upstream_divergence()
+ {
+ self.status_symbols.upstream_divergence = Some(d);
+ }
+
+ // Gate 5 (user marker — position 6).
+ if self.status_symbols.user_marker.is_none()
+ && let Some(m) = self.try_gate_user_marker()
+ {
+ self.status_symbols.user_marker = Some(m);
+ }
+ }
+
+ /// Gate 1: working tree flags. Resolves as soon as `working_tree_status`
+ /// is loaded (for worktrees) or immediately (for branches, which have
+ /// no working tree).
+ fn try_gate_working_tree(&self) -> Option<WorkingTreeStatus> {
+ match &self.kind {
+ ItemKind::Worktree(data) => data.working_tree_status,
+ // Branches have no working tree; treat as permanently clean.
+ ItemKind::Branch => Some(WorkingTreeStatus::default()),
+ }
+ }
+ /// Gate 2: operation state. Resolves once both `has_conflicts` and
+ /// `git_operation` have reported. Priority within the gate:
+ /// `has_conflicts` > rebase > merge > none.
+ fn try_gate_operation_state(&self) -> Option<OperationState> {
match &self.kind {
ItemKind::Worktree(data) => {
- // Full status computation for worktrees
-
- // Worktree location state - priority: branch_worktree_mismatch > prunable > locked
- let worktree_state = if data.branch_worktree_mismatch {
- WorktreeState::BranchWorktreeMismatch
- } else if data.is_prunable() {
- WorktreeState::Prunable
- } else if data.locked.is_some() {
- WorktreeState::Locked
- } else {
- WorktreeState::None
- };
-
- // Operation state - priority: conflicts > rebase > merge
- let operation_state = if has_conflicts {
- OperationState::Conflicts
- } else if data.git_operation == ActiveGitOperation::Rebase {
- OperationState::Rebase
- } else if data.git_operation == ActiveGitOperation::Merge {
- OperationState::Merge
- } else {
- OperationState::None
- };
-
- // Check if content is integrated into main (safe to delete)
- let has_untracked = working_tree_status.is_some_and(|s| s.untracked);
- // is_clean requires working_tree_diff to be loaded AND empty, plus no untracked.
- // Don't assume clean when unknown to avoid premature integration state
- // (which would cause UI flash during progressive loading).
- let is_clean = data
- .working_tree_diff
- .as_ref()
- .is_some_and(|d| d.is_empty())
- && !has_untracked;
- let integration =
- self.check_integration_state(data.is_main, default_branch, is_clean);
-
- // Separately detect SameCommit: same commit as main but with uncommitted work
- // This is NOT an integration state (has work that would be lost on delete)
- // Use ahead==0 && behind==0 (vs stats_base/main) to detect same commit
- let has_tracked_changes = data
- .working_tree_diff
- .as_ref()
- .is_some_and(|d| !d.is_empty());
- let is_same_commit_dirty = counts.ahead == 0
- && counts.behind == 0
- && (has_tracked_changes || has_untracked);
-
- // Compute main state: combines is_main, would_conflict, integration, and divergence
- let main_state = MainState::from_integration_and_counts(
- data.is_main,
- has_merge_tree_conflicts,
- integration,
- is_same_commit_dirty,
- self.is_orphan.unwrap_or(false),
- counts.ahead,
- counts.behind,
- );
-
- self.status_symbols = Some(StatusSymbols {
- main_state,
- operation_state,
- worktree_state,
- upstream_divergence,
- working_tree: working_tree_status.unwrap_or_default(),
- user_marker,
- });
+ let has_conflicts = data.has_conflicts?;
+ if has_conflicts {
+ return Some(OperationState::Conflicts);
+ }
+ let git_operation = data.git_operation.as_ref()?;
+ match git_operation {
+ ActiveGitOperation::Rebase => Some(OperationState::Rebase),
+ ActiveGitOperation::Merge => Some(OperationState::Merge),
+ ActiveGitOperation::None => Some(OperationState::None),
+ }
}
- ItemKind::Branch => {
- // Simplified status computation for branches
- // Only compute symbols that apply to branches (no working tree, git operation, or worktree attrs)
-
- // Branches don't have working trees, so always clean
- let integration = self.check_integration_state(
- false, // branches are never main worktree
- default_branch,
- true, // branches are always clean (no working tree)
- );
-
- // Compute main state
- // Branches can't have is_same_commit_dirty (no working tree)
- let main_state = MainState::from_integration_and_counts(
- false, // not main
- has_merge_tree_conflicts,
- integration,
- false, // branches have no working tree, can't be dirty
- self.is_orphan.unwrap_or(false),
- counts.ahead,
- counts.behind,
- );
-
- self.status_symbols = Some(StatusSymbols {
- main_state,
- operation_state: OperationState::None,
- worktree_state: WorktreeState::Branch,
- upstream_divergence,
- working_tree: WorkingTreeStatus::default(),
- user_marker,
- });
+ // Branches have no operation state; trivially resolved to None.
+ ItemKind::Branch => Some(OperationState::None),
+ }
+ }
+
+ /// Gate 3: main state. Walks the priority chain tier by tier, using
+ /// the per-tier helpers from `state.rs`.
+ fn try_gate_main_state(&self, default_branch: Option<&str>) -> Option<MainState> {
+ use super::state::{
+ Tier, tier_integration_or_counts, tier_is_main, tier_orphan, tier_would_conflict,
+ };
+
+ let is_main = matches!(&self.kind, ItemKind::Worktree(data) if data.is_main);
+
+ // Tier 1: IsMain (immediate if `is_main`, otherwise rule out).
+ match tier_is_main(is_main) {
+ Tier::Fired(s) => return Some(s),
+ Tier::RuledOut => {}
+ Tier::Wait => return None, // unreachable: tier 1 never waits
+ }
+
+ // Tier 2: Orphan.
+ match tier_orphan(self.is_orphan) {
+ Tier::Fired(s) => return Some(s),
+ Tier::RuledOut => {}
+ Tier::Wait => return None,
+ }
+
+ // Tier 3: WouldConflict. For branches, there's no working-tree
+ // conflict probe, so we substitute `Some(None)` (the "task ran
+ // but working tree is clean / N/A" sentinel).
+ let has_working_tree_conflicts = match &self.kind {
+ ItemKind::Worktree(data) => data.has_working_tree_conflicts,
+ ItemKind::Branch => Some(None),
+ };
+ match tier_would_conflict(self.has_merge_tree_conflicts, has_working_tree_conflicts) {
+ Tier::Fired(s) => return Some(s),
+ Tier::RuledOut => {}
+ Tier::Wait => return None,
+ }
+
+ // Tiers 4-6: integration / same-commit-dirty / counts-based. Needs
+ // `counts` and `is_clean`, plus the integration signals fed
+ // through `check_integration_state` (which is short-circuiting and
+ // treats missing integration signals as "no info, fall through").
+ let is_clean = match &self.kind {
+ ItemKind::Worktree(data) => {
+ let diff = data.working_tree_diff.as_ref()?;
+ let status = data.working_tree_status?;
+ Some(diff.is_empty() && !status.untracked)
+ }
+ // Branches have no working tree; trivially clean.
+ ItemKind::Branch => Some(true),
+ };
+ let integration = match &self.kind {
+ ItemKind::Worktree(data) => {
+ self.check_integration_state(data.is_main, default_branch, is_clean?)
}
+ ItemKind::Branch => self.check_integration_state(false, default_branch, true),
+ };
+
+ match tier_integration_or_counts(self.counts, is_clean, integration) {
+ Tier::Fired(s) => Some(s),
+ Tier::RuledOut | Tier::Wait => None,
}
}
+ /// Gate 4: upstream divergence. Resolves once `upstream` is loaded.
+ fn try_gate_upstream_divergence(&self) -> Option<Divergence> {
+ let upstream = self.upstream.as_ref()?;
+ Some(match upstream.active() {
+ Some(active) => Divergence::from_counts_with_remote(active.ahead, active.behind),
+ None => Divergence::None,
+ })
+ }
+
+ /// Gate 5: user marker. Resolves once the `UserMarker` task reports,
+ /// carrying either `Some(marker)` or `None` (no marker configured).
+ fn try_gate_user_marker(&self) -> Option<Option<String>> {
+ self.user_marker.clone()
+ }
+
/// Check if branch content is integrated into the default branch (safe to delete).
///
/// Returns `Some(MainState)` only for truly integrated states:
@@ -760,4 +872,228 @@ mod tests {
"Clean working tree should show as integrated"
);
}
+
+ // ============================================================================
+ // Per-gate refresh_status_symbols tests
+ //
+ // Each test exercises one gate's "waiting for inputs" / "short-circuit
+ // resolved" behavior. These replace the old
+ // `test_compute_status_symbols_waits_for_every_required_field` in
+ // results.rs, which fused all five gates into one "this field gates
+ // the whole function" assertion list.
+ // ============================================================================
+
+ /// Build a worktree `ListItem` pointing at a non-null HEAD, with
+ /// `is_main=false` so tests can exercise the full gate chain without
+ /// hitting the main-worktree short-circuit.
+ fn make_worktree_item() -> ListItem {
+ use crate::commands::list::collect::build_worktree_item;
+ use worktrunk::git::WorktreeInfo;
+ let wt = WorktreeInfo {
+ path: std::path::PathBuf::from("/tmp/wt"),
+ head: "abc123".into(),
+ branch: Some("feat".into()),
+ bare: false,
+ detached: false,
+ locked: None,
+ prunable: None,
+ };
+ build_worktree_item(&wt, false, false, false)
+ }
+
+ // ---- Gate 1: working tree flags (positions 0-2) ----
+
+ #[test]
+ fn gate_working_tree_loading_vs_resolved() {
+ use super::super::super::model::WorkingTreeStatus;
+
+ // Branch items are treated as permanently clean — gate 1 always
+ // resolves to `Some(default)` on first refresh.
+ let mut item = ListItem::new_branch("abc".into(), "feat".into());
+ item.refresh_status_symbols(None);
+ assert_eq!(
+ item.status_symbols.working_tree,
+ Some(WorkingTreeStatus::default())
+ );
+
+ // Worktree items with no `working_tree_status` → gate 1 stays
+ // None (Loading).
+ let mut item = make_worktree_item();
+ item.refresh_status_symbols(None);
+ assert_eq!(item.status_symbols.working_tree, None);
+
+ // Set working_tree_status → gate 1 resolves on next refresh.
+ if let ItemKind::Worktree(ref mut data) = item.kind {
+ data.working_tree_status =
+ Some(WorkingTreeStatus::new(true, false, false, false, false));
+ }
+ item.refresh_status_symbols(None);
+ assert!(item.status_symbols.working_tree.unwrap().staged);
+ }
+
+ // ---- Gate 2: operation state (position 3) ----
+
+ #[test]
+ fn gate_operation_state_short_circuits_on_conflicts() {
+ // `has_conflicts = Some(true)` fires the gate immediately without
+ // waiting for `git_operation`.
+ let mut item = make_worktree_item();
+ if let ItemKind::Worktree(ref mut data) = item.kind {
+ data.has_conflicts = Some(true);
+ // git_operation deliberately left None
+ }
+ item.refresh_status_symbols(None);
+ assert_eq!(
+ item.status_symbols.operation_state,
+ Some(OperationState::Conflicts)
+ );
+ }
+
+ #[test]
+ fn gate_operation_state_waits_for_both_inputs() {
+ // `has_conflicts = Some(false)` but `git_operation = None` →
+ // gate stays Loading (could still become Rebase/Merge).
+ let mut item = make_worktree_item();
+ if let ItemKind::Worktree(ref mut data) = item.kind {
+ data.has_conflicts = Some(false);
+ data.git_operation = None;
+ }
+ item.refresh_status_symbols(None);
+ assert_eq!(item.status_symbols.operation_state, None);
+
+ // Set git_operation → gate resolves.
+ if let ItemKind::Worktree(ref mut data) = item.kind {
+ data.git_operation = Some(ActiveGitOperation::Rebase);
+ }
+ item.refresh_status_symbols(None);
+ assert_eq!(
+ item.status_symbols.operation_state,
+ Some(OperationState::Rebase)
+ );
+ }
+
+ // ---- Gate 3: main state (position 4) ----
+
+ #[test]
+ fn gate_main_state_is_main_short_circuit() {
+ // Construct a main-worktree ListItem directly.
+ use crate::commands::list::collect::build_worktree_item;
+ use worktrunk::git::WorktreeInfo;
+ let wt = WorktreeInfo {
+ path: std::path::PathBuf::from("/tmp/main"),
+ head: "abc123".into(),
+ branch: Some("main".into()),
+ bare: false,
+ detached: false,
+ locked: None,
+ prunable: None,
+ };
+ let mut item = build_worktree_item(&wt, true, false, false);
+ // No other inputs set — tier 1 fires on metadata alone.
+ item.refresh_status_symbols(Some("main"));
+ assert_eq!(item.status_symbols.main_state, Some(MainState::IsMain));
+ }
+
+ #[test]
+ fn gate_main_state_orphan_blocks_lower_tiers() {
+ let mut item = make_worktree_item();
+ item.is_orphan = Some(true);
+ // Other inputs deliberately left None — tier 2 fires without them.
+ item.refresh_status_symbols(None);
+ assert_eq!(item.status_symbols.main_state, Some(MainState::Orphan));
+ }
+
+ #[test]
+ fn gate_main_state_would_conflict_requires_both_conflict_signals() {
+ // `has_merge_tree_conflicts = None` → tier 3 waits even with
+ // `has_working_tree_conflicts` saying "clean."
+ let mut item = make_worktree_item();
+ item.is_orphan = Some(false);
+ item.has_merge_tree_conflicts = None;
+ if let ItemKind::Worktree(ref mut data) = item.kind {
+ data.has_working_tree_conflicts = Some(None); // clean working tree
+ }
+ item.refresh_status_symbols(None);
+ assert_eq!(item.status_symbols.main_state, None);
+
+ // Set the merge-tree probe to "no conflict" → tier 3 rules out,
+ // fall through to lower tiers. But counts is still None, so
+ // tier 4 waits and gate stays None.
+ item.has_merge_tree_conflicts = Some(false);
+ item.refresh_status_symbols(None);
+ assert_eq!(item.status_symbols.main_state, None);
+ }
+
+ #[test]
+ fn gate_main_state_tier4_waits_for_counts_and_clean() {
+ use super::super::super::model::{AheadBehind, WorkingTreeStatus};
+ use worktrunk::git::LineDiff;
+
+ let mut item = make_worktree_item();
+ item.is_orphan = Some(false);
+ item.has_merge_tree_conflicts = Some(false);
+ if let ItemKind::Worktree(ref mut data) = item.kind {
+ data.has_working_tree_conflicts = Some(None);
+ }
+ // counts set but is_clean inputs missing → Wait.
+ item.counts = Some(AheadBehind {
+ ahead: 3,
+ behind: 2,
+ });
+ item.refresh_status_symbols(None);
+ assert_eq!(item.status_symbols.main_state, None);
+
+ // Fill in the is_clean inputs → gate resolves.
+ if let ItemKind::Worktree(ref mut data) = item.kind {
+ data.working_tree_diff = Some(LineDiff::default());
+ data.working_tree_status = Some(WorkingTreeStatus::default());
+ }
+ item.refresh_status_symbols(None);
+ assert_eq!(item.status_symbols.main_state, Some(MainState::Diverged));
+ }
+
+ // ---- Gate 4: upstream divergence (position 5) ----
+
+ #[test]
+ fn gate_upstream_divergence() {
+ use super::super::super::model::UpstreamStatus;
+
+ let mut item = make_worktree_item();
+ // upstream None → Loading.
+ item.refresh_status_symbols(None);
+ assert_eq!(item.status_symbols.upstream_divergence, None);
+
+ // Default UpstreamStatus has remote=None, so active() returns
+ // None → resolves to Divergence::None.
+ item.upstream = Some(UpstreamStatus::default());
+ item.refresh_status_symbols(None);
+ assert_eq!(
+ item.status_symbols.upstream_divergence,
+ Some(Divergence::None)
+ );
+ }
+
+ // ---- Gate 5: user marker (position 6) ----
+
+ #[test]
+ fn gate_user_marker() {
+ // Loading until user_marker is Some(_).
+ let mut item = make_worktree_item();
+ item.refresh_status_symbols(None);
+ assert_eq!(item.status_symbols.user_marker, None);
+
+ // Task ran, no marker configured → resolves to Some(None).
+ item.user_marker = Some(None);
+ item.refresh_status_symbols(None);
+ assert_eq!(item.status_symbols.user_marker, Some(None));
+
+ // Task ran with a marker value → resolves to Some(Some(s)).
+ let mut item = make_worktree_item();
+ item.user_marker = Some(Some("🔥".to_string()));
+ item.refresh_status_symbols(None);
+ assert_eq!(
+ item.status_symbols.user_marker,
+ Some(Some("🔥".to_string()))
+ );
+ }
}
diff --git a/src/commands/list/model/state.rs b/src/commands/list/model/state.rs
index 61b83bfa7..b5a2e82b4 100644
--- a/src/commands/list/model/state.rs
+++ b/src/commands/list/model/state.rs
@@ -213,6 +213,12 @@ impl MainState {
/// - Orphan is a fundamental property (no common ancestor)
/// - Merge conflicts for orphan branches are expected but not actionable normally
/// - Users should understand "this is an orphan branch" rather than "this would conflict"
+ ///
+ /// This function takes every input up front — it's the "all data is
+ /// available" path. For the per-gate resolver that walks tiers with
+ /// partial data, see [`tier_is_main`], [`tier_orphan`],
+ /// [`tier_would_conflict`], [`tier_integration_or_counts`], and the
+ /// [`Tier`] helper below.
pub fn from_integration_and_counts(
is_main: bool,
would_conflict: bool,
@@ -243,6 +249,152 @@ impl MainState {
}
}
+/// Result of attempting to resolve a single tier of the main_state priority
+/// chain with partial data.
+///
+/// The main-state gate (`refresh_status_symbols` gate 3) walks tiers in
+/// priority order. Each tier returns one of:
+///
+/// - [`Tier::Fired`] — this tier's signal is both known and positive; use
+/// the carried value and ignore lower-priority tiers.
+/// - [`Tier::RuledOut`] — this tier's signal is known to be negative; move
+/// on to the next (lower-priority) tier.
+/// - [`Tier::Wait`] — this tier's signal is not yet loaded; we cannot
+/// safely fall through to a lower tier because a later drain tick might
+/// still produce a higher-priority answer. Stop and return `None` from
+/// the gate resolver so the cell renders `⋯`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Tier<T> {
+ /// Tier signal is known and positive — short-circuit with this value.
+ Fired(T),
+ /// Tier signal is known and negative — fall through to the next tier.
+ RuledOut,
+ /// Tier signal not yet loaded — the gate must wait.
+ Wait,
+}
+
+impl<T> Tier<T> {
+ /// Convert to `Option`, treating `Wait` and `RuledOut` both as `None`.
+ /// Callers use this at the bottom of a tier chain when they've run out
+ /// of tiers and need to collapse the result.
+ #[allow(dead_code)] // Used by `refresh_status_symbols` (step 4).
+ pub fn or_none(self) -> Option<T> {
+ match self {
+ Self::Fired(v) => Some(v),
+ Self::RuledOut | Self::Wait => None,
+ }
+ }
+}
+
+/// Tier 1: `IsMain`. Resolves immediately since `is_main` is metadata.
+///
+/// Returns `Fired(IsMain)` for main worktrees, `RuledOut` otherwise.
+#[allow(dead_code)] // Used by `refresh_status_symbols` (step 4).
+pub fn tier_is_main(is_main: bool) -> Tier<MainState> {
+ if is_main {
+ Tier::Fired(MainState::IsMain)
+ } else {
+ Tier::RuledOut
+ }
+}
+
+/// Tier 2: `Orphan`. Requires `is_orphan` to be loaded.
+///
+/// Orphan branches have no common ancestor with the default branch, so
+/// every lower-priority signal (ahead/behind, integration, conflict) is
+/// meaningless for them. Once we know `is_orphan == Some(true)`, the gate
+/// short-circuits without needing anything else.
+#[allow(dead_code)] // Used by `refresh_status_symbols` (step 4).
+pub fn tier_orphan(is_orphan: Option<bool>) -> Tier<MainState> {
+ match is_orphan {
+ Some(true) => Tier::Fired(MainState::Orphan),
+ Some(false) => Tier::RuledOut,
+ None => Tier::Wait,
+ }
+}
+
+/// Tier 3: `WouldConflict`. Requires *both* conflict probes to be loaded.
+///
+/// `has_merge_tree_conflicts` is the committed-HEAD probe (from
+/// `MergeTreeConflicts`). `has_working_tree_conflicts` is the dirty-tree
+/// probe (from `WorkingTreeConflicts`), with a nested Option: outer `None`
+/// = task not run, `Some(None)` = task ran but working tree is clean (no
+/// dirty-tree result, fall back to the HEAD probe), `Some(Some(b))` =
+/// dirty-tree result.
+///
+/// Behavior:
+/// - If either probe reports `true`, fire `WouldConflict` — no need to
+/// wait for the other.
+/// - If the HEAD probe is `None`, wait (we can't rule out a conflict
+/// without it).
+/// - If the HEAD probe is `Some(false)` and the working-tree probe is
+/// `None`, wait — the working-tree result could still flip us to
+/// `WouldConflict`.
+/// - If both report "no conflict" (HEAD probe `Some(false)` and
+/// working-tree probe either `Some(None)` or `Some(Some(false))`), rule
+/// out.
+#[allow(dead_code)] // Used by `refresh_status_symbols` (step 4).
+pub fn tier_would_conflict(
+ has_merge_tree_conflicts: Option<bool>,
+ has_working_tree_conflicts: Option<Option<bool>>,
+) -> Tier<MainState> {
+ // Working-tree probe short-circuit: if it reports a dirty conflict,
+ // fire regardless of the HEAD probe.
+ if let Some(Some(true)) = has_working_tree_conflicts {
+ return Tier::Fired(MainState::WouldConflict);
+ }
+ // HEAD probe short-circuit.
+ match has_merge_tree_conflicts {
+ Some(true) => return Tier::Fired(MainState::WouldConflict),
+ Some(false) => {}
+ None => return Tier::Wait,
+ }
+ // HEAD probe says "no conflict" — still need the working-tree probe
+ // to complete (unless it's already reported a non-dirty result).
+ match has_working_tree_conflicts {
+ Some(_) => Tier::RuledOut,
+ None => Tier::Wait,
+ }
+}
+
+/// Tiers 4–6: integration / same-commit-dirty / counts-based fallback.
+///
+/// Once tiers 1–3 have been ruled out, the gate needs `counts` and
+/// `is_clean`, plus whatever integration signals the caller can provide.
+/// This delegates to [`MainState::from_integration_and_counts`] with
+/// `is_main = false`, `would_conflict = false`, `is_orphan = false`
+/// (callers enforce those invariants via the earlier tiers).
+///
+/// Returns:
+/// - `Fired(state)` if `counts` and `is_clean` are both known. (`state`
+/// may be `MainState::None` when there's nothing to display, which
+/// callers should still treat as a resolved gate.)
+/// - `Wait` if either `counts` or `is_clean` is still loading.
+#[allow(dead_code)] // Used by `refresh_status_symbols` (step 4).
+pub fn tier_integration_or_counts(
+ counts: Option<super::stats::AheadBehind>,
+ is_clean: Option<bool>,
+ integration: Option<MainState>,
+) -> Tier<MainState> {
+ let Some(counts) = counts else {
+ return Tier::Wait;
+ };
+ let Some(is_clean) = is_clean else {
+ return Tier::Wait;
+ };
+ // is_same_commit_dirty requires counts and !is_clean.
+ let is_same_commit_dirty = !is_clean && counts.ahead == 0 && counts.behind == 0;
+ Tier::Fired(MainState::from_integration_and_counts(
+ false, // is_main — tier 1 ruled this out
+ false, // would_conflict — tier 3 ruled this out
+ integration,
+ is_same_commit_dirty,
+ false, // is_orphan — tier 2 ruled this out
+ counts.ahead,
+ counts.behind,
+ ))
+}
+
impl serde::Serialize for MainState {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
@@ -611,6 +763,144 @@ mod tests {
));
}
+ // ============================================================================
+ // MainState Tier Tests (per-gate resolution with partial data)
+ // ============================================================================
+
+ #[test]
+ fn test_tier_is_main() {
+ assert_eq!(tier_is_main(true), Tier::Fired(MainState::IsMain));
+ assert_eq!(tier_is_main(false), Tier::RuledOut);
+ }
+
+ #[test]
+ fn test_tier_orphan() {
+ assert_eq!(tier_orphan(Some(true)), Tier::Fired(MainState::Orphan));
+ assert_eq!(tier_orphan(Some(false)), Tier::RuledOut);
+ assert_eq!(tier_orphan(None), Tier::Wait);
+ }
+
+ #[test]
+ fn test_tier_would_conflict() {
+ // HEAD probe says conflict → fire, even if working-tree probe
+ // hasn't reported.
+ assert_eq!(
+ tier_would_conflict(Some(true), None),
+ Tier::Fired(MainState::WouldConflict)
+ );
+ // Working-tree probe says dirty conflict → fire, even if HEAD
+ // probe hasn't reported.
+ assert_eq!(
+ tier_would_conflict(None, Some(Some(true))),
+ Tier::Fired(MainState::WouldConflict)
+ );
+ // Both probes report "no conflict" (HEAD: Some(false), WT:
+ // Some(None) meaning "working tree is clean, no dirty-tree
+ // result") → rule out.
+ assert_eq!(tier_would_conflict(Some(false), Some(None)), Tier::RuledOut);
+ // HEAD probe says "no conflict" and WT probe reports a clean
+ // dirty-tree result (Some(Some(false))) → rule out.
+ assert_eq!(
+ tier_would_conflict(Some(false), Some(Some(false))),
+ Tier::RuledOut
+ );
+ // HEAD probe hasn't reported → wait (could flip us to conflict).
+ assert_eq!(tier_would_conflict(None, None), Tier::Wait);
+ assert_eq!(tier_would_conflict(None, Some(None)), Tier::Wait);
+ // HEAD probe says "no conflict" but WT probe hasn't reported →
+ // wait (WT could still flip us).
+ assert_eq!(tier_would_conflict(Some(false), None), Tier::Wait);
+ }
+
+ #[test]
+ fn test_tier_integration_or_counts() {
+ use super::super::stats::AheadBehind;
+
+ // counts missing → wait
+ assert_eq!(
+ tier_integration_or_counts(None, Some(true), None),
+ Tier::Wait
+ );
+
+ // is_clean missing → wait
+ assert_eq!(
+ tier_integration_or_counts(
+ Some(AheadBehind {
+ ahead: 0,
+ behind: 0
+ }),
+ None,
+ None
+ ),
+ Tier::Wait
+ );
+
+ // in-sync clean → Fired(None)
+ assert_eq!(
+ tier_integration_or_counts(
+ Some(AheadBehind {
+ ahead: 0,
+ behind: 0
+ }),
+ Some(true),
+ None
+ ),
+ Tier::Fired(MainState::None)
+ );
+
+ // in-sync dirty → SameCommit
+ assert_eq!(
+ tier_integration_or_counts(
+ Some(AheadBehind {
+ ahead: 0,
+ behind: 0
+ }),
+ Some(false),
+ None
+ ),
+ Tier::Fired(MainState::SameCommit)
+ );
+
+ // Ahead only
+ assert_eq!(
+ tier_integration_or_counts(
+ Some(AheadBehind {
+ ahead: 3,
+ behind: 0
+ }),
+ Some(true),
+ None
+ ),
+ Tier::Fired(MainState::Ahead)
+ );
+
+ // Diverged
+ assert_eq!(
+ tier_integration_or_counts(
+ Some(AheadBehind {
+ ahead: 3,
+ behind: 2
+ }),
+ Some(true),
+ None
+ ),
+ Tier::Fired(MainState::Diverged)
+ );
+
+ // Integration state wins over counts
+ assert_eq!(
+ tier_integration_or_counts(
+ Some(AheadBehind {
+ ahead: 5,
+ behind: 0
+ }),
+ Some(true),
+ Some(MainState::Integrated(IntegrationReason::Ancestor)),
+ ),
+ Tier::Fired(MainState::Integrated(IntegrationReason::Ancestor))
+ );
+ }
+
// ============================================================================
// OperationState Tests
// ============================================================================
diff --git a/src/commands/list/model/status_symbols.rs b/src/commands/list/model/status_symbols.rs
index c3a6b484c..45aae1977 100644
--- a/src/commands/list/model/status_symbols.rs
+++ b/src/commands/list/model/status_symbols.rs
@@ -1,7 +1,258 @@
-//! Status symbol types for rendering worktree and branch state.
+//! Status symbol types and per-symbol atomic rendering rules.
//!
-//! These types handle the visual representation of various states in the
-//! status column of `wt list` output.
+//! # Goal
+//!
+//! Each symbol in the Status column is computed and rendered independently.
+//! A symbol only appears once we have the data needed to compute **that
+//! specific symbol**. Symbols whose inputs have not arrived render as a
+//! position-level loading / timeout placeholder, and stay that way if the
+//! drain deadline fires before the data lands.
+//!
+//! The core rule is: **each position is atomic in its own inputs**. The cell
+//! as a whole is never atomic — parts that are ready render; parts that are
+//! not render `⋯`.
+//!
+//! # Positions
+//!
+//! The Status column has seven rendered positions (see [`PositionMask`]).
+//! They render left-to-right and are independently gated:
+//!
+//! | # | Name | Symbols | Answers |
+//! |---|---------------------|----------------------|---------------------------------------|
+//! | 0 | `STAGED` | `+` | Are there staged changes? |
+//! | 1 | `MODIFIED` | `!` | Are there unstaged modifications? |
+//! | 2 | `UNTRACKED` | `?` | Are there untracked files? |
+//! | 3 | `WORKTREE_STATE` | `✘ ⤴ ⤵ ⚑ ⊟ ⊞ /` | Operation / worktree attribute |
+//! | 4 | `MAIN_STATE` | `^ ✗ _ – ⊂ ↕ ↑ ↓` | Relationship to the default branch |
+//! | 5 | `UPSTREAM_DIVERGENCE` | \| ⇅ ⇡ ⇣ | Relationship to the tracked remote |
+//! | 6 | `USER_MARKER` | emoji / text | User-defined annotation |
+//!
+//! Positions 0–2 are three visual slots but **one logical decision** — they
+//! all come from `data.working_tree_status` and resolve together. Each of
+//! positions 3, 4, 5, 6 is an independent logical decision with its own
+//! input set. There are effectively **five independent gates** on the Status
+//! cell.
+//!
+//! # Gate 1: Working tree flags (positions 0–2)
+//!
+//! **Renders:** any combination of `+`, `!`, `?` (plus `»` / `✘` for renamed
+//! / deleted when used).
+//!
+//! **Inputs:** `data.working_tree_status` — produced by the `WorkingTreeDiff`
+//! task, or seeded at spawn time for items whose tasks will not run.
+//!
+//! **Rule:**
+//! - `Some(_)` → render the flags it contains. A clean tree leaves all three
+//! positions blank.
+//! - `None` → all three positions render the position-level `⋯` placeholder.
+//!
+//! Branches and prunable worktrees seed `working_tree_status` to a "no
+//! working tree" sentinel at spawn time, so their positions render blank,
+//! not `⋯`.
+//!
+//! # Gate 2: Worktree state (position 3)
+//!
+//! **Renders:** at most one of `✘ ⤴ ⤵ ⚑ ⊟ ⊞ /`, priority
+//! `✘ > ⤴ > ⤵ > ⚑ > ⊟ > ⊞ > /`. The operation family (`✘⤴⤵`) comes from live
+//! task data; the attribute family (`⚑⊟⊞/`) is metadata, always known.
+//!
+//! **Inputs:** `data.has_conflicts`, `data.git_operation`, plus metadata
+//! (`locked`, `prunable`, `branch_worktree_mismatch`, `ItemKind::Branch`).
+//!
+//! **Rule — short-circuit on priority:** a higher-priority signal, once known
+//! to be positive, resolves the gate immediately without waiting for
+//! lower-priority signals. Formally, render as soon as we can identify which
+//! row of the priority table is the answer:
+//!
+//! 1. `has_conflicts == Some(true)` → `✘`.
+//! 2. `has_conflicts == Some(false)` and `git_operation == Some(Rebase)` → `⤴`.
+//! 3. `has_conflicts == Some(false)` and `git_operation == Some(Merge)` → `⤵`.
+//! 4. `has_conflicts == Some(false)` and `git_operation == Some(None)` and
+//! metadata says mismatched → `⚑`.
+//! 5. …continuing down through `⊟`, `⊞`, `/`, nothing.
+//!
+//! Until both `has_conflicts` and `git_operation` are known, we cannot rule
+//! out `✘/⤴/⤵`, so the position renders `⋯` even if metadata would otherwise
+//! produce `⊟` or `⊞`.
+//!
+//! **Exception — items with no working tree:** branches and prunable
+//! worktrees have seeded sentinels (`has_conflicts = Some(false)`,
+//! `git_operation = Some(None)`) at spawn time, so the operation family is
+//! ruled out immediately and metadata wins.
+//!
+//! # Gate 3: Main state (position 4)
+//!
+//! **Renders:** at most one of `^ ✗ _ – ⊂ ↕ ↑ ↓`. Priority:
+//! `IsMain > Orphan > WouldConflict > Empty(_) > SameCommitDirty(–) >
+//! Integrated(⊂) > Diverged(↕) > Ahead(↑) > Behind(↓) > None`.
+//!
+//! **Inputs:**
+//! - `is_main` (metadata)
+//! - `is_orphan` (from `AheadBehind`)
+//! - `has_merge_tree_conflicts` (from `MergeTreeConflicts`)
+//! - `has_working_tree_conflicts` (from `WorkingTreeConflicts`)
+//! - Integration signals: `is_ancestor`, `committed_trees_match`,
+//! `has_file_changes`, `would_merge_add`, `is_patch_id_match`
+//! - `counts` (from `AheadBehind`)
+//! - `working_tree_diff` + `working_tree_status` (used for `is_clean`, which
+//! distinguishes `Empty(_)` from `SameCommitDirty(–)`)
+//!
+//! **Rule — short-circuit on priority (same pattern as gate 2):** render as
+//! soon as the priority-winning signal can be identified.
+//!
+//! 1. `is_main == true` (metadata) → `^`. Always immediate for the main
+//! worktree, regardless of any other field.
+//! 2. `is_orphan == Some(true)` → orphan display.
+//! 3. `has_merge_tree_conflicts == Some(true)` or
+//! `has_working_tree_conflicts == Some(Some(true))` → `✗`.
+//! 4. Distinguish Empty / SameCommitDirty / Integrated — requires `counts`,
+//! `is_clean` (from `working_tree_diff` + `working_tree_status` for
+//! worktrees; trivially clean for branches), and the integration signals.
+//! Render as soon as all signals needed to pick a row have landed.
+//! 5. Otherwise fall through to `↕/↑/↓/None` from `counts`.
+//!
+//! **Exception — unborn items (`HEAD == NULL_OID`):** all commit-dependent
+//! tasks are skipped at spawn time. Their fields are seeded with "no commits"
+//! sentinels (`counts = (0, 0)`, `is_orphan = false`, integration signals
+//! conservatively false, `has_merge_tree_conflicts = false`). With those
+//! seeded, gate 3 resolves to `None` for unborn non-main items and the row
+//! still renders.
+//!
+//! **Exception — stale branches and `--skip-tasks`:** fields for
+//! deliberately-skipped tasks are seeded at spawn time with conservative
+//! defaults. Stale branches can render a less-specific main-state symbol
+//! than fresh ones (e.g., `↕` instead of `⊂`).
+//!
+//! TODO: review whether the conservative-seed strategy for stale branches is
+//! the right trade-off. An alternative is to leave skipped-task fields as
+//! `None` so stale-branch rows show `⋯` in the affected positions — more
+//! honest, but noisier in the picker.
+//!
+//! # Gate 4: Upstream divergence (position 5)
+//!
+//! **Renders:** at most one of `| ⇅ ⇡ ⇣`.
+//!
+//! **Inputs:** `upstream` (from `Upstream`).
+//!
+//! **Rule:**
+//! - `Some(UpstreamStatus::None)` → nothing (no upstream configured).
+//! - `Some(active)` → render the divergence glyph from `active.ahead/behind`.
+//! - `None` → `⋯`.
+//!
+//! **Exception — unborn:** `Upstream` is a `COMMIT_TASK` and is skipped for
+//! unborn items. `upstream` is seeded to "no upstream" at spawn time so
+//! gate 4 renders blank for unborn rows, not `⋯`.
+//!
+//! # Gate 5: User marker (position 6)
+//!
+//! **Renders:** whatever the user's marker lookup produced.
+//!
+//! **Inputs:** `user_marker` (from `UserMarker`).
+//!
+//! **Rule:**
+//! - `Some(Some(s))` → render `s`.
+//! - `Some(None)` → nothing (no marker for this item).
+//! - `None` → `⋯`.
+//!
+//! # Rendering `⋯` at the position level
+//!
+//! `⋯` is a position-level placeholder emitted by the render function for
+//! each gate that hasn't resolved yet. It takes the full allocated width of
+//! its position so table alignment is preserved across rows.
+//!
+//! An in-progress cell might look like:
+//!
+//! ```text
+//! +! ⋯ ↕ | ⋯ ← staged + modified known; worktree state + user marker still loading
+//! ⋯⋯⋯ ⋯ ^ | ⋯ ← main worktree known from metadata; other gates still loading
+//! ^ | 💬 ← everything resolved: main worktree, in sync, user marker
+//! ```
+//!
+//! TODO: the current glyph is a dim `⋯` rendered at the full position width.
+//! Consider a lighter placeholder (e.g., a dim middle dot `·`) to reduce
+//! visual noise in busy tables. Revisit once the gated rendering is in place
+//! and we can see it end-to-end.
+//!
+//! # Timeout behavior
+//!
+//! When the drain deadline fires (`wt switch` picker budget,
+//! `[list].timeout-ms`):
+//!
+//! 1. Each position's last-known state is displayed: resolved positions show
+//! their symbol; unresolved positions show `⋯`.
+//! 2. The diagnostic footer already lists which tasks did not finish per
+//! item — this continues unchanged and gives the user the mapping from
+//! "`⋯` in position X" back to "`TaskKind::Foo` timed out."
+//! 3. JSON output omits fields that correspond to unresolved gates
+//! (`working_tree`, `main_state`, `operation_state`, `upstream_divergence`,
+//! etc.) so machine consumers can distinguish "loading / timeout" from
+//! "loaded with no symbol."
+//!
+//! # Error handling
+//!
+//! A task that errors counts as "result received, carrying no information."
+//! The affected field remains `None` and its gate renders `⋯`. There is **no
+//! conservative-defaults fallback** for errored status-feeder tasks — a
+//! failed `WorkingTreeDiff` shows `⋯` in positions 0–2 and 3, not a
+//! fabricated clean state. The error itself is still captured and shown in
+//! the post-render diagnostic section.
+//!
+//! # Data model
+//!
+//! Each gate's output is an `Option` inside [`StatusSymbols`]. `None` means
+//! loading / unresolved; `Some(default)` means resolved with nothing to
+//! display; `Some(value)` means resolved with a symbol.
+//!
+//! ```text
+//! pub struct StatusSymbols {
+//! working_tree: Option<WorkingTreeStatus>, // positions 0–2 (one decision)
+//! worktree_state: Option<ResolvedWorktreeState>, // position 3
+//! main_state: Option<MainState>, // position 4
+//! upstream_divergence: Option<Divergence>, // position 5
+//! user_marker: Option<Option<String>>, // position 6
+//! }
+//! ```
+//!
+//! `item.status_symbols` is always `Some(StatusSymbols::default())` after the
+//! skeleton render — every gate starts as `None` → `⋯`. Per-gate resolution
+//! populates individual fields as task results arrive.
+//!
+//! `refresh_status_symbols` (replacing the current "all or nothing"
+//! `compute_status_symbols`) is called after every drain tick: it tries each
+//! gate independently and sets any fields whose inputs are now ready. It is
+//! idempotent — a gate, once resolved, is never un-resolved.
+//!
+//! TODO: replace `Option<T>` on status-feeding fields with a `TaskInput<T>`
+//! enum that distinguishes `Pending` / `Skipped` / `Ready(T)`. Currently the
+//! "task won't run" state is encoded by seeding a conservative `Some(value)`
+//! via `seed_skipped_task_defaults`, which conflates "measured and got this
+//! answer" with "fabricated a safe default." A typed enum would:
+//!
+//! - Eliminate the fabricated-value class of bugs (e.g., seeding a clean
+//! `WorkingTreeDiff` for a dirty worktree).
+//! - Make JSON output trivially correct (`Ready(v)` emits, others don't).
+//! - Let each gate explicitly decide what `Skipped` means for its tier
+//! logic, instead of relying on a convention about which sentinel value
+//! is "safe."
+//! - Collapse the `Option<Option<T>>` hacks on `has_working_tree_conflicts`
+//! and `user_marker` into `TaskInput<Option<T>>`.
+//! - Subsume the `SkipReason` concept — the field itself carries the state.
+//!
+//! Natural inflection point: when caching lands, cached values become a
+//! fourth source (`Cached(T)`) that needs the same "real vs fabricated"
+//! distinction. The enum refactor would pay for itself at that point.
+//! Estimated scope: ~15 fields × all read sites, ~300–500 lines mechanical.
+//!
+//! # Non-goals
+//!
+//! - **Animated `⋯`.** Out of scope.
+//! - **Partial rendering within a gate.** Gate 3 does not render `⊟` just
+//! because prunable metadata says so — it waits until the operation family
+//! can be ruled out. Atomicity *within* a gate is preserved; only *between*
+//! gates are decisions independent.
+//! - **Retrying timed-out or errored tasks.** Separate concern.
+//! - **Tuning picker budgets or task skip lists.** This spec only defines
+//! what happens when data does or does not arrive in time.
use super::state::{Divergence, MainState, OperationState, WorktreeState};
@@ -55,7 +306,7 @@ impl PositionMask {
/// Working tree changes as structured booleans
///
/// This is the canonical internal representation. Display strings are derived from this.
-#[derive(Debug, Clone, Copy, Default, serde::Serialize)]
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize)]
pub struct WorkingTreeStatus {
pub staged: bool,
pub modified: bool,
@@ -154,61 +405,86 @@ impl WorkingTreeStatus {
/// - Working tree symbols (+!?): Can have multiple types of changes
#[derive(Debug, Clone, Default)]
pub struct StatusSymbols {
- /// Main branch relationship state (single position, horizontal arrows)
- /// Priority: IsMain (^) > WouldConflict (✗) > Empty (_) > SameCommit (–) > Integrated (⊂) > Diverged (↕) > Ahead (↑) > Behind (↓)
- pub(crate) main_state: MainState,
-
- /// Worktree operation and location state (single position)
- /// Operations (✘⤴⤵) take priority over location states (/⚑⊟⊞)
- pub(crate) operation_state: OperationState,
-
- /// Worktree location state: / for branches, ⚑⊟⊞ for worktrees
- pub(crate) worktree_state: WorktreeState,
-
- /// Remote/upstream divergence state (mutually exclusive)
- pub(crate) upstream_divergence: Divergence,
-
- /// Working tree changes (NOT mutually exclusive, can have multiple)
- pub(crate) working_tree: WorkingTreeStatus,
-
- /// User-defined status annotation (custom labels, e.g., 💬, 🤖)
- pub(crate) user_marker: Option<String>,
+ /// Gate 3 output (position 4). `None` = loading; `Some(MainState::None)`
+ /// = resolved to nothing. Priority: IsMain (^) > Orphan > WouldConflict
+ /// (✗) > Empty (_) > SameCommit (–) > Integrated (⊂) > Diverged (↕) >
+ /// Ahead (↑) > Behind (↓).
+ pub(crate) main_state: Option<MainState>,
+
+ /// Gate 2 output — operation family (position 3). `None` = loading (we
+ /// can't rule out `✘⤴⤵`); `Some(OperationState::None)` = resolved to
+ /// nothing (fall through to `worktree_state`).
+ pub(crate) operation_state: Option<OperationState>,
+
+ /// Gate 2 output — metadata family (position 3). `None` = not yet
+ /// inspected; `Some(WorktreeState::None)` = normal worktree, no
+ /// location/attribute to display. Populated synchronously from
+ /// `WorktreeData` metadata at refresh entry, so in practice this is
+ /// `Some` whenever `refresh_status_symbols` has been called at least
+ /// once.
+ pub(crate) worktree_state: Option<WorktreeState>,
+
+ /// Gate 4 output (position 5). `None` = loading; `Some(Divergence::None)`
+ /// = resolved to nothing (in sync or no upstream).
+ pub(crate) upstream_divergence: Option<Divergence>,
+
+ /// Gate 1 output (positions 0-2). `None` = loading; `Some(default)` =
+ /// resolved clean; `Some(dirty)` = one or more flags set.
+ pub(crate) working_tree: Option<WorkingTreeStatus>,
+
+ /// Gate 5 output (position 6). Outer `None` = loading; `Some(None)` =
+ /// resolved, no marker configured; `Some(Some(s))` = marker `s`.
+ pub(crate) user_marker: Option<Option<String>>,
}
impl StatusSymbols {
- /// Render symbols with selective alignment based on position mask
+ /// Render symbols with selective alignment based on position mask.
///
- /// Only includes positions present in the mask. This ensures vertical
- /// scannability - each symbol type appears at the same column position
- /// across all rows, while minimizing wasted space.
+ /// Each position renders according to its [`SlotState`]:
+ /// - `Loading` → `placeholder` padded to the slot width (dimmed).
+ /// Normal rows pass `⋯`; `render_list_item_stale` passes `·`.
+ /// - `Empty` → whitespace padded to the slot width.
+ /// - `Visible(s)` → styled content padded to the slot width.
///
- /// See [`StatusSymbols`] struct doc for symbol categories.
- pub fn render_with_mask(&self, mask: &PositionMask) -> String {
+ /// CRITICAL: Always use [`PositionMask::FULL`] for consistent spacing
+ /// between progressive and final rendering. The mask provides the
+ /// maximum width needed for each position across all rows.
+ ///
+ /// TODO: the `⋯` / `·` glyphs are intentional for now. Consider a
+ /// lighter placeholder (e.g. dim middle dot in all slots) once the
+ /// per-symbol rendering is in place and we can evaluate the visual
+ /// density end-to-end.
+ pub fn render_with_mask(&self, mask: &PositionMask, placeholder: &str) -> String {
+ use anstyle::Style;
use worktrunk::styling::StyledLine;
let mut result = String::with_capacity(64);
- if self.is_empty() {
- return result;
- }
-
- // Grid-based rendering: each position gets a fixed width for vertical alignment.
- // CRITICAL: Always use PositionMask::FULL for consistent spacing between progressive and final rendering.
- // The mask provides the maximum width needed for each position across all rows.
- // Accept wider Status column with whitespace as tradeoff for perfect alignment.
- for (pos, styled_content, has_data) in self.styled_symbols() {
+ for (pos, slot) in self.styled_symbols() {
let allocated_width = mask.width(pos);
- if has_data {
- // Use StyledLine to handle width calculation (strips ANSI codes automatically)
- let mut segment = StyledLine::new();
- segment.push_raw(styled_content);
- segment.pad_to(allocated_width);
- result.push_str(&segment.render());
- } else {
- // Fill empty position with spaces for alignment
- for _ in 0..allocated_width {
- result.push(' ');
+ match slot {
+ SlotState::Visible(content) => {
+ let mut segment = StyledLine::new();
+ segment.push_raw(content);
+ segment.pad_to(allocated_width);
+ result.push_str(&segment.render());
+ }
+ SlotState::Loading => {
+ // Emit the placeholder glyph (dimmed) padded to the
+ // slot's allocated width. Unlike `Empty`, this
+ // represents "gate has not resolved" — the user
+ // should see a visible marker, not blank space.
+ let mut segment = StyledLine::new();
+ segment.push_styled(placeholder.to_string(), Style::new().dimmed());
+ segment.pad_to(allocated_width);
+ result.push_str(&segment.render());
+ }
+ SlotState::Empty => {
+ // Fill with spaces for alignment.
+ for _ in 0..allocated_width {
+ result.push(' ');
+ }
}
}
}
@@ -216,14 +492,30 @@ impl StatusSymbols {
result
}
- /// Check if symbols are empty
+ /// True iff every gate is either unresolved (`None`) or resolved to a
+ /// "nothing to display" variant. Used by the in-file tests as a
+ /// sanity check for the `Default` / `None`-variant semantics of the
+ /// gate outputs. Non-test code no longer needs this predicate — the
+ /// renderer emits per-position placeholders rather than branching
+ /// on a cell-level empty check.
+ #[cfg(test)]
pub fn is_empty(&self) -> bool {
- self.main_state == MainState::None
- && self.operation_state == OperationState::None
- && self.worktree_state == WorktreeState::None
- && self.upstream_divergence == Divergence::None
- && !self.working_tree.is_dirty()
- && self.user_marker.is_none()
+ let main_empty = self.main_state.is_none_or(|s| s == MainState::None);
+ let op_empty = self
+ .operation_state
+ .is_none_or(|s| s == OperationState::None);
+ let wt_state_empty = self.worktree_state.is_none_or(|s| s == WorktreeState::None);
+ let upstream_empty = self
+ .upstream_divergence
+ .is_none_or(|s| s == Divergence::None);
+ let working_tree_empty = self.working_tree.is_none_or(|wt| !wt.is_dirty());
+ let user_marker_empty = self.user_marker.as_ref().is_none_or(|m| m.is_none());
+ main_empty
+ && op_empty
+ && wt_state_empty
+ && upstream_empty
+ && working_tree_empty
+ && user_marker_empty
}
/// Render status symbols in compact form for statusline (no grid alignment).
@@ -232,91 +524,136 @@ impl StatusSymbols {
pub fn format_compact(&self) -> String {
self.styled_symbols()
.into_iter()
- .filter_map(|(_, styled, has_data)| has_data.then_some(styled))
+ .filter_map(|(_, slot)| match slot {
+ SlotState::Visible(s) => Some(s),
+ // Loading and Empty contribute nothing to the compact form —
+ // the statusline has no column alignment, so unresolved gates
+ // are just omitted.
+ SlotState::Loading | SlotState::Empty => None,
+ })
.collect()
}
/// Build styled symbols array with position indices.
///
- /// Returns: `[(position_mask, styled_string, has_data); 7]`
+ /// Returns one [`SlotState`] per position. The renderer uses this to
+ /// emit three kinds of cell content: `Loading` slots are rendered as the
+ /// position-level placeholder (`⋯` / `·`), `Empty` slots as allocated
+ /// whitespace, and `Visible` slots as styled symbols.
///
- /// Order: working_tree (+!?) → main_state → upstream_divergence → worktree_state → user_marker
+ /// Order: working_tree (0-2) → worktree state (3) → main state (4) →
+ /// upstream divergence (5) → user marker (6).
///
/// Styling follows semantic meaning:
/// - Cyan: Working tree changes (activity indicator)
/// - Red: Conflicts (blocking problems)
/// - Yellow: Git operations, would_conflict, locked/prunable (states needing attention)
/// - Dimmed: Main state symbols, divergence arrows, branch indicator (informational)
- pub(crate) fn styled_symbols(&self) -> [(usize, String, bool); 7] {
+ pub(crate) fn styled_symbols(&self) -> [(usize, SlotState); 7] {
use color_print::cformat;
- // Working tree symbols split into 3 fixed columns for vertical alignment
- let style_working = |has: bool, sym: char| -> (String, bool) {
- if has {
- (cformat!("<cyan>{sym}</>"), true)
- } else {
- (String::new(), false)
+ // Gate 1 — working tree flags (positions 0-2). Loading together.
+ let (staged, modified, untracked) = match self.working_tree {
+ Some(wt) => {
+ let flag = |has: bool, sym: char| -> SlotState {
+ if has {
+ SlotState::Visible(cformat!("<cyan>{sym}</>"))
+ } else {
+ SlotState::Empty
+ }
+ };
+ (
+ flag(wt.staged, '+'),
+ flag(wt.modified, '!'),
+ flag(wt.untracked, '?'),
+ )
}
+ None => (SlotState::Loading, SlotState::Loading, SlotState::Loading),
};
- let (staged_str, has_staged) = style_working(self.working_tree.staged, '+');
- let (modified_str, has_modified) = style_working(self.working_tree.modified, '!');
- let (untracked_str, has_untracked) = style_working(self.working_tree.untracked, '?');
-
- // Main state (merged column: ^✗_⊂↕↑↓)
- let (main_state_str, has_main_state) = self
- .main_state
- .styled()
- .map_or((String::new(), false), |s| (s, true));
-
- // Upstream divergence (|⇅⇡⇣)
- let (upstream_divergence_str, has_upstream_divergence) = self
- .upstream_divergence
- .styled()
- .map_or((String::new(), false), |s| (s, true));
-
- // Worktree state: operations (✘⤴⤵) take priority over location (/⚑⊟⊞)
- let (worktree_str, has_worktree) = if self.operation_state != OperationState::None {
- // Operation state takes priority
- (self.operation_state.styled().unwrap_or_default(), true)
- } else {
- // Fall back to location state
- match self.worktree_state {
- WorktreeState::None => (String::new(), false),
- // Branch indicator (/) is informational (dimmed)
- WorktreeState::Branch => (cformat!("<dim>{}</>", self.worktree_state), true),
- // Branch-worktree mismatch (⚑) is a stronger warning (red)
- WorktreeState::BranchWorktreeMismatch => {
- (cformat!("<red>{}</>", self.worktree_state), true)
- }
- // Other worktree attrs (⊟⊞) are warnings (yellow)
- _ => (cformat!("<yellow>{}</>", self.worktree_state), true),
+
+ // Gate 3 — main state (position 4).
+ let main_state_slot = match self.main_state {
+ Some(ms) => match ms.styled() {
+ Some(s) => SlotState::Visible(s),
+ None => SlotState::Empty,
+ },
+ None => SlotState::Loading,
+ };
+
+ // Gate 4 — upstream divergence (position 5).
+ let upstream_slot = match self.upstream_divergence {
+ Some(d) => match d.styled() {
+ Some(s) => SlotState::Visible(s),
+ None => SlotState::Empty,
+ },
+ None => SlotState::Loading,
+ };
+
+ // Gate 2 — worktree state (position 3). Operation family (`✘⤴⤵`)
+ // takes priority over metadata family (`⚑⊟⊞/`). The gate is
+ // `Loading` iff `operation_state` is still `None` — even when
+ // `worktree_state` metadata would yield `⊟`, we cannot safely show
+ // it without ruling out a pending operation signal. Once
+ // `operation_state == Some(None)`, fall through to `worktree_state`
+ // metadata (which `refresh_status_symbols` fills synchronously, so
+ // it's always `Some` by the time `operation_state` resolves).
+ let worktree_slot = match self.operation_state {
+ None => SlotState::Loading,
+ Some(op) if op != OperationState::None => {
+ SlotState::Visible(op.styled().unwrap_or_default())
}
+ Some(_) => match self.worktree_state {
+ None | Some(WorktreeState::None) => SlotState::Empty,
+ Some(WorktreeState::Branch) => {
+ SlotState::Visible(cformat!("<dim>{}</>", WorktreeState::Branch))
+ }
+ Some(WorktreeState::BranchWorktreeMismatch) => SlotState::Visible(cformat!(
+ "<red>{}</>",
+ WorktreeState::BranchWorktreeMismatch
+ )),
+ Some(other) => SlotState::Visible(cformat!("<yellow>{}</>", other)),
+ },
};
- let user_marker_str = self.user_marker.as_deref().unwrap_or("").to_string();
+ // Gate 5 — user marker (position 6).
+ let user_marker_slot = match &self.user_marker {
+ None => SlotState::Loading,
+ Some(None) => SlotState::Empty,
+ Some(Some(s)) => SlotState::Visible(s.clone()),
+ };
// CRITICAL: Display order must match position indices for correct rendering.
// Order: Working tree (0-2) → Worktree (3) → Main (4) → Remote (5) → User (6)
[
- (PositionMask::STAGED, staged_str, has_staged),
- (PositionMask::MODIFIED, modified_str, has_modified),
- (PositionMask::UNTRACKED, untracked_str, has_untracked),
- (PositionMask::WORKTREE_STATE, worktree_str, has_worktree),
- (PositionMask::MAIN_STATE, main_state_str, has_main_state),
- (
- PositionMask::UPSTREAM_DIVERGENCE,
- upstream_divergence_str,
- has_upstream_divergence,
- ),
- (
- PositionMask::USER_MARKER,
- user_marker_str,
- self.user_marker.is_some(),
- ),
+ (PositionMask::STAGED, staged),
+ (PositionMask::MODIFIED, modified),
+ (PositionMask::UNTRACKED, untracked),
+ (PositionMask::WORKTREE_STATE, worktree_slot),
+ (PositionMask::MAIN_STATE, main_state_slot),
+ (PositionMask::UPSTREAM_DIVERGENCE, upstream_slot),
+ (PositionMask::USER_MARKER, user_marker_slot),
]
}
}
+/// State of a single Status-column slot when rendering.
+///
+/// Returned by [`StatusSymbols::styled_symbols`] so the renderer can decide,
+/// per position, whether to emit a position-level placeholder (`Loading`),
+/// blank whitespace (`Empty`), or the styled content (`Visible`).
+#[derive(Debug, Clone)]
+pub(crate) enum SlotState {
+ /// Gate has not resolved — emit the placeholder glyph padded to the
+ /// slot's allocated width.
+ Loading,
+ /// Gate resolved to "nothing to display" — emit whitespace padded to
+ /// the slot's allocated width.
+ Empty,
+ /// Gate resolved with content — emit the styled string (padded by the
+ /// caller to the slot's allocated width).
+ Visible(String),
+}
+
#[cfg(test)]
mod tests {
use insta::assert_snapshot;
@@ -387,40 +724,53 @@ mod tests {
assert!(symbols.is_empty());
let symbols = StatusSymbols {
- main_state: MainState::Ahead,
+ main_state: Some(MainState::Ahead),
..Default::default()
};
assert!(!symbols.is_empty());
let symbols = StatusSymbols {
- operation_state: OperationState::Rebase,
+ operation_state: Some(OperationState::Rebase),
..Default::default()
};
assert!(!symbols.is_empty());
let symbols = StatusSymbols {
- worktree_state: WorktreeState::Locked,
+ worktree_state: Some(WorktreeState::Locked),
..Default::default()
};
assert!(!symbols.is_empty());
let symbols = StatusSymbols {
- upstream_divergence: Divergence::Ahead,
+ upstream_divergence: Some(Divergence::Ahead),
..Default::default()
};
assert!(!symbols.is_empty());
let symbols = StatusSymbols {
- working_tree: WorkingTreeStatus::new(true, false, false, false, false),
+ working_tree: Some(WorkingTreeStatus::new(true, false, false, false, false)),
..Default::default()
};
assert!(!symbols.is_empty());
let symbols = StatusSymbols {
- user_marker: Some("🔥".to_string()),
+ user_marker: Some(Some("🔥".to_string())),
..Default::default()
};
assert!(!symbols.is_empty());
+
+ // Gates resolved to the "None" variant are still is_empty == true
+ // (resolved, but nothing to show). This matches the pre-step-2
+ // behavior for a cleanly-computed row that has no visible symbols.
+ let symbols = StatusSymbols {
+ main_state: Some(MainState::None),
+ operation_state: Some(OperationState::None),
+ worktree_state: Some(WorktreeState::None),
+ upstream_divergence: Some(Divergence::None),
+ working_tree: Some(WorkingTreeStatus::default()),
+ user_marker: Some(None),
+ };
+ assert!(symbols.is_empty());
}
#[test]
@@ -431,15 +781,15 @@ mod tests {
// Single symbol
let symbols = StatusSymbols {
- main_state: MainState::Ahead,
+ main_state: Some(MainState::Ahead),
..Default::default()
};
assert_snapshot!(symbols.format_compact(), @"↑");
// Multiple symbols
let symbols = StatusSymbols {
- working_tree: WorkingTreeStatus::new(true, true, false, false, false),
- main_state: MainState::Ahead,
+ working_tree: Some(WorkingTreeStatus::new(true, true, false, false, false)),
+ main_state: Some(MainState::Ahead),
..Default::default()
};
assert_snapshot!(symbols.format_compact(), @"+!↑");
@@ -448,11 +798,11 @@ mod tests {
#[test]
fn test_status_symbols_render_with_mask() {
let symbols = StatusSymbols {
- main_state: MainState::Ahead,
+ main_state: Some(MainState::Ahead),
..Default::default()
};
- let rendered = symbols.render_with_mask(&PositionMask::FULL);
- assert_snapshot!(rendered, @" ↑");
+ let rendered = symbols.render_with_mask(&PositionMask::FULL, "⋯");
+ assert_snapshot!(rendered, @"⋯⋯⋯⋯↑⋯⋯");
}
#[test]
diff --git a/src/commands/list/render.rs b/src/commands/list/render.rs
index 7ad03ae52..ba9fb470e 100644
--- a/src/commands/list/render.rs
+++ b/src/commands/list/render.rs
@@ -390,11 +390,17 @@ impl ColumnLayout {
self.render_text_cell(text, text_style)
}
ColumnKind::Status => {
- let Some(ref status_symbols) = item.status_symbols else {
- return self.placeholder_cell(placeholder);
- };
+ // `render_with_mask` emits the placeholder glyph per
+ // position for unresolved gates, so a row whose Status
+ // cell is partially loaded renders e.g. `+! ⋯ ↕ | ⋯`
+ // rather than a cell-level `⋯`. The `placeholder` arg
+ // comes from `render_list_item_line` (`⋯`) or
+ // `render_list_item_stale` (`·`).
let mut cell = StyledLine::new();
- cell.push_raw(status_symbols.render_with_mask(status_mask));
+ cell.push_raw(
+ item.status_symbols
+ .render_with_mask(status_mask, placeholder),
+ );
let mut cell = cell.truncate_to_width(self.width);
cell.pad_to(self.width);
cell
@@ -1299,25 +1305,27 @@ mod tests {
use super::super::model::{ListItem, PositionMask};
use std::path::PathBuf;
- // Minimal layout with just a Status column
+ // Layout with a Summary column — it emits the placeholder via
+ // `placeholder_cell` when `item.summary` is `None`. The Status
+ // column's cell-level placeholder was dropped in step 1 of the
+ // per-symbol rendering refactor; step 5 reinstates per-position
+ // placeholders for unresolved status gates.
let layout = LayoutConfig {
columns: vec![ColumnLayout {
- kind: ColumnKind::Status,
- header: "Status",
+ kind: ColumnKind::Summary,
+ header: "Summary",
start: 0,
width: 10,
format: ColumnFormat::Text,
}],
main_worktree_path: PathBuf::from("/tmp"),
max_message_len: 0,
- max_summary_len: 0,
+ max_summary_len: 10,
hidden_column_count: 0,
status_position_mask: PositionMask::FULL,
};
- // Item with no status_symbols (simulates budget timeout)
let item = ListItem::new_branch("abc123".into(), "feat".into());
- assert!(item.status_symbols.is_none());
// render_list_item_line uses ⋯
let line = layout.render_list_item_line(&item);
diff --git a/src/commands/list/snapshots/wt__commands__list__layout__tests__snapshot_path_yields_to_summary.snap b/src/commands/list/snapshots/wt__commands__list__layout__tests__snapshot_path_yields_to_summary.snap
index 5ec2f7d7b..701f7fc9e 100644
--- a/src/commands/list/snapshots/wt__commands__list__layout__tests__snapshot_path_yields_to_summary.snap
+++ b/src/commands/list/snapshots/wt__commands__list__layout__tests__snapshot_path_yields_to_summary.snap
@@ -3,7 +3,7 @@ source: src/commands/list/layout.rs
expression: table
---
Branch Status HEAD± main↕ main…± Summary Remote⇅ CI Commit Age Message
-@ main | a620bcfe 1y Some comm…
-+ hourly-maintenance ↑2 ⋯ ⋯ a620bcfe 1y Some comm…
-+ lab-continue ↑1 ↓2 +28 -1 Add extend and block insert in Markdown parser | a620bcfe 1y Some comm…
-+ dry-run-pager ↑3 ↓1 ⋯ | a620bcfe 1y Some comm…
+@ main ⋯⋯⋯⋯⋯⋯⋯ | a620bcfe 1y Some comm…
++ hourly-maintenance ⋯⋯⋯⋯⋯⋯⋯ ↑2 ⋯ ⋯ a620bcfe 1y Some comm…
++ lab-continue ⋯⋯⋯⋯⋯⋯⋯ ↑1 ↓2 +28 -1 Add extend and block insert in Markdown parser | a620bcfe 1y Some comm…
++ dry-run-pager ⋯⋯⋯⋯⋯⋯⋯ ↑3 ↓1 ⋯ | a620bcfe 1y Some comm…
diff --git a/tests/snapshots/integration__integration_tests__list__list_empty_repo.snap b/tests/snapshots/integration__integration_tests__list__list_empty_repo.snap
index 6b3051afa..119f16844 100644
--- a/tests/snapshots/integration__integration_tests__list__list_empty_repo.snap
+++ b/tests/snapshots/integration__integration_tests__list__list_empty_repo.snap
@@ -40,7 +40,7 @@ success: true
exit_code: 0
----- stdout -----
Branch Status HEAD± main↕ Remote⇅ Path Commit Age Message
-@ main ^ ⋯ . ⋯ ⋯
+@ main ^ . ⋯ ⋯
○ Showing 1 worktree
diff --git a/tests/snapshots/integration__integration_tests__list__list_shows_warning_on_git_error.snap b/tests/snapshots/integration__integration_tests__list__list_shows_warning_on_git_error.snap
index 1bbc64eec..de61ec844 100644
--- a/tests/snapshots/integration__integration_tests__list__list_shows_warning_on_git_error.snap
+++ b/tests/snapshots/integration__integration_tests__list__list_shows_warning_on_git_error.snap
@@ -46,7 +46,7 @@ exit_code: 0
+ feature-a ↑ ↑1 ../repo.feature-a 1b87d473 16h Add feature-a file
+ feature-b ↑ ↑1 ../repo.feature-b f62940fc 16h Add feature-b file
+ feature-c ↑ ↑1 ../repo.feature-c 345c7c93 16h Add feature-c file
-+ feature ⋯ ⋯ ../repo.feature ⋯ ⋯
++ feature ⋯⋯⋯⋯ ⋯ ⋯ ../repo.feature ⋯ ⋯
○ Showing 5 worktrees, 3 ahead. 2 tasks failed