Skip to content

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

Key picker previews by canonical row identity (#3926)

Maximilian Roos086305741f1b
diff --git a/src/commands/list/ci_status/mod.rs b/src/commands/list/ci_status/mod.rs
index c0eb869b9..22c112baa 100644
--- a/src/commands/list/ci_status/mod.rs
+++ b/src/commands/list/ci_status/mod.rs
@@ -18,7 +18,7 @@ use super::layout::LinkStyle;
use anstyle::{AnsiColor, Color, Style};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize, de::DeserializeOwned};
-use worktrunk::git::{BranchRef, Repository, parse_owner_repo};
+use worktrunk::git::{BranchRef, RefType, Repository, parse_owner_repo};
use worktrunk::shell_exec::Cmd;
use worktrunk::utils::epoch_now;
@@ -307,25 +307,43 @@ pub enum CiSource {
Branch,
}
-/// A PR/MR reference: number plus the forge's display sigil.
+/// A PR/MR reference: number plus its resolved reference type.
///
/// Displays as `#3035` (GitHub, Gitea, Azure DevOps) or `!3035` (GitLab).
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct PrRef {
pub number: u64,
- /// Display sigil: `#` (GitHub, Gitea, Azure DevOps) or `!` (GitLab)
- pub sigil: char,
+ /// The CI cache represents the type under the `sigil` key.
+ #[serde(rename = "sigil", with = "ref_type_sigil")]
+ ref_type: RefType,
}
impl PrRef {
/// A pull-request reference: `#3035` (GitHub, Gitea, Azure DevOps).
pub fn pr(number: u64) -> Self {
- Self { number, sigil: '#' }
+ Self {
+ number,
+ ref_type: RefType::Pr,
+ }
}
/// A merge-request reference: `!3035` (GitLab).
pub fn mr(number: u64) -> Self {
- Self { number, sigil: '!' }
+ Self {
+ number,
+ ref_type: RefType::Mr,
+ }
+ }
+
+ pub fn ref_type(self) -> RefType {
+ self.ref_type
+ }
+
+ pub fn sigil(self) -> char {
+ match self.ref_type {
+ RefType::Pr => '#',
+ RefType::Mr => '!',
+ }
}
/// Rendered width in terminal columns (sigil + digits).
@@ -336,7 +354,35 @@ impl PrRef {
impl std::fmt::Display for PrRef {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(f, "{}{}", self.sigil, self.number)
+ write!(f, "{}{}", self.sigil(), self.number)
+ }
+}
+
+mod ref_type_sigil {
+ use serde::{Deserialize, Deserializer, Serializer};
+ use worktrunk::git::RefType;
+
+ pub fn serialize<S>(ref_type: &RefType, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ serializer.serialize_char(match ref_type {
+ RefType::Pr => '#',
+ RefType::Mr => '!',
+ })
+ }
+
+ pub fn deserialize<'de, D>(deserializer: D) -> Result<RefType, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ match char::deserialize(deserializer)? {
+ '#' => Ok(RefType::Pr),
+ '!' => Ok(RefType::Mr),
+ sigil => Err(serde::de::Error::custom(format_args!(
+ "unknown PR/MR sigil {sigil:?}"
+ ))),
+ }
}
}
@@ -681,7 +727,7 @@ impl PrStatus {
/// Rows with no usable cache entry are left `None` (pending): the live task
/// fills them, so they must not be resolved to "no PR" here.
///
-/// `item.branch` is the cache key for every row shape: local worktrees and
+/// `ListItem::branch()` is the cache key for every row shape: local worktrees and
/// branches cache under the bare name, remote rows under `origin/...` —
/// the same `full_name` the `CiStatus` task writes.
pub(crate) fn populate_from_cache(repo: &Repository, items: &mut [super::model::ListItem]) {
@@ -695,13 +741,13 @@ pub(crate) fn populate_from_cache(repo: &Repository, items: &mut [super::model::
};
let now_secs = epoch_now();
for item in items.iter_mut() {
- let Some(branch) = item.branch.as_deref() else {
+ let Some(branch) = item.branch() else {
continue;
};
let Some(cached) = CachedCiStatus::read(repo, branch) else {
continue;
};
- if cached.is_valid(&item.head, now_secs, &repo_path) {
+ if cached.is_valid(item.head(), now_secs, &repo_path) {
item.pr_status = Some(cached.status);
} else if let Some(stale) = cached.status.filter(|s| s.number.is_some()) {
// Show the number now, but render it neutral-dim: the cached color
@@ -891,8 +937,14 @@ mod tests {
assert_eq!(pr_ref_width(10), 3);
assert_eq!(pr_ref_width(3035), 5);
assert_eq!(pr_ref_width(99999), 6);
- assert_eq!(PrRef::mr(3035).to_string(), "!3035");
- assert_eq!(PrRef::mr(3035).width(), 5);
+ let mr = PrRef::mr(3035);
+ assert_eq!(mr.ref_type(), RefType::Mr);
+ assert_eq!(mr.to_string(), "!3035");
+ assert_eq!(mr.width(), 5);
+
+ let cached = serde_json::to_value(mr).unwrap();
+ assert_eq!(cached, serde_json::json!({ "number": 3035, "sigil": "!" }));
+ assert_eq!(serde_json::from_value::<PrRef>(cached).unwrap(), mr);
}
#[test]
@@ -927,11 +979,8 @@ mod tests {
#[test]
fn test_ci_branch_name_from_detached_head() {
- let detached = BranchRef {
- full_ref: None,
- commit_sha: "abc123".to_string(),
- worktree_path: None,
- };
+ let detached =
+ worktrunk::git::WorktreeRef::new("/tmp/detached", None, "abc123").into_branch_ref();
assert!(CiBranchName::from_branch_ref(&detached).is_none());
}
diff --git a/src/commands/list/collect/execution.rs b/src/commands/list/collect/execution.rs
index 9a5839db0..8720ea12b 100644
--- a/src/commands/list/collect/execution.rs
+++ b/src/commands/list/collect/execution.rs
@@ -22,9 +22,9 @@
use std::sync::Arc;
use crossbeam_channel as chan;
-use worktrunk::git::{BranchRef, Repository, WorktreeInfo};
+use worktrunk::git::Repository;
-use super::super::model::{ItemKind, ListItem, UpstreamStatus, WorkingTreeStatus};
+use super::super::model::{ListItem, UpstreamStatus, WorkingTreeStatus};
use super::CollectOptions;
use super::tasks::{
AheadBehindTask, BranchDiffTask, CiStatusTask, CommittedTreesMatchTask, GitOperationTask,
@@ -234,7 +234,7 @@ pub(super) fn seed_skipped_task_defaults(item: &mut ListItem, kind: TaskKind) {
// waits and renders `·`.
}
TaskKind::WorkingTreeConflicts => {
- if let ItemKind::Worktree(data) = &mut item.kind {
+ if let Some(data) = item.worktree_data_mut() {
// `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`.
@@ -242,7 +242,7 @@ pub(super) fn seed_skipped_task_defaults(item: &mut ListItem, kind: TaskKind) {
}
}
TaskKind::GitOperation => {
- if let ItemKind::Worktree(data) = &mut item.kind {
+ if let Some(data) = item.worktree_data_mut() {
data.git_operation = Some(None);
}
}
@@ -260,7 +260,7 @@ pub(super) fn seed_skipped_task_defaults(item: &mut ListItem, kind: TaskKind) {
/// `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);
+ let is_main = item.is_main();
item.status_symbols.main_state = Some(if is_main {
super::super::model::MainState::IsMain
} else {
@@ -322,7 +322,6 @@ pub(super) fn seed_prunable_item(item: &mut ListItem) {
/// via Arc.
pub fn work_items_for_worktree(
repo: &Repository,
- wt: &WorktreeInfo,
item_idx: usize,
options: &CollectOptions,
expected_results: &Arc<ExpectedResults>,
@@ -332,7 +331,7 @@ pub fn work_items_for_worktree(
// 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() {
+ if item.worktree_data().is_some_and(|data| data.is_prunable()) {
seed_prunable_item(item);
return vec![];
}
@@ -344,9 +343,9 @@ pub fn work_items_for_worktree(
// Expand URL template for this item (only if URL status is enabled).
let item_url = if include_url {
options.url_template.as_ref().and_then(|template| {
- wt.branch.as_ref().and_then(|branch| {
+ item.branch().and_then(|branch| {
let mut vars = std::collections::HashMap::new();
- vars.insert("branch", branch.as_str());
+ vars.insert("branch", branch);
worktrunk::config::expand_template(
template,
&vars,
@@ -376,7 +375,7 @@ pub fn work_items_for_worktree(
let ctx = TaskContext {
repo: repo.clone(),
- branch_ref: BranchRef::from(wt),
+ branch_ref: item.branch_ref().clone(),
item_idx,
item_url,
llm_command: options.llm_command.clone(),
@@ -385,7 +384,7 @@ pub fn work_items_for_worktree(
snapshot: options.snapshot.clone(),
};
- let has_commits = wt.has_commits();
+ let has_commits = item.head() != worktrunk::git::NULL_OID;
let mut items = Vec::with_capacity(15);
@@ -452,42 +451,20 @@ pub fn work_items_for_worktree(
/// Task preconditions are enforced here, same as [`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,
-}
-
+/// The item's [`BranchRef`](worktrunk::git::BranchRef) already records whether
+/// it is local or remote, so this layer does not reconstruct ref qualification.
pub fn work_items_for_branch(
repo: &Repository,
- branch: BranchSpawn<'_>,
+ item_idx: usize,
options: &CollectOptions,
expected_results: &Arc<ExpectedResults>,
item: &mut ListItem,
) -> Vec<WorkItem> {
- let BranchSpawn {
- name: branch_name,
- commit_sha,
- item_idx,
- is_remote,
- } = branch;
-
let run = &options.tasks;
- let branch_ref = if is_remote {
- BranchRef::remote_branch(branch_name, commit_sha)
- } else {
- BranchRef::local_branch(branch_name, commit_sha)
- };
-
let ctx = TaskContext {
repo: repo.clone(),
- branch_ref,
+ branch_ref: item.branch_ref().clone(),
item_idx,
item_url: None, // Branches without worktrees don't have URLs
llm_command: options.llm_command.clone(),
@@ -547,6 +524,7 @@ pub fn work_items_for_branch(
mod tests {
use super::*;
use crate::commands::list::collect::build_worktree_item;
+ use worktrunk::git::WorktreeInfo;
/// Every seed arm must point the negative direction: `json_v2` trusts a
/// positive `check_integration` match even when sibling signals were
@@ -655,8 +633,7 @@ mod tests {
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, &mut item);
+ let items = work_items_for_worktree(&repo, 0, &options, &expected_results, &tx, &mut item);
// No placeholder UrlStatus result was sent to the channel.
assert!(rx.try_recv().is_err());
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rs
index d40b013ef..626f75183 100644
--- a/src/commands/list/collect/mod.rs
+++ b/src/commands/list/collect/mod.rs
@@ -313,10 +313,9 @@ use std::sync::LazyLock;
use anstyle::Style;
use color_print::cformat;
use crossbeam_channel as chan;
-use dunce::canonicalize;
use once_cell::sync::OnceCell;
use rayon::prelude::*;
-use worktrunk::git::{ErrorExt, LocalBranch, Repository, WorktreeInfo};
+use worktrunk::git::{ErrorExt, LocalBranch, Repository, WorktreeId, WorktreeInfo, WorktreeRef};
use worktrunk::styling::{
INFO_SYMBOL, eprintln, format_with_gutter, hint_message, terminal_width, truncate_visible,
warning_message,
@@ -325,7 +324,7 @@ use worktrunk::styling::{
use crate::commands::is_worktree_at_expected_path;
use worktrunk::styling::println;
-use super::model::{CommitDetails, ItemKind, ListItem, StatusSymbols, WorktreeData};
+use super::model::{CommitDetails, ListItem, WorktreeData};
use super::progressive::RenderTarget;
use super::progressive_table::ProgressiveTable;
@@ -1024,26 +1023,32 @@ pub fn collect(
Vec::new()
};
+ // Build each Git subject once and keep it paired with the inventory entry
+ // it describes. The registered path remains available for display and
+ // commands; the subject's ID owns canonical path equality.
+ let worktree_subjects: Vec<(&WorktreeInfo, WorktreeRef)> =
+ worktrees.iter().map(|wt| (wt, wt.worktree_ref())).collect();
+
// Detect current worktree using git rev-parse --show-toplevel (via WorkingTree::root).
// This correctly handles worktrees placed inside other worktrees (e.g., .worktrees/ layout)
// by letting git resolve the actual worktree root rather than using prefix matching.
- // Canonicalize both paths to handle symlinks (e.g., macOS /var -> /private/var).
- let current_worktree_path = repo.current_worktree().root().ok().and_then(|root| {
- worktrees
- .iter()
- .find(|wt| canonicalize(&wt.path).map(|p| p == root).unwrap_or(false))
- .map(|wt| wt.path.clone())
- });
+ let current_worktree_id = repo.current_worktree().root().ok().map(WorktreeId::new);
// Main worktree is the primary worktree (for sorting and is_main display).
// - Normal repos: the main worktree (repo root)
// - Bare repos: the default branch's worktree
- let primary_path = repo.primary_worktree()?;
- let main_worktree = primary_path
- .as_ref()
- .and_then(|p| worktrees.iter().find(|wt| wt.path == *p))
- .or_else(|| worktrees.iter().find(|wt| !wt.is_prunable()))
- .cloned()
- .ok_or_else(|| anyhow::anyhow!("No worktrees found"))?;
+ let primary_id = repo.primary_worktree()?.as_ref().map(WorktreeId::new);
+ let (main_worktree, main_worktree_id) = {
+ let (wt, worktree_ref) = primary_id
+ .as_ref()
+ .and_then(|id| {
+ worktree_subjects
+ .iter()
+ .find(|(_, worktree_ref)| worktree_ref.id() == id)
+ })
+ .or_else(|| worktree_subjects.iter().find(|(wt, _)| !wt.is_prunable()))
+ .ok_or_else(|| anyhow::anyhow!("No worktrees found"))?;
+ (*wt, worktree_ref.id().clone())
+ };
// Defer previous_branch lookup until after skeleton - set is_previous later
// (skeleton shows placeholder gutter, actual symbols appear when data loads)
@@ -1080,9 +1085,9 @@ pub fn collect(
// Sort worktrees: current first, main second, then by timestamp descending
let sorted_worktrees = sort_worktrees_with_cache(
- worktrees,
- &main_worktree,
- current_worktree_path.as_ref(),
+ worktree_subjects,
+ &main_worktree_id,
+ current_worktree_id.as_ref(),
&commit_details_map,
);
@@ -1097,10 +1102,6 @@ pub fn collect(
sha.as_str()
});
- // Pre-canonicalize main_worktree.path for is_main comparison
- // (paths from git worktree list may differ based on symlinks or working directory)
- let main_worktree_canonical = canonicalize(&main_worktree.path).ok();
-
// Branches living in more than one worktree. Every row on such a branch
// is flagged, including the one `wt` resolves to: that choice is git's
// listing order, so no row is the legitimate one.
@@ -1110,18 +1111,9 @@ pub fn collect(
// Initialize worktree items with identity fields and None for computed fields
let mut all_items: Vec<ListItem> = sorted_worktrees
.iter()
- .map(|wt| {
- // Canonicalize paths for comparison - git worktree list may return different
- // path representations depending on symlinks or which directory you run from
- let wt_canonical = canonicalize(&wt.path).ok();
- let is_main = match (&wt_canonical, &main_worktree_canonical) {
- (Some(wt_c), Some(main_c)) => wt_c == main_c,
- // Fallback to direct comparison if canonicalization fails
- _ => wt.path == main_worktree.path,
- };
- let is_current = current_worktree_path
- .as_ref()
- .is_some_and(|cp| wt_canonical.as_ref() == Some(cp));
+ .map(|(wt, worktree_ref)| {
+ let is_main = worktree_ref.id() == &main_worktree_id;
+ let is_current = current_worktree_id.as_ref() == Some(worktree_ref.id());
// is_previous set to false initially - computed after skeleton
let is_previous = false;
@@ -1138,32 +1130,7 @@ pub fn collect(
.is_some_and(|branch| duplicated.contains(branch));
// URL expanded post-skeleton to minimize time-to-skeleton
- ListItem {
- head: wt.head.clone(),
- short_sha: String::new(),
- branch: wt.branch.clone(),
- commit: None,
- counts: None,
- branch_diff: None,
- committed_trees_match: None,
- has_file_changes: None,
- would_merge_add: None,
- is_patch_id_match: None,
- is_ancestor: None,
- is_orphan: None,
- upstream: None,
- pr_status: None,
- url: None,
- url_active: None,
- summary: None,
- has_merge_tree_conflicts: None,
- user_marker: None,
- status_symbols: StatusSymbols::default(),
- statusline: None,
- custom_values: Vec::new(),
- seeded: super::model::SeededFacts::default(),
- kind: ItemKind::Worktree(Box::new(worktree_data)),
- }
+ ListItem::new_worktree(worktree_ref.clone(), worktree_data)
})
.collect();
@@ -1191,7 +1158,7 @@ pub fn collect(
// move costs no fork. Rows the batch didn't cover (unborn branches, a failed
// batch) keep the empty string and render an empty cell.
for item in &mut all_items {
- if let Some((short_sha, _, _)) = commit_details_map.get(&item.head) {
+ if let Some((short_sha, _, _)) = commit_details_map.get(item.head()) {
item.short_sha = short_sha.clone();
}
}
@@ -1506,6 +1473,7 @@ pub fn collect(
let fsmonitor_worktrees: Vec<_> = if repo.is_builtin_fsmonitor_enabled() {
sorted_worktrees
.iter()
+ .map(|(wt, _)| *wt)
.filter(|wt| !wt.is_prunable())
.collect()
} else {
@@ -1644,7 +1612,7 @@ pub fn collect(
// Update is_previous on items
if let Some(prev) = previous_branch.as_deref() {
for item in &mut all_items {
- if item.branch.as_deref() == Some(prev)
+ if item.branch() == Some(prev)
&& let Some(wt_data) = item.worktree_data_mut()
{
wt_data.is_previous = true;
@@ -1665,7 +1633,7 @@ pub fn collect(
if item.worktree_data().is_some_and(|d| d.is_prunable()) {
continue;
}
- let Some((_, timestamp, commit_message)) = commit_details_map.get(&item.head) else {
+ let Some((_, timestamp, commit_message)) = commit_details_map.get(item.head()) else {
continue;
};
item.commit = Some(CommitDetails {
@@ -1687,25 +1655,18 @@ pub fn collect(
// Collect errors for display after rendering
let mut errors: Vec<TaskError> = Vec::new();
- // 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 {
- let mut all_branches = Vec::new();
- if show_branches {
- all_branches.extend(branches_without_worktrees.iter().enumerate().map(
- |(idx, (name, sha))| (branch_start_idx + idx, name.clone(), sha.clone(), false),
- ));
- }
- if show_remotes {
- all_branches.extend(remote_branches.iter().enumerate().map(
- |(idx, (name, sha))| (remote_start_idx + idx, name.clone(), sha.clone(), true),
- ));
- }
- all_branches
- } else {
- Vec::new()
- };
+ // Branch item indices; each item already owns its canonical Git subject.
+ let branch_indices: Vec<usize> = (show_branches)
+ .then(|| branch_start_idx..branch_start_idx + branches_without_worktrees.len())
+ .into_iter()
+ .flatten()
+ .chain(
+ (show_remotes)
+ .then(|| remote_start_idx..remote_start_idx + remote_branches.len())
+ .into_iter()
+ .flatten(),
+ )
+ .collect();
// 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
@@ -1715,31 +1676,29 @@ pub fn collect(
let mut all_work_items = Vec::new();
// Worktree work items
- for (idx, wt) in sorted_worktrees.iter().enumerate() {
+ for (idx, item) in all_items
+ .iter_mut()
+ .enumerate()
+ .take(sorted_worktrees.len())
+ {
all_work_items.extend(work_items_for_worktree(
repo,
- wt,
idx,
&options,
&expected_results,
&tx,
- &mut all_items[idx],
+ item,
));
}
// Branch work items (local + remote)
- for (item_idx, branch_name, commit_sha, is_remote) in &branch_data {
+ for item_idx in branch_indices {
all_work_items.extend(work_items_for_branch(
repo,
- execution::BranchSpawn {
- name: branch_name,
- commit_sha,
- item_idx: *item_idx,
- is_remote: *is_remote,
- },
+ item_idx,
&options,
&expected_results,
- &mut all_items[*item_idx],
+ &mut all_items[item_idx],
));
}
@@ -2108,33 +2067,24 @@ where
/// Sort worktrees: current first, main second, then by timestamp descending.
/// Uses the pre-fetched commit-details map for efficiency.
-fn sort_worktrees_with_cache(
- worktrees: &[WorktreeInfo],
- main_worktree: &WorktreeInfo,
- current_path: Option<&std::path::PathBuf>,
+fn sort_worktrees_with_cache<'a>(
+ mut worktrees: Vec<(&'a WorktreeInfo, WorktreeRef)>,
+ main_worktree_id: &WorktreeId,
+ current_worktree_id: Option<&WorktreeId>,
commit_details: &std::collections::HashMap<String, (String, i64, String)>,
-) -> Vec<WorktreeInfo> {
- // Embed timestamp and priority in tuple to avoid parallel Vec and index lookups
- let mut with_sort_key: Vec<_> = worktrees
- .iter()
- .map(|wt| {
- let priority = if current_path.is_some_and(|cp| &wt.path == cp) {
- 0 // Current first
- } else if wt.path == main_worktree.path {
- 1 // Main second
- } else {
- 2 // Rest by timestamp
- };
- let ts = commit_details.get(&wt.head).map_or(0, |(_, ts, _)| *ts);
- (wt, priority, ts)
- })
- .collect();
-
- with_sort_key.sort_by_key(|(_, priority, ts)| (*priority, std::cmp::Reverse(*ts)));
- with_sort_key
- .into_iter()
- .map(|(wt, _, _)| wt.clone())
- .collect()
+) -> Vec<(&'a WorktreeInfo, WorktreeRef)> {
+ worktrees.sort_by_key(|(wt, worktree_ref)| {
+ let priority = if current_worktree_id == Some(worktree_ref.id()) {
+ 0 // Current first
+ } else if worktree_ref.id() == main_worktree_id {
+ 1 // Main second
+ } else {
+ 2 // Rest by timestamp
+ };
+ let ts = commit_details.get(&wt.head).map_or(0, |(_, ts, _)| *ts);
+ (priority, std::cmp::Reverse(ts))
+ });
+ worktrees
}
// ============================================================================
@@ -2151,37 +2101,10 @@ pub fn build_worktree_item(
is_current: bool,
is_previous: bool,
) -> ListItem {
- ListItem {
- head: wt.head.clone(),
- short_sha: String::new(),
- branch: wt.branch.clone(),
- commit: None,
- counts: None,
- branch_diff: None,
- committed_trees_match: None,
- has_file_changes: None,
- would_merge_add: None,
- is_patch_id_match: None,
- is_ancestor: None,
- is_orphan: None,
- upstream: None,
- pr_status: None,
- url: None,
- url_active: None,
- summary: None,
- has_merge_tree_conflicts: None,
- user_marker: None,
- status_symbols: StatusSymbols::default(),
- statusline: None,
- custom_values: Vec::new(),
- seeded: super::model::SeededFacts::default(),
- kind: ItemKind::Worktree(Box::new(WorktreeData::from_worktree(
- wt,
- is_main,
- is_current,
- is_previous,
- ))),
- }
+ ListItem::new_worktree(
+ wt.worktree_ref(),
+ WorktreeData::from_worktree(wt, is_main, is_current, is_previous),
+ )
}
/// Populate computed fields for items in parallel (blocking).
@@ -2215,9 +2138,9 @@ pub fn populate_item(
// timestamp/message bundle is skipped for prunable rows to match the old
// task-queue UX where probes against a missing worktree dir failed.
let is_prunable = item.worktree_data().is_some_and(|d| d.is_prunable());
- if item.head != worktrunk::git::NULL_OID
- && let Ok(map) = repo.commit_details_many(&[&item.head])
- && let Some((short_sha, timestamp, commit_message)) = map.get(&item.head)
+ if item.head() != worktrunk::git::NULL_OID
+ && let Ok(map) = repo.commit_details_many(&[item.head()])
+ && let Some((short_sha, timestamp, commit_message)) = map.get(item.head())
{
item.short_sha = short_sha.clone();
if !is_prunable {
@@ -2229,9 +2152,9 @@ pub fn populate_item(
}
// Extract worktree data (skip if not a worktree item)
- let Some(data) = item.worktree_data() else {
+ if item.worktree_data().is_none() {
return Ok(());
- };
+ }
// Populate default_branch / snapshot / integration_targets if the
// caller didn't. Tasks read these through `TaskContext`; `None`
@@ -2265,24 +2188,10 @@ pub fn populate_item(
// Collect errors (logged silently for statusline)
let mut errors: Vec<TaskError> = Vec::new();
- // 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(),
- branch: item.branch.clone(),
- bare: false,
- detached: false,
- locked: None,
- prunable: None,
- };
-
// 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,
diff --git a/src/commands/list/collect/results.rs b/src/commands/list/collect/results.rs
index 0c7663507..2d47bf51f 100644
--- a/src/commands/list/collect/results.rs
+++ b/src/commands/list/collect/results.rs
@@ -16,7 +16,7 @@ use std::time::{Duration, Instant};
use crossbeam_channel as chan;
-use super::super::model::{ItemKind, ListItem};
+use super::super::model::ListItem;
use super::execution::ExpectedResults;
use super::types::{DrainOutcome, MissingResult, TaskError, TaskKind, TaskResult};
@@ -303,7 +303,7 @@ pub(super) fn drain_results_with_timings(
has_conflicts,
..
} => {
- if let ItemKind::Worktree(data) = &mut item.kind {
+ if let Some(data) = item.worktree_data_mut() {
data.working_tree_diff = Some(working_tree_diff);
data.working_tree_status = Some(working_tree_status);
data.has_conflicts = Some(has_conflicts);
@@ -321,14 +321,14 @@ pub(super) fn drain_results_with_timings(
has_working_tree_conflicts,
..
} => {
- if let ItemKind::Worktree(data) = &mut item.kind {
+ if let Some(data) = item.worktree_data_mut() {
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 {
+ if let Some(data) = item.worktree_data_mut() {
data.git_operation = Some(git_operation);
} else {
debug_assert!(false, "GitOperation result for non-worktree item");
@@ -404,7 +404,7 @@ mod tests {
// 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 {
+ if let Some(data) = item.worktree_data_mut() {
data.working_tree_diff = Some(LineDiff::default());
data.working_tree_status = Some(WorkingTreeStatus::default());
data.has_conflicts = Some(false);
diff --git a/src/commands/list/collect/tasks.rs b/src/commands/list/collect/tasks.rs
index 04d42a290..c8fed77e6 100644
--- a/src/commands/list/collect/tasks.rs
+++ b/src/commands/list/collect/tasks.rs
@@ -933,7 +933,7 @@ impl Task for SummaryGenerateTask {
};
let branch = ctx.branch_ref.short_name().unwrap_or("(detached)");
- let worktree_path = ctx.branch_ref.worktree_path.as_deref();
+ let worktree_path = ctx.branch_ref.worktree_path();
let summary = crate::summary::generate_summary_core(
branch,
diff --git a/src/commands/list/custom_columns.rs b/src/commands/list/custom_columns.rs
index 8e00dce93..e3485cf09 100644
--- a/src/commands/list/custom_columns.rs
+++ b/src/commands/list/custom_columns.rs
@@ -147,21 +147,20 @@ pub fn expand_custom_columns(
for item in items {
let (worktree_path, worktree_name) = if needs_worktree {
- item.worktree_data()
- .map(|data| {
- let path = to_posix_path(&data.path.to_string_lossy());
- let name = data
- .path
+ item.worktree_path()
+ .map(|path| {
+ let display_path = to_posix_path(&path.to_string_lossy());
+ let name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
- (path, name)
+ (display_path, name)
})
.unwrap_or_default()
} else {
Default::default()
};
- let branch = item.branch.as_deref().unwrap_or("");
+ let branch = item.branch().unwrap_or("");
let mut context: HashMap<String, Value> = HashMap::new();
context.insert("branch".to_string(), Value::from(branch));
diff --git a/src/commands/list/json_output.rs b/src/commands/list/json_output.rs
index b4cce7eb0..2cf58a261 100644
--- a/src/commands/list/json_output.rs
+++ b/src/commands/list/json_output.rs
@@ -279,7 +279,7 @@ impl JsonItem {
ci_provider_override: Option<&str>,
custom_columns: &[ResolvedCustomColumn],
) -> Self {
- let (kind_str, worktree_data) = match &item.kind {
+ let (kind_str, worktree_data) = match item.kind() {
ItemKind::Worktree(data) => ("worktree", Some(data.as_ref())),
// Local and remote branch rows both serialize as "branch" — the
// remote-qualified `branch` name (e.g. "origin/feature") already
@@ -297,10 +297,10 @@ impl JsonItem {
// `core.abbrev` and disambiguates without an extra subprocess. Lives on
// `ListItem` directly so prunable worktrees still carry it even though
// their `commit` (timestamp + message) is intentionally left empty.
- let sha = if item.head == worktrunk::git::NULL_OID {
+ let sha = if item.head() == worktrunk::git::NULL_OID {
String::new()
} else {
- item.head.clone()
+ item.head().to_string()
};
let commit = JsonCommit {
sha,
@@ -362,7 +362,7 @@ impl JsonItem {
let remote = item
.upstream
.as_ref()
- .and_then(|u| upstream_to_json(u, &item.branch));
+ .and_then(|u| upstream_to_json(u, item.branch()));
// Worktree state
let worktree = worktree_data.map(|data| {
@@ -375,7 +375,7 @@ impl JsonItem {
});
// Path
- let path = worktree_data.map(|d| d.path.clone());
+ let path = item.worktree_path().map(std::path::Path::to_path_buf);
// CI status
let ci = item
@@ -389,7 +389,7 @@ impl JsonItem {
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 = super::json_v2::take_vars(item.branch.as_deref(), all_vars);
+ let vars = super::json_v2::take_vars(item.branch(), all_vars);
// Summary: flatten Option<Option<String>> → Option<String>
let summary = item.summary.as_ref().and_then(|s| s.clone());
@@ -398,7 +398,7 @@ impl JsonItem {
let columns = super::json_v2::columns_map(custom_columns, &item.custom_values);
JsonItem {
- branch: item.branch.clone(),
+ branch: item.branch().map(str::to_string),
path,
kind: kind_str,
commit,
@@ -427,13 +427,13 @@ impl JsonItem {
}
/// Convert UpstreamStatus to JsonRemote
-fn upstream_to_json(upstream: &UpstreamStatus, branch: &Option<String>) -> Option<JsonRemote> {
+fn upstream_to_json(upstream: &UpstreamStatus, branch: Option<&str>) -> Option<JsonRemote> {
upstream.active().map(|active| {
// Use local branch name since UpstreamStatus only stores the remote name,
// not the full tracking refspec. In most cases these match (e.g., feature -> origin/feature).
JsonRemote {
name: active.remote.to_string(),
- branch: branch.clone().unwrap_or_default(),
+ branch: branch.unwrap_or_default().to_string(),
ahead: active.ahead,
behind: active.behind,
}
@@ -771,7 +771,7 @@ mod tests {
..Default::default()
};
let branch = Some("feature".to_string());
- let json = upstream_to_json(&upstream, &branch);
+ let json = upstream_to_json(&upstream, branch.as_deref());
assert!(json.is_some());
let json = json.unwrap();
assert_eq!(json.name, "origin");
@@ -789,7 +789,7 @@ mod tests {
..Default::default()
};
let branch = Some("feature".to_string());
- let json = upstream_to_json(&upstream, &branch);
+ let json = upstream_to_json(&upstream, branch.as_deref());
assert!(json.is_none());
}
@@ -802,7 +802,7 @@ mod tests {
..Default::default()
};
let branch = None;
- let json = upstream_to_json(&upstream, &branch);
+ let json = upstream_to_json(&upstream, branch);
assert!(json.is_some());
let json = json.unwrap();
assert_eq!(json.branch, ""); // Empty string when branch is None
@@ -814,7 +814,6 @@ mod tests {
fn make_worktree_data() -> WorktreeData {
WorktreeData {
- path: PathBuf::from("/test/path"),
is_main: false,
is_current: false,
is_previous: false,
diff --git a/src/commands/list/json_v2.rs b/src/commands/list/json_v2.rs
index 05fddc37d..e7742bde4 100644
--- a/src/commands/list/json_v2.rs
+++ b/src/commands/list/json_v2.rs
@@ -587,41 +587,50 @@ impl JsonItemV2 {
ci_provider_override: Option<&str>,
custom_columns: &[ResolvedCustomColumn],
) -> Self {
- let (worktree_data, remote_scope) = match &item.kind {
+ let (worktree_data, remote_scope) = match item.kind() {
ItemKind::Worktree(data) => (Some(data.as_ref()), false),
ItemKind::Branch(scope) => (None, *scope == BranchScope::Remote),
};
// Remote rows store the remote-qualified short name ("origin/feature");
// split it into the remote and the bare branch name.
- let (branch, remote) = match (&item.branch, remote_scope) {
+ let (branch, remote) = match (item.branch(), remote_scope) {
(Some(name), true) => match name.split_once('/') {
Some((remote, branch)) => (Some(branch.to_string()), Some(remote.to_string())),
- None => (Some(name.clone()), None),
+ None => (Some(name.to_string()), None),
},
- (name, _) => (name.clone(), None),
+ (name, _) => (name.map(str::to_string), None),
};
// HEAD — null for unborn branches (no sentinel strings).
let head =
- (!item.head.is_empty() && item.head != worktrunk::git::NULL_OID).then(|| JsonHead {
- sha: item.head.clone(),
- short_sha: item.short_sha.clone(),
- subject: item.commit.as_ref().map(|c| c.commit_message.clone()),
- committed_at: item
- .commit
- .as_ref()
- .and_then(|c| worktrunk::utils::format_timestamp_iso8601_opt(c.timestamp)),
+ (!item.head().is_empty() && item.head() != worktrunk::git::NULL_OID).then(|| {
+ JsonHead {
+ sha: item.head().to_string(),
+ short_sha: item.short_sha.clone(),
+ subject: item.commit.as_ref().map(|c| c.commit_message.clone()),
+ committed_at: item
+ .commit
+ .as_ref()
+ .and_then(|c| worktrunk::utils::format_timestamp_iso8601_opt(c.timestamp)),
+ }
});
- let worktree = worktree_data.map(json_worktree);
+ let worktree = worktree_data.map(|data| {
+ json_worktree(
+ data,
+ item.worktree_path()
+ .expect("typed worktree rows always carry a worktree path"),
+ )
+ });
// The default branch itself gets no relation object. Matching on the
// worktree's main flag alone would miss a branch-only row for the
// default branch, so compare names too. Use the remote-stripped
- // `branch` (not `item.branch`) so a remote-only row of the default
- // branch (`origin/main`) also matches — otherwise it fails the name
- // check and gets a spurious self-referential relation.
+ // `branch`, rather than the remote-qualified name
+ // returned by `item.branch()`, so a remote-only row of the default
+ // branch (`origin/main`) also matches. Otherwise it gets a spurious
+ // self-referential relation.
let is_default_branch_row = worktree_data.is_some_and(|d| d.is_main)
|| (branch.is_some() && branch.as_deref() == default_branch);
let default_branch = if is_default_branch_row {
@@ -674,7 +683,7 @@ impl JsonItemV2 {
}
};
- let vars = take_vars(item.branch.as_deref(), all_vars);
+ let vars = take_vars(item.branch(), all_vars);
let columns = columns_map(custom_columns, &item.custom_values);
let display = JsonDisplay {
@@ -704,7 +713,7 @@ impl JsonItemV2 {
}
}
-fn json_worktree(data: &WorktreeData) -> JsonWorktreeV2 {
+fn json_worktree(data: &WorktreeData, path: &std::path::Path) -> JsonWorktreeV2 {
// Empty lock/prune reasons (git records the state without a message)
// become `reason: null`.
let reason = |r: &Option<String>| {
@@ -730,7 +739,7 @@ fn json_worktree(data: &WorktreeData) -> JsonWorktreeV2 {
});
JsonWorktreeV2 {
- path: data.path.clone(),
+ path: path.to_path_buf(),
main: data.is_main,
current: data.is_current,
previous: data.is_previous,
@@ -1074,7 +1083,7 @@ mod tests {
#[test]
fn test_remote_row_splits_branch_and_remote() {
let mut item = item_with("origin/feature");
- item.kind = ItemKind::Branch(BranchScope::Remote);
+ item.reclassify_as_branch(BranchScope::Remote, "origin/feature".into());
let json = to_value(&convert(&item, Collected::default()));
assert_eq!(json["branch"], "feature");
assert_eq!(json["remote"], "origin");
@@ -1082,8 +1091,7 @@ mod tests {
#[test]
fn test_unborn_branch_head_is_null() {
- let mut item = item_with("new");
- item.head = worktrunk::git::NULL_OID.to_string();
+ let item = ListItem::new_branch(worktrunk::git::NULL_OID.to_string(), "new".into());
let json = to_value(&convert(&item, Collected::default()));
assert!(json["head"].is_null());
}
@@ -1102,7 +1110,7 @@ mod tests {
// "main", not the raw "origin/main", so it gets no self-referential
// relation object.
let mut item = item_with("origin/main");
- item.kind = ItemKind::Branch(BranchScope::Remote);
+ item.reclassify_as_branch(BranchScope::Remote, "origin/main".into());
let json = to_value(&convert(&item, Collected::default()));
assert_eq!(json["branch"], "main");
assert!(json.get("default_branch").is_none());
@@ -1257,9 +1265,10 @@ mod tests {
}
fn worktree_item(branch: &str, data: WorktreeData) -> ListItem {
- let mut item = item_with(branch);
- item.kind = ItemKind::Worktree(Box::new(data));
- item
+ ListItem::new_worktree(
+ worktrunk::git::WorktreeRef::new("/test", Some(branch), "abc123"),
+ data,
+ )
}
/// `JsonIntegrationReason` covers every `IntegrationReason`, under the
@@ -1314,7 +1323,7 @@ mod tests {
#[test]
fn test_remote_row_without_slash_keeps_name() {
let mut item = item_with("weird");
- item.kind = ItemKind::Branch(BranchScope::Remote);
+ item.reclassify_as_branch(BranchScope::Remote, "weird".into());
let json = to_value(&convert(&item, Collected::default()));
assert_eq!(json["branch"], "weird");
assert!(json.get("remote").is_none());
diff --git a/src/commands/list/layout.rs b/src/commands/list/layout.rs
index a9be4afaf..83ec9d64e 100644
--- a/src/commands/list/layout.rs
+++ b/src/commands/list/layout.rs
@@ -1185,7 +1185,7 @@ pub fn calculate_layout_with_width(
// Include branch names from both worktrees and standalone branches
let longest_branch = items
.iter()
- .filter_map(|item| item.branch.as_deref())
+ .filter_map(|item| item.branch())
.max_by_key(|b| b.width());
// A detached row shows its abbreviated HEAD in this column
@@ -1194,7 +1194,7 @@ pub fn calculate_layout_with_width(
// and stretches further still to disambiguate.
let detached_width = items
.iter()
- .filter(|item| item.branch.is_none())
+ .filter(|item| item.branch().is_none())
.map(|item| item.short_sha.width())
.max();
@@ -1209,7 +1209,7 @@ pub fn calculate_layout_with_width(
let path_data_width = items
.iter()
.filter_map(|item| item.worktree_path())
- .map(|path| shorten_path(path.as_path(), main_worktree_path).width())
+ .map(|path| shorten_path(path, main_worktree_path).width())
.max()
.unwrap_or(0);
let max_path_width = fit_header(ColumnKind::Path.header(), path_data_width);
@@ -1616,65 +1616,38 @@ mod tests {
#[test]
fn test_visible_columns_follow_gap_rule() {
use crate::commands::list::model::{
- AheadBehind, BranchDiffTotals, CommitDetails, ItemKind, ListItem, StatusSymbols,
- UpstreamStatus, WorktreeData,
+ AheadBehind, BranchDiffTotals, CommitDetails, ListItem, UpstreamStatus, WorktreeData,
};
// Create test data with specific widths to verify position calculation
- let item = ListItem {
- head: "abc12345".to_string(),
- short_sha: "abc1234".to_string(),
- branch: Some("feature".to_string()),
- commit: Some(CommitDetails {
- timestamp: 1234567890,
- commit_message: "Test commit message".to_string(),
- }),
- counts: Some(AheadBehind {
- ahead: 5,
- behind: 10,
- }),
- branch_diff: Some(BranchDiffTotals {
- diff: LineDiff::from((200, 30)),
- }),
- committed_trees_match: Some(false),
- has_file_changes: Some(true),
- would_merge_add: None,
- is_patch_id_match: None,
- is_ancestor: None,
- is_orphan: None,
- upstream: Some(UpstreamStatus {
- remote: Some("origin".to_string()),
- ahead: 4,
- behind: 2,
- ..Default::default()
- }),
- pr_status: None,
- url: None,
- url_active: None,
- summary: None,
- has_merge_tree_conflicts: None,
- user_marker: None,
- status_symbols: StatusSymbols::default(),
- statusline: None,
- custom_values: Vec::new(),
- seeded: Default::default(),
- kind: ItemKind::Worktree(Box::new(WorktreeData {
- path: PathBuf::from("/test/path"),
- detached: false,
- locked: None,
- prunable: None,
+ let mut item = ListItem::new_worktree(
+ worktrunk::git::WorktreeRef::new("/test/path", Some("feature"), "abc12345"),
+ WorktreeData {
working_tree_diff: Some(LineDiff::from((100, 50))),
- working_tree_status: None,
- has_conflicts: None,
- has_working_tree_conflicts: None,
git_operation: Some(None),
- is_main: false,
- is_current: false,
- is_previous: false,
- branch_worktree_mismatch: false,
- duplicate_branch: false,
- })),
- };
+ ..Default::default()
+ },
+ );
+ item.short_sha = "abc1234".to_string();
+ item.commit = Some(CommitDetails {
+ timestamp: 1234567890,
+ commit_message: "Test commit message".to_string(),
+ });
+ item.counts = Some(AheadBehind {
+ ahead: 5,
+ behind: 10,
+ });
+ item.branch_diff = Some(BranchDiffTotals {
+ diff: LineDiff::from((200, 30)),
+ });
+ item.committed_trees_match = Some(false);
+ item.has_file_changes = Some(true);
+ item.upstream = Some(UpstreamStatus {
+ remote: Some("origin".to_string()),
+ ahead: 4,
+ behind: 2,
+ ..Default::default()
+ });
let items = vec![item];
let tasks = run_except(&[TaskKind::BranchDiff, TaskKind::CiStatus]);
@@ -1741,60 +1714,34 @@ mod tests {
#[test]
fn test_column_positions_with_empty_columns() {
use crate::commands::list::model::{
- AheadBehind, BranchDiffTotals, CommitDetails, ItemKind, ListItem, StatusSymbols,
- UpstreamStatus, WorktreeData,
+ AheadBehind, BranchDiffTotals, CommitDetails, ListItem, UpstreamStatus, WorktreeData,
};
// Create minimal data - most columns will be empty
- let item = ListItem {
- head: "abc12345".to_string(),
- short_sha: "abc1234".to_string(),
- branch: Some("main".to_string()),
- commit: Some(CommitDetails {
- timestamp: 1234567890,
- commit_message: "Test".to_string(),
- }),
- counts: Some(AheadBehind {
- ahead: 0,
- behind: 0,
- }),
- branch_diff: Some(BranchDiffTotals {
- diff: LineDiff::default(),
- }),
- committed_trees_match: Some(false),
- has_file_changes: Some(true),
- would_merge_add: None,
- is_patch_id_match: None,
- is_ancestor: None,
- is_orphan: None,
- upstream: Some(UpstreamStatus::default()),
- pr_status: None,
- url: None,
- url_active: None,
- summary: None,
- has_merge_tree_conflicts: None,
- user_marker: None,
- status_symbols: StatusSymbols::default(),
- statusline: None,
- custom_values: Vec::new(),
- seeded: Default::default(),
- kind: ItemKind::Worktree(Box::new(WorktreeData {
- path: PathBuf::from("/test"),
- detached: false,
- locked: None,
- prunable: None,
+ let mut item = ListItem::new_worktree(
+ worktrunk::git::WorktreeRef::new("/test", Some("main"), "abc12345"),
+ WorktreeData {
working_tree_diff: Some(LineDiff::default()),
- working_tree_status: None,
- has_conflicts: None,
- has_working_tree_conflicts: None,
git_operation: Some(None),
is_main: true, // Primary worktree: no ahead/behind shown
- is_current: false,
- is_previous: false,
- branch_worktree_mismatch: false,
- duplicate_branch: false,
- })),
- };
+ ..Default::default()
+ },
+ );
+ item.short_sha = "abc1234".to_string();
+ item.commit = Some(CommitDetails {
+ timestamp: 1234567890,
+ commit_message: "Test".to_string(),
+ });
+ item.counts = Some(AheadBehind {
+ ahead: 0,
+ behind: 0,
+ });
+ item.branch_diff = Some(BranchDiffTotals {
+ diff: LineDiff::default(),
+ });
+ item.committed_trees_match = Some(false);
+ item.has_file_changes = Some(true);
+ item.upstream = Some(UpstreamStatus::default());
let items = vec![item];
let tasks = run_except(&[TaskKind::BranchDiff, TaskKind::CiStatus]);
@@ -1888,48 +1835,16 @@ 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::{ItemKind, StatusSymbols, WorktreeData};
- super::super::model::ListItem {
- head: "abc12345".to_string(),
- short_sha: "abc1234".to_string(),
- branch: Some(branch.to_string()),
- commit: None,
- counts: None,
- branch_diff: None,
- committed_trees_match: None,
- has_file_changes: None,
- would_merge_add: None,
- is_patch_id_match: None,
- is_ancestor: None,
- is_orphan: None,
- upstream: None,
- pr_status: None,
- url: None,
- url_active: None,
- summary: None,
- has_merge_tree_conflicts: None,
- user_marker: None,
- status_symbols: StatusSymbols::default(),
- statusline: None,
- custom_values: Vec::new(),
- seeded: Default::default(),
- kind: ItemKind::Worktree(Box::new(WorktreeData {
- path: PathBuf::from("/test/wt"),
- detached: false,
- locked: None,
- prunable: None,
- working_tree_diff: None,
- working_tree_status: None,
- has_conflicts: None,
- has_working_tree_conflicts: None,
+ use crate::commands::list::model::WorktreeData;
+ let mut item = super::super::model::ListItem::new_worktree(
+ worktrunk::git::WorktreeRef::new("/test/wt", Some(branch), "abc12345"),
+ WorktreeData {
git_operation: Some(None),
- is_main: false,
- is_current: false,
- is_previous: false,
- branch_worktree_mismatch: false,
- duplicate_branch: false,
- })),
- }
+ ..Default::default()
+ },
+ );
+ item.short_sha = "abc1234".to_string();
+ item
}
/// Helper: compute layout with explicit terminal width and run plan.
@@ -2117,8 +2032,14 @@ mod tests {
/// runs.
#[test]
fn test_branch_column_fits_a_detached_rows_sha() {
- let mut detached = make_test_item("main");
- detached.branch = None;
+ let mut detached = super::super::model::ListItem::new_worktree(
+ worktrunk::git::WorktreeRef::new("/test/detached", None, "abc12345"),
+ super::super::model::WorktreeData {
+ detached: true,
+ ..Default::default()
+ },
+ );
+ detached.short_sha = "abc1234".to_string();
let items = vec![make_test_item("main"), detached];
let layout = calculate_layout_with_width(
@@ -2413,48 +2334,16 @@ 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::{ItemKind, StatusSymbols, WorktreeData};
- super::super::model::ListItem {
- head: "abc12345".to_string(),
- short_sha: "abc1234".to_string(),
- branch: Some(branch.to_string()),
- commit: None,
- counts: None,
- branch_diff: None,
- committed_trees_match: None,
- has_file_changes: None,
- would_merge_add: None,
- is_patch_id_match: None,
- is_ancestor: None,
- is_orphan: None,
- upstream: None,
- pr_status: None,
- url: None,
- url_active: None,
- summary: None,
- has_merge_tree_conflicts: None,
- user_marker: None,
- status_symbols: StatusSymbols::default(),
- statusline: None,
- custom_values: Vec::new(),
- seeded: Default::default(),
- kind: ItemKind::Worktree(Box::new(WorktreeData {
- path: PathBuf::from(path),
- detached: false,
- locked: None,
- prunable: None,
- working_tree_diff: None,
- working_tree_status: None,
- has_conflicts: None,
- has_working_tree_conflicts: None,
+ use crate::commands::list::model::WorktreeData;
+ let mut item = super::super::model::ListItem::new_worktree(
+ worktrunk::git::WorktreeRef::new(path, Some(branch), "abc12345"),
+ WorktreeData {
git_operation: Some(None),
- is_main: false,
- is_current: false,
- is_previous: false,
- branch_worktree_mismatch: false,
- duplicate_branch: false,
- })),
- }
+ ..Default::default()
+ },
+ );
+ item.short_sha = "abc1234".to_string();
+ item
}
/// When paths are consistent (no mismatch), Path should yield space to Summary.
@@ -2471,7 +2360,7 @@ mod tests {
let items = vec![
{
let mut item = make_test_item_at("main", "/test/worktrunk");
- if let super::super::model::ItemKind::Worktree(ref mut data) = item.kind {
+ if let Some(data) = item.worktree_data_mut() {
data.is_main = true;
}
item
@@ -2543,8 +2432,7 @@ mod tests {
#[test]
fn test_snapshot_path_yields_to_summary() {
use crate::commands::list::model::{
- AheadBehind, BranchDiffTotals, CommitDetails, ItemKind, StatusSymbols, UpstreamStatus,
- WorktreeData,
+ AheadBehind, BranchDiffTotals, CommitDetails, UpstreamStatus, WorktreeData,
};
use worktrunk::git::LineDiff;
@@ -2574,50 +2462,27 @@ mod tests {
behind: 0,
..Default::default()
});
- super::super::model::ListItem {
- head: "a620bcfe".to_string(),
- short_sha: "a620bcf".to_string(),
- branch: Some(branch.to_string()),
- commit: Some(CommitDetails {
- timestamp: ts,
- commit_message: "Some commit message".to_string(),
- }),
- counts,
- branch_diff,
- committed_trees_match: None,
- has_file_changes: None,
- would_merge_add: None,
- is_patch_id_match: None,
- is_ancestor: None,
- is_orphan: None,
- upstream: upstream_status,
- pr_status: Some(None), // loaded, no CI
- url: None,
- url_active: None,
- summary: Some(summary.map(|s| s.to_string())),
- has_merge_tree_conflicts: None,
- user_marker: None,
- status_symbols: StatusSymbols::default(),
- statusline: None,
- custom_values: Vec::new(),
- seeded: Default::default(),
- kind: ItemKind::Worktree(Box::new(WorktreeData {
- path: PathBuf::from(path),
- detached: false,
- locked: None,
- prunable: None,
+ let mut item = super::super::model::ListItem::new_worktree(
+ worktrunk::git::WorktreeRef::new(path, Some(branch), "a620bcfe"),
+ WorktreeData {
working_tree_diff: Some(LineDiff::default()),
- working_tree_status: None,
- has_conflicts: None,
- has_working_tree_conflicts: None,
git_operation: Some(None),
is_main,
is_current,
- is_previous: false,
- branch_worktree_mismatch: false,
- duplicate_branch: false,
- })),
- }
+ ..Default::default()
+ },
+ );
+ item.short_sha = "a620bcf".to_string();
+ item.commit = Some(CommitDetails {
+ timestamp: ts,
+ commit_message: "Some commit message".to_string(),
+ });
+ item.counts = counts;
+ item.branch_diff = branch_diff;
+ item.upstream = upstream_status;
+ item.pr_status = Some(None); // loaded, no CI
+ item.summary = Some(summary.map(str::to_string));
+ item
};
let items = vec![
diff --git a/src/commands/list/mod.rs b/src/commands/list/mod.rs
index 95cce35b2..e536c0e26 100644
--- a/src/commands/list/mod.rs
+++ b/src/commands/list/mod.rs
@@ -316,7 +316,7 @@ impl SummaryMetrics {
// may legitimately be named `origin/foo`, so a name-prefix
// heuristic would misclassify it. See `BranchScope` in
// `model/item.rs`.
- match item.kind {
+ match item.kind() {
ItemKind::Branch(BranchScope::Remote) => self.remote_branches += 1,
_ => self.local_branches += 1,
}
diff --git a/src/commands/list/model/item.rs b/src/commands/list/model/item.rs
index 5aca0ce8a..a2ded2128 100644
--- a/src/commands/list/model/item.rs
+++ b/src/commands/list/model/item.rs
@@ -3,11 +3,12 @@
//! This module contains the main data structures used to represent
//! worktrees and branches in `wt list` output.
-use std::path::PathBuf;
+use std::path::Path;
use color_print::cformat;
use worktrunk::git::{
- InProgressOperation, IntegrationReason, IntegrationSignals, LineDiff, check_integration,
+ BranchRef, GitItemId, InProgressOperation, IntegrationReason, IntegrationSignals, LineDiff,
+ WorktreeRef, check_integration,
};
use super::state::{Divergence, MainState, OperationState, WorktreeState};
@@ -44,7 +45,9 @@ fn metadata_worktree_state(data: &WorktreeData) -> WorktreeState {
/// Type-specific data for worktrees
#[derive(Clone, Default)]
pub struct WorktreeData {
- pub path: PathBuf,
+ /// Whether Git reports a detached HEAD. This is not equivalent to a
+ /// missing branch: during a rebase, worktree parsing recovers the branch
+ /// name while Git still reports the checkout as detached.
pub detached: bool,
pub locked: Option<String>,
pub prunable: Option<String>,
@@ -108,8 +111,7 @@ impl WorktreeData {
is_previous: bool,
) -> Self {
Self {
- // Identity fields (known immediately from worktree list)
- path: wt.path.clone(),
+ // Metadata known immediately from the worktree list.
detached: wt.detached,
locked: wt.locked.clone(),
prunable: wt.prunable.clone(),
@@ -125,9 +127,8 @@ impl WorktreeData {
/// Discriminator for item type (worktree vs branch)
///
-/// WorktreeData is boxed to reduce the size of ItemKind enum (304 bytes → 24 bytes).
-/// This reduces stack pressure when passing ListItem by value and improves cache locality
-/// in `Vec<ListItem>` by keeping the discriminant and common fields together.
+/// WorktreeData is boxed to keep the common `ListItem` fields compact and
+/// reduce stack pressure when passing items by value.
#[derive(Clone)]
pub enum ItemKind {
Worktree(Box<WorktreeData>),
@@ -230,8 +231,11 @@ impl BranchScope {
/// or `Option<PrStatus>` (CI may not exist).
#[derive(Clone)]
pub struct ListItem {
- // Common fields (present for both worktrees and branches)
- pub head: String,
+ /// Canonical Git subject captured when the row kind is established. It is
+ /// the source of truth for identity, HEAD, branch, and worktree path.
+ /// List tasks and picker caches share this snapshot instead of rebuilding
+ /// any of those facts downstream.
+ branch_ref: BranchRef,
/// Abbreviated form of `head`, honoring `core.abbrev` and auto-extending
/// for ambiguous prefixes. Always populated when there is a HEAD commit
/// to abbreviate (the `git log` batch in `collect()` emits `%h` for every
@@ -246,8 +250,6 @@ pub struct ListItem {
/// `%ct` — so those cells paint with the skeleton rather than filling in
/// late, and the Commit/Branch columns size to the width git chose.
pub short_sha: String,
- /// Branch name - None for detached worktrees
- pub branch: Option<String>,
pub commit: Option<CommitDetails>,
pub counts: Option<AheadBehind>,
@@ -324,8 +326,8 @@ pub struct ListItem {
/// null (undetermined) instead of presenting a seed as a determined fact.
pub seeded: SeededFacts,
- // Type-specific data (worktree vs branch)
- pub kind: ItemKind,
+ // Kept private so classification cannot drift from `branch_ref`.
+ kind: ItemKind,
}
/// Per-fact-family record of seeded (not computed) values on a [`ListItem`].
@@ -384,10 +386,25 @@ impl ListItem {
}
fn new_branch_with_scope(head: String, branch: String, scope: BranchScope) -> Self {
+ let branch_ref = match scope {
+ BranchScope::Local => BranchRef::local_branch(&branch, &head),
+ BranchScope::Remote => BranchRef::remote_branch(&branch, &head),
+ };
+ Self::new(branch_ref, ItemKind::Branch(scope))
+ }
+
+ /// Create a row for a registered worktree.
+ pub(crate) fn new_worktree(worktree_ref: WorktreeRef, data: WorktreeData) -> Self {
+ Self::new(
+ worktree_ref.into_branch_ref(),
+ ItemKind::Worktree(Box::new(data)),
+ )
+ }
+
+ fn new(branch_ref: BranchRef, kind: ItemKind) -> Self {
Self {
- head,
+ branch_ref,
short_sha: String::new(),
- branch: Some(branch),
commit: None,
counts: None,
branch_diff: None,
@@ -408,12 +425,49 @@ impl ListItem {
statusline: None,
custom_values: Vec::new(),
seeded: SeededFacts::default(),
- kind: ItemKind::Branch(scope),
+ kind,
}
}
pub fn branch_name(&self) -> &str {
- self.branch.as_deref().unwrap_or("(detached)")
+ self.branch().unwrap_or("(detached)")
+ }
+
+ /// Stable identity for this row's Git item.
+ ///
+ /// Kept separate from [`Self::branch_name`] and [`Self::display_name`]:
+ /// both are presentation fallbacks and can collapse distinct rows. The
+ /// identity follows [`GitItemId`]'s canonical rules — worktree path for a
+ /// worktree, full ref for a branch-only row. It is captured when the row
+ /// kind is established, so this accessor performs no filesystem work.
+ pub fn id(&self) -> &GitItemId {
+ self.branch_ref.id()
+ }
+
+ /// Git snapshot shared with list tasks.
+ pub(crate) fn branch_ref(&self) -> &BranchRef {
+ &self.branch_ref
+ }
+
+ pub(crate) fn kind(&self) -> &ItemKind {
+ &self.kind
+ }
+
+ /// Replace this row's kind and branch while preserving the identity
+ /// invariant. The picker's removal morph reclassifies a throwaway clone
+ /// (`build_morph_branch_row`), so the live row's `PickerRowId` is
+ /// unaffected: a morphed row's previews stay under its worktree key.
+ pub(crate) fn reclassify_as_branch(&mut self, scope: BranchScope, branch: String) {
+ let head = self.head().to_string();
+ self.branch_ref = match scope {
+ BranchScope::Local => BranchRef::local_branch(&branch, &head),
+ BranchScope::Remote => BranchRef::remote_branch(&branch, &head),
+ };
+ self.kind = ItemKind::Branch(scope);
+ }
+
+ pub fn branch(&self) -> Option<&str> {
+ self.branch_ref.short_name()
}
/// Short display name for this item — the branch if present, otherwise
@@ -425,7 +479,7 @@ impl ListItem {
/// there, so the column shows this instead (styled `DETACHED`, since a SHA
/// is a legal branch name too).
pub fn display_name(&self) -> &str {
- self.branch.as_deref().unwrap_or(&self.short_sha)
+ self.branch().unwrap_or(&self.short_sha)
}
pub fn is_main(&self) -> bool {
@@ -433,7 +487,7 @@ impl ListItem {
}
pub fn head(&self) -> &str {
- &self.head
+ &self.branch_ref.commit_sha
}
pub fn branch_diff(&self) -> Option<&BranchDiffTotals> {
@@ -454,8 +508,8 @@ impl ListItem {
}
}
- pub fn worktree_path(&self) -> Option<&PathBuf> {
- self.worktree_data().map(|data| &data.path)
+ pub fn worktree_path(&self) -> Option<&Path> {
+ self.branch_ref.worktree_path()
}
/// Determine if the item contains no unique work and can likely be removed.
@@ -922,8 +976,13 @@ mod tests {
let item = ListItem::new_branch("abc123".to_string(), "feature".to_string());
assert_eq!(item.branch_name(), "feature");
- let mut item = ListItem::new_branch("abc123".to_string(), "feature".to_string());
- item.branch = None; // Simulate detached
+ let item = ListItem::new_worktree(
+ WorktreeRef::new("detached", None, "abc123"),
+ WorktreeData {
+ detached: true,
+ ..Default::default()
+ },
+ );
assert_eq!(item.branch_name(), "(detached)");
}
@@ -934,12 +993,19 @@ mod tests {
#[test]
fn test_list_item_display_name_falls_back_to_short_sha() {
let head = "abc123def456abc123def456abc123def456abcd";
- let mut item = ListItem::new_branch(head.to_string(), "feature".to_string());
- item.short_sha = "abc123d".to_string();
- assert_eq!(item.display_name(), "feature");
-
- item.branch = None; // Simulate detached
- assert_eq!(item.display_name(), "abc123d");
+ let mut branch = ListItem::new_branch(head.to_string(), "feature".to_string());
+ branch.short_sha = "abc123d".to_string();
+ assert_eq!(branch.display_name(), "feature");
+
+ let mut detached = ListItem::new_worktree(
+ WorktreeRef::new("detached", None, head),
+ WorktreeData {
+ detached: true,
+ ..Default::default()
+ },
+ );
+ detached.short_sha = "abc123d".to_string();
+ assert_eq!(detached.display_name(), "abc123d");
}
#[test]
@@ -1065,6 +1131,21 @@ mod tests {
assert_eq!(counts.behind, 3);
}
+ #[test]
+ fn construction_and_reclassification_update_list_item_identity() {
+ let root = tempfile::tempdir().unwrap();
+ let worktree_ref = WorktreeRef::new(root.path(), Some("feature"), "abc123");
+ let worktree_id = worktree_ref.clone().into_branch_ref().id().clone();
+ let mut item = ListItem::new_worktree(worktree_ref, WorktreeData::default());
+ assert_eq!(item.id(), &worktree_id);
+
+ item.reclassify_as_branch(BranchScope::Remote, "feature".into());
+ assert_eq!(
+ item.id(),
+ BranchRef::remote_branch("feature", "abc123").id()
+ );
+ }
+
#[test]
fn test_list_item_branch_diff() {
let item = ListItem::new_branch("abc123".to_string(), "feature".to_string());
@@ -1228,7 +1309,7 @@ mod tests {
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 {
+ if let Some(data) = item.worktree_data_mut() {
data.working_tree_status =
Some(WorkingTreeStatus::new(true, false, false, false, false));
}
@@ -1243,7 +1324,7 @@ mod tests {
// `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 {
+ if let Some(data) = item.worktree_data_mut() {
data.has_conflicts = Some(true);
// git_operation deliberately left None
}
@@ -1259,7 +1340,7 @@ mod tests {
// `has_conflicts = Some(false)` but `git_operation = None` →
// gate stays Loading (an operation could still report).
let mut item = make_worktree_item();
- if let ItemKind::Worktree(ref mut data) = item.kind {
+ if let Some(data) = item.worktree_data_mut() {
data.has_conflicts = Some(false);
data.git_operation = None;
}
@@ -1267,7 +1348,7 @@ mod tests {
assert_eq!(item.status_symbols.operation_state, None);
// Set git_operation → gate resolves.
- if let ItemKind::Worktree(ref mut data) = item.kind {
+ if let Some(data) = item.worktree_data_mut() {
data.git_operation = Some(Some(InProgressOperation::Rebase));
}
item.refresh_status_symbols(None);
@@ -1313,7 +1394,7 @@ mod tests {
fn mark_working_tree_clean(item: &mut ListItem) {
use super::super::super::model::WorkingTreeStatus;
use worktrunk::git::LineDiff;
- if let ItemKind::Worktree(ref mut data) = item.kind {
+ if let Some(data) = item.worktree_data_mut() {
data.working_tree_diff = Some(LineDiff::default());
data.working_tree_status = Some(WorkingTreeStatus::default());
data.has_working_tree_conflicts = Some(None); // clean: defer to HEAD probe
@@ -1348,7 +1429,7 @@ mod tests {
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 {
+ if let Some(data) = item.worktree_data_mut() {
data.has_working_tree_conflicts = Some(None);
}
// counts set but is_clean inputs missing → the gate can't even
diff --git a/src/commands/list/render.rs b/src/commands/list/render.rs
index c55ad3a7d..b5a3da811 100644
--- a/src/commands/list/render.rs
+++ b/src/commands/list/render.rs
@@ -307,7 +307,7 @@ impl LayoutConfig {
// Branch scope is known at construction, so its sigil
// (`/`/`|`) renders immediately, dimmed to match the final
// render (and its Status-column twin) — no flash or flicker.
- match &item.kind {
+ match item.kind() {
ItemKind::Worktree(_) => cell.push_styled(format!("{spinner} "), dim),
ItemKind::Branch(scope) => {
cell.push_styled(format!("{} ", scope.gutter_glyph()), dim)
@@ -320,7 +320,7 @@ impl LayoutConfig {
// row's `DETACHED` style, so the cell doesn't restyle as
// the row fills in. Empty text goes unstyled for the reason
// [`Self::render_text_cell`] gives.
- if item.branch.is_none() && !branch.is_empty() {
+ if item.branch().is_none() && !branch.is_empty() {
cell.push_styled(branch.to_string(), DETACHED);
} else {
cell.push_raw(branch.to_string());
@@ -462,8 +462,8 @@ impl ColumnLayout {
let mut cell = StyledLine::new();
// `glyph` + trailing space = the two-cell sigil; the bare glyph
// also feeds the picker's fuzzy-search text (`gutter_glyph`).
- let sigil = format!("{} ", item.kind.gutter_glyph());
- match &item.kind {
+ let sigil = format!("{} ", item.kind().gutter_glyph());
+ match item.kind() {
// Worktree rows are materialized on disk — render bright.
ItemKind::Worktree(_) => cell.push_raw(sigil),
// Branch rows are refs with no working copy — render dim.
@@ -479,7 +479,7 @@ impl ColumnLayout {
// the removable dim still reaches this row's Path and Message
// cells, while yellow keeps the SHA from reading as a branch
// that happens to be named like one.
- let style = if item.branch.is_none() {
+ let style = if item.branch().is_none() {
Some(DETACHED)
} else {
text_style
@@ -531,10 +531,10 @@ impl ColumnLayout {
}
}
ColumnKind::Path => {
- let Some(data) = worktree_data else {
+ let Some(path) = item.worktree_path() else {
return StyledLine::new();
};
- let path_str = shorten_path(&data.path, main_worktree_path);
+ let path_str = shorten_path(path, main_worktree_path);
self.render_text_cell(&path_str, text_style)
}
ColumnKind::Upstream => {
@@ -1542,7 +1542,7 @@ mod tests {
#[test]
fn test_working_diff_placeholder_when_not_loaded() {
use super::super::layout::ColumnLayout;
- use super::super::model::{ItemKind, ListItem};
+ use super::super::model::ListItem;
use worktrunk::styling::{ADDITION, DELETION};
let col = ColumnLayout {
@@ -1568,8 +1568,10 @@ mod tests {
assert!(cell.render().is_empty(), "branch item should be blank");
// Worktree item with working_tree_diff: None → placeholder
- let mut wt_item = ListItem::new_branch("abc123".into(), "feat".into());
- wt_item.kind = ItemKind::Worktree(Box::default());
+ let wt_item = ListItem::new_worktree(
+ worktrunk::git::WorktreeRef::new(".", Some("feat"), "abc123"),
+ Default::default(),
+ );
let cell = col.render_cell(&wt_item, &cell_layout(col.clone()), PLACEHOLDER);
insta::assert_snapshot!(cell.render(), @" ·");
diff --git a/src/commands/picker/items.rs b/src/commands/picker/items.rs
index 40947b3d8..210d38db7 100644
--- a/src/commands/picker/items.rs
+++ b/src/commands/picker/items.rs
@@ -1,8 +1,8 @@
//! Skim item implementations.
//!
//! The unified [`PickerRow`] (a branch/worktree row or a listed `--prs` row,
-//! distinguished by `local: Option<LocalCheckout>`) and the header row, both
-//! implementing `SkimItem` for the interactive selector.
+//! distinguished by [`PickerRowSubject`]) and the header row, both implementing
+//! `SkimItem` for the interactive selector.
use std::borrow::Cow;
use std::collections::HashSet;
@@ -108,10 +108,42 @@ fn anchor_faint_under_selection(
line
}
-/// Cache key for pre-computed previews: `(row-key, mode)`, where the row-key is
-/// the row's [`PickerRow::preview_key`] — a branch for a worktree row, the
-/// `pr:N` / `mr:N` token for a listed `--prs` row.
-pub(super) type PreviewCacheKey = (String, PreviewMode);
+/// Canonical identity of a picker row.
+///
+/// Local rows wrap the Git model's [`worktrunk::git::GitItemId`], so
+/// worktrees are path-keyed and branch-only rows are full-ref-keyed. Listed
+/// PR/MR rows use their structured forge reference. Display labels and skim's
+/// string `output()` tokens are intentionally not identities.
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub(super) enum PickerRowId {
+ Local(worktrunk::git::GitItemId),
+ ChangeRequest(PrRef),
+}
+
+impl PickerRowId {
+ pub(super) fn local(item: &ListItem) -> Self {
+ Self::Local(item.id().clone())
+ }
+
+ pub(super) fn change_request(pr_ref: PrRef) -> Self {
+ Self::ChangeRequest(pr_ref)
+ }
+}
+
+impl std::fmt::Display for PickerRowId {
+ /// Tagged diagnostic form; never parsed back into an identity.
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::Local(key) => key.fmt(f),
+ Self::ChangeRequest(pr_ref) => {
+ write!(f, "{}{}", pr_ref.ref_type().syntax(), pr_ref.number)
+ }
+ }
+ }
+}
+
+/// Cache key for pre-computed previews: `(canonical row identity, mode)`.
+pub(super) type PreviewCacheKey = (PickerRowId, PreviewMode);
/// Cache for pre-computed previews, keyed by [`PreviewCacheKey`].
/// Shared across all PickerRows for background pre-computation. This is the
@@ -414,15 +446,17 @@ pub(super) struct PickerRow {
/// skeleton render and is replaced in place as data arrives; for a `--prs`
/// row it's built once and never mutated.
pub rendered: Arc<Mutex<String>>,
+ /// The row's identity-bearing data. Keeping local checkout data and listed
+ /// change-request identity in one enum makes the row key a derivation of
+ /// the subject rather than parallel state that constructors can mismatch.
+ pub subject: PickerRowSubject,
/// Branch name (the head branch for a `--prs` row). Used by switch
- /// selection, the `pr` pane's branch line, and — for a worktree row — the
- /// preview cache key (see [`Self::preview_key`]).
+ /// selection and the `pr` pane's branch line; never as identity.
pub branch_name: String,
/// Selection result returned by `output()`, and the `shortcut_table` key.
/// `worktree_output_token` (`worktree-path:<path>` or `<branch>`) for a
- /// worktree row; `pr:N` / `mr:N` for a `--prs` row. Distinct from the
- /// *preview* key (see [`Self::preview_key`]): for a worktree row the two
- /// differ (path-token vs branch).
+ /// worktree row; `pr:N` / `mr:N` for a `--prs` row. This is a user-facing
+ /// address token, distinct from the typed preview key.
pub output_token: String,
/// Shared cache for pre-computed previews (all modes)
pub preview_cache: PreviewCache,
@@ -434,11 +468,32 @@ pub(super) struct PickerRow {
/// orchestrator pokes a repaint when that key's compute lands (see
/// [`PreviewNotifier`]).
pub notifier: Arc<PreviewNotifier>,
- /// Local-branch data — `Some` for a local worktree or branch-only row,
- /// `None` for a listed `--prs` row (whose head isn't available as a local
- /// `ListItem`). Its presence is the single axis the preview/output paths
- /// branch on.
- pub local: Option<LocalCheckout>,
+}
+
+/// Identity-bearing data for one picker row.
+///
+/// Local rows derive their canonical key from the contained [`ListItem`];
+/// listed PR/MR rows derive it from their structured forge reference. This is
+/// also the single axis the preview and output paths branch on.
+pub(super) enum PickerRowSubject {
+ Local(LocalCheckout),
+ ChangeRequest(PrRef),
+}
+
+impl PickerRowSubject {
+ fn id(&self) -> PickerRowId {
+ match self {
+ Self::Local(local) => PickerRowId::local(&local.item),
+ Self::ChangeRequest(pr_ref) => PickerRowId::change_request(*pr_ref),
+ }
+ }
+
+ fn local(&self) -> Option<&LocalCheckout> {
+ match self {
+ Self::Local(local) => Some(local),
+ Self::ChangeRequest(_) => None,
+ }
+ }
}
/// The local-git-backed half of a [`PickerRow`]: present for local worktree and
@@ -479,18 +534,9 @@ pub(super) struct LocalCheckout {
}
impl PickerRow {
- /// Key for every preview-cache read, the `pr`-pane memo, and the
- /// `PreviewNotifier` `awaiting` record: the branch name for a worktree row
- /// (its local previews are computed and cached by branch), the `pr:N` /
- /// `mr:N` token for a `--prs` row (its deferred `log`/`comments` fetches key
- /// by that token — see the `prs` module). Git forbids `:` in branch names,
- /// so the two keyspaces never collide.
- fn preview_key(&self) -> &str {
- if self.local.is_some() {
- &self.branch_name
- } else {
- &self.output_token
- }
+ /// Key for every preview-cache read and notifier record.
+ pub(super) fn preview_key(&self) -> PickerRowId {
+ self.subject.id()
}
}
@@ -527,8 +573,9 @@ impl SkimItem for PickerRow {
// An `alt-x` morph turned this worktree row into a branch-only row: its
// selection token is the bare branch name, like any branch row (so a
// later switch/`alt-x` treats it as a branch, and `alt-y` finds it under
- // the re-keyed token). `--prs` rows have no `local`, so they never morph.
- if let Some(local) = &self.local
+ // the re-keyed token). Listed PR/MR rows have no local checkout, so
+ // they never morph.
+ if let Some(local) = self.subject.local()
&& local.morphed.load(Ordering::Relaxed)
{
return Cow::Owned(self.branch_name.clone());
@@ -543,7 +590,7 @@ impl SkimItem for PickerRow {
// (it's per-process picker state); everything else is derived in
// `render_preview`, which takes the mode explicitly so it's testable
// without touching that global state.
- let default_mode = if self.local.is_some() {
+ let default_mode = if self.subject.local().is_some() {
PreviewMode::UnifiedDiff
} else {
PreviewMode::Pr
@@ -556,9 +603,10 @@ impl SkimItem for PickerRow {
// Record what this (selected) row is showing *before* reading the cache,
// so a background fill that lands right after a miss still finds the key
// set and pokes a repaint (see `PreviewNotifier`). Keyed by `preview_key`
- // (branch for a worktree row, `pr:N` for a `--prs` row) so the awaited
- // key matches the one the background fill writes.
- self.notifier.note_awaiting(self.preview_key(), mode);
+ // so the awaited key matches the typed identity the background fill
+ // writes.
+ let preview_key = self.preview_key();
+ self.notifier.note_awaiting(&preview_key, mode);
// A miss on a local-git tab means the placeholder below would sit
// until background precompute reaches this (row, mode) — in a large
// repo, seconds. Ask the demand worker to compute it now; the fill
@@ -569,12 +617,10 @@ impl SkimItem for PickerRow {
// effort: a request parked in the instant before the morph is still
// served from the frozen item.) A row an `alt-r` rebuild superseded
// is refused at the channel via the spawn token it posts.
- if let Some(local) = &self.local
+ if let Some(local) = self.subject.local()
&& mode.is_local_git()
&& !local.morphed.load(Ordering::Relaxed)
- && !self
- .preview_cache
- .contains_key(&(self.preview_key().to_string(), mode))
+ && !self.preview_cache.contains_key(&(preview_key, mode))
{
local.demand.request(
Arc::clone(&local.item),
@@ -606,7 +652,7 @@ enum PrPreview {
/// The three states the `pr` and `comments` tabs branch on, read from a live
/// `pr_status` slot value without cloning the status. The discriminant mirrors
/// [`PickerRow::pr_preview`] exactly. The `comments` pane is byte-identical
-/// within `HasPr` (its thread is branch-keyed and surfaced by `notify_filled`),
+/// within `HasPr` (its thread is row-keyed and surfaced by `notify_filled`),
/// so the collect handler re-renders that tab on a *presence* change, not on
/// every `pr_status` field — re-running it for an unchanged body would only
/// reset the user's scroll. See [`PreviewNotifier`].
@@ -1050,7 +1096,7 @@ impl PickerRow {
// branch-diff/upstream/summary) compute locally for a local row; a `--prs` row has no
// checkout, so its `log` loads from the forge and the rest point at
// the `pr` tab (see `render_listed_pr_mode`).
- _ => match &self.local {
+ _ => match self.subject.local() {
Some(_) => self.preview_for_mode(mode, width, height),
None => self.render_listed_pr_mode(mode),
},
@@ -1076,7 +1122,7 @@ impl PickerRow {
/// The same live availability used by the tab bar and sequential cycling.
fn tab_availability(&self) -> TabAvailability {
- match &self.local {
+ match self.subject.local() {
Some(local) => TabAvailability::worktree(
*local.local_content.lock().unwrap(),
local.has_upstream,
@@ -1098,7 +1144,7 @@ impl PickerRow {
/// for a `--prs` row, whose slot is static, `prs::listed_pr_row` removes it
/// when the row is (re)built on an `alt-r` reload.
pub(super) fn render_pr_pane_cached(&self, width: usize) -> String {
- let key = (self.preview_key().to_string(), PreviewMode::Pr);
+ let key = (self.preview_key(), PreviewMode::Pr);
if let Some(cached) = self.preview_cache.get(&key) {
return cached.value().clone();
}
@@ -1127,10 +1173,10 @@ impl PickerRow {
/// `--prs` row's comments tab. When the branch has an open PR, the thread is
/// fetched in the background (spawned from `progressive_handler`'s
/// `on_update`/`on_skeleton` once the CI fetch surfaces the PR) and read here
- /// from the shared cache, keyed by branch name; a miss is the in-flight
- /// window and shows the same loading placeholder a `--prs` row's tab does. No
- /// PR — or a CI fetch that hasn't resolved yet — mirrors the `pr` tab's
- /// empty/loading states, so the two PR-backed tabs stay consistent. The
+ /// from the shared cache, keyed by canonical row identity; a miss is the
+ /// in-flight window and shows the same loading placeholder a `--prs` row's
+ /// tab does. No PR — or a CI fetch that hasn't resolved yet — mirrors the
+ /// `pr` tab's empty/loading states, so the two PR-backed tabs stay consistent. The
/// background fetch renders at the preview width, so this reads it back
/// without re-wrapping (via `cached_or_loading`).
fn render_comments_pane(&self) -> String {
@@ -1158,7 +1204,7 @@ impl PickerRow {
/// once it lands.
pub(super) fn cached_or_loading(&self, mode: PreviewMode) -> String {
self.preview_cache
- .get(&(self.preview_key().to_string(), mode))
+ .get(&(self.preview_key(), mode))
.map(|v| v.value().clone())
.unwrap_or_else(|| super::prs::pr_deferred_loading(mode))
}
@@ -1183,9 +1229,9 @@ impl PickerRow {
/// (see [`PreviewNotifier`]).
fn preview_for_mode(&self, mode: PreviewMode, width: usize, _height: usize) -> String {
// Reached only for a worktree row (the `Some(_)` arm in `render_preview`),
- // so `preview_key` is the branch — the key the orchestrator precomputes
- // local previews under.
- let cache_key = (self.preview_key().to_string(), mode);
+ // so the key is the canonical local identity the orchestrator
+ // precomputes under.
+ let cache_key = (self.preview_key(), mode);
let content = self
.preview_cache
.get(&cache_key)
@@ -1326,7 +1372,7 @@ impl PickerRow {
/// including committed, staged, unstaged, and untracked changes.
fn compute_unified_diff_preview(repo: &Repository, item: &ListItem, width: usize) -> String {
let branch = item.branch_name();
- let Some(wt_info) = item.worktree_data() else {
+ let Some(worktree_path) = item.worktree_path() else {
// A branch-only row has no mutable worktree state, so its complete
// diff is exactly the committed diff and can reuse that disk cache.
return Self::compute_branch_diff_preview(repo, item, width);
@@ -1335,7 +1381,7 @@ impl PickerRow {
// the complete view is exactly the committed view, so reuse its SHA-keyed
// disk cache and skip the temporary index. A status failure falls through
// to the diff itself, which may still succeed and is the better authority.
- let worktree_state = Self::worktree_diff_state(repo, &wt_info.path);
+ let worktree_state = Self::worktree_diff_state(repo, worktree_path);
if worktree_state == WorktreeDiffState::Clean {
return Self::compute_branch_diff_preview(repo, item, width);
}
@@ -1349,7 +1395,7 @@ impl PickerRow {
return Self::unavailable_diff(branch, "complete diff");
};
- match Self::compute_live_worktree_diff(repo, &wt_info.path, base, width, worktree_state) {
+ match Self::compute_live_worktree_diff(repo, worktree_path, base, width, worktree_state) {
Ok(Some(diff)) => diff,
Ok(None) => {
let base_name = &spec.base_name;
@@ -1367,7 +1413,7 @@ impl PickerRow {
/// Compute Tab 2: staged, unstaged, and untracked changes vs HEAD.
fn compute_working_tree_preview(repo: &Repository, item: &ListItem, width: usize) -> String {
let branch = item.branch_name();
- let Some(wt_info) = item.worktree_data() else {
+ let Some(worktree_path) = item.worktree_path() else {
let reset = Reset;
return cformat!(
"{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} is branch only — press Enter to create worktree\n"
@@ -1375,13 +1421,13 @@ impl PickerRow {
};
let reset = Reset;
- let worktree_state = Self::worktree_diff_state(repo, &wt_info.path);
+ let worktree_state = Self::worktree_diff_state(repo, worktree_path);
if worktree_state == WorktreeDiffState::Clean {
return cformat!(
"{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} has no working-tree changes\n"
);
}
- match Self::compute_live_worktree_diff(repo, &wt_info.path, "HEAD", width, worktree_state) {
+ match Self::compute_live_worktree_diff(repo, worktree_path, "HEAD", width, worktree_state) {
Ok(Some(diff)) => diff,
Ok(None) => cformat!(
"{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} has no working-tree changes\n"
@@ -1793,9 +1839,15 @@ impl PickerRow {
#[cfg(test)]
mod tests {
use super::*;
+ use crate::commands::list::model::WorktreeData;
use ansi_str::AnsiStr;
use insta::assert_snapshot;
+ fn as_worktree(item: ListItem, path: &std::path::Path, data: WorktreeData) -> ListItem {
+ let subject = worktrunk::git::WorktreeRef::new(path, item.branch(), item.head());
+ ListItem::new_worktree(subject, data)
+ }
+
/// `anchor_faint_under_selection` recolors faint text to an explicit gray
/// only on the selected row (and only foreground-less faint spans), so the
/// "safe to delete" gray survives skim's selection highlight while
@@ -1880,7 +1932,11 @@ mod tests {
}
}
- /// Build a worktree-backed [`PickerRow`] (`local: Some`) for tests, with the
+ fn test_local_row_id(branch: &str) -> PickerRowId {
+ PickerRowId::local(&test_local_checkout(branch).item)
+ }
+
+ /// Build a worktree-backed [`PickerRow`] for tests, with the
/// given branch, preview cache, and live `pr_status` slot value; the local
/// signals default (no upstream, no summaries, unknown diff content).
fn worktree_test_row(
@@ -1888,16 +1944,17 @@ mod tests {
preview_cache: PreviewCache,
pr_status: Option<Option<PrStatus>>,
) -> PickerRow {
+ let local = test_local_checkout(branch);
PickerRow {
search_base: String::new(),
gutter: '@',
rendered: Arc::new(Mutex::new(String::new())),
branch_name: branch.to_string(),
output_token: branch.to_string(),
+ subject: PickerRowSubject::Local(local),
preview_cache,
pr_status: Arc::new(Mutex::new(pr_status)),
notifier: PreviewNotifier::detached(),
- local: Some(test_local_checkout(branch)),
}
}
@@ -2014,9 +2071,7 @@ mod tests {
/// `ListItem`, matching exactly what the corresponding pane renders.
#[test]
fn local_content_mirrors_item_diff_state() {
- use crate::commands::list::model::{
- ItemKind, UpstreamStatus, WorkingTreeStatus, WorktreeData,
- };
+ use crate::commands::list::model::{UpstreamStatus, WorkingTreeStatus, WorktreeData};
// A branch-only row has no working tree, so its working-tree tab is empty
// immediately (no loading window). The other signals are still unknown.
@@ -2084,11 +2139,14 @@ mod tests {
// `working_tree` matches the temporary-index diff: tracked and untracked
// changes both count.
let worktree_with = |status: WorkingTreeStatus| {
- let mut item = ListItem::new_branch("abc".into(), "feature".into());
- item.kind = ItemKind::Worktree(Box::new(WorktreeData {
- working_tree_status: Some(status),
- ..Default::default()
- }));
+ let item = as_worktree(
+ ListItem::new_branch("abc".into(), "feature".into()),
+ std::path::Path::new("/tmp/feature"),
+ WorktreeData {
+ working_tree_status: Some(status),
+ ..Default::default()
+ },
+ );
LocalContent::from_item(&item).working_tree
};
// staged, modified, renamed, deleted → tracked content present.
@@ -2105,8 +2163,11 @@ mod tests {
"untracked alone is shown by the working-tree diff"
);
// A worktree whose status task hasn't landed yet stays loading.
- let mut pending = ListItem::new_branch("abc".into(), "feature".into());
- pending.kind = ItemKind::Worktree(Box::default());
+ let pending = as_worktree(
+ ListItem::new_branch("abc".into(), "feature".into()),
+ std::path::Path::new("/tmp/feature"),
+ WorktreeData::default(),
+ );
assert_eq!(LocalContent::from_item(&pending).working_tree, None);
}
@@ -2404,7 +2465,7 @@ mod tests {
let cache_hit = {
let preview_cache: PreviewCache = Arc::new(DashMap::new());
preview_cache.insert(
- ("feature".to_string(), PreviewMode::Summary),
+ (test_local_row_id("feature"), PreviewMode::Summary),
"Add auth module\n\nImplements JWT-based authentication.".to_string(),
);
worktree_test_row("feature", preview_cache, None)
@@ -2607,7 +2668,7 @@ mod tests {
// A PR with the thread already cached → the cached thread is shown.
let cache: PreviewCache = Arc::new(DashMap::new());
cache.insert(
- ("feature".to_string(), PreviewMode::Comments),
+ (test_local_row_id("feature"), PreviewMode::Comments),
"@octocat\nLooks good\n".to_string(),
);
let with_thread = row(pr_status(Some(PrRef::pr(7))), Arc::clone(&cache));
@@ -2805,17 +2866,18 @@ mod tests {
// invalidate the entry the way the collect handler's `on_update` does.
let cache: PreviewCache = Arc::new(DashMap::new());
let slot: PrStatusSlot = Arc::new(Mutex::new(status("First title")));
- let key = ("feature".to_string(), PreviewMode::Pr);
+ let local = test_local_checkout("feature");
+ let key = (PickerRowId::local(&local.item), PreviewMode::Pr);
let row = PickerRow {
search_base: String::new(),
gutter: '@',
rendered: Arc::new(Mutex::new(String::new())),
branch_name: "feature".into(),
output_token: "feature".into(),
+ subject: PickerRowSubject::Local(local),
preview_cache: Arc::clone(&cache),
pr_status: Arc::clone(&slot),
notifier: PreviewNotifier::detached(),
- local: Some(test_local_checkout("feature")),
};
// First render populates the shared cache.
@@ -2903,7 +2965,7 @@ mod tests {
#[test]
fn unified_diff_is_net_change_and_subsidiary_diffs_include_untracked() {
- use crate::commands::list::model::{ItemKind, WorktreeData};
+ use crate::commands::list::model::WorktreeData;
let (t, repo) = repo_with_main();
let shared = t.path().join("shared.txt");
@@ -2925,11 +2987,7 @@ mod tests {
repo.run_command(&["config", "status.showUntrackedFiles", "no"])
.unwrap();
- let mut item = item_at(&repo, "feature");
- item.kind = ItemKind::Worktree(Box::new(WorktreeData {
- path: t.path().to_path_buf(),
- ..Default::default()
- }));
+ let item = as_worktree(item_at(&repo, "feature"), t.path(), WorktreeData::default());
let real_index = repo.current_worktree().git_dir().unwrap().join("index");
let index_before = std::fs::read(&real_index).unwrap();
@@ -2962,7 +3020,7 @@ mod tests {
#[test]
fn worktree_diff_surfaces_full_diff_command_failure() {
- use crate::commands::list::model::{ItemKind, WorktreeData};
+ use crate::commands::list::model::WorktreeData;
let (t, repo) = repo_with_main();
std::fs::write(t.path().join(".gitattributes"), "*.txt diff=explode\n").unwrap();
@@ -2975,11 +3033,7 @@ mod tests {
.unwrap();
std::fs::write(t.path().join("tracked.txt"), "changed\n").unwrap();
- let mut item = item_at(&repo, "main");
- item.kind = ItemKind::Worktree(Box::new(WorktreeData {
- path: t.path().to_path_buf(),
- ..Default::default()
- }));
+ let item = as_worktree(item_at(&repo, "main"), t.path(), WorktreeData::default());
let unified = PickerRow::compute_unified_diff_preview(&repo, &item, 80);
let working = PickerRow::compute_working_tree_preview(&repo, &item, 80);
@@ -3119,14 +3173,10 @@ mod tests {
fn working_tree_preview_clean_worktree_headline() {
// A worktree with no uncommitted changes renders the empty-state
// headline (the diff body is `None`).
- use crate::commands::list::model::{ItemKind, WorktreeData};
+ use crate::commands::list::model::WorktreeData;
let (t, repo) = repo_with_main();
- let mut item = item_at(&repo, "main");
- item.kind = ItemKind::Worktree(Box::new(WorktreeData {
- path: t.path().to_path_buf(),
- ..Default::default()
- }));
+ let item = as_worktree(item_at(&repo, "main"), t.path(), WorktreeData::default());
let output = PickerRow::compute_working_tree_preview(&repo, &item, 80);
assert!(
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rs
index c8fa78e64..0be1bca6f 100644
--- a/src/commands/picker/mod.rs
+++ b/src/commands/picker/mod.rs
@@ -129,7 +129,7 @@ use crate::output::print_json;
use super::hook_plan::{ApprovedHookPlan, HookPlanBuilder};
use super::hooks::HookAnnouncer;
use super::list::collect;
-use super::list::model::{BranchScope, ItemKind, ListItem};
+use super::list::model::{BranchScope, ListItem};
use super::list::progressive::RenderTarget;
use super::list::render::PLACEHOLDER;
use super::repository_ext::{RemoveTarget, RepositoryCliExt};
@@ -595,8 +595,12 @@ impl AltXRemover {
layout.as_ref(),
) {
(Some(handle), Some(layout)) => {
- let (branch_line, branch_local) =
- build_morph_branch_row(layout, &handle.item, default_branch.as_deref());
+ let (branch_line, branch_local) = build_morph_branch_row(
+ layout,
+ &handle.item,
+ &branch,
+ default_branch.as_deref(),
+ );
Some(MorphSlots {
rendered: Arc::clone(&handle.rendered),
morphed: Arc::clone(&handle.morphed),
@@ -816,10 +820,11 @@ struct MorphRevert {
fn build_morph_branch_row(
layout: &crate::commands::list::layout::LayoutConfig,
worktree_item: &ListItem,
+ branch: &str,
default_branch: Option<&str>,
) -> (String, LocalContent) {
let mut branch_item = worktree_item.clone();
- branch_item.kind = ItemKind::Branch(BranchScope::Local);
+ branch_item.reclassify_as_branch(BranchScope::Local, branch.to_string());
branch_item.status_symbols = Default::default();
branch_item.refresh_status_symbols(default_branch);
let line = layout
@@ -1418,8 +1423,9 @@ impl PipelineFactory {
// the skeleton handler's inventory reads all share this one snapshot.
let spawn_repo = if rebuild_repo {
// A refresh recomputes previews too, not just the row inventory.
- // The in-memory preview cache is keyed by `(branch, mode)` with no
- // SHA — the working-tree diff has no stable hash to key on — so a
+ // The in-memory preview cache is keyed by `(row identity, mode)`
+ // with no content signature — the working-tree diff has no stable
+ // hash to key on — so a
// warm entry outlives the branch's commits or working tree moving
// and would re-serve a stale diff / log / summary. `refresh`
// supersedes the prior spawn's still-in-flight producers, rebinds
@@ -1725,16 +1731,15 @@ pub fn handle_picker(
current_worktree.root(),
current_worktree.head_sha(),
) {
- use super::list::model::{ItemKind, ListItem, WorktreeData};
+ use super::list::model::{ListItem, WorktreeData};
// UnifiedDiff resolves its comparison base from the row's HEAD. An
// empty placeholder would let this speculative producer cache an
// error before collection's real row gets a chance to fill the same
// key, so the warm-up only runs with a resolved commit.
- let mut item = ListItem::new_branch(head, branch);
- item.kind = ItemKind::Worktree(Box::new(WorktreeData {
- path,
- ..Default::default()
- }));
+ let item = ListItem::new_worktree(
+ worktrunk::git::WorktreeRef::new(&path, Some(&branch), &head),
+ WorktreeData::default(),
+ );
// num_items doesn't matter for Right (dims independent of it); for
// Down it only affects height, which doesn't alter pager wrapping.
let dims = state
@@ -2526,7 +2531,10 @@ fn switch_pipeline_repo(repo: &Repository, is_recovered: bool) -> anyhow::Result
#[cfg(test)]
pub mod tests {
- use super::items::{LocalCheckout, LocalContent, PickerRow, worktree_output_token};
+ use super::items::{
+ LocalCheckout, LocalContent, PickerRow, PickerRowId, PickerRowSubject,
+ worktree_output_token,
+ };
use super::{
AltXRemover, PickerAction, RemovalEffect, RemoveTarget, drain_stashed_warnings,
install_preview_tab_keybindings, install_shortcut_keybindings, parse_removal_target,
@@ -2534,7 +2542,7 @@ pub mod tests {
resolve_shortcut_branch, resolve_shortcut_url, summary_command_and_hint,
switch_pipeline_repo,
};
- use crate::commands::list::model::{BranchScope, ItemKind, ListItem, WorktreeData};
+ use crate::commands::list::model::{BranchScope, ListItem, WorktreeData};
use crate::commands::worktree::RemovalPlan;
use insta::assert_yaml_snapshot;
use skim::prelude::SkimItem;
@@ -3128,10 +3136,7 @@ pub mod tests {
rendered: Arc::new(Mutex::new(String::new())),
branch_name: branch_name.to_string(),
output_token,
- preview_cache: Arc::new(dashmap::DashMap::new()),
- pr_status,
- notifier: super::preview_notify::PreviewNotifier::detached(),
- local: Some(LocalCheckout {
+ subject: PickerRowSubject::Local(LocalCheckout {
item,
demand: super::preview_orchestrator::PreviewDemand::new(),
spawn_gen: super::preview_orchestrator::SpawnGeneration::default(),
@@ -3140,28 +3145,30 @@ pub mod tests {
local_content: Arc::new(Mutex::new(LocalContent::default())),
morphed: Arc::new(std::sync::atomic::AtomicBool::new(false)),
}),
+ preview_cache: Arc::new(dashmap::DashMap::new()),
+ pr_status,
+ notifier: super::preview_notify::PreviewNotifier::detached(),
}) as Arc<dyn SkimItem>
}
/// Build a `PickerRow` standing in for a detached-worktree row.
fn detached_picker_item(path: &Path) -> Arc<dyn SkimItem> {
- let mut item = ListItem::new_branch("abc123".to_string(), "(detached)".to_string());
- item.branch = None;
- item.kind = ItemKind::Worktree(Box::new(WorktreeData {
- path: path.to_path_buf(),
- detached: true,
- ..Default::default()
- }));
+ let item = ListItem::new_worktree(
+ worktrunk::git::WorktreeRef::new(path, None, "abc123"),
+ WorktreeData {
+ detached: true,
+ ..Default::default()
+ },
+ );
picker_item("(detached)", item)
}
/// Build a `PickerRow` standing in for a branched-worktree row.
fn branched_picker_item(branch: &str, path: &Path) -> Arc<dyn SkimItem> {
- let mut item = ListItem::new_branch("abc123".to_string(), branch.to_string());
- item.kind = ItemKind::Worktree(Box::new(WorktreeData {
- path: path.to_path_buf(),
- ..Default::default()
- }));
+ let item = ListItem::new_worktree(
+ worktrunk::git::WorktreeRef::new(path, Some(branch), "abc123"),
+ WorktreeData::default(),
+ );
picker_item(branch, item)
}
@@ -3189,11 +3196,10 @@ pub mod tests {
Arc<Mutex<String>>,
Arc<std::sync::atomic::AtomicBool>,
) {
- let mut item = ListItem::new_branch("abc123".to_string(), branch.to_string());
- item.kind = ItemKind::Worktree(Box::new(WorktreeData {
- path: path.to_path_buf(),
- ..Default::default()
- }));
+ let item = ListItem::new_worktree(
+ worktrunk::git::WorktreeRef::new(path, Some(branch), "abc123"),
+ WorktreeData::default(),
+ );
let item_arc = Arc::new(item);
let rendered = Arc::new(Mutex::new(format!("+ {branch}")));
let local_content = Arc::new(Mutex::new(LocalContent::default()));
@@ -3204,10 +3210,7 @@ pub mod tests {
rendered: Arc::clone(&rendered),
branch_name: branch.to_string(),
output_token: worktree_output_token(&item_arc, branch),
- preview_cache: Arc::new(dashmap::DashMap::new()),
- pr_status: Arc::new(Mutex::new(None)),
- notifier: super::preview_notify::PreviewNotifier::detached(),
- local: Some(LocalCheckout {
+ subject: PickerRowSubject::Local(LocalCheckout {
item: Arc::clone(&item_arc),
demand: super::preview_orchestrator::PreviewDemand::new(),
spawn_gen: super::preview_orchestrator::SpawnGeneration::default(),
@@ -3216,6 +3219,9 @@ pub mod tests {
local_content: Arc::clone(&local_content),
morphed: Arc::clone(&morphed),
}),
+ preview_cache: Arc::new(dashmap::DashMap::new()),
+ pr_status: Arc::new(Mutex::new(None)),
+ notifier: super::preview_notify::PreviewNotifier::detached(),
});
let token = row.output().to_string();
@@ -3497,7 +3503,7 @@ pub mod tests {
/// A refresh (`alt-r`, `spawn(true)`) drops the warm in-memory preview cache
/// so each rebuilt row recomputes against the fresh repo; the initial spawn
- /// (`spawn(false)`) keeps it warm. The probe entry is keyed under a branch
+ /// (`spawn(false)`) keeps it warm. The probe entry uses a branch-ref identity
/// with no row, so the background precompute never re-fills it — the entry's
/// fate is the clear alone, not a race with recompute.
#[test]
@@ -3507,7 +3513,13 @@ pub mod tests {
let test = worktrunk::testing::TestRepo::with_initial_commit();
let repo = worktrunk::git::Repository::at(test.path()).unwrap();
let factory = test_factory(repo);
- let ghost = ("ghost-branch".to_string(), PreviewMode::WorkingTree);
+ let ghost = (
+ PickerRowId::local(&ListItem::new_branch(
+ "0000000".to_string(),
+ "ghost-branch".to_string(),
+ )),
+ PreviewMode::WorkingTree,
+ );
// Initial spawn (`false`) preserves warm previews.
factory
@@ -4203,11 +4215,10 @@ pub mod tests {
fn test_build_morph_branch_row() {
use ansi_str::AnsiStr;
- let mut worktree_item = ListItem::new_branch("abc123".to_string(), "feature".to_string());
- worktree_item.kind = ItemKind::Worktree(Box::new(WorktreeData {
- path: Path::new("/tmp/wt.feature").to_path_buf(),
- ..Default::default()
- }));
+ let worktree_item = ListItem::new_worktree(
+ worktrunk::git::WorktreeRef::new("/tmp/wt.feature", Some("feature"), "abc123"),
+ WorktreeData::default(),
+ );
let layout = crate::commands::list::layout::calculate_layout_with_width(
std::slice::from_ref(&worktree_item),
&crate::commands::list::columns::all_tasks(),
@@ -4224,7 +4235,8 @@ pub mod tests {
},
);
- let (line, local) = super::build_morph_branch_row(&layout, &worktree_item, Some("main"));
+ let (line, local) =
+ super::build_morph_branch_row(&layout, &worktree_item, "feature", Some("main"));
let plain = line.ansi_strip();
assert!(
plain.trim_start().starts_with('/'),
@@ -4242,7 +4254,7 @@ pub mod tests {
local,
LocalContent::from_item(&{
let mut b = ListItem::new_branch("abc123".to_string(), "feature".to_string());
- b.kind = ItemKind::Branch(BranchScope::Local);
+ b.reclassify_as_branch(BranchScope::Local, "feature".into());
b
}),
"the morphed row's diff signals are the branch's (working_tree empty)"
diff --git a/src/commands/picker/preview_notify.rs b/src/commands/picker/preview_notify.rs
index 477a58930..4e50ae463 100644
--- a/src/commands/picker/preview_notify.rs
+++ b/src/commands/picker/preview_notify.rs
@@ -40,7 +40,7 @@
//! any real change. The collect handler excludes `is_priming` (a list-cell dim
//! hint the pane never draws — see `items::pr_status_pane_eq`) so a
//! cache-prime→live flip that only clears it doesn't reset scroll.
-//! - **`comments` tab** — body is the branch-keyed thread (surfaced by
+//! - **`comments` tab** — body is the row-keyed thread (surfaced by
//! `notify_filled`), invariant to `PrStatus` fields once a PR exists, so it
//! re-runs only on a [`PrPresence`](super::items::PrPresence) change
//! (Loading/NoPr/HasPr), not on every field.
@@ -63,7 +63,7 @@ use std::sync::{Arc, Mutex, OnceLock};
use skim::prelude::Event;
use tokio::sync::mpsc::Sender;
-use super::items::PreviewCacheKey;
+use super::items::{PickerRowId, PreviewCacheKey};
use super::preview::PreviewMode;
/// What about a row's live `pr_status` changed, at the granularity each
@@ -77,7 +77,7 @@ pub(super) struct PrStatusDelta {
/// never draws. Gates the `pr` tab. See `items::pr_status_pane_eq`.
pub(super) pane_changed: bool,
/// The [`PrPresence`](super::items::PrPresence) (Loading/NoPr/HasPr) changed.
- /// Gates the `comments` tab, whose body is otherwise the branch-keyed thread
+ /// Gates the `comments` tab, whose body is otherwise the row-keyed thread
/// surfaced by [`PreviewNotifier::notify_filled`]. Implies `pane_changed`.
pub(super) presence_changed: bool,
}
@@ -98,9 +98,9 @@ pub(super) struct PreviewNotifier {
render_tx: Arc<OnceLock<Sender<Event>>>,
/// The `(row-key, mode)` the selected row's preview is currently showing or
/// awaiting. Written by `*SkimItem::preview` on every render; read on each
- /// background fill. The row-key is the branch name for worktree rows and the
- /// `pr:{N}` / `mr:{N}` token for `--prs` rows — exactly the
- /// [`PreviewCacheKey`] string, so a fill's key compares directly.
+ /// background fill. The typed row key is a canonical Git item identity for
+ /// local rows and a structured PR/MR reference for `--prs` rows — exactly
+ /// the identity in [`PreviewCacheKey`], so a fill's key compares directly.
awaiting: Mutex<Option<PreviewCacheKey>>,
}
@@ -115,8 +115,8 @@ impl PreviewNotifier {
/// Record the `(row-key, mode)` the selected row is rendering, so a matching
/// background fill knows to surface itself. Called from `*SkimItem::preview`
/// before it reads the cache (see the module docstring on ordering).
- pub(super) fn note_awaiting(&self, row_key: &str, mode: PreviewMode) {
- *self.awaiting.lock().unwrap() = Some((row_key.to_string(), mode));
+ pub(super) fn note_awaiting(&self, row_id: &PickerRowId, mode: PreviewMode) {
+ *self.awaiting.lock().unwrap() = Some((row_id.clone(), mode));
}
/// Inject an `Event::RunPreview` if `key` is the preview the selected row is
@@ -130,17 +130,17 @@ impl PreviewNotifier {
}
}
- /// Inject an `Event::RunPreview` if the selected row is `row_key` *and* the
+ /// Inject an `Event::RunPreview` if the selected row is `row_id` *and* the
/// part of `pr_status` its visible tab renders actually changed, so the live
/// `CiStatus` fetch surfaces on its own without resetting the scroll of an
/// unchanged pane. `delta` carries the two per-tab change signals the collect
/// handler computed (see [`PrStatusDelta`]); a diff / log / summary tab reads
/// neither, so it matches nothing and injects nothing.
- pub(super) fn notify_pr_status_changed(&self, row_key: &str, delta: PrStatusDelta) {
+ pub(super) fn notify_pr_status_changed(&self, row_id: &PickerRowId, delta: PrStatusDelta) {
let relevant = {
let awaiting = self.awaiting.lock().unwrap();
awaiting.as_ref().is_some_and(|(k, mode)| {
- k == row_key
+ k == row_id
&& match mode {
PreviewMode::Pr => delta.pane_changed,
PreviewMode::Comments => delta.presence_changed,
@@ -173,6 +173,7 @@ impl PreviewNotifier {
#[cfg(test)]
mod tests {
use super::*;
+ use crate::commands::list::model::ListItem;
/// `notify_pr_status_changed` re-runs the selected row's preview only when
/// the *visible* tab's own change signal fired: the `pr` tab on a pane
@@ -185,6 +186,8 @@ mod tests {
let render_tx = Arc::new(OnceLock::new());
render_tx.set(tx).unwrap();
let notifier = PreviewNotifier::new(render_tx);
+ let feature = PickerRowId::local(&ListItem::new_branch("abc".into(), "feature".into()));
+ let other = PickerRowId::local(&ListItem::new_branch("def".into(), "other".into()));
let pane_only = PrStatusDelta {
pane_changed: true,
@@ -203,21 +206,21 @@ mod tests {
};
// `pr` tab: any pane change re-runs it (e.g. "Fetching…" → resolved PR).
- notifier.note_awaiting("feature", PreviewMode::Pr);
- notifier.notify_pr_status_changed("feature", pane_only);
+ notifier.note_awaiting(&feature, PreviewMode::Pr);
+ notifier.notify_pr_status_changed(&feature, pane_only);
assert_eq!(drain(&mut rx), 1, "a pr-pane change re-runs the pr tab");
// `comments` tab: a pane-only change (no presence flip) does NOT re-run —
- // its body is the unchanged branch-keyed thread, so re-running would only
+ // its body is the unchanged row-keyed thread, so re-running would only
// reset the scroll. A presence change (e.g. NoPr → HasPr) does re-run.
- notifier.note_awaiting("feature", PreviewMode::Comments);
- notifier.notify_pr_status_changed("feature", pane_only);
+ notifier.note_awaiting(&feature, PreviewMode::Comments);
+ notifier.notify_pr_status_changed(&feature, pane_only);
assert_eq!(
drain(&mut rx),
0,
"a pane-only change must not reset a scrolled comments thread"
);
- notifier.notify_pr_status_changed("feature", presence_too);
+ notifier.notify_pr_status_changed(&feature, presence_too);
assert_eq!(
drain(&mut rx),
1,
@@ -225,8 +228,8 @@ mod tests {
);
// A diff tab reads neither signal → never re-runs (preserves diff scroll).
- notifier.note_awaiting("feature", PreviewMode::WorkingTree);
- notifier.notify_pr_status_changed("feature", presence_too);
+ notifier.note_awaiting(&feature, PreviewMode::WorkingTree);
+ notifier.notify_pr_status_changed(&feature, presence_too);
assert_eq!(
drain(&mut rx),
0,
@@ -234,8 +237,8 @@ mod tests {
);
// A different row's update injects nothing.
- notifier.note_awaiting("feature", PreviewMode::Pr);
- notifier.notify_pr_status_changed("other", presence_too);
+ notifier.note_awaiting(&feature, PreviewMode::Pr);
+ notifier.notify_pr_status_changed(&other, presence_too);
assert_eq!(
drain(&mut rx),
0,
diff --git a/src/commands/picker/preview_orchestrator.rs b/src/commands/picker/preview_orchestrator.rs
index 8a2375106..28d094661 100644
--- a/src/commands/picker/preview_orchestrator.rs
+++ b/src/commands/picker/preview_orchestrator.rs
@@ -16,14 +16,15 @@
//! the Pr/Comments panes, but those aren't cache reads.) Session-scoped, and
//! **shared across every
//! `alt-r` spawn** (the one `Arc` is reused). The key is `(row-key, mode)`,
-//! where row-key is the branch for a worktree row or the `pr:N` / `mr:N` token
-//! for a `--prs` row — with **no SHA or content hash**. Two consequences: every
-//! mode shares one key shape (a `--prs` row's forge fetches and a worktree
-//! row's git diffs coexist), and a `git fetch` or new commit that moves a
-//! branch does *not* invalidate the entry — the key is unchanged, so a warm
-//! entry can outlive the content it was computed from. That staleness is
-//! reconciled two ways, both below: per-event invalidation for the PR tabs, and
-//! a wholesale clear on refresh.
+//! where row-key is a canonical Git item identity for a local row or a
+//! structured PR/MR reference for a `--prs` row — with **no content hash**.
+//! Two consequences: every mode shares one key shape (a `--prs` row's forge
+//! fetches and a worktree row's git diffs coexist), and a `git fetch` or new
+//! commit that moves a branch does *not* invalidate the entry — the key is
+//! unchanged, so a warm entry can outlive the content it was computed from.
+//! That staleness is reconciled two ways, both below: per-event invalidation
+//! for the PR tabs, and a wholesale clear on refresh.
+//! Worktrees key by canonical path, while branch-only rows key by full ref.
//!
//! **On-disk** — content-addressed, cross-session, consulted only on an
//! in-memory miss. [`super::preview_cache`] holds Log / BranchDiff /
@@ -156,7 +157,7 @@ use skim::prelude::Event;
use tokio::sync::mpsc::Sender;
use worktrunk::git::Repository;
-use super::items::{PickerRow, PreviewCache, PreviewCacheKey};
+use super::items::{PickerRow, PickerRowId, PreviewCache, PreviewCacheKey};
use super::preview::{LOCAL_GIT_MODES, PreviewMode};
use super::preview_notify::PreviewNotifier;
use super::summary;
@@ -442,7 +443,7 @@ impl PreviewOrchestrator {
if !req.spawn_gen.is_current() {
return;
}
- let key = (req.item.branch_name().to_string(), req.mode);
+ let key = (PickerRowId::local(&req.item), req.mode);
if cache.contains_key(&key) {
return;
}
@@ -452,7 +453,7 @@ impl PreviewOrchestrator {
}));
let Ok((value, log_disk_hit)) = computed else {
tracing::debug!(
- branch = key.0,
+ row = %key.0,
mode = ?key.1,
"preview demand compute panicked; leaving the tab to precompute"
);
@@ -569,7 +570,7 @@ impl PreviewOrchestrator {
if !spawn_gen.is_current() {
return;
}
- let cache_key = (item.branch_name().to_string(), mode);
+ let cache_key = (PickerRowId::local(&item), mode);
if cache.contains_key(&cache_key) {
return;
}
@@ -626,7 +627,7 @@ impl PreviewOrchestrator {
&cache,
&notifier,
&spawn_gen,
- (item.branch_name().to_string(), PreviewMode::Log),
+ (PickerRowId::local(&item), PreviewMode::Log),
rendered,
);
}
@@ -653,7 +654,7 @@ impl PreviewOrchestrator {
&cache,
&notifier,
&spawn_gen,
- (item.branch_name().to_string(), PreviewMode::Summary),
+ (PickerRowId::local(&item), PreviewMode::Summary),
summary,
);
});
@@ -778,7 +779,7 @@ impl PreviewOrchestrator {
pub(super) fn seed_summary_hints(&self, items: &[Arc<ListItem>], hint: &str) {
for item in items {
self.cache.insert(
- (item.branch_name().to_string(), PreviewMode::Summary),
+ (PickerRowId::local(item), PreviewMode::Summary),
hint.to_string(),
);
}
@@ -821,7 +822,7 @@ impl PreviewOrchestrator {
}
/// Preview-cache inventory for the dry-run dump: one sorted
- /// `{branch, mode, bytes, content}` object per cached preview. Content is
+ /// `{row_id, mode, bytes, content}` object per cached preview. Content is
/// included because dry-run integration tests need to distinguish a real
/// preview from an equally non-empty error pane; the dump is test-only.
pub(super) fn cache_entries_json(&self) -> serde_json::Value {
@@ -829,9 +830,9 @@ impl PreviewOrchestrator {
.cache
.iter()
.map(|e| {
- let (branch, mode) = e.key();
+ let (row, mode) = e.key();
(
- branch.clone(),
+ row.to_string(),
*mode as u8,
e.value().len(),
e.value().clone(),
@@ -842,9 +843,9 @@ impl PreviewOrchestrator {
entries
.into_iter()
- .map(|(branch, mode, bytes, content)| {
+ .map(|(row, mode, bytes, content)| {
serde_json::json!({
- "branch": branch,
+ "row_id": row,
"mode": mode,
"bytes": bytes,
"content": content,
@@ -867,16 +868,36 @@ impl Drop for PreviewOrchestrator {
#[cfg(test)]
mod tests {
use super::*;
- use crate::commands::list::model::{ItemKind, WorktreeData};
+ use crate::commands::list::model::WorktreeData;
use std::fs;
use worktrunk::testing::TestRepo;
+ fn as_worktree(item: ListItem, path: &std::path::Path, data: WorktreeData) -> ListItem {
+ let subject = worktrunk::git::WorktreeRef::new(path, item.branch(), item.head());
+ ListItem::new_worktree(subject, data)
+ }
+
fn orch_for(t: &TestRepo) -> PreviewOrchestrator {
// No render_tx published, so fills don't notify — these tests assert on
// the cache, not on skim repaints (see `fill_notifies_only_awaited_key`).
PreviewOrchestrator::new(Repository::at(t.path()).unwrap(), Arc::new(OnceLock::new()))
}
+ fn item_key(item: &ListItem) -> PickerRowId {
+ PickerRowId::local(item)
+ }
+
+ fn branch_key(branch: &str) -> PickerRowId {
+ item_key(&ListItem::new_branch(
+ "0000000".to_string(),
+ branch.to_string(),
+ ))
+ }
+
+ fn pr_key(number: u64) -> PickerRowId {
+ PickerRowId::change_request(crate::commands::list::ci_status::PrRef::pr(number))
+ }
+
fn dirty_worktree_item() -> (TestRepo, Arc<ListItem>) {
let t = TestRepo::new();
fs::write(t.path().join("README.md"), "# Project\n").unwrap();
@@ -891,14 +912,25 @@ mod tests {
.unwrap()
.trim()
.to_string();
- let mut item = ListItem::new_branch(head, "main".to_string());
- item.kind = ItemKind::Worktree(Box::new(WorktreeData {
- path: t.path().to_path_buf(),
- ..Default::default()
- }));
+ let item = as_worktree(
+ ListItem::new_branch(head, "main".to_string()),
+ t.path(),
+ WorktreeData::default(),
+ );
(t, Arc::new(item))
}
+ fn detached_worktree_item(path: &std::path::Path, head: &str) -> Arc<ListItem> {
+ let item = ListItem::new_worktree(
+ worktrunk::git::WorktreeRef::new(path, None, head),
+ WorktreeData {
+ detached: true,
+ ..Default::default()
+ },
+ );
+ Arc::new(item)
+ }
+
/// End-to-end: orchestrator spawns real previews, populates the cache.
/// Regression test for the "previews never load" class of bugs — if the
/// spawn pipeline silently fails, this catches it without needing skim.
@@ -921,8 +953,9 @@ mod tests {
);
orch.wait_for_idle();
- let wt_key = ("main".to_string(), PreviewMode::WorkingTree);
- let log_key = ("main".to_string(), PreviewMode::Log);
+ let row_id = item_key(&item);
+ let wt_key = (row_id.clone(), PreviewMode::WorkingTree);
+ let log_key = (row_id, PreviewMode::Log);
assert!(
orch.cache.contains_key(&wt_key),
"WorkingTree preview not cached"
@@ -934,6 +967,73 @@ mod tests {
);
}
+ /// Two detached worktrees can point at the same commit while carrying
+ /// different mutable state. Visiting the clean one first must not make the
+ /// dirty one's producer short-circuit against the clean preview.
+ #[test]
+ fn detached_worktrees_at_same_commit_have_distinct_preview_ids() {
+ let t = TestRepo::with_initial_commit();
+ let linked = tempfile::tempdir().unwrap();
+ let clean_path = linked.path().join("clean");
+ let dirty_path = linked.path().join("dirty");
+ let clean_arg = clean_path.to_str().unwrap();
+ let dirty_arg = dirty_path.to_str().unwrap();
+ t.repo
+ .run_command(&["worktree", "add", "--detach", clean_arg, "HEAD"])
+ .unwrap();
+ t.repo
+ .run_command(&["worktree", "add", "--detach", dirty_arg, "HEAD"])
+ .unwrap();
+ fs::write(dirty_path.join("file.txt"), "hello\nchanged\n").unwrap();
+
+ let head = t
+ .repo
+ .run_command(&["rev-parse", "HEAD"])
+ .unwrap()
+ .trim()
+ .to_string();
+ let clean = detached_worktree_item(&clean_path, &head);
+ let dirty = detached_worktree_item(&dirty_path, &head);
+ let clean_key = item_key(&clean);
+ let dirty_key = item_key(&dirty);
+ assert_ne!(clean_key, dirty_key, "worktree path is part of identity");
+
+ let orch = orch_for(&t);
+ orch.spawn_preview(
+ &orch.generation(),
+ Arc::clone(&clean),
+ PreviewMode::UnifiedDiff,
+ (80, 24),
+ );
+ orch.wait_for_idle();
+ orch.spawn_preview(
+ &orch.generation(),
+ Arc::clone(&dirty),
+ PreviewMode::UnifiedDiff,
+ (80, 24),
+ );
+ orch.wait_for_idle();
+
+ let clean_preview = orch
+ .cache
+ .get(&(clean_key, PreviewMode::UnifiedDiff))
+ .expect("clean preview cached")
+ .clone();
+ let dirty_preview = orch
+ .cache
+ .get(&(dirty_key, PreviewMode::UnifiedDiff))
+ .expect("dirty preview cached")
+ .clone();
+ assert!(
+ !clean_preview.contains("changed"),
+ "clean checkout preview: {clean_preview:?}"
+ );
+ assert!(
+ dirty_preview.contains("file.txt") && dirty_preview.contains("changed"),
+ "dirty checkout preview: {dirty_preview:?}"
+ );
+ }
+
#[test]
fn duplicate_spawn_short_circuits() {
let (t, item) = dirty_worktree_item();
@@ -946,12 +1046,8 @@ mod tests {
(80, 24),
);
orch.wait_for_idle();
- let first = orch
- .cache
- .get(&("main".to_string(), PreviewMode::WorkingTree))
- .unwrap()
- .value()
- .clone();
+ let key = (item_key(&item), PreviewMode::WorkingTree);
+ let first = orch.cache.get(&key).unwrap().value().clone();
// Second spawn should hit `contains_key` and skip.
orch.spawn_preview(
@@ -961,12 +1057,7 @@ mod tests {
(80, 24),
);
orch.wait_for_idle();
- let second = orch
- .cache
- .get(&("main".to_string(), PreviewMode::WorkingTree))
- .unwrap()
- .value()
- .clone();
+ let second = orch.cache.get(&key).unwrap().value().clone();
assert_eq!(first, second);
}
@@ -989,7 +1080,7 @@ mod tests {
assert!(
orch.cache
- .contains_key(&("main".to_string(), PreviewMode::Summary)),
+ .contains_key(&(item_key(&item), PreviewMode::Summary)),
"Summary entry not cached"
);
}
@@ -1034,7 +1125,7 @@ mod tests {
let in_memory = orch
.cache
- .get(&("main".to_string(), PreviewMode::Log))
+ .get(&(item_key(&item), PreviewMode::Log))
.expect("in-memory entry present")
.clone();
assert!(
@@ -1087,57 +1178,43 @@ mod tests {
let orch = orch_for(&t);
// A populated value lands in the cache under its key.
- orch.spawn_compute(
- &orch.generation(),
- ("pr:7".to_string(), PreviewMode::Log),
- |_| Some("commit list".to_string()),
- );
+ orch.spawn_compute(&orch.generation(), (pr_key(7), PreviewMode::Log), |_| {
+ Some("commit list".to_string())
+ });
orch.wait_for_idle();
assert_eq!(
orch.cache
- .get(&("pr:7".to_string(), PreviewMode::Log))
+ .get(&(pr_key(7), PreviewMode::Log))
.map(|v| v.clone()),
Some("commit list".to_string())
);
// A second spawn for the same key short-circuits on `contains_key`, so
// the original value survives even though this closure would overwrite.
- orch.spawn_compute(
- &orch.generation(),
- ("pr:7".to_string(), PreviewMode::Log),
- |_| Some("REPLACED".to_string()),
- );
+ let replacement = Some("REPLACED".to_string());
+ let duplicate_key = (pr_key(7), PreviewMode::Log);
+ orch.spawn_compute(&orch.generation(), duplicate_key, move |_| replacement);
orch.wait_for_idle();
assert_eq!(
orch.cache
- .get(&("pr:7".to_string(), PreviewMode::Log))
+ .get(&(pr_key(7), PreviewMode::Log))
.map(|v| v.clone()),
Some("commit list".to_string()),
"duplicate key short-circuits"
);
// `None` (forge failure) and `Some("")` both leave the slot empty.
- orch.spawn_compute(
- &orch.generation(),
- ("pr:9".to_string(), PreviewMode::Log),
- |_| None,
- );
- orch.spawn_compute(
- &orch.generation(),
- ("pr:8".to_string(), PreviewMode::Log),
- |_| Some(String::new()),
- );
+ orch.spawn_compute(&orch.generation(), (pr_key(9), PreviewMode::Log), |_| None);
+ orch.spawn_compute(&orch.generation(), (pr_key(8), PreviewMode::Log), |_| {
+ Some(String::new())
+ });
orch.wait_for_idle();
assert!(
- !orch
- .cache
- .contains_key(&("pr:9".to_string(), PreviewMode::Log)),
+ !orch.cache.contains_key(&(pr_key(9), PreviewMode::Log)),
"None is not cached"
);
assert!(
- !orch
- .cache
- .contains_key(&("pr:8".to_string(), PreviewMode::Log)),
+ !orch.cache.contains_key(&(pr_key(8), PreviewMode::Log)),
"empty string is not cached"
);
}
@@ -1148,13 +1225,14 @@ mod tests {
/// not depend on speculative bulk precompute.
#[test]
fn preview_miss_is_served_by_demand_worker() {
- use super::super::items::{LocalCheckout, LocalContent, PickerRow};
+ use super::super::items::{LocalCheckout, LocalContent, PickerRow, PickerRowSubject};
use skim::prelude::{PreviewContext, SkimItem};
use std::sync::Mutex;
use std::sync::atomic::AtomicBool;
let (t, item) = dirty_worktree_item();
let orch = orch_for(&t);
+ let row_id = item_key(&item);
let row = PickerRow {
search_base: String::new(),
@@ -1162,10 +1240,7 @@ mod tests {
rendered: Arc::new(Mutex::new(String::new())),
branch_name: "main".to_string(),
output_token: "main".to_string(),
- preview_cache: Arc::clone(&orch.cache),
- pr_status: Arc::new(Mutex::new(None)),
- notifier: Arc::clone(orch.notifier()),
- local: Some(LocalCheckout {
+ subject: PickerRowSubject::Local(LocalCheckout {
item: Arc::clone(&item),
demand: Arc::clone(orch.demand()),
spawn_gen: orch.generation(),
@@ -1174,6 +1249,9 @@ mod tests {
local_content: Arc::new(Mutex::new(LocalContent::default())),
morphed: Arc::new(AtomicBool::new(false)),
}),
+ preview_cache: Arc::clone(&orch.cache),
+ pr_status: Arc::new(Mutex::new(None)),
+ notifier: Arc::clone(orch.notifier()),
};
// The picker opens on UnifiedDiff — the process-global default tab,
@@ -1196,7 +1274,7 @@ mod tests {
// The demand worker fills the key with the real diff. Bounded poll so
// a dead worker fails instead of hanging the suite.
- let key = ("main".to_string(), PreviewMode::UnifiedDiff);
+ let key = (row_id, PreviewMode::UnifiedDiff);
let deadline = std::time::Instant::now() + Duration::from_secs(60);
while !orch.cache.contains_key(&key) {
assert!(
@@ -1218,11 +1296,11 @@ mod tests {
let head = first.head().to_string();
t.repo.run_command(&["branch", "branch-only"]).unwrap();
- let mut offscreen = ListItem::new_branch(head.clone(), "offscreen".to_string());
- offscreen.kind = ItemKind::Worktree(Box::new(WorktreeData {
- path: t.path().to_path_buf(),
- ..Default::default()
- }));
+ let offscreen = as_worktree(
+ ListItem::new_branch(head.clone(), "offscreen".to_string()),
+ &t.path().join("offscreen"),
+ WorktreeData::default(),
+ );
let offscreen = Arc::new(offscreen);
let branch = Arc::new(ListItem::new_branch(head, "branch-only".to_string()));
@@ -1238,12 +1316,12 @@ mod tests {
assert!(
!orch
.cache
- .contains_key(&("offscreen".to_string(), PreviewMode::UnifiedDiff)),
+ .contains_key(&(item_key(&offscreen), PreviewMode::UnifiedDiff)),
"off-screen worktree should wait for selected-row demand"
);
assert!(
orch.cache
- .contains_key(&("branch-only".to_string(), PreviewMode::UnifiedDiff)),
+ .contains_key(&(item_key(&branch), PreviewMode::UnifiedDiff)),
"branch-only default should be prewarmed from the committed diff"
);
}
@@ -1255,7 +1333,8 @@ mod tests {
fn serve_demand_skips_already_filled_key() {
let (t, item) = dirty_worktree_item();
let orch = orch_for(&t);
- let key = ("main".to_string(), PreviewMode::WorkingTree);
+ let row_id = item_key(&item);
+ let key = (row_id.clone(), PreviewMode::WorkingTree);
orch.fill_external(&orch.generation(), key.clone(), "already here".to_string());
PreviewOrchestrator::serve_demand(
@@ -1286,6 +1365,7 @@ mod tests {
fn serve_demand_contains_a_panicking_compute() {
let (t, item) = dirty_worktree_item();
let orch = orch_for(&t);
+ let row_id = item_key(&item);
PreviewOrchestrator::serve_demand(
&orch.cache,
@@ -1301,9 +1381,7 @@ mod tests {
);
assert!(
- !orch
- .cache
- .contains_key(&("main".to_string(), PreviewMode::Pr)),
+ !orch.cache.contains_key(&(row_id, PreviewMode::Pr)),
"a panicked compute fills nothing"
);
}
@@ -1324,6 +1402,7 @@ mod tests {
super::super::preview_cache::write_log(&repo, item.head(), 80, 24, &stale);
let orch = orch_for(&t);
+ let row_id = item_key(&item);
PreviewOrchestrator::serve_demand(
&orch.cache,
orch.notifier(),
@@ -1340,7 +1419,7 @@ mod tests {
let in_memory = orch
.cache
- .get(&("main".to_string(), PreviewMode::Log))
+ .get(&(row_id, PreviewMode::Log))
.expect("in-memory entry present")
.clone();
assert!(
@@ -1360,6 +1439,7 @@ mod tests {
let (t, item) = dirty_worktree_item();
let orch = orch_for(&t);
let stale = orch.generation();
+ let row_id = item_key(&item);
orch.refresh(Repository::at(t.path()).unwrap());
@@ -1371,7 +1451,7 @@ mod tests {
(80, 24),
);
orch.spawn_summary(&stale, Arc::clone(&item), "/bin/cat".to_string());
- orch.spawn_compute(&stale, ("pr:1".to_string(), PreviewMode::Log), |_| {
+ orch.spawn_compute(&stale, (pr_key(1), PreviewMode::Log), |_| {
Some("stale".to_string())
});
PreviewOrchestrator::spawn_log_refresh(
@@ -1390,7 +1470,7 @@ mod tests {
&orch.cache,
orch.notifier(),
&stale,
- ("main".to_string(), PreviewMode::WorkingTree),
+ (row_id.clone(), PreviewMode::WorkingTree),
"stale".to_string(),
);
assert!(
@@ -1406,8 +1486,7 @@ mod tests {
);
orch.wait_for_idle();
assert!(
- orch.cache
- .contains_key(&("main".to_string(), PreviewMode::WorkingTree)),
+ orch.cache.contains_key(&(row_id, PreviewMode::WorkingTree)),
"the live spawn's fill lands"
);
}
@@ -1521,16 +1600,18 @@ mod tests {
let render_tx = Arc::new(OnceLock::new());
render_tx.set(tx).unwrap();
let orch = PreviewOrchestrator::new(Repository::at(t.path()).unwrap(), render_tx);
+ let main = branch_key("main");
+ let feature = branch_key("feature");
// The selected row is showing main's working-tree diff (a cache miss, so
// it's awaiting that key).
orch.notifier()
- .note_awaiting("main", PreviewMode::WorkingTree);
+ .note_awaiting(&main, PreviewMode::WorkingTree);
// The awaited compute lands → skim is poked to repaint.
orch.fill_external(
&orch.generation(),
- ("main".to_string(), PreviewMode::WorkingTree),
+ (main.clone(), PreviewMode::WorkingTree),
"diff".to_string(),
);
assert!(
@@ -1541,12 +1622,12 @@ mod tests {
// Fills for other rows / other tabs must not poke — no preview thrash.
orch.fill_external(
&orch.generation(),
- ("feature".to_string(), PreviewMode::WorkingTree),
+ (feature, PreviewMode::WorkingTree),
"x".to_string(),
);
orch.fill_external(
&orch.generation(),
- ("main".to_string(), PreviewMode::Log),
+ (main, PreviewMode::Log),
"y".to_string(),
);
assert!(
@@ -1560,17 +1641,17 @@ mod tests {
let t = TestRepo::new();
let orch = orch_for(&t);
orch.cache.insert(
- ("branch-a".to_string(), PreviewMode::WorkingTree),
+ (branch_key("branch-a"), PreviewMode::WorkingTree),
"x".to_string(),
);
orch.cache
- .insert(("branch-b".to_string(), PreviewMode::Log), "xy".to_string());
+ .insert((branch_key("branch-b"), PreviewMode::Log), "xy".to_string());
// Structural assertion — future field additions shouldn't flake the test.
let entries = orch.cache_entries_json();
let entries = entries.as_array().expect("entries array");
assert_eq!(entries.len(), 2);
for e in entries {
- assert!(e["branch"].is_string());
+ assert!(e["row_id"].is_string());
assert!(e["mode"].is_number());
assert!(e["bytes"].is_number());
assert!(e["content"].is_string());
diff --git a/src/commands/picker/progressive_handler.rs b/src/commands/picker/progressive_handler.rs
index 19e994a32..fe6bdf6c9 100644
--- a/src/commands/picker/progressive_handler.rs
+++ b/src/commands/picker/progressive_handler.rs
@@ -42,8 +42,6 @@ use skim::prelude::*;
use worktrunk::git::Repository;
use worktrunk::styling::{HINT_SYMBOL, StyledLine};
-use super::super::list::ci_status::PrStatus;
-
/// Minimum gap between repaint pokes during collection. Holds the redraw rate
/// at ~60fps so a burst of task results can't flood skim's (effectively
/// unbounded) event channel ahead of the user's key presses. A directly-sent
@@ -52,8 +50,9 @@ const RENDER_THROTTLE: Duration = Duration::from_millis(16);
use super::items::{
HeaderFlash, HeaderLoading, HeaderSkimItem, LayoutSlot, LocalCheckout, LocalContent,
- LocalContentSlot, MorphHandle, PickerRow, PrStatusSlot, PreviewCache, RowShortcutData, RowUrl,
- ShortcutTable, pr_presence, pr_status_pane_eq, worktree_output_token,
+ LocalContentSlot, MorphHandle, PickerRow, PickerRowId, PickerRowSubject, PrStatusSlot,
+ PreviewCache, RowShortcutData, RowUrl, ShortcutTable, pr_presence, pr_status_pane_eq,
+ worktree_output_token,
};
use super::preview::PreviewMode;
use super::preview_notify::PrStatusDelta;
@@ -194,18 +193,11 @@ impl PickerHandler {
/// repeated `on_update`s short-circuit — and a *changed* number (a reused
/// branch, a stale prime corrected by the live fetch) drops the now-wrong
/// cached thread and re-fetches, keeping the `comments` tab consistent with
- /// the `pr` tab. Keyed by branch name — `--prs` rows key by their `pr:{N}`
- /// token, and git forbids `:` in branch names, so the two keyspaces never
- /// collide.
- fn maybe_spawn_comments(
- &self,
- idx: usize,
- branch_name: &str,
- pr_status: &Option<Option<PrStatus>>,
- ) {
+ /// the `pr` tab. Both local and `--prs` rows use their structured row ID.
+ fn maybe_spawn_comments(&self, idx: usize, item: &ListItem) {
// A superseded handler (its collect thread draining past an `alt-r`)
// must not act at all: its corrected-number path below *removes* the
- // shared `(branch, Comments)` entry — possibly the one the live spawn
+ // shared `(row, Comments)` entry — possibly the one the live spawn
// just fetched — and its replacement fetch would then drop at `fill`
// on the stale token, stranding the tab on its loading placeholder
// (nothing else refills Comments; the live handler's dedup slot
@@ -213,7 +205,7 @@ impl PickerHandler {
if !self.spawn_gen.is_current() {
return;
}
- let Some(Some(status)) = pr_status else {
+ let Some(Some(status)) = &item.pr_status else {
return;
};
let Some(pr_ref) = status.number else { return };
@@ -237,16 +229,17 @@ impl PickerHandler {
if previous == number {
return; // this PR's comments are already fetched (or in flight)
}
+ let row_id = PickerRowId::local(item);
if previous != 0 {
// The live fetch corrected the PR number — drop the stale thread so
// the re-fetch (below) replaces it rather than serving the old PR.
self.preview_cache
- .remove(&(branch_name.to_string(), PreviewMode::Comments));
+ .remove(&(row_id.clone(), PreviewMode::Comments));
}
super::prs::spawn_worktree_comments_fetch(
&self.orchestrator,
&self.spawn_gen,
- branch_name.to_string(),
+ row_id,
number as u32,
status.updated_at.clone(),
self.preview_dims.0,
@@ -262,11 +255,11 @@ impl PickerHandler {
fn collect_shown_branches(items: &[ListItem]) -> HashSet<String> {
let mut shown = HashSet::new();
for item in items {
- let Some(name) = item.branch.as_deref() else {
+ let Some(name) = item.branch() else {
continue;
};
shown.insert(name.to_string());
- if matches!(item.kind, ItemKind::Branch(BranchScope::Remote))
+ if matches!(item.kind(), ItemKind::Branch(BranchScope::Remote))
&& let Some((_, bare)) = name.split_once('/')
{
shown.insert(bare.to_string());
@@ -373,7 +366,6 @@ impl PickerProgressHandler for PickerHandler {
let path_str = item
.worktree_path()
.map(|p| {
- let p = p.as_path();
path_base
.as_deref()
.and_then(|base| p.strip_prefix(base).ok())
@@ -396,7 +388,7 @@ impl PickerProgressHandler for PickerHandler {
// `!` is skim's inverse-match operator, so only the bare number
// filters those (see
// `folded_pr_reference_filters_under_skims_default_engine`).
- let gutter = item.kind.gutter_glyph();
+ let gutter = item.kind().gutter_glyph();
// `display_name`, not `branch_name`: a detached row shows its
// abbreviated HEAD in the Branch column, so that's what the user
// reads and types. `branch_name`'s `"(detached)"` matches nothing
@@ -437,7 +429,7 @@ impl PickerProgressHandler for PickerHandler {
// collector's mutation surfaces on the same item skim renders.
let morphed = Arc::new(AtomicBool::new(false));
let morph = (item_arc.worktree_data().is_some()
- && item_arc.branch.is_some()
+ && item_arc.branch().is_some()
&& !item_arc.is_main())
.then(|| MorphHandle {
item: Arc::clone(&item_arc),
@@ -454,7 +446,7 @@ impl PickerProgressHandler for PickerHandler {
shortcut_map.insert(
output_token.clone(),
RowShortcutData {
- branch: item_arc.branch.clone(),
+ branch: item_arc.branch().map(str::to_string),
url: RowUrl::Live(Arc::clone(&pr_status_arc)),
morph,
},
@@ -464,12 +456,7 @@ impl PickerProgressHandler for PickerHandler {
search_base,
gutter,
rendered: rendered_arc,
- branch_name,
- output_token,
- preview_cache: Arc::clone(&self.preview_cache),
- pr_status: pr_status_arc,
- notifier: Arc::clone(self.orchestrator.notifier()),
- local: Some(LocalCheckout {
+ subject: PickerRowSubject::Local(LocalCheckout {
item: Arc::clone(&item_arc),
demand: Arc::clone(self.orchestrator.demand()),
spawn_gen: self.spawn_gen.clone(),
@@ -478,6 +465,11 @@ impl PickerProgressHandler for PickerHandler {
local_content: local_content_arc,
morphed,
}),
+ branch_name,
+ output_token,
+ preview_cache: Arc::clone(&self.preview_cache),
+ pr_status: pr_status_arc,
+ notifier: Arc::clone(self.orchestrator.notifier()),
}) as Arc<dyn SkimItem>);
}
@@ -545,7 +537,7 @@ impl PickerProgressHandler for PickerHandler {
// skeleton time — kick off its `comments` fetch now so the tab is warm.
// Rows whose PR only surfaces later get theirs from `on_update`.
for (idx, item) in list_items.iter().enumerate() {
- self.maybe_spawn_comments(idx, item.branch_name(), &item.pr_status);
+ self.maybe_spawn_comments(idx, item);
}
// Static Summary hint is a synchronous in-memory insert, no
// contention concern. Pre-fill every row at skeleton time so the
@@ -563,6 +555,7 @@ impl PickerProgressHandler for PickerHandler {
}
fn on_update(&self, idx: usize, rendered: String, item: &ListItem) {
+ let row_id = PickerRowId::local(item);
if let Some(slots) = self.rendered_slots.get()
&& let Some(slot) = slots.get(idx)
{
@@ -595,7 +588,7 @@ impl PickerProgressHandler for PickerHandler {
// re-renders from the status just mirrored — see
// `PickerRow::render_pr_pane_cached`.
self.preview_cache
- .remove(&(item.branch_name().to_string(), PreviewMode::Pr));
+ .remove(&(row_id.clone(), PreviewMode::Pr));
}
// Mirror the row's live diff-content signals so the `working_tree` /
// `branch_diff` / `upstream` tabs dim once their diff is known empty.
@@ -609,7 +602,7 @@ impl PickerProgressHandler for PickerHandler {
// If this update is where the row's PR first surfaced, kick off its
// `comments` background fetch (once per row) so the `comments` tab loads
// the thread — the same fetch a `--prs` row makes.
- self.maybe_spawn_comments(idx, item.branch_name(), &item.pr_status);
+ self.maybe_spawn_comments(idx, item);
// `request_render` sends `Event::Render`, which repaints the *list* row
// (its CI/status cells just changed) but does NOT re-run the preview.
// When the `pr` pane changed, poke a `RunPreview` so the selected row's
@@ -624,7 +617,7 @@ impl PickerProgressHandler for PickerHandler {
if delta.pane_changed {
self.orchestrator
.notifier()
- .notify_pr_status_changed(item.branch_name(), delta);
+ .notify_pr_status_changed(&row_id, delta);
}
self.request_render(false);
}
@@ -674,9 +667,14 @@ impl PickerProgressHandler for PickerHandler {
#[cfg(test)]
mod tests {
use super::*;
- use crate::commands::list::model::ListItem;
+ use crate::commands::list::model::{ListItem, WorktreeData};
use worktrunk::testing::TestRepo;
+ fn as_worktree(item: ListItem, path: &std::path::Path, data: WorktreeData) -> ListItem {
+ let subject = worktrunk::git::WorktreeRef::new(path, item.branch(), item.head());
+ ListItem::new_worktree(subject, data)
+ }
+
/// Build a handler with explicit `repo` (the per-spawn inventory source)
/// and `orchestrator` (preview compute). Diverging the two lets a test
/// prove which one `on_skeleton`'s inventory reads consult. `render_tx` is
@@ -734,6 +732,13 @@ mod tests {
(handler, test, rx)
}
+ fn branch_key(branch: &str) -> PickerRowId {
+ PickerRowId::local(&ListItem::new_branch(
+ "0000000".to_string(),
+ branch.to_string(),
+ ))
+ }
+
fn header(text: &str) -> StyledLine {
let mut line = StyledLine::new();
line.push_raw(text);
@@ -754,7 +759,7 @@ mod tests {
/// strips to a relative tail only if `on_skeleton` consulted `self.repo`.
#[test]
fn on_skeleton_reads_inventory_from_handler_repo_not_orchestrator() {
- use crate::commands::list::model::{ItemKind, WorktreeData};
+ use crate::commands::list::model::WorktreeData;
let self_repo = TestRepo::with_initial_commit();
let orchestrator_repo = TestRepo::with_initial_commit();
@@ -773,11 +778,11 @@ mod tests {
// A worktree row under the handler-repo's tree. The shared parent strips
// only if path_base comes from self_repo (parent of `<temp>/repo`), not
// from orchestrator_repo (a different temp parent).
- let mut item = ListItem::new_branch("abc".into(), "feature".into());
- item.kind = ItemKind::Worktree(Box::new(WorktreeData {
- path: self_repo.path().join("feature"),
- ..Default::default()
- }));
+ let item = as_worktree(
+ ListItem::new_branch("abc".into(), "feature".into()),
+ &self_repo.path().join("feature"),
+ WorktreeData::default(),
+ );
handler.on_skeleton(vec![item], vec!["skel".into()], header("hdr"), grid());
let received = rx.recv().expect("skeleton batch");
@@ -984,7 +989,7 @@ mod tests {
handler
.orchestrator
.notifier()
- .note_awaiting("feature", mode)
+ .note_awaiting(&branch_key("feature"), mode)
};
// Cursor on `feature`'s `pr` tab (still loading). The CI fetch lands as a
@@ -1017,7 +1022,7 @@ mod tests {
);
// Cursor on the `comments` tab: a pr-field change that keeps the PR
- // present (#7, badge flips back) leaves the branch-keyed thread
+ // present (#7, badge flips back) leaves the row-keyed thread
// unchanged, so it must NOT re-run a scrolled thread.
await_tab(PreviewMode::Comments);
handler.on_update(0, "r".into(), &row(false, CiStatus::Passed));
@@ -1053,7 +1058,7 @@ mod tests {
handler
.orchestrator
.notifier()
- .note_awaiting("other", PreviewMode::Pr);
+ .note_awaiting(&branch_key("other"), PreviewMode::Pr);
handler.on_update(0, "r".into(), &no_pr());
assert_eq!(
run_previews(&mut render_rx),
@@ -1062,7 +1067,7 @@ mod tests {
);
}
- /// A row's `comments` fetch is once-per-PR, keyed by branch name — but if the
+ /// A row's `comments` fetch is once-per-PR, keyed by row identity — but if the
/// live CI fetch corrects the PR number (a stale prime, a reused branch), the
/// now-wrong cached thread is dropped and re-fetched, so the `comments` tab
/// can't keep serving the old PR's thread under the new number. The
@@ -1100,14 +1105,14 @@ mod tests {
}));
item
};
- let key = ("feature".to_string(), PreviewMode::Comments);
+ let key = (branch_key("feature"), PreviewMode::Comments);
// First the row resolves to PR #41 → its comments fetch fires and caches.
handler.on_update(0, "r".into(), &with_pr(41));
handler.orchestrator.wait_for_idle();
assert!(
handler.preview_cache.contains_key(&key),
- "PR #41's comments fetch populated the branch-keyed cache"
+ "PR #41's comments fetch populated the row-keyed cache"
);
// A repeat update with the SAME number must not re-fetch: overwrite with a
@@ -1182,7 +1187,7 @@ mod tests {
}));
item
};
- let key = ("feature".to_string(), PreviewMode::Comments);
+ let key = (branch_key("feature"), PreviewMode::Comments);
// Expired prime → skipped: no comments fetch, cache stays empty. (The
// prime also must not consume the dedup slot, or the live update below
@@ -1254,16 +1259,17 @@ mod tests {
/// `"(detached)"` label `branch_name()` falls back to.
#[test]
fn shortcut_table_branch_is_none_for_detached_worktree() {
- use crate::commands::list::model::{ItemKind, WorktreeData};
+ use crate::commands::list::model::WorktreeData;
let (handler, _test, _rx) = make_handler();
- let mut item = ListItem::new_branch("abc123".into(), "(detached)".into());
- item.branch = None;
- item.kind = ItemKind::Worktree(Box::new(WorktreeData {
- path: std::path::PathBuf::from("/tmp/wt-detached"),
- detached: true,
- ..Default::default()
- }));
+ let path = std::path::PathBuf::from("/tmp/wt-detached");
+ let item = ListItem::new_worktree(
+ worktrunk::git::WorktreeRef::new(&path, None, "abc123"),
+ WorktreeData {
+ detached: true,
+ ..Default::default()
+ },
+ );
handler.on_skeleton(vec![item], vec!["skel".into()], header("hdr"), grid());
@@ -1423,7 +1429,7 @@ mod tests {
/// shared parent keeps its full path via the `strip_prefix` fallback.
#[test]
fn search_text_strips_shared_worktree_parent() {
- use crate::commands::list::model::{ItemKind, WorktreeData};
+ use crate::commands::list::model::WorktreeData;
let (handler, mut test, rx) = make_handler();
// A genuine sibling worktree at `{temp}/repo.feat`; read its path back from
@@ -1439,12 +1445,11 @@ mod tests {
let outside_path = std::path::PathBuf::from("/nonexistent-root/external-wt");
let worktree_item = |branch: &str, path: &Path| {
- let mut item = ListItem::new_branch("abc".into(), branch.into());
- item.kind = ItemKind::Worktree(Box::new(WorktreeData {
- path: path.to_path_buf(),
- ..Default::default()
- }));
- item
+ as_worktree(
+ ListItem::new_branch("abc".into(), branch.into()),
+ path,
+ WorktreeData::default(),
+ )
};
handler.on_skeleton(
@@ -1617,7 +1622,7 @@ mod tests {
// Static Summary hint primed for every item at skeleton time.
for branch in ["alpha", "beta", "gamma"] {
- let key = (branch.to_string(), PreviewMode::Summary);
+ let key = (branch_key(branch), PreviewMode::Summary);
let hint = handler.preview_cache.get(&key).unwrap_or_else(|| {
panic!("Summary hint should be filled for {branch} at skeleton time")
});
@@ -1637,7 +1642,9 @@ mod tests {
PreviewMode::UpstreamDiff,
] {
assert!(
- handler.preview_cache.contains_key(&("alpha".into(), mode)),
+ handler
+ .preview_cache
+ .contains_key(&(branch_key("alpha"), mode)),
"first item should have {mode:?} cached after on_skeleton"
);
}
@@ -1647,7 +1654,7 @@ mod tests {
assert!(
handler
.preview_cache
- .contains_key(&(branch.into(), PreviewMode::UnifiedDiff)),
+ .contains_key(&(branch_key(branch), PreviewMode::UnifiedDiff)),
"{branch}.UnifiedDiff should be cached after on_skeleton (initial tier)"
);
}
@@ -1661,7 +1668,9 @@ mod tests {
PreviewMode::UpstreamDiff,
] {
assert!(
- !handler.preview_cache.contains_key(&(branch.into(), mode)),
+ !handler
+ .preview_cache
+ .contains_key(&(branch_key(branch), mode)),
"{branch}.{mode:?} should remain demand-loaded"
);
}
@@ -1680,7 +1689,9 @@ mod tests {
PreviewMode::UpstreamDiff,
] {
assert!(
- !handler.preview_cache.contains_key(&(branch.into(), mode)),
+ !handler
+ .preview_cache
+ .contains_key(&(branch_key(branch), mode)),
"{branch}.{mode:?} should remain demand-loaded after collection"
);
}
@@ -1723,7 +1734,9 @@ mod tests {
PreviewMode::Summary,
] {
assert!(
- handler.preview_cache.contains_key(&("solo".into(), mode)),
+ handler
+ .preview_cache
+ .contains_key(&(branch_key("solo"), mode)),
"first-item phase should have cached {mode:?}"
);
}
@@ -1778,7 +1791,7 @@ mod tests {
/// A superseded handler's `maybe_spawn_comments` is fully inert. Its
/// corrected-number path would otherwise evict the live spawn's
- /// `(branch, Comments)` entry from the shared cache while its own refetch
+ /// `(row, Comments)` entry from the shared cache while its own refetch
/// drops at `fill` on the stale token — stranding the tab on its loading
/// placeholder, since the live handler's dedup slot already records the
/// number and nothing else refills Comments.
@@ -1811,14 +1824,17 @@ mod tests {
grid(),
);
let _ = rx.recv();
+ let mut item = ListItem::new_branch("abc".into(), "b".into());
+ let row_id = PickerRowId::local(&item);
// Record PR #5 in this handler's dedup slot (the fetch resolves
// synchronously to the "unsupported forge" pane — the test repo has
// no forge remote — only the recorded number matters here).
- handler.maybe_spawn_comments(0, "b", &status(5));
+ item.pr_status = status(5);
+ handler.maybe_spawn_comments(0, &item);
// A refresh supersedes this handler; the live spawn fetches the thread.
handler.orchestrator.refresh(test.repo.clone());
- let key = ("b".to_string(), PreviewMode::Comments);
+ let key = (row_id.clone(), PreviewMode::Comments);
handler.orchestrator.fill_external(
&handler.orchestrator.generation(),
key.clone(),
@@ -1827,7 +1843,8 @@ mod tests {
// The stale handler observing a corrected number must not touch the
// live spawn's entry.
- handler.maybe_spawn_comments(0, "b", &status(6));
+ item.pr_status = status(6);
+ handler.maybe_spawn_comments(0, &item);
handler.orchestrator.wait_for_idle();
assert_eq!(
handler.preview_cache.get(&key).map(|v| v.clone()),
diff --git a/src/commands/picker/prs.rs b/src/commands/picker/prs.rs
index 4981db415..cfcca4499 100644
--- a/src/commands/picker/prs.rs
+++ b/src/commands/picker/prs.rs
@@ -58,7 +58,9 @@ use super::super::list::ci_status::{
};
use super::super::list::columns::ColumnKind;
use super::super::list::layout::ColumnGrid;
-use super::items::{PickerRow, PreviewCache, RowShortcutData, RowUrl, ShortcutTable};
+use super::items::{
+ PickerRow, PickerRowId, PickerRowSubject, PreviewCache, RowShortcutData, RowUrl, ShortcutTable,
+};
use super::pr_pane;
use super::preview::PreviewMode;
use super::preview_cache::CommentEntry;
@@ -169,9 +171,9 @@ impl PrEntry {
}
}
- /// The `pr:{N}` / `mr:{N}` shortcut. Doubles as the row's selection
- /// `output()` and as the preview-cache key prefix — git forbids `:` in ref
- /// names, so it can never collide with a worktree row's branch-name key.
+ /// The `pr:{N}` / `mr:{N}` selection shortcut returned by the row's
+ /// `output()`. Preview caching uses the structured [`PickerRowId`], not
+ /// this user-facing address token.
fn output_token(&self) -> String {
format!("{}{}", self.kind.syntax(), self.number)
}
@@ -432,7 +434,7 @@ fn fetch_and_stream(
let _ = tx.send(items);
}
-/// Build a listed `--prs` row: a [`PickerRow`] with `local: None` and a static
+/// Build a listed `--prs` row: a [`PickerRow`] with a change-request subject and a static
/// PR slot pre-filled from `entry` via [`PrEntry::display_status`], which
/// overlays the entry's number/title/author/body/url/draft onto its CI status
/// so `text()` folds the same tokens and `render_pr_pane_body` renders the same
@@ -456,7 +458,8 @@ fn listed_pr_row(
notifier: Arc<PreviewNotifier>,
) -> PickerRow {
let output_token = entry.output_token();
- preview_cache.remove(&(output_token.clone(), PreviewMode::Pr));
+ let row_id = PickerRowId::change_request(entry.pr_ref());
+ preview_cache.remove(&(row_id.clone(), PreviewMode::Pr));
// The display line is built once and never mutated (a `--prs` row has no
// live list pipeline behind it).
let rendered = match grid {
@@ -467,12 +470,12 @@ fn listed_pr_row(
search_base: entry.head_branch.clone(),
gutter: '#',
rendered: Arc::new(Mutex::new(rendered)),
+ subject: PickerRowSubject::ChangeRequest(entry.pr_ref()),
branch_name: entry.head_branch.clone(),
output_token,
preview_cache,
pr_status: Arc::new(Mutex::new(Some(Some(entry.display_status())))),
notifier,
- local: None,
}
}
@@ -504,12 +507,12 @@ fn spawn_pr_previews(
entry: &PrEntry,
preview_dims: (usize, usize),
) {
- let token = entry.output_token();
+ let row_id = PickerRowId::change_request(entry.pr_ref());
let (kind, number) = (entry.kind, entry.number);
let (width, height) = preview_dims;
let head_oid = entry.head_oid.clone();
let head_branch = entry.head_branch.clone();
- orchestrator.spawn_compute(spawn_gen, (token.clone(), PreviewMode::Log), move |repo| {
+ orchestrator.spawn_compute(spawn_gen, (row_id.clone(), PreviewMode::Log), move |repo| {
Some(
compute_pr_log(
repo,
@@ -526,7 +529,7 @@ fn spawn_pr_previews(
spawn_comments_fetch(
orchestrator,
spawn_gen,
- token,
+ row_id,
entry.kind,
entry.number,
entry.updated_at.clone(),
@@ -534,15 +537,15 @@ fn spawn_pr_previews(
);
}
-/// Spawn the background `comments` fetch keyed by `key_token`, fetching through
+/// Spawn the background `comments` fetch keyed by canonical row identity, fetching through
/// the given forge `kind`.
///
/// The single comments-fetch path for both row types: a `--prs` row passes its
-/// `pr:{N}` / `mr:{N}` token and `entry.kind` (both already resolved from the
+/// structured PR/MR reference and `entry.kind` (both already resolved from the
/// forge in the listing call); a worktree row goes through
/// [`spawn_worktree_comments_fetch`], which resolves `kind` from the repo's
-/// platform. Git forbids `:` in branch names, so the token-keyed and branch-keyed
-/// keyspaces can't collide. A failed fetch caches a terminal [`pr_unavailable_pane`]
+/// platform. The [`PickerRowId`] enum keeps forge and Git identities in
+/// separate variants. A failed fetch caches a terminal [`pr_unavailable_pane`]
/// (not `None`), so the tab never strands on its loading placeholder — see
/// [`spawn_pr_previews`] and [`PreviewOrchestrator::spawn_compute`].
///
@@ -554,13 +557,13 @@ fn spawn_pr_previews(
fn spawn_comments_fetch(
orchestrator: &PreviewOrchestrator,
spawn_gen: &SpawnGeneration,
- key_token: String,
+ row_id: PickerRowId,
kind: RefType,
number: u32,
updated_at: Option<String>,
width: usize,
) {
- orchestrator.spawn_compute(spawn_gen, (key_token, PreviewMode::Comments), move |repo| {
+ orchestrator.spawn_compute(spawn_gen, (row_id, PreviewMode::Comments), move |repo| {
Some(
compute_pr_comments(repo, kind, number, updated_at.as_deref(), width)
.unwrap_or_else(|| pr_unavailable_pane("comments")),
@@ -569,7 +572,7 @@ fn spawn_comments_fetch(
}
/// Spawn the `comments` fetch for a worktree row whose branch has an open PR,
-/// keyed by branch name.
+/// keyed by the worktree or branch's canonical Git identity.
///
/// The forge CLI is chosen from the repository's platform, NOT the PR
/// reference's sigil — `#` is shared by GitHub, Gitea, and Azure DevOps, so the
@@ -581,7 +584,7 @@ fn spawn_comments_fetch(
pub(super) fn spawn_worktree_comments_fetch(
orchestrator: &PreviewOrchestrator,
spawn_gen: &SpawnGeneration,
- branch: String,
+ row_id: PickerRowId,
number: u32,
updated_at: Option<String>,
width: usize,
@@ -591,7 +594,7 @@ pub(super) fn spawn_worktree_comments_fetch(
_ => {
orchestrator.fill_external(
spawn_gen,
- (branch, PreviewMode::Comments),
+ (row_id, PreviewMode::Comments),
comments_unsupported_forge_pane(),
);
return;
@@ -600,7 +603,7 @@ pub(super) fn spawn_worktree_comments_fetch(
spawn_comments_fetch(
orchestrator,
spawn_gen,
- branch,
+ row_id,
kind,
number,
updated_at,
@@ -1330,9 +1333,10 @@ mod tests {
use super::super::items::PreviewCache;
use super::super::preview_notify::PreviewNotifier;
use super::*;
+ use crate::commands::list::model::ListItem;
use dashmap::DashMap;
- /// Build a listed-`--prs` `PickerRow` (`local: None`) with a throwaway empty
+ /// Build a listed-`--prs` `PickerRow` with a throwaway empty
/// preview cache — the same shape `fetch_and_stream` builds. The deferred
/// `log` tab is exercised separately (see `log_tab_reads_cache_then_placeholder`).
fn pr_item(entry: PrEntry, list_width: usize, grid: Option<&ColumnGrid>) -> PickerRow {
@@ -1865,6 +1869,47 @@ mod tests {
);
}
+ #[test]
+ fn worktree_comments_use_the_row_id_on_a_supported_forge() {
+ let test = worktrunk::testing::TestRepo::with_initial_commit();
+ test.run_git(&[
+ "remote",
+ "add",
+ "origin",
+ "https://github.com/example/project.git",
+ ]);
+ let updated_at = "2026-08-26T00:00:00Z";
+ crate::commands::picker::preview_cache::write_comments(
+ &test.repo,
+ 42,
+ updated_at,
+ &[CommentEntry {
+ author: "alice".into(),
+ body: "Canonical identity".into(),
+ created_at: updated_at.into(),
+ }],
+ );
+
+ let orchestrator = PreviewOrchestrator::new(test.repo.clone(), Arc::new(OnceLock::new()));
+ let generation = orchestrator.generation();
+ let row_id = PickerRowId::local(&ListItem::new_branch("abc".into(), "feature".into()));
+ spawn_worktree_comments_fetch(
+ &orchestrator,
+ &generation,
+ row_id.clone(),
+ 42,
+ Some(updated_at.into()),
+ 80,
+ );
+ orchestrator.wait_for_idle();
+
+ let pane = orchestrator
+ .cache
+ .get(&(row_id, PreviewMode::Comments))
+ .expect("supported forge fills the row-keyed comments cache");
+ assert!(pane.contains("Canonical identity"));
+ }
+
#[test]
fn stream_open_prs_clears_loading_and_pokes_render_on_bail() {
// No forge remote → the fetch bails, but the wrapper still drops the
@@ -2009,8 +2054,8 @@ mod tests {
#[test]
fn log_tab_reads_cache_then_placeholder() {
// The deferred `log` tab reads the shared cache keyed by the row's
- // output token. A miss shows the loading placeholder (pointing at
- // alt-4); once the background fetch lands a value under that key, the
+ // structured PR identity. A miss shows the loading placeholder
+ // (pointing at alt-4); once the background fetch lands a value under that key, the
// pane shows it.
let cache: PreviewCache = Arc::new(DashMap::new());
let pr = pr_item_with_cache(entry(RefType::Pr, 42, "t"), 120, None, Arc::clone(&cache));
@@ -2019,7 +2064,7 @@ mod tests {
assert!(miss.contains("Loading commit log"), "miss: {miss:?}");
cache.insert(
- ("pr:42".to_string(), PreviewMode::Log),
+ (pr.preview_key(), PreviewMode::Log),
"abc12345 Fix it\n".to_string(),
);
assert_eq!(pr.cached_or_loading(PreviewMode::Log), "abc12345 Fix it\n");
@@ -2162,8 +2207,8 @@ mod tests {
#[test]
fn comments_tab_reads_cache_then_placeholder() {
// Like the log tab, the deferred `comments` tab reads the shared cache
- // keyed by the row's output token, with a loading placeholder (pointing
- // at alt-8) on a miss.
+ // keyed by the row's structured PR identity, with a loading placeholder
+ // (pointing at alt-8) on a miss.
let cache: PreviewCache = Arc::new(DashMap::new());
let pr = pr_item_with_cache(entry(RefType::Mr, 7, "t"), 120, None, Arc::clone(&cache));
@@ -2171,7 +2216,7 @@ mod tests {
assert!(miss.contains("Loading comments"), "miss: {miss:?}");
cache.insert(
- ("mr:7".to_string(), PreviewMode::Comments),
+ (pr.preview_key(), PreviewMode::Comments),
"rendered thread".to_string(),
);
assert_eq!(
diff --git a/src/commands/picker/summary.rs b/src/commands/picker/summary.rs
index 15e119bae..18e8a8b97 100644
--- a/src/commands/picker/summary.rs
+++ b/src/commands/picker/summary.rs
@@ -46,7 +46,7 @@ pub(super) fn generate_summary_for_item(
repo: &Repository,
) -> String {
let branch = item.branch_name();
- let worktree_path = item.worktree_data().map(|d| d.path.as_path());
+ let worktree_path = item.worktree_path();
crate::summary::generate_summary(branch, item.head(), worktree_path, llm_command, repo)
}
@@ -55,7 +55,7 @@ mod tests {
use insta::assert_snapshot;
use super::*;
- use crate::commands::list::model::{ItemKind, WorktreeData};
+ use crate::commands::list::model::WorktreeData;
use std::fs;
use worktrunk::testing::TestRepo;
@@ -109,12 +109,10 @@ mod tests {
}
fn feature_item(head: &str, path: &std::path::Path) -> ListItem {
- let mut item = ListItem::new_branch(head.to_string(), "feature".to_string());
- item.kind = ItemKind::Worktree(Box::new(WorktreeData {
- path: path.to_path_buf(),
- ..Default::default()
- }));
- item
+ ListItem::new_worktree(
+ worktrunk::git::WorktreeRef::new(path, Some("feature"), head),
+ WorktreeData::default(),
+ )
}
#[test]
diff --git a/src/commands/remove.rs b/src/commands/remove.rs
index 2d1e7545f..e8dbf02d3 100644
--- a/src/commands/remove.rs
+++ b/src/commands/remove.rs
@@ -102,6 +102,7 @@ fn validate_remove_targets(
// across candidates here. Errors propagate to per-candidate calls, which
// fall back to capturing internally when None.
let snapshot = repo.capture_refs().ok();
+ let mut seen_targets = HashSet::new();
for branch_name in branches {
let resolved = match repo.resolve_worktree(&branch_name) {
@@ -111,10 +112,21 @@ fn validate_remove_targets(
continue;
}
};
+ // Branch and path spellings are aliases for one registered worktree.
+ // Once resolution has produced the Git model's canonical identity,
+ // plan that target only once regardless of how many aliases were
+ // supplied.
+ if resolved
+ .id()
+ .is_some_and(|id| !seen_targets.insert(id.clone()))
+ {
+ continue;
+ }
let target = match resolved {
- ResolvedWorktree::Worktree { path, branch: _ } => {
- // Use canonical paths to avoid symlink/normalization mismatches
+ ResolvedWorktree::Worktree { path, .. } => {
+ // `dunce::canonicalize` keeps the path spelling Git operates
+ // on; `WorktreeId` is only for matching aliases.
let path_canonical = dunce::canonicalize(&path).unwrap_or(path);
// Remove exactly the resolved worktree by its path. Targeting by
@@ -126,7 +138,7 @@ fn validate_remove_targets(
// otherwise (see its shared-branch handling).
RemoveTarget::WorktreePath(path_canonical)
}
- ResolvedWorktree::BranchOnly { branch } => RemoveTarget::BranchOnly(branch),
+ ResolvedWorktree::BranchOnly { branch, .. } => RemoveTarget::BranchOnly(branch),
// Resolution tried the argument as a branch and as a worktree path
// and matched neither, so a directory sitting there is a leftover
// skeleton rather than anything wt can remove. Only a typed
@@ -479,6 +491,29 @@ mod tests {
use super::*;
use worktrunk::testing::TestRepo;
+ #[test]
+ fn validation_deduplicates_branch_and_path_aliases() {
+ let mut test = TestRepo::with_initial_commit();
+ let worktree = test.add_worktree("feature");
+ let repo = Repository::at(test.root_path()).unwrap();
+
+ let plans = validate_remove_targets(
+ &repo,
+ vec![
+ "feature".to_string(),
+ worktree.to_string_lossy().into_owned(),
+ ],
+ true,
+ false,
+ false,
+ );
+
+ assert!(plans.errors.is_empty());
+ assert_eq!(plans.others.len(), 1);
+ assert!(plans.branch_only.is_empty());
+ assert!(plans.current.is_none());
+ }
+
/// Resolution sees a registered worktree, but preparation discovers its
/// directory is gone and degrades the result to BranchOnly. Ordered
/// execution must bucket that returned plan with other branch-only plans,
diff --git a/src/commands/statusline.rs b/src/commands/statusline.rs
index e783e5d49..235e335b1 100644
--- a/src/commands/statusline.rs
+++ b/src/commands/statusline.rs
@@ -20,11 +20,9 @@ use std::env;
use std::io::{self, IsTerminal, Read};
use std::path::{Component, Path, PathBuf};
-use dunce::canonicalize;
-
use ansi_str::AnsiStr;
use anyhow::{Context, Result};
-use worktrunk::git::{Repository, WorkingTree};
+use worktrunk::git::{Repository, WorkingTree, WorktreeId};
use worktrunk::styling::{
ColorChoice, fix_dim_after_color_reset, println, terminal_width_for_statusline,
truncate_visible,
@@ -889,26 +887,20 @@ fn statusline_options(repo: &Repository) -> CollectOptions {
fn current_worktree_item(worktree: &WorkingTree) -> Result<Option<list::model::ListItem>> {
let repo = worktree.repo();
- // Use git rev-parse --show-toplevel (via WorkingTree::root()) to correctly identify
- // the worktree containing that directory, rather than prefix matching which fails for
- // nested worktrees.
- let worktree_root = worktree.root()?;
- let Some(wt) = repo.list_worktrees()?.iter().find(|wt| {
- canonicalize(&wt.path)
- .map(|p| p == worktree_root)
- .unwrap_or(false)
- }) else {
+ // `WorkingTree::root()` identifies the checkout containing a nested
+ // directory. Convert it once to the same canonical identity every
+ // inventory and primary-worktree comparison uses.
+ let current_id = WorktreeId::new(worktree.root()?);
+ let worktrees = repo.list_worktrees()?;
+ let Some(wt) = worktrees.iter().find(|wt| wt.id() == current_id) else {
return Ok(None);
};
// Determine if this is the primary worktree
// - Normal repos: the main worktree (repo root)
// - Bare repos: the default branch's worktree
- let is_home = repo
- .primary_worktree()
- .ok()
- .flatten()
- .is_some_and(|p| wt.path == p);
+ let primary_id = repo.primary_worktree().ok().flatten().map(WorktreeId::new);
+ let is_home = primary_id.as_ref() == Some(&current_id);
Ok(Some(list::build_worktree_item(wt, is_home, true, false)))
}
@@ -962,10 +954,10 @@ fn run_json() -> Result<()> {
// Convert to JSON format — single-branch lookup (not all_vars_entries)
let mut all_vars = HashMap::new();
- if let Some(branch) = &item.branch {
+ if let Some(branch) = item.branch() {
let entries = repo.vars_entries(branch);
if !entries.is_empty() {
- all_vars.insert(branch.clone(), entries);
+ all_vars.insert(branch.to_string(), entries);
}
}
// No custom columns: the statusline path never expands `[list.custom-columns]`
@@ -1048,7 +1040,7 @@ fn git_status_segments(worktree: &WorkingTree) -> Result<Vec<StatuslineSegment>>
// If we can't determine the default branch, just show current branch
if repo.default_branch().is_none() {
return Ok(vec![StatuslineSegment::from_column(
- item.branch.as_deref().unwrap_or("HEAD").to_string(),
+ item.branch().unwrap_or("HEAD").to_string(),
ColumnKind::Branch,
)]);
}
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rs
index 493652186..c35565904 100644
--- a/src/commands/worktree/switch.rs
+++ b/src/commands/worktree/switch.rs
@@ -22,7 +22,7 @@ use worktrunk::git::remote_ref::{
};
use worktrunk::git::{
ForgeKind, GitError, GitRemoteUrl, RefType, Repository, ResolvedWorktree, Selector,
- SwitchSuggestionCtx, current_or_recover,
+ SwitchSuggestionCtx, WorktreeId, current_or_recover,
};
use worktrunk::shell_exec::{
ShellEscapeMode, directive_shell_escape_mode, shell_cwd, shell_escape_for,
@@ -823,7 +823,7 @@ fn plan_switch(
// Resolving before the path template is also the fast path: an existing
// worktree answers without the ~7 git commands `compute_worktree_path` runs.
match repo.resolve_selector(&target.selector)? {
- ResolvedWorktree::Worktree { path, branch } => {
+ ResolvedWorktree::Worktree { path, branch, .. } => {
// A registration whose directory is gone or broken has nothing to
// switch into; `wt remove` is the one command that still wants it.
if repo.worktree_is_unusable(&path)? {
@@ -834,7 +834,7 @@ fn plan_switch(
.into());
}
return Ok(SwitchPlan::Existing {
- path: canonicalize(&path).unwrap_or(path),
+ path: operational_worktree_path(path),
branch,
new_previous,
});
@@ -872,6 +872,18 @@ fn plan_switch(
})
}
+/// Preserve the filesystem spelling Git and downstream commands can operate
+/// on. This is deliberately separate from [`WorktreeId`]'s comparison form:
+/// on deep Windows paths, `dunce` keeps the `\\?\` prefix while the identity
+/// drops it so paths on opposite sides of the legacy-length threshold compare.
+fn operational_worktree_path(path: PathBuf) -> PathBuf {
+ canonicalize(&path).unwrap_or(path)
+}
+
+fn same_worktree_path(left: &Path, right: &Path) -> bool {
+ WorktreeId::new(left) == WorktreeId::new(right)
+}
+
/// Execute a validated switch plan.
///
/// Takes a `SwitchPlan` from `plan_switch()` and executes it.
@@ -891,13 +903,9 @@ fn execute_switch(
branch,
new_previous,
} => {
- let current_dir = std::env::current_dir()
+ let already_at_worktree = std::env::current_dir()
.ok()
- .and_then(|p| canonicalize(&p).ok());
- let already_at_worktree = current_dir
- .as_ref()
- .map(|cur| cur == &path)
- .unwrap_or(false);
+ .is_some_and(|current| same_worktree_path(&current, &path));
// Only update switch history when actually switching worktrees.
// Updating on AlreadyAt would corrupt `wt switch -` by recording
@@ -2093,6 +2101,40 @@ mod tests {
use super::*;
use worktrunk::testing::TestRepo;
+ /// Windows needs two representations of a deep worktree path: the
+ /// verbatim spelling that filesystem operations accept, and the
+ /// prefix-free canonical identity used for equality. Keep both sides of
+ /// that boundary pinned without asking Git to register an overlong
+ /// administrative `$GIT_DIR` path.
+ #[test]
+ #[cfg(windows)]
+ fn deep_worktree_keeps_operational_path_separate_from_identity() {
+ let temp = tempfile::tempdir().expect("temp dir");
+ let mut deep = temp.path().join("deep");
+ while deep.as_os_str().len() < 320 {
+ deep.push("nested-worktree-directory");
+ }
+ std::fs::create_dir_all(&deep).expect("create deep tree");
+
+ let operational = operational_worktree_path(deep.clone());
+ let identity = worktrunk::path::canonicalize_with_parents(&deep);
+ assert!(
+ operational.to_string_lossy().starts_with(r"\\?\"),
+ "dunce should retain the verbatim prefix: {}",
+ operational.display()
+ );
+ assert!(
+ !identity.to_string_lossy().starts_with(r"\\?\"),
+ "identity should remove the verbatim prefix: {}",
+ identity.display()
+ );
+ assert_ne!(operational, identity, "the representations should differ");
+ assert!(
+ same_worktree_path(&operational, &identity),
+ "canonical identity should still recognize one worktree"
+ );
+ }
+
#[test]
fn is_clean_program_token_matches_only_bare_names() {
// Bare program names — unchanged under the argv input model.
diff --git a/src/git/error.rs b/src/git/error.rs
index 55adf4877..769f683c0 100644
--- a/src/git/error.rs
+++ b/src/git/error.rs
@@ -37,7 +37,7 @@ use crate::styling::{
/// Platform-specific reference type (PR vs MR).
///
/// Used to unify error handling across supported forges.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RefType {
/// Pull request (GitHub, Gitea, or Azure DevOps)
Pr,
diff --git a/src/git/mod.rs b/src/git/mod.rs
index afb376fa8..98e817afd 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -1,6 +1,6 @@
//! Git operations and repository management
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
// Submodules
mod ci_platform;
@@ -32,6 +32,7 @@ mod test;
// Heavy operations protected:
// - git rev-list --count (accesses commit-graph via mmap)
// - git diff --shortstat (accesses pack files and indexes via mmap)
+use crate::path::canonicalize_with_parents;
use crate::sync::Semaphore;
use std::sync::LazyLock;
static HEAVY_OPS_SEMAPHORE: LazyLock<Semaphore> = LazyLock::new(|| Semaphore::new(4));
@@ -529,7 +530,8 @@ impl HookType {
///
/// # Construction
///
-/// - From a worktree: `BranchRef::from(&worktree_info)`
+/// - From a worktree: `worktree_info.worktree_ref()` and then
+/// [`WorktreeRef::into_branch_ref()`]
/// - For a local branch: `BranchRef::local_branch("feature", "abc123")`
/// - For a remote branch: `BranchRef::remote_branch("origin/feature", "abc123")`
///
@@ -539,6 +541,9 @@ impl HookType {
/// which returns `Some(WorkingTree)` only when this ref has a worktree path.
#[derive(Debug, Clone)]
pub struct BranchRef {
+ /// Repository-scoped identity of this inventory item. Constructed with the
+ /// snapshot so downstream users never reinterpret paths or ref names.
+ id: GitItemId,
/// Full git ref (e.g., `refs/heads/feature`, `refs/remotes/origin/feature`).
/// `None` for detached HEAD.
///
@@ -547,19 +552,114 @@ pub struct BranchRef {
/// literally named `origin/foo`, and `git rev-parse origin/foo` then picks
/// `refs/heads/origin/foo` over `refs/remotes/origin/foo`. With the full
/// ref there is nothing to disambiguate.
- pub full_ref: Option<String>,
+ full_ref: Option<String>,
/// Commit SHA this branch/worktree points to.
pub commit_sha: String,
/// Path to worktree, if this branch has one.
/// None for branch-only items (remote branches, local branches without worktrees).
- pub worktree_path: Option<PathBuf>,
+ worktree_path: Option<PathBuf>,
+}
+
+/// Canonical snapshot of a registered worktree.
+///
+/// This is the typed construction boundary for worktree-backed items. Inner
+/// layers can accept it instead of an arbitrary [`BranchRef`], which makes a
+/// missing worktree path unrepresentable while preserving the same canonical
+/// [`WorktreeId`] used for equality.
+#[derive(Debug, Clone)]
+pub struct WorktreeRef(BranchRef);
+
+/// Canonical identity of one registered worktree.
+///
+/// Git's registered path remains available separately for display and command
+/// execution. Equality uses the canonical path so aliases such as `/var` and
+/// `/private/var` name the same worktree.
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub struct WorktreeId(PathBuf);
+
+impl WorktreeId {
+ pub fn new(path: impl AsRef<Path>) -> Self {
+ Self(canonicalize_with_parents(path.as_ref()))
+ }
+}
+
+/// Repository-scoped identity for a worktree or branch-only item.
+///
+/// This is deliberately separate from every adjacent string representation:
+///
+/// - a worktree is identified by its canonical path, because detached
+/// worktrees have no ref and Git can force-check out one branch more than
+/// once;
+/// - a branch-only item is identified by its full ref, so a local branch named
+/// `origin/foo` cannot collide with `refs/remotes/origin/foo`.
+///
+/// The key identifies the item, not its current content. Caches whose values
+/// depend on a commit or tree must include that content signature separately.
+/// Likewise, user-facing selectors and display labels are representations of
+/// an item, not substitutes for this key.
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub struct GitItemId(GitItemIdKind);
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+enum GitItemIdKind {
+ Worktree(WorktreeId),
+ Ref(String),
+}
+
+impl GitItemId {
+ /// Identify a worktree by the canonical form used for path comparisons.
+ fn worktree(path: impl AsRef<Path>) -> Self {
+ WorktreeId::new(path).into()
+ }
+
+ /// Identify a branch-only item by an already-qualified ref.
+ fn full_ref(full_ref: impl Into<String>) -> Self {
+ Self(GitItemIdKind::Ref(full_ref.into()))
+ }
+
+ fn local_branch(branch: &str) -> Self {
+ Self::full_ref(local_ref(branch))
+ }
+
+ fn remote_branch(branch: &str) -> Self {
+ Self::full_ref(remote_ref(branch))
+ }
+}
+
+fn local_ref(branch: &str) -> String {
+ format!("refs/heads/{branch}")
+}
+
+fn remote_ref(branch: &str) -> String {
+ format!("refs/remotes/{branch}")
+}
+
+impl From<WorktreeId> for GitItemId {
+ fn from(id: WorktreeId) -> Self {
+ Self(GitItemIdKind::Worktree(id))
+ }
+}
+
+impl std::fmt::Display for GitItemId {
+ /// Tagged diagnostic form. Equality and hashing use the structured key;
+ /// this string exists only for logs and test-only cache inventories.
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match &self.0 {
+ GitItemIdKind::Worktree(id) => {
+ write!(f, "worktree:{}", id.0.to_string_lossy())
+ }
+ GitItemIdKind::Ref(full_ref) => write!(f, "ref:{full_ref}"),
+ }
+ }
}
impl BranchRef {
/// Create a BranchRef for a local branch without a worktree.
pub fn local_branch(branch: &str, commit_sha: &str) -> Self {
+ let full_ref = local_ref(branch);
Self {
- full_ref: Some(format!("refs/heads/{branch}")),
+ id: GitItemId::local_branch(branch),
+ full_ref: Some(full_ref),
commit_sha: commit_sha.to_string(),
worktree_path: None,
}
@@ -571,13 +671,20 @@ impl BranchRef {
/// as produced by `%(refname:lstrip=2)` in `list_remote_branches`. It is
/// stored as `refs/remotes/<branch>`.
pub fn remote_branch(branch: &str, commit_sha: &str) -> Self {
+ let full_ref = remote_ref(branch);
Self {
- full_ref: Some(format!("refs/remotes/{branch}")),
+ id: GitItemId::remote_branch(branch),
+ full_ref: Some(full_ref),
commit_sha: commit_sha.to_string(),
worktree_path: None,
}
}
+ /// Repository-scoped identity of this worktree or branch-only item.
+ pub fn id(&self) -> &GitItemId {
+ &self.id
+ }
+
/// Get a working tree handle for this branch's worktree.
///
/// Returns `Some(WorkingTree)` if this branch has a worktree path,
@@ -588,9 +695,9 @@ impl BranchRef {
.map(|p| repo.worktree_at(p.clone()))
}
- /// Returns true if this branch has a worktree.
- pub fn has_worktree(&self) -> bool {
- self.worktree_path.is_some()
+ /// Git's registered path for a worktree-backed item.
+ pub fn worktree_path(&self) -> Option<&Path> {
+ self.worktree_path.as_deref()
}
/// Full git ref (e.g., `refs/heads/feature`, `refs/remotes/origin/feature`),
@@ -632,21 +739,31 @@ impl BranchRef {
}
}
-impl From<&WorktreeInfo> for BranchRef {
- fn from(wt: &WorktreeInfo) -> Self {
- // `WorktreeInfo.branch` is the short form produced by
- // `parse_porcelain_list` (one `refs/heads/` prefix stripped). Worktrees
- // always point at local branches, so re-qualifying with `refs/heads/`
- // gives the full ref. Note: git permits a branch literally named
- // `refs/heads/foo`; in that case `wt.branch == "refs/heads/foo"` and
- // this produces `refs/heads/refs/heads/foo` — which is the correct full
- // ref for that pathological branch, so we don't special-case it.
- Self {
- full_ref: wt.branch.as_deref().map(|b| format!("refs/heads/{b}")),
- commit_sha: wt.head.clone(),
- worktree_path: Some(wt.path.clone()),
+impl WorktreeRef {
+ /// Capture a worktree's identity and Git snapshot once while preserving
+ /// the registered path spelling for commands and display.
+ pub fn new(path: impl Into<PathBuf>, branch: Option<&str>, commit_sha: &str) -> Self {
+ let path = path.into();
+ Self(BranchRef {
+ id: WorktreeId::new(&path).into(),
+ full_ref: branch.map(local_ref),
+ commit_sha: commit_sha.to_string(),
+ worktree_path: Some(path),
+ })
+ }
+
+ /// Canonical worktree identity captured by [`Self::new`].
+ pub fn id(&self) -> &WorktreeId {
+ match &self.0.id.0 {
+ GitItemIdKind::Worktree(id) => id,
+ GitItemIdKind::Ref(_) => unreachable!("WorktreeRef always contains a worktree ID"),
}
}
+
+ /// Pass the already-canonicalized subject to an inner layer.
+ pub fn into_branch_ref(self) -> BranchRef {
+ self.0
+ }
}
/// Parsed worktree data from `git worktree list --porcelain`.
@@ -676,6 +793,21 @@ pub fn path_dir_name(path: &std::path::Path) -> &str {
}
impl WorktreeInfo {
+ /// Canonical identity of this inventory entry. The registered path remains
+ /// unchanged on [`Self::path`] for display and Git operations.
+ pub fn id(&self) -> WorktreeId {
+ WorktreeId::new(&self.path)
+ }
+
+ /// Build the canonical worktree subject for this inventory entry.
+ pub fn worktree_ref(&self) -> WorktreeRef {
+ // `branch` is the short form produced by `parse_porcelain_list` (one
+ // `refs/heads/` prefix stripped). Re-qualifying it in the worktree
+ // constructor preserves even a pathological branch literally named
+ // `refs/heads/foo` as `refs/heads/refs/heads/foo`.
+ WorktreeRef::new(self.path.clone(), self.branch.as_deref(), &self.head)
+ }
+
/// Returns true if this worktree is prunable (directory deleted but git still tracks metadata).
///
/// Prunable worktrees cannot be operated on - the directory doesn't exist.
@@ -937,7 +1069,7 @@ mod tests {
prunable: None,
};
- let branch_ref = BranchRef::from(&wt);
+ let branch_ref = wt.worktree_ref().into_branch_ref();
assert_eq!(branch_ref.full_ref(), Some("refs/heads/feature"));
assert_eq!(branch_ref.short_name(), Some("feature"));
@@ -946,7 +1078,7 @@ mod tests {
branch_ref.worktree_path,
Some(PathBuf::from("/repo.feature"))
);
- assert!(branch_ref.has_worktree());
+ assert!(branch_ref.worktree_path().is_some());
assert!(!branch_ref.is_remote()); // Worktrees are always local
}
@@ -958,7 +1090,7 @@ mod tests {
assert_eq!(branch_ref.short_name(), Some("feature"));
assert_eq!(branch_ref.commit_sha, "abc123");
assert_eq!(branch_ref.worktree_path, None);
- assert!(!branch_ref.has_worktree());
+ assert!(branch_ref.worktree_path().is_none());
assert!(!branch_ref.is_remote());
}
@@ -970,7 +1102,7 @@ mod tests {
assert_eq!(branch_ref.short_name(), Some("origin/feature"));
assert_eq!(branch_ref.commit_sha, "abc123");
assert_eq!(branch_ref.worktree_path, None);
- assert!(!branch_ref.has_worktree());
+ assert!(branch_ref.worktree_path().is_none());
assert!(branch_ref.is_remote());
}
@@ -994,14 +1126,40 @@ mod tests {
assert!(!local.is_remote());
}
+ #[test]
+ fn branch_ref_preserves_git_item_identity() {
+ let root = tempfile::tempdir().unwrap();
+ let first_path = root.path().join("first");
+ let second_path = root.path().join("second");
+ std::fs::create_dir_all(&first_path).unwrap();
+ std::fs::create_dir_all(&second_path).unwrap();
+
+ // Worktree state belongs to the checkout, not to its branch or commit.
+ // Two detached worktrees at one commit and two force-checkouts of one
+ // branch therefore remain distinct keys.
+ assert_ne!(
+ WorktreeRef::new(&first_path, None, "abc").id(),
+ WorktreeRef::new(&second_path, None, "abc").id()
+ );
+
+ // Equivalent path spellings converge on the same checkout identity.
+ let same_path = WorktreeRef::new(first_path.join("."), None, "abc");
+ assert_eq!(
+ WorktreeRef::new(&first_path, None, "abc").id(),
+ same_path.id()
+ );
+
+ // A short name is presentation; the full ref is identity.
+ assert_ne!(
+ BranchRef::local_branch("origin/foo", "abc").id(),
+ BranchRef::remote_branch("origin/foo", "abc").id()
+ );
+ }
+
#[test]
fn test_branch_ref_detached_has_no_ref() {
// Detached HEAD has no branch name — callers fall back to commit_sha.
- let detached = BranchRef {
- full_ref: None,
- commit_sha: "abc".into(),
- worktree_path: None,
- };
+ let detached = WorktreeRef::new("/tmp/detached", None, "abc").into_branch_ref();
assert_eq!(detached.full_ref(), None);
assert_eq!(detached.short_name(), None);
assert!(!detached.is_remote());
@@ -1183,11 +1341,11 @@ mod tests {
prunable: None,
};
- let branch_ref = BranchRef::from(&wt);
+ let branch_ref = wt.worktree_ref().into_branch_ref();
assert_eq!(branch_ref.full_ref(), None);
assert_eq!(branch_ref.short_name(), None);
assert_eq!(branch_ref.commit_sha, "def456");
- assert!(branch_ref.has_worktree());
+ assert!(branch_ref.worktree_path().is_some());
}
}
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index 3d2814f09..0dd035b04 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -139,7 +139,9 @@ use dunce::canonicalize;
use crate::config::{LoadError, ProjectConfig, ResolvedConfig, UserConfig};
// Import types from parent module
-use super::{CommandError, DefaultBranchName, ForgeKind, GitError, LineDiff, WorktreeInfo};
+use super::{
+ CommandError, DefaultBranchName, ForgeKind, GitError, GitItemId, LineDiff, WorktreeInfo,
+};
// Re-export types needed by submodules
pub(super) use super::{
@@ -371,11 +373,15 @@ pub enum ResolvedWorktree {
path: PathBuf,
/// The branch name, if known (None for detached HEAD)
branch: Option<String>,
+ /// Canonical identity captured when the selector resolves.
+ id: GitItemId,
},
/// Only a branch exists (no worktree)
BranchOnly {
/// The branch name
branch: String,
+ /// Canonical local-ref identity captured when the selector resolves.
+ id: GitItemId,
},
/// The selector named a directory holding no worktree — the skeleton an
/// interrupted create or remove leaves behind.
@@ -391,6 +397,27 @@ pub enum ResolvedWorktree {
},
}
+impl ResolvedWorktree {
+ fn worktree(path: PathBuf, branch: Option<String>) -> Self {
+ let id = GitItemId::worktree(&path);
+ Self::Worktree { path, branch, id }
+ }
+
+ fn branch_only(branch: String) -> Self {
+ let id = GitItemId::local_branch(&branch);
+ Self::BranchOnly { branch, id }
+ }
+
+ /// Canonical identity selected by this resolution, when it names a Git
+ /// item rather than an unregistered directory.
+ pub fn id(&self) -> Option<&GitItemId> {
+ match self {
+ Self::Worktree { id, .. } | Self::BranchOnly { id, .. } => Some(id),
+ Self::NoWorktreeAtPath { .. } => None,
+ }
+ }
+}
+
/// A worktree selector after normalization and expansion — the token to look
/// up, plus whether it may still be tried as a *path*.
///
diff --git a/src/git/repository/tests.rs b/src/git/repository/tests.rs
index 95112dc67..fd03e00fc 100644
--- a/src/git/repository/tests.rs
+++ b/src/git/repository/tests.rs
@@ -293,12 +293,12 @@ use super::ResolvedWorktree;
#[test]
fn test_resolved_worktree_clone() {
- let wt = ResolvedWorktree::Worktree {
- path: PathBuf::from("/path/to/worktree"),
- branch: Some("feature".to_string()),
- };
+ let wt = ResolvedWorktree::worktree(
+ PathBuf::from("/path/to/worktree"),
+ Some("feature".to_string()),
+ );
let cloned = wt.clone();
- if let ResolvedWorktree::Worktree { path, branch } = cloned {
+ if let ResolvedWorktree::Worktree { path, branch, .. } = cloned {
assert_eq!(path, PathBuf::from("/path/to/worktree"));
assert_eq!(branch, Some("feature".to_string()));
} else {
@@ -309,11 +309,8 @@ fn test_resolved_worktree_clone() {
#[test]
fn test_resolved_worktree_none_branch() {
// Worktree with detached HEAD (no branch)
- let wt = ResolvedWorktree::Worktree {
- path: PathBuf::from("/path/to/worktree"),
- branch: None,
- };
- if let ResolvedWorktree::Worktree { path, branch } = wt {
+ let wt = ResolvedWorktree::worktree(PathBuf::from("/path/to/worktree"), None);
+ if let ResolvedWorktree::Worktree { path, branch, .. } = wt {
assert_eq!(path, PathBuf::from("/path/to/worktree"));
assert!(branch.is_none());
} else {
@@ -1373,14 +1370,22 @@ fn resolve_worktree_accepts_branch_and_path() {
// A relative path resolves against `-C`, which only a spawned `wt` has —
// `switch::switch_by_relative_worktree_path` covers that spelling.
+ let mut ids = Vec::new();
for selector in ["feature", worktree_path.to_str().unwrap()] {
let resolved = test.repo.resolve_worktree(selector).unwrap();
- let ResolvedWorktree::Worktree { path, branch } = resolved else {
+ ids.push(
+ resolved
+ .id()
+ .expect("resolved Git item has an identity")
+ .clone(),
+ );
+ let ResolvedWorktree::Worktree { path, branch, .. } = resolved else {
panic!("{selector} should resolve to a worktree");
};
assert_eq!(canonicalize(&path).unwrap(), worktree_path);
assert_eq!(branch.as_deref(), Some("feature"));
}
+ assert_eq!(ids[0], ids[1]);
}
/// A directory whose name matches a branch does not shadow it: `wt switch docs`
@@ -1397,7 +1402,8 @@ fn resolve_worktree_prefers_branch_over_same_named_directory() {
let nested = test.root_path().join("docs");
test.add_worktree_at_path("docs-nested", &nested);
- let ResolvedWorktree::Worktree { path, branch } = test.repo.resolve_worktree("docs").unwrap()
+ let ResolvedWorktree::Worktree { path, branch, .. } =
+ test.repo.resolve_worktree("docs").unwrap()
else {
panic!("docs should resolve to a worktree");
};
@@ -1417,7 +1423,7 @@ fn resolve_worktree_reaches_detached_worktree_by_path() {
let worktree_path = test.add_worktree("feature");
test.detach_head_in_worktree("feature");
- let ResolvedWorktree::Worktree { path, branch } = test
+ let ResolvedWorktree::Worktree { path, branch, .. } = test
.repo
.resolve_worktree(worktree_path.to_str().unwrap())
.unwrap()
@@ -1454,7 +1460,7 @@ fn resolve_worktree_does_not_treat_shortcuts_as_paths() {
let resolved = test.repo.resolve_worktree("^").unwrap();
let branch = match resolved {
ResolvedWorktree::Worktree { branch, .. } => branch,
- ResolvedWorktree::BranchOnly { branch } => Some(branch),
+ ResolvedWorktree::BranchOnly { branch, .. } => Some(branch),
ResolvedWorktree::NoWorktreeAtPath { path } => {
panic!("`^` resolved to a directory: {}", path.display())
}
@@ -1472,7 +1478,7 @@ fn resolve_worktree_falls_through_to_branch_only() {
let test = TestRepo::with_initial_commit();
let resolved = test.repo.resolve_worktree("nowhere").unwrap();
- let ResolvedWorktree::BranchOnly { branch } = resolved else {
+ let ResolvedWorktree::BranchOnly { branch, .. } = resolved else {
panic!("an unmatched selector should resolve to branch-only");
};
assert_eq!(branch, "nowhere");
diff --git a/src/git/repository/worktrees.rs b/src/git/repository/worktrees.rs
index 8f87c49bc..53d1db4b8 100644
--- a/src/git/repository/worktrees.rs
+++ b/src/git/repository/worktrees.rs
@@ -12,6 +12,7 @@ use super::{
GitError, Repository, ResolvedWorktree, Selector, WorktreeInfo, is_valid_branch_name,
normalize_selector, resolve_input_path,
};
+use crate::git::WorktreeId;
use crate::path::{format_path_for_display, paths_match};
use crate::styling::{
eprintln, format_with_gutter, hint_message, suggest_command, warning_message,
@@ -418,14 +419,16 @@ impl Repository {
.map_err(|_| GitError::NotInWorktree {
action: Some("resolve @".into()),
})?;
- // root() returns canonicalized path, so canonicalize worktree paths
- // for comparison to handle symlinks (e.g., macOS /var -> /private/var)
+ // Compare canonical identities so alternate path spellings (for
+ // example macOS `/var` and `/private/var`) select one inventory
+ // entry without changing Git's registered path.
+ let current_id = WorktreeId::new(&path);
let branch = self
.list_worktrees()?
.iter()
- .find(|wt| canonicalize(&wt.path).map(|p| p == path).unwrap_or(false))
+ .find(|wt| wt.id() == current_id)
.and_then(|wt| wt.branch.clone());
- return Ok(ResolvedWorktree::Worktree { path, branch });
+ return Ok(ResolvedWorktree::worktree(path, branch));
}
self.resolve_selector(&self.expand_selector(name)?)
@@ -443,10 +446,7 @@ impl Repository {
let token = selector.token();
if let Some(path) = self.worktree_for_branch(token)? {
- return Ok(ResolvedWorktree::Worktree {
- path,
- branch: Some(token.to_string()),
- });
+ return Ok(ResolvedWorktree::worktree(path, Some(token.to_string())));
}
// Both remaining steps are about the token as a path, so
@@ -456,16 +456,11 @@ impl Repository {
// to create, and a directory sitting at that spelling is the clobber
// check's business.
if !selector.names_a_path() {
- return Ok(ResolvedWorktree::BranchOnly {
- branch: token.to_string(),
- });
+ return Ok(ResolvedWorktree::branch_only(token.to_string()));
}
if let Some((path, wt_branch)) = self.worktree_at_input_path(token)? {
- return Ok(ResolvedWorktree::Worktree {
- path,
- branch: wt_branch,
- });
+ return Ok(ResolvedWorktree::worktree(path, wt_branch));
}
// Nothing matched, so say which of the two the selector was reaching
@@ -473,9 +468,7 @@ impl Repository {
// returns on `is_valid_branch_name` before touching the filesystem.
Ok(match self.path_selector_directory(token) {
Some(path) => ResolvedWorktree::NoWorktreeAtPath { path },
- None => ResolvedWorktree::BranchOnly {
- branch: token.to_string(),
- },
+ None => ResolvedWorktree::branch_only(token.to_string()),
})
}
@@ -493,13 +486,15 @@ impl Repository {
branch: Some(branch),
..
} => Ok(branch),
- ResolvedWorktree::BranchOnly { branch } => Ok(branch),
+ ResolvedWorktree::BranchOnly { branch, .. } => Ok(branch),
// A path spelling can't be the branch the caller is about to key
// state by.
ResolvedWorktree::NoWorktreeAtPath { path } => {
Err(GitError::WorktreeNotFoundAtPath { path }.into())
}
- ResolvedWorktree::Worktree { path, branch: None } => Err(GitError::DetachedHead {
+ ResolvedWorktree::Worktree {
+ path, branch: None, ..
+ } => Err(GitError::DetachedHead {
action: Some(cformat!(
"{action} — <bold>{}</> is detached",
format_path_for_display(&path)
@@ -523,7 +518,7 @@ impl Repository {
pub fn require_worktree(&self, name: &str) -> anyhow::Result<PathBuf> {
match self.resolve_worktree(name)? {
ResolvedWorktree::Worktree { path, .. } => Ok(path),
- ResolvedWorktree::BranchOnly { branch } => Err(self.no_worktree_error(branch)),
+ ResolvedWorktree::BranchOnly { branch, .. } => Err(self.no_worktree_error(branch)),
ResolvedWorktree::NoWorktreeAtPath { path } => {
Err(GitError::WorktreeNotFoundAtPath { path }.into())
}
diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rs
index 7c06b6621..658de792d 100644
--- a/tests/integration_tests/switch.rs
+++ b/tests/integration_tests/switch.rs
@@ -2646,15 +2646,15 @@ fn test_switch_prs_dry_run_github(repo: TestRepo) {
let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("stdout is valid JSON");
let entries = parsed["entries"].as_array().expect("entries array");
assert!(
- entries.iter().any(|e| e["branch"] == "pr:42"),
+ entries.iter().any(|e| e["row_id"] == "pr:42"),
"expected a pr:42 cache entry proving the PR row rendered, got:\n{stdout}"
);
}
/// The `log` tab on a `--prs` row loads its commits in the background: as each
/// PR row streams in, `spawn_pr_previews` kicks off `gh pr view <n> --json
-/// commits` on `COLLECT_POOL`, keyed by the row's `pr:{N}` token. The dry-run
-/// path joins that work and dumps the preview cache, so a `{branch:"pr:42",
+/// commits` on `COLLECT_POOL`, keyed by the row's structured PR identity. The dry-run
+/// path joins that work and dumps the preview cache, so a `{row_id:"pr:42",
/// mode:4}` (Log) entry with non-empty bytes proves the whole mechanism end to
/// end: `spawn_compute` → `compute_pr_log` → `parse_github_commits` → cache.
///
@@ -2698,7 +2698,7 @@ fn test_switch_prs_dry_run_github_log_tab(repo: TestRepo) {
// Mode 4 is Log (see `PreviewMode`); the row keys its cache by `pr:42`.
let log_entry = entries
.iter()
- .find(|e| e["branch"] == "pr:42" && e["mode"] == 4)
+ .find(|e| e["row_id"] == "pr:42" && e["mode"] == 4)
.unwrap_or_else(|| panic!("no pr:42 Log cache entry in dump:\n{stdout}"));
assert!(
log_entry["bytes"].as_u64().unwrap_or(0) > 0,
@@ -2757,7 +2757,7 @@ fn test_switch_prs_dry_run_github_log_tab_local(repo: TestRepo) {
let entries = parsed["entries"].as_array().expect("entries array");
let log_entry = entries
.iter()
- .find(|e| e["branch"] == "pr:42" && e["mode"] == 4)
+ .find(|e| e["row_id"] == "pr:42" && e["mode"] == 4)
.unwrap_or_else(|| panic!("no pr:42 Log cache entry in dump:\n{stdout}"));
assert!(
log_entry["bytes"].as_u64().unwrap_or(0) > 0,
@@ -2771,7 +2771,7 @@ fn test_switch_prs_dry_run_github_log_tab_local(repo: TestRepo) {
// `pr view` rigged to exit 1.
let comments_entry = entries
.iter()
- .find(|e| e["branch"] == "pr:42" && e["mode"] == 8)
+ .find(|e| e["row_id"] == "pr:42" && e["mode"] == 8)
.unwrap_or_else(|| {
panic!("failed comments fetch must cache a couldn't-load pane:\n{stdout}")
});
@@ -2826,7 +2826,7 @@ fn test_switch_prs_dry_run_github_deferred_fetch_failure(repo: TestRepo) {
for (mode, tab) in [(4, "log"), (8, "comments")] {
let entry = entries
.iter()
- .find(|e| e["branch"] == "pr:42" && e["mode"] == mode)
+ .find(|e| e["row_id"] == "pr:42" && e["mode"] == mode)
.unwrap_or_else(|| panic!("no pr:42 {tab} cache entry in dump:\n{stdout}"));
assert!(
entry["bytes"].as_u64().unwrap_or(0) > 0,
@@ -2837,7 +2837,7 @@ fn test_switch_prs_dry_run_github_deferred_fetch_failure(repo: TestRepo) {
/// The `comments` tab (8) loads the PR discussion in the background, the same
/// way the `log` tab loads commits: `spawn_pr_previews` fires `gh pr view <n>
-/// --json comments` keyed by the row's `pr:{N}` token. A `{branch:"pr:42",
+/// --json comments` keyed by the row's structured PR identity. A `{row_id:"pr:42",
/// mode:8}` entry in the dry-run cache dump proves `compute_pr_comments` →
/// `render_github_comments` → cache ran end to end. (`gh pr view --json
/// commits` and `--json comments` both match the mock's `pr view` key, so the
@@ -2878,7 +2878,7 @@ fn test_switch_prs_dry_run_github_comments_tab(repo: TestRepo) {
// Mode 8 is Comments; the row keys its cache by `pr:42`.
let comments_entry = entries
.iter()
- .find(|e| e["branch"] == "pr:42" && e["mode"] == 8)
+ .find(|e| e["row_id"] == "pr:42" && e["mode"] == 8)
.unwrap_or_else(|| panic!("no pr:42 Comments cache entry in dump:\n{stdout}"));
assert!(
comments_entry["bytes"].as_u64().unwrap_or(0) > 0,
@@ -2913,7 +2913,7 @@ fn test_switch_prs_dry_run_gitlab(repo: TestRepo) {
let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("stdout is valid JSON");
let entries = parsed["entries"].as_array().expect("entries array");
assert!(
- entries.iter().any(|e| e["branch"] == "mr:7"),
+ entries.iter().any(|e| e["row_id"] == "mr:7"),
"expected an mr:7 cache entry proving the MR row rendered, got:\n{stdout}"
);
}
@@ -2921,7 +2921,7 @@ fn test_switch_prs_dry_run_gitlab(repo: TestRepo) {
/// GitLab counterpart of the GitHub `_log_tab` / `_comments_tab` dry-run tests:
/// an MR row's deferred `log` and `comments` tabs load via background `glab api
/// --paginate projects/:fullpath/merge_requests/<n>/commits` / `…/notes?sort=asc`
-/// calls keyed by the row's `mr:{N}` token. Both `mode:4` (Log) and `mode:8`
+/// calls keyed by the row's structured MR identity. Both `mode:4` (Log) and `mode:8`
/// (Comments) cache entries with non-empty bytes prove `compute_pr_log` /
/// `compute_pr_comments` → `parse_gitlab_commits` / `render_gitlab_notes` →
/// cache for the GitLab forge — the half the unit tests (canned JSON straight
@@ -2967,7 +2967,7 @@ fn test_switch_prs_dry_run_gitlab_deferred_tabs(repo: TestRepo) {
for (mode, label) in [(4, "Log"), (8, "Comments")] {
let entry = entries
.iter()
- .find(|e| e["branch"] == "mr:7" && e["mode"] == mode)
+ .find(|e| e["row_id"] == "mr:7" && e["mode"] == mode)
.unwrap_or_else(|| panic!("no mr:7 {label} cache entry in dump:\n{stdout}"));
assert!(
entry["bytes"].as_u64().unwrap_or(0) > 0,
diff --git a/tests/integration_tests/switch_picker_dry_run.rs b/tests/integration_tests/switch_picker_dry_run.rs
index cd7b89ca5..9295c3084 100644
--- a/tests/integration_tests/switch_picker_dry_run.rs
+++ b/tests/integration_tests/switch_picker_dry_run.rs
@@ -18,6 +18,10 @@ fn main_only_repo() -> TestRepo {
TestRepo::standard_main_only()
}
+fn worktree_row_id(path: &std::path::Path) -> String {
+ worktrunk::git::GitItemId::from(worktrunk::git::WorktreeId::new(path)).to_string()
+}
+
/// Install a strict fake summary command through TestRepo's cross-platform
/// mock-PATH wiring. Tests observe its external call log to distinguish the
/// generated-summary route from the static mode-5 config hint.
@@ -99,15 +103,13 @@ fn test_picker_dry_run_emits_configured_rows_and_cache_json(
"expected at least one cache entry, got: {stdout}"
);
- // Every entry has {branch: string, mode: u8, bytes: usize, content: string}. Asserting
+ // Every entry has {row_id: string, mode: u8, bytes: usize, content: string}. Asserting
// schema (not specific branches/modes) keeps the test robust to fixture
// changes while still covering the dump format.
for e in entries {
assert!(
- e["branch"]
- .as_str()
- .is_some_and(|branch| !branch.is_empty()),
- "entry missing nonempty branch: {e}"
+ e["row_id"].as_str().is_some_and(|key| !key.is_empty()),
+ "entry missing nonempty row ID: {e}"
);
assert!(
e["mode"]
@@ -140,7 +142,7 @@ fn test_picker_dry_run_emits_configured_rows_and_cache_json(
}
/// The speculative default-preview producer runs before list collection. It
-/// must carry a real HEAD, or it can poison the `(branch, UnifiedDiff)` cache
+/// must carry a real HEAD, or it can poison the `(row, UnifiedDiff)` cache
/// key with an error pane before the collected row tries to fill it. One Rayon
/// worker makes that ordering deterministic. The hidden-untracked setting also
/// pins that the shared cleanliness signal cannot suppress the file.
@@ -150,7 +152,7 @@ fn test_picker_dry_run_speculative_complete_diff_uses_real_head(
) {
repo.run_git(&["config", "status.showUntrackedFiles", "no"]);
std::fs::write(repo.path().join("untracked-preview.txt"), "preview\n").unwrap();
- let branch = repo.current_branch();
+ let row_id = worktree_row_id(repo.path());
let output = repo
.wt_command()
@@ -172,7 +174,7 @@ fn test_picker_dry_run_speculative_complete_diff_uses_real_head(
.as_array()
.expect("top-level `entries` array")
.iter()
- .find(|entry| entry["branch"] == branch && entry["mode"] == 1)
+ .find(|entry| entry["row_id"] == row_id && entry["mode"] == 1)
.expect("current branch has a complete-diff cache entry");
let content = complete["content"].as_str().expect("content is a string");
@@ -202,6 +204,7 @@ fn test_picker_dry_run_tempdir_inside_worktree_has_no_worktrunk_artifacts(
repo.run_git(&["commit", "-m", "track local temp directory"]);
std::fs::write(repo.path().join("loose.txt"), "loose\n").unwrap();
let branch = repo.current_branch();
+ let row_id = worktree_row_id(repo.path());
let output = repo
.wt_command()
@@ -225,7 +228,7 @@ fn test_picker_dry_run_tempdir_inside_worktree_has_no_worktrunk_artifacts(
for mode in [1, 2] {
let pane = entries
.iter()
- .find(|entry| entry["branch"] == branch && entry["mode"] == mode)
+ .find(|entry| entry["row_id"] == row_id && entry["mode"] == mode)
.unwrap_or_else(|| panic!("branch {branch} has mode-{mode} cache entry"));
let content = pane["content"].as_str().expect("content is a string");
assert!(
@@ -261,6 +264,7 @@ fn test_picker_dry_run_includes_untracked_outside_sparse_checkout(
std::fs::create_dir_all(&hidden).unwrap();
std::fs::write(hidden.join("loose.txt"), "loose\n").unwrap();
let branch = repo.current_branch();
+ let row_id = worktree_row_id(repo.path());
let output = repo
.wt_command()
@@ -282,7 +286,7 @@ fn test_picker_dry_run_includes_untracked_outside_sparse_checkout(
for mode in [1, 2] {
let pane = entries
.iter()
- .find(|entry| entry["branch"] == branch && entry["mode"] == mode)
+ .find(|entry| entry["row_id"] == row_id && entry["mode"] == mode)
.unwrap_or_else(|| panic!("branch {branch} has mode-{mode} cache entry"));
let content = pane["content"].as_str().expect("content is a string");
assert!(
@@ -439,25 +443,27 @@ fn test_picker_dry_run_shows_cached_pr_numbers(mut repo: TestRepo) {
);
// The worktree row with a PR spawns a `comments` background fetch keyed by
- // its branch name (PreviewMode::Comments == 8) — the same fetch a `--prs`
- // row makes, so the comments tab is no longer `--prs`-only. In this no-network
+ // its canonical worktree identity (PreviewMode::Comments == 8) — the same
+ // fetch a `--prs` row makes, so the comments tab is no longer `--prs`-only. In this no-network
// test the entry holds a terminal pane (a "couldn't load" on a GitHub remote,
// or a "forge unsupported" note otherwise), but its presence proves the fetch
- // fired and keyed by branch. The PR-less row spawns no such fetch.
- let comments_branches: Vec<&str> = parsed["entries"]
+ // fired and keyed by row. The PR-less row spawns no such fetch.
+ let comments_keys: Vec<&str> = parsed["entries"]
.as_array()
.expect("top-level `entries` array")
.iter()
.filter(|e| e["mode"] == 8)
- .map(|e| e["branch"].as_str().expect("branch is a string"))
+ .map(|e| e["row_id"].as_str().expect("row_id is a string"))
.collect();
+ let feature_a_key = worktree_row_id(repo.worktree_path("feature-a"));
+ let feature_b_key = worktree_row_id(repo.worktree_path("feature-b"));
assert!(
- comments_branches.contains(&"feature-a"),
- "the PR-bearing worktree row spawns a branch-keyed comments fetch, got: {comments_branches:?}"
+ comments_keys.contains(&feature_a_key.as_str()),
+ "the PR-bearing worktree row spawns a row-ID-keyed comments fetch, got: {comments_keys:?}"
);
assert!(
- !comments_branches.contains(&"feature-b"),
- "the PR-less worktree row spawns no comments fetch, got: {comments_branches:?}"
+ !comments_keys.contains(&feature_b_key.as_str()),
+ "the PR-less worktree row spawns no comments fetch, got: {comments_keys:?}"
);
}