Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat(switch): unify picker preview tabs and dim empty diff tabs (#3223)
Maximilian Roos11d525dda2c0
diff --git a/CLAUDE.md b/CLAUDE.mdindex 8b2a5799c..cf58c647f 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -102,7 +102,7 @@ Before adding an accessor that could reach the wire (`gh`, `glab`, `git fetch`,What currently reaches the wire:- `wt list --full`, `wt list statusline` — CI status-- `wt switch` (interactive picker, no target) — per-row CI status, primed from the local cache then fetched live and streamed into the rows+- `wt switch` (interactive picker, no target) — per-row CI status, primed from the local cache then fetched live and streamed into the rows; once a row's CI fetch surfaces an open PR/MR, a per-row background `gh pr view <n> --json comments` (`glab api …/notes` on GitLab) fills that row's `comments` preview tab — the same fetch a `--prs` row makes, spawned once per row from `progressive_handler` (see `picker::prs::spawn_comments_fetch`). The `comments` tab is the only PR data fetched lazily here; `pr` rides the CI call and `log` is the local `git log`- generating a branch summary with a `commit.generation` command- generating a commit message with a `commit.generation` command- `wt switch pr:<n>`, `wt switch mr:<n>` — host API to resolve the PR/MR, then `git fetch` of its branchdiff --git a/src/commands/picker/items.rs b/src/commands/picker/items.rsindex 727a1dbfe..69a74ddca 100644--- a/src/commands/picker/items.rs+++ b/src/commands/picker/items.rs@@ -67,6 +67,14 @@ pub(super) type PreviewCache = Arc<DashMap<PreviewCacheKey, String>>;/// `Some(Some(status))` = a PR/MR with status.pub(super) type PrStatusSlot = Arc<Mutex<Option<Option<PrStatus>>>>;+/// Per-row live content signals for the local-checkout tabs, shared with the+/// collect handler. Like [`PrStatusSlot`], the frozen `item` snapshot can't+/// carry these (its `counts` / `upstream` / `working_tree_status` are `None` at+/// skeleton and never update), so the handler mirrors them here as the list+/// pipeline lands (`on_update`). Read live by [`WorktreeSkimItem::render_preview`]+/// to dim a tab once its diff is known empty.+pub(super) type LocalContentSlot = Arc<Mutex<LocalContent>>;+/// Prefix on a worktree-backed item's `output()` token. Detached worktrees/// all share the `(detached)` branch label, so `output()` returns the/// worktree path (which is unique) behind this prefix instead.@@ -193,6 +201,13 @@ pub(super) struct WorktreeSkimItem {/// skeleton), this slot is primed from the cache and then overwritten as the/// `CiStatus` task streams in — so the `pr` tab reflects the live fetch.pub pr_status: PrStatusSlot,+ /// Live diff-content signals for the `working_tree` / `branch_diff` /+ /// `upstream` tabs, shared with the collect handler. The frozen `item`+ /// snapshot can't carry these (its `counts` / `upstream` /+ /// `working_tree_status` are `None` at skeleton and never update), so the+ /// handler mirrors them here as the pipeline lands — letting those tabs dim+ /// once their diff is known empty (see [`LocalContent`]).+ pub local_content: LocalContentSlot,}impl SkimItem for WorktreeSkimItem {@@ -243,19 +258,128 @@ enum PrPreview {HasPr(PrRef, PrStatus),}+/// Live, content-aware availability for the local-checkout tabs whose pane is a+/// diff — `working_tree`, `branch_diff`, and `upstream`. Each tab dims once its+/// diff is *known* empty, the same way the `pr` tab dims once the fetch reports+/// no PR (see [`WorktreeSkimItem::pr_tab_available`]).+///+/// The diff emptiness is async (the `counts` / `upstream` / `working_tree_status`+/// fields are `None` at skeleton and land via the list pipeline), so each signal+/// is `Option<bool>`: `None` while loading, `Some(has_content)` once known. A tab+/// stays available while its signal is `None` — we don't dim before we know it's+/// empty — and dims when the signal resolves to "no content". Each predicate+/// mirrors exactly what its pane renders, so a dimmed number never contradicts a+/// non-empty pane.+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]+pub(super) struct LocalContent {+ /// `working_tree`: tracked uncommitted changes exist. Matches the pane's+ /// `git diff HEAD` — staged/modified/renamed/deleted, NOT untracked (which+ /// `git diff HEAD` doesn't show). `Some(false)` for a branch-only row (no+ /// working tree to diff).+ working_tree: Option<bool>,+ /// `branch_diff`: the branch has commits ahead of the **local** default+ /// branch — the same base `compute_branch_diff_preview`'s pane diffs against+ /// (`default_branch_sha()`). Deliberately NOT `has_file_changes`, which+ /// measures against the *integration target*: when the local default is+ /// behind or diverged from its upstream, that target is the upstream, so a+ /// branch already integrated upstream resolves `has_file_changes = false`+ /// while the pane (vs the stale local default) still shows a diff — dimming+ /// over a non-empty pane, the one case the invariant rules out.+ branch_diff: Option<bool>,+ /// `upstream`: the branch is ahead of or behind its tracking ref. Combined+ /// with the synchronous `has_upstream` floor (no tracking ref dims the tab+ /// immediately, with no loading window); this only narrows a *present*+ /// upstream from "available" to "dim" once it's known to be up to date.+ upstream_diverged: Option<bool>,+}++impl LocalContent {+ /// Read the content signals off a row's `ListItem`. Called from the collect+ /// handler each time a row updates, then stored in the row's live slot.+ pub(super) fn from_item(item: &ListItem) -> Self {+ let working_tree = match item.worktree_data() {+ // A real worktree: tracked changes per the porcelain status (matches+ // the pane's `git diff HEAD`, which excludes untracked files).+ Some(data) => data+ .working_tree_status+ .map(|s| s.staged || s.modified || s.renamed || s.deleted),+ // Branch-only row: no working tree, so nothing to diff.+ None => Some(false),+ };+ Self {+ working_tree,+ // Commits ahead of the local default (matching the pane's base). An+ // orphan has no merge base with the default, so its three-dot diff is+ // ill-defined — keep the tab available rather than dim a pane that may+ // show content. `counts` and `is_orphan` land together (one task), so+ // when `counts` is known `is_orphan` is too.+ branch_diff: item+ .counts+ .map(|c| c.ahead > 0 || item.is_orphan == Some(true)),+ upstream_diverged: item+ .upstream+ .as_ref()+ .map(|u| u.active().is_some_and(|a| a.ahead > 0 || a.behind > 0)),+ }+ }+}++/// The local-checkout-backed preview tabs — present for a row with a local+/// worktree, absent for a listed PR/MR row (`--prs`), which has no local copy.+/// Grouping them names *why* they're empty on a `--prs` row (no checkout), so+/// the difference reads as a data fact rather than a row-type policy.+#[derive(Debug, Clone, Copy, Default)]+struct LocalTabs {+ working_tree: bool,+ branch_diff: bool,+ upstream: bool,+ summary: bool,+}++impl LocalTabs {+ /// A worktree-backed row. The diff tabs (`working_tree`, `branch_diff`,+ /// `upstream`) follow the live [`LocalContent`] signals — available while+ /// loading, dim once their diff is known empty; `upstream` also requires the+ /// synchronous `has_upstream` floor (no tracking ref → dim with no loading+ /// window). `summary` follows the process-wide `[commit.generation]` flag.+ fn worktree(content: LocalContent, has_upstream: bool, summaries_enabled: bool) -> Self {+ Self {+ working_tree: content.working_tree.unwrap_or(true),+ branch_diff: content.branch_diff.unwrap_or(true),+ upstream: has_upstream && content.upstream_diverged.unwrap_or(true),+ summary: summaries_enabled,+ }+ }+}+/// Which preview tabs have renderable content for the selected row.////// Empty tabs are de-emphasized in the bar (number dimmed). Skim computes a/// preview once per selection and cannot re-query it mid-selection (see-/// `loading_placeholder`). `upstream` and `summary` are synchronous-/// skeleton-time facts, read to avoid locking the bar into a stale state:-/// `upstream` reads `Repository::local_branches()` (the pre-skeleton-/// `for-each-ref` scan), NOT the async `item.upstream`; `summary` reads the-/// process-wide `[commit.generation]` flag, NOT the async `item.summary`. `pr`-/// reads the row's live status slot (primed from the CI cache, then refreshed-/// by the `CiStatus` task — see [`WorktreeSkimItem::pr_status`]), so it can-/// change between selections: it dims once the fetch reports no PR, and stays-/// available while loading or with a PR. `--prs` rows always render their PR.+/// `loading_placeholder`). Two genuine axes drive availability, and `--prs`+/// touches neither — it only decides whether a PR row is *listed* at all:+///+/// - The local-checkout tabs ([`LocalTabs`]): the three diff tabs+/// (`working_tree` / `branch_diff` / `upstream`) follow the row's live+/// [`LocalContent`] — available while their diff is still loading, dim once+/// it's known empty (a clean working tree, no commits ahead, up to date with+/// upstream), the same loading-then-dim shape as the `pr` tab. `upstream` also+/// carries a synchronous `has_upstream` floor (`Repository::local_branches()`),+/// so a branch with no tracking ref dims immediately with no loading window.+/// `summary` follows the process-wide `[commit.generation]` flag. A `--prs` row+/// has no local checkout, so all four are empty.+/// - The PR-backed tabs: `pr` and `comments` are available together, gated by+/// `has_pr`. On a worktree row that's the live status slot (primed from the CI+/// cache, then refreshed by the `CiStatus` task — see+/// [`WorktreeSkimItem::pr_tab_available`]): it dims once the fetch reports no+/// PR, and stays available while loading or with a PR. A `--prs` row always+/// has a PR, so both are available.+///+/// `comments` tracks `has_pr` on *every* row, so the comments tab behaves the+/// same whether the row is a worktree or a listed PR — only its content differs+/// where the data legitimately does (no local checkout). `log` is always+/// present (local `git log` on a worktree row, a background forge fetch on a+/// `--prs` row).#[derive(Debug, Clone, Copy)]pub(super) struct TabAvailability {working_tree: bool,@@ -268,38 +392,46 @@ pub(super) struct TabAvailability {}impl TabAvailability {- /// A worktree-backed row: working-tree/log/branch-diff always render; the- /// upstream and summary tabs depend on synchronous skeleton-time facts; the- /// `pr` tab is available unless the live fetch has reported no PR for this- /// branch (see [`WorktreeSkimItem::pr_preview`]). The `comments` tab is- /// always empty here — comments are fetched only for `--prs` rows.- pub(super) fn worktree(has_upstream: bool, summaries_enabled: bool, pr: bool) -> Self {+ /// Build from the two genuine axes: which local-checkout tabs the row has,+ /// and whether it has a PR. Centralizing the mapping pins the invariants the+ /// task depends on — `log` is always present, and the PR-backed tabs (`pr`,+ /// `comments`) both follow `has_pr` — so they can't drift between a worktree+ /// row and a listed-PR row.+ fn from_axes(local: LocalTabs, has_pr: bool) -> Self {Self {- working_tree: true,+ working_tree: local.working_tree,log: true,- branch_diff: true,- upstream: has_upstream,- summary: summaries_enabled,- pr,- comments: false,+ branch_diff: local.branch_diff,+ upstream: local.upstream,+ summary: local.summary,+ pr: has_pr,+ comments: has_pr,}}- /// A `--prs` row: it carries no local worktree, so the working-tree,- /// branch-diff, upstream, and summary tabs are empty. The `pr` tab is built- /// at construction; the `log` and `comments` tabs load in the background- /// (see `prs::compute_pr_log` / `prs::compute_pr_comments`), so all three- /// are available.- pub(super) fn pull_request() -> Self {- Self {- working_tree: false,- log: true,- branch_diff: false,- upstream: false,- summary: false,- pr: true,- comments: true,- }+ /// A worktree-backed row: the local-checkout tabs follow [`LocalTabs`]+ /// (diff tabs gated by the live [`LocalContent`] + the `has_upstream` floor);+ /// the PR-backed tabs follow the live PR status (see+ /// [`WorktreeSkimItem::pr_tab_available`]).+ pub(super) fn worktree(+ content: LocalContent,+ has_upstream: bool,+ summaries_enabled: bool,+ has_pr: bool,+ ) -> Self {+ Self::from_axes(+ LocalTabs::worktree(content, has_upstream, summaries_enabled),+ has_pr,+ )+ }++ /// A listed PR/MR row (`--prs`): no local checkout, so the local-checkout+ /// tabs are empty; it always has a PR, so the `pr` and `comments` tabs are+ /// available and the `log` tab loads in the background (see+ /// `prs::compute_pr_log`). The differences from a worktree row are only the+ /// genuine data ones — no local checkout, and a PR that's always present.+ pub(super) fn listed_pr() -> Self {+ Self::from_axes(LocalTabs::default(), true)}}@@ -474,10 +606,10 @@ fn render_tab_row_compact(tabs: &[Tab], reset: Reset) -> String {/// doesn't expose them) falls back to a reference-only header and skips the/// missing lines.///-/// The `comments` line shows only the count — the full thread is a `--prs`-only-/// fetch (see [`WorktreeSkimItem::comments_unavailable_pane`]). A PR with no-/// comments carries `None` (zero is flattened at the mapping boundary), so the-/// line is skipped.+/// The `comments` line shows only the count; the full thread is the `comments`+/// tab's own background fetch (see [`WorktreeSkimItem::render_comments_pane`]).+/// A PR with no comments carries `None` (zero is flattened at the mapping+/// boundary), so the line is skipped.////// `width` is the live preview-pane width, used to wrap the markdown body.fn render_worktree_pr(branch: &str, pr_ref: PrRef, status: &PrStatus, width: usize) -> String {@@ -504,13 +636,14 @@ impl WorktreeSkimItem {fn render_preview(&self, mode: PreviewMode, width: usize, height: usize) -> String {// Build preview: tabs header + content. `has_upstream` and// `summaries_enabled` are synchronous skeleton-time facts (see- // `TabAvailability`); `pr` reads the row's live status slot, refreshed as- // the `CiStatus` task streams in, so it can change between selections.- // The `pr` tab dims only once the fetch reports no PR — while loading or- // with a PR it stays available. `pr_tab_available` is a cheap- // discriminant read (no body clone); the pane itself is rendered once and- // memoized in `render_pr_pane_cached`.+ // `TabAvailability`); the diff tabs' live emptiness (`local_content`) and+ // `pr` (`pr_tab_available`) read the row's live slots, refreshed as the+ // list pipeline / `CiStatus` task stream in, so they can change between+ // selections — a tab dims once its diff (or PR) is known empty, and stays+ // available while still loading. Both reads are cheap (no body clone); the+ // panes themselves are rendered once and memoized.let avail = TabAvailability::worktree(+ self.local_content(),self.has_upstream,self.summaries_enabled,self.pr_tab_available(),@@ -518,9 +651,10 @@ impl WorktreeSkimItem {let mut result = render_preview_tabs(mode, avail, width);result.push_str(&match mode {PreviewMode::Pr => self.render_pr_pane_cached(width),- // The `comments` tab (7) is `--prs`-only — worktree rows don't fetch- // PR discussion — so it shows a pointer rather than the cache path.- PreviewMode::Comments => Self::comments_unavailable_pane(),+ // The PR-backed tabs share one source: the live `pr_status` slot. The+ // `comments` tab renders the same background-fetched thread a `--prs`+ // row's does when the branch has a PR (see `render_comments_pane`).+ PreviewMode::Comments => self.render_comments_pane(),_ => self.preview_for_mode(mode, width, height),});result@@ -542,11 +676,12 @@ impl WorktreeSkimItem {}}- /// Whether the `pr` tab has content for this row — it dims only once the- /// live fetch reports no PR. A cheap discriminant read of the `pr_status`- /// slot (no `PrStatus` clone, unlike [`Self::pr_preview`]), so the tab bar- /// can be drawn on every `preview()` call without re-cloning the- /// possibly-large body that [`Self::render_pr_pane_cached`] already memoizes.+ /// Whether the PR-backed tabs (`pr` and `comments`) have content for this+ /// row — they dim together only once the live fetch reports no PR. A cheap+ /// discriminant read of the `pr_status` slot (no `PrStatus` clone, unlike+ /// [`Self::pr_preview`]), so the tab bar can be drawn on every `preview()`+ /// call without re-cloning the possibly-large body that+ /// [`Self::render_pr_pane_cached`] already memoizes.fn pr_tab_available(&self) -> bool {match &*self.pr_status.lock().unwrap() {None => true, // still fetching@@ -555,6 +690,14 @@ impl WorktreeSkimItem {}}+ /// Snapshot the row's live diff-content signals for the `working_tree` /+ /// `branch_diff` / `upstream` tabs (see [`LocalContent`]). A cheap copy of+ /// three `Option<bool>`s; the collect handler overwrites the slot as the list+ /// pipeline lands.+ fn local_content(&self) -> LocalContent {+ *self.local_content.lock().unwrap()+ }+/// Render the `pr` pane, memoized in the shared `preview_cache` so repeated/// `preview()` calls (every keystroke while the tab is active) don't re-run/// the markdown render of the body. The other modes are pre-computed into@@ -589,13 +732,35 @@ impl WorktreeSkimItem {}}- /// The `comments` tab's pane on a worktree row. The discussion thread is- /// fetched only for `--prs` rows (a worktree row has no PR number until its- /// `pr` tab resolves one, and no background comments fetch wired to it), so- /// the tab dims and points at where comments live.- fn comments_unavailable_pane() -> String {+ /// The `comments` tab's pane on a worktree row — identical in behavior to a+ /// `--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+ /// background fetch renders at the preview width, so this reads it back+ /// without re-wrapping (matching `PrSkimItem::cached_pane`).+ fn render_comments_pane(&self) -> String {let reset = Reset;- cformat!("{INFO_SYMBOL}{reset} Comments show on <bold>wt switch --prs</>{reset} rows\n")+ let branch = self.item.branch_name();+ match self.pr_preview() {+ // The CI fetch hasn't reported yet — we don't know whether there's a+ // PR to fetch comments for. Mirror the `pr` tab's loading state,+ // pointing at this tab's accelerator.+ PrPreview::Loading => cformat!(+ "○ Fetching PR status for <bold>{branch}</>{reset}… press <bold>alt-7</>{reset} to refresh\n"+ ),+ PrPreview::NoPr => {+ cformat!("{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} has no PR\n")+ }+ PrPreview::HasPr(..) => self+ .preview_cache+ .get(&(self.branch_name.clone(), PreviewMode::Comments))+ .map(|v| v.value().clone())+ .unwrap_or_else(|| super::prs::pr_deferred_loading(PreviewMode::Comments)),+ }}/// Render preview for the given mode with specified dimensions.@@ -634,13 +799,14 @@ impl WorktreeSkimItem {PreviewMode::BranchDiff => ("Loading", "branch diff"),PreviewMode::UpstreamDiff => ("Loading", "upstream diff"),PreviewMode::Summary => ("Generating", "summary"),- // The `pr` and `comments` tabs have no worktree-row background task —- // `preview()` renders `pr` from the cached `pr_status` via- // `render_pr_pane` and routes `comments` to `comments_unavailable_pane`,- // never here.+ // `preview()` routes the PR-backed tabs around this path: `pr` renders+ // from the cached `pr_status` via `render_pr_pane`, and `comments`+ // through `render_comments_pane` (which uses the `--prs` rows' shared+ // `pr_deferred_loading` for its own in-flight placeholder), so neither+ // reaches here.PreviewMode::Pr => unreachable!("pr tab renders via render_pr_pane"),PreviewMode::Comments => {- unreachable!("comments tab renders via comments_unavailable_pane")+ unreachable!("comments tab renders via render_comments_pane")}};let key = mode as u8;@@ -1102,14 +1268,32 @@ mod tests {/// full bar (the compact fallback has its own test).const WIDE: usize = 200;+ /// A worktree row whose three diff tabs (working-tree, branch-diff, upstream)+ /// all have content — every diff signal known and non-empty.+ const CONTENT_FULL: LocalContent = LocalContent {+ working_tree: Some(true),+ branch_diff: Some(true),+ upstream_diverged: Some(true),+ };++ /// A worktree row whose three diff tabs are all *known* empty — a clean+ /// working tree, no commits ahead, and up to date with a present upstream.+ const CONTENT_EMPTY: LocalContent = LocalContent {+ working_tree: Some(false),+ branch_diff: Some(false),+ upstream_diverged: Some(false),+ };+#[test]fn test_render_preview_tabs() {- // Each mode active, on a worktree row with upstream + summaries enabled- // but no PR (tabs 1-5 available; tabs 6 pr and 7 comments dim). The- // active mode's label is bold, inactive available labels dim, and on the- // `pr` iteration tab 6 is active-but-empty — exercising the rule that- // emptiness dims even the active tab. Verifies labels and structure.- let wt = TabAvailability::worktree(true, true, false);+ // Each mode active, on a worktree row whose diffs all have content+ // (uncommitted changes, commits ahead, diverged from upstream) with+ // summaries enabled but no PR (tabs 1-5 available; tabs 6 pr and 7+ // comments dim). The active mode's label is bold, inactive available+ // labels dim, and on the `pr` iteration tab 6 is active-but-empty —+ // exercising the rule that emptiness dims even the active tab. Verifies+ // labels and structure.+ let wt = TabAvailability::worktree(CONTENT_FULL, true, true, false);for (name, mode) in [("working_tree", PreviewMode::WorkingTree),("log", PreviewMode::Log),@@ -1121,20 +1305,175 @@ mod tests {assert_snapshot!(name, render_preview_tabs(mode, wt, WIDE));}- // Empty states: a worktree row with no upstream and summaries disabled- // dims tabs 4 and 5 (number dim too); a --prs row dims the- // working-tree/branch-diff/upstream/summary tabs but keeps log/pr/comments.+ // Empty states. Three rows:+ // - `empty_upstream_and_summary`: diffs still loading (so tabs 1 and 3+ // read as available), no upstream ref, summaries disabled, no PR — dims+ // tabs 4, 5, 6, and 7.+ // - `empty_all_local_diffs`: every diff *known* empty (clean working tree,+ // no commits ahead, up to date with a present upstream) — dims tabs 1,+ // 3, 4, plus 5/6/7, leaving only `log`. This is the behavior the diff+ // tabs gained: a dimmed number once the diff is known empty.+ // - `pr_row`: a listed-PR row dims the working-tree/branch-diff/upstream/+ // summary tabs but keeps log/pr/comments.assert_snapshot!("empty_upstream_and_summary",render_preview_tabs(PreviewMode::WorkingTree,- TabAvailability::worktree(false, false, false),+ TabAvailability::worktree(LocalContent::default(), false, false, false),+ WIDE,+ )+ );+ assert_snapshot!(+ "empty_all_local_diffs",+ render_preview_tabs(+ PreviewMode::WorkingTree,+ TabAvailability::worktree(CONTENT_EMPTY, true, false, false),WIDE,));assert_snapshot!("pr_row",- render_preview_tabs(PreviewMode::Pr, TabAvailability::pull_request(), WIDE)+ render_preview_tabs(PreviewMode::Pr, TabAvailability::listed_pr(), WIDE)+ );+ }++ /// `LocalContent::from_item` reads each diff tab's emptiness off the row's+ /// `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,+ };++ // 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.+ let branch = ListItem::new_branch("abc".into(), "feature".into());+ let c = LocalContent::from_item(&branch);+ assert_eq!(c.working_tree, Some(false), "branch-only: no working tree");+ assert_eq!(c.branch_diff, None, "branch_diff loads from item.counts");+ assert_eq!(+ c.upstream_diverged, None,+ "upstream loads from item.upstream"+ );++ // `branch_diff` follows the commits-ahead count vs the local default (the+ // pane's base), not `has_file_changes` (integration target).+ use crate::commands::list::model::AheadBehind;+ let mut ahead = ListItem::new_branch("abc".into(), "feature".into());+ ahead.counts = Some(AheadBehind {+ ahead: 2,+ behind: 0,+ });+ assert_eq!(LocalContent::from_item(&ahead).branch_diff, Some(true));+ ahead.counts = Some(AheadBehind {+ ahead: 0,+ behind: 3,+ });+ assert_eq!(+ LocalContent::from_item(&ahead).branch_diff,+ Some(false),+ "behind-only (no commits ahead) is empty"+ );+ // An orphan has an ill-defined three-dot diff — stays available even with+ // a zero ahead count.+ ahead.is_orphan = Some(true);+ assert_eq!(+ LocalContent::from_item(&ahead).branch_diff,+ Some(true),+ "orphan keeps branch_diff available"+ );++ // `upstream_diverged` is true only when a *present* upstream is ahead or+ // behind; a configured-but-even upstream, and no remote at all, are empty.+ let with_upstream = |remote: Option<&str>, a: usize, b: usize| {+ let mut item = ListItem::new_branch("abc".into(), "feature".into());+ item.upstream = Some(UpstreamStatus {+ remote: remote.map(String::from),+ ahead: a,+ behind: b,+ });+ LocalContent::from_item(&item).upstream_diverged+ };+ assert_eq!(with_upstream(Some("origin/feature"), 2, 0), Some(true));+ assert_eq!(with_upstream(Some("origin/feature"), 0, 3), Some(true));+ assert_eq!(+ with_upstream(Some("origin/feature"), 0, 0),+ Some(false),+ "up to date with a present upstream is empty"+ );+ assert_eq!(+ with_upstream(None, 0, 0),+ Some(false),+ "no remote configured is empty"+ );++ // `working_tree` matches `git diff HEAD`: tracked changes count, untracked+ // alone does not (the pane wouldn't show them).+ 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()+ }));+ LocalContent::from_item(&item).working_tree+ };+ // staged, modified, renamed, deleted → tracked content present.+ assert_eq!(+ worktree_with(WorkingTreeStatus::new(false, true, false, false, false)),+ Some(true),+ "modified is tracked content"+ );+ // untracked only → `git diff HEAD` is empty.+ assert_eq!(+ worktree_with(WorkingTreeStatus::new(false, false, true, false, false)),+ Some(false),+ "untracked alone is not shown by `git diff HEAD`"+ );+ // 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());+ assert_eq!(LocalContent::from_item(&pending).working_tree, None);+ }++ /// The diff tabs stay available while their signal is still loading, dim once+ /// it's known empty, and `upstream` additionally requires the synchronous+ /// `has_upstream` floor — a branch with no tracking ref dims immediately, even+ /// before (or despite) the live ahead/behind signal.+ #[test]+ fn diff_tabs_dim_only_once_known_empty() {+ let has = |avail: TabAvailability| (avail.working_tree, avail.branch_diff, avail.upstream);++ // Loading (default): every diff tab available — we don't dim before we know.+ assert_eq!(+ has(TabAvailability::worktree(+ LocalContent::default(),+ true,+ false,+ false+ )),+ (true, true, true),+ "loading → available"+ );++ // Known empty + a present upstream: all three dim.+ assert_eq!(+ has(TabAvailability::worktree(CONTENT_EMPTY, true, false, false)),+ (false, false, false),+ "known empty → dim"+ );++ // Known non-empty: all three available.+ assert_eq!(+ has(TabAvailability::worktree(CONTENT_FULL, true, false, false)),+ (true, true, true),+ "known content → available"+ );++ // No tracking ref: the upstream tab dims regardless of the live signal —+ // the synchronous floor wins over a (stale or loading) divergence read.+ assert!(+ !has(TabAvailability::worktree(CONTENT_FULL, false, false, false)).2,+ "no upstream ref → dim despite a 'diverged' signal");}@@ -1145,7 +1484,7 @@ mod tests {#[test]fn render_preview_tabs_compacts_when_narrow() {// A --prs row with the `pr` tab active, in a narrow pane.- let compact = render_preview_tabs(PreviewMode::Pr, TabAvailability::pull_request(), 40);+ let compact = render_preview_tabs(PreviewMode::Pr, TabAvailability::listed_pr(), 40);let plain = compact.lines().next().unwrap().ansi_strip().to_string();// Every digit 1-7 is present; only the active tab keeps its label.for n in 1..=7 {@@ -1164,7 +1503,7 @@ mod tests {assert!(visual_width(&plain) <= 40, "fits the pane: {plain:?}");// The same row in a wide pane uses the full bar (labels for all tabs).- let full = render_preview_tabs(PreviewMode::Pr, TabAvailability::pull_request(), WIDE);+ let full = render_preview_tabs(PreviewMode::Pr, TabAvailability::listed_pr(), WIDE);assert!(full.contains("7: ") && full.contains("comments"),"wide pane keeps full labels"@@ -1174,7 +1513,7 @@ mod tests {// bar's own width, then check that exactly that width stays full while one// column narrower compacts (the `pr` tab is active, so only the full bar// carries the inactive `comments` label).- let avail = TabAvailability::pull_request();+ let avail = TabAvailability::listed_pr();let full_w = visual_width(full.lines().next().unwrap());let at_fit = render_preview_tabs(PreviewMode::Pr, avail, full_w);assert!(@@ -1270,6 +1609,7 @@ mod tests {has_upstream: false,summaries_enabled: false,pr_status: Arc::new(Mutex::new(None)),+ local_content: Arc::new(Mutex::new(LocalContent::default())),}};@@ -1284,6 +1624,7 @@ mod tests {has_upstream: false,summaries_enabled: false,pr_status: Arc::new(Mutex::new(None)),+ local_content: Arc::new(Mutex::new(LocalContent::default())),}};@@ -1329,6 +1670,7 @@ mod tests {has_upstream: false,summaries_enabled: false,pr_status: Arc::new(Mutex::new(pr_status)),+ local_content: Arc::new(Mutex::new(LocalContent::default())),}};@@ -1404,6 +1746,76 @@ mod tests {assert!(matches!(branch_ci.pr_preview(), PrPreview::NoPr));}+ #[test]+ fn comments_tab_mirrors_pr_status_and_reads_the_shared_cache() {+ use crate::commands::list::ci_status::{CiSource, CiStatus, PrRef};++ // A worktree row's `comments` tab behaves like a `--prs` row's: with a+ // PR it reads the background-fetched thread from the shared cache (keyed+ // by branch name), and with no PR — or while CI is still loading — it+ // mirrors the `pr` tab's empty/loading states.+ let pr_status = |number: Option<PrRef>| {+ Some(Some(PrStatus {+ ci_status: CiStatus::Passed,+ source: CiSource::PullRequest,+ is_stale: false,+ is_priming: false,+ url: None,+ number,+ review_state: None,+ title: None,+ body: None,+ comment_count: None,+ }))+ };+ let row = |slot: Option<Option<PrStatus>>, cache: PreviewCache| WorktreeSkimItem {+ search_text: String::new(),+ rendered: Arc::new(Mutex::new(String::new())),+ branch_name: "feature".into(),+ item: Arc::new(ListItem::new_branch("abc".into(), "feature".into())),+ preview_cache: cache,+ has_upstream: false,+ summaries_enabled: false,+ pr_status: Arc::new(Mutex::new(slot)),+ local_content: Arc::new(Mutex::new(LocalContent::default())),+ };++ // CI hasn't reported (None) → fetching hint pointing at this tab's key.+ let loading = row(None, Arc::new(DashMap::new()));+ let pane = loading.render_comments_pane();+ assert!(pane.contains("Fetching PR status"), "loading: {pane:?}");+ assert!(pane.contains("alt-7"), "loading points at alt-7: {pane:?}");++ // No PR (Some(None)) → "has no PR", matching the `pr` tab.+ let no_pr = row(Some(None), Arc::new(DashMap::new()));+ assert!(+ no_pr.render_comments_pane().contains("has no PR"),+ "no-pr state"+ );++ // 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),+ "@octocat\nLooks good\n".to_string(),+ );+ let with_thread = row(pr_status(Some(PrRef::pr(7))), Arc::clone(&cache));+ assert_eq!(+ with_thread.render_comments_pane(),+ "@octocat\nLooks good\n",+ "cached thread served verbatim"+ );++ // A PR whose fetch hasn't landed → the shared `--prs` loading placeholder,+ // so a worktree row and a `--prs` row show the identical in-flight pane.+ let pending = row(pr_status(Some(PrRef::pr(7))), Arc::new(DashMap::new()));+ assert_eq!(+ pending.render_comments_pane(),+ super::super::prs::pr_deferred_loading(PreviewMode::Comments),+ "cache miss falls back to the shared loading placeholder"+ );+ }+#[test]fn worktree_pr_pane_shows_comment_count() {use crate::commands::list::ci_status::{CiSource, CiStatus, PrRef};@@ -1469,6 +1881,7 @@ mod tests {body: Some("Adds a **bounded** retry.".into()),comment_count: None,})))),+ local_content: Arc::new(Mutex::new(LocalContent::default())),};// In Pr mode, `render_preview` assembles the tab bar plus the worktree PR@@ -1550,6 +1963,7 @@ mod tests {has_upstream: false,summaries_enabled: false,pr_status: Arc::clone(&slot),+ local_content: Arc::new(Mutex::new(LocalContent::default())),};// First render populates the shared cache.@@ -1883,7 +2297,7 @@ mod tests {// (not compact) bar.let output = render_preview_tabs(PreviewMode::WorkingTree,- TabAvailability::worktree(true, true, false),+ TabAvailability::worktree(CONTENT_FULL, true, true, false),WIDE,);diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex 840836c3a..c610e69ed 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -1259,6 +1259,8 @@ pub fn handle_picker(shared_items: Arc::clone(&shared_items),rendered_slots: std::sync::OnceLock::new(),pr_status_slots: std::sync::OnceLock::new(),+ comments_fetched: std::sync::OnceLock::new(),+ local_content_slots: std::sync::OnceLock::new(),preview_cache: Arc::clone(&preview_cache),orchestrator: Arc::clone(&orchestrator),preview_dims,@@ -1608,7 +1610,7 @@ fn resolve_identifier(#[cfg(test)]pub mod tests {- use super::items::WorktreeSkimItem;+ use super::items::{LocalContent, WorktreeSkimItem};use super::{PickerAction, PickerCollector, PickerRemovalTarget, drain_stashed_warnings,install_preview_tab_keybindings, parse_reload_remove_token, picker_item_identifier,@@ -2053,6 +2055,7 @@ pub mod tests {has_upstream: false,summaries_enabled: false,pr_status,+ local_content: Arc::new(Mutex::new(LocalContent::default())),}) as Arc<dyn SkimItem>}diff --git a/src/commands/picker/preview.rs b/src/commands/picker/preview.rsindex 5575490c7..7be959492 100644--- a/src/commands/picker/preview.rs+++ b/src/commands/picker/preview.rs@@ -14,15 +14,17 @@ use std::sync::atomic::{AtomicU8, Ordering};/// 4. UpstreamDiff: Diff vs upstream tracking branch (ahead/behind)/// 5. Summary: LLM-generated branch summary (requires [commit.generation] config)/// 6. Pr: The selected row's PR/MR, rendered from already-fetched data (no network)-/// 7. Comments: The PR/MR's comment thread (background forge fetch on `--prs` rows)+/// 7. Comments: The PR/MR's comment thread (background forge fetch on any row+/// whose branch has an open PR — worktree row or `--prs` row alike)////// A mode whose content is structurally absent for the current row is rendered/// de-emphasized in the tab bar (see `TabAvailability` / `render_preview_tabs`):-/// tab 4 when the branch has no upstream, tab 5 when summaries are disabled,-/// the working-tree/branch-diff/upstream/summary tabs on a `--prs` row (no-/// local worktree), tab 6 on a worktree row (PR previews render only on `--prs`-/// rows), and tab 7 (comments) on a worktree row (comments are fetched only for-/// `--prs` rows).+/// tab 4 when the branch has no upstream, tab 5 when summaries are disabled, the+/// working-tree/branch-diff/upstream/summary tabs on a `--prs` row (no local+/// worktree), and the PR-backed tabs 6 (pr) and 7 (comments) when the row's+/// branch has no PR. The PR-backed tabs are available together, by the same+/// rule, on every row — `--prs` only decides whether a PR row is listed, not how+/// these tabs behave.////// Loosely aligned with `wt list` columns, though not a perfect match:/// - Tab 1 corresponds to "HEAD±" columndiff --git a/src/commands/picker/progressive_handler.rs b/src/commands/picker/progressive_handler.rsindex ca04233f2..05164666b 100644--- a/src/commands/picker/progressive_handler.rs+++ b/src/commands/picker/progressive_handler.rs@@ -34,7 +34,7 @@use std::collections::HashSet;use std::path::Path;-use std::sync::atomic::AtomicBool;+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};use std::sync::{Arc, Mutex, OnceLock};use std::time::{Duration, Instant};@@ -42,13 +42,18 @@ use color_print::cformat;use skim::prelude::*;use worktrunk::styling::{StyledLine, strip_osc8_hyperlinks};+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/// `Event::Render` bypasses skim's own frame-rate cap, so we cap it here.const RENDER_THROTTLE: Duration = Duration::from_millis(16);-use super::items::{HeaderLoading, HeaderSkimItem, PrStatusSlot, PreviewCache, WorktreeSkimItem};+use super::items::{+ HeaderLoading, HeaderSkimItem, LocalContent, LocalContentSlot, PrStatusSlot, PreviewCache,+ WorktreeSkimItem,+};use super::preview::PreviewMode;use super::preview_orchestrator::PreviewOrchestrator;use crate::commands::list::collect::PickerProgressHandler;@@ -83,6 +88,21 @@ pub(super) struct PickerHandler {/// cache-filled snapshot), then written by `on_update` as the `CiStatus`/// task reports, so the `pr` tab reflects the live fetch.pub(super) pr_status_slots: OnceLock<Box<[PrStatusSlot]>>,+ /// Per data row, the PR/MR number whose `comments` thread was last fetched+ /// (`0` = none yet). Set once in `on_skeleton`. The `comments` tab's+ /// background forge fetch must fire at most once per PR, but the PR surfaces+ /// asynchronously (a cache prime at skeleton, or the live `CiStatus` task via+ /// `on_update`) and `on_update` fires repeatedly — so a fetch fires only when+ /// the observed number differs from this slot, and a corrected number (a+ /// reused branch, a stale prime) re-fetches and keeps the `comments` tab+ /// consistent with the `pr` tab. See [`Self::maybe_spawn_comments`].+ pub(super) comments_fetched: OnceLock<Box<[Arc<AtomicU64>]>>,+ /// One live `LocalContent` slot per data row — same Arcs the+ /// `WorktreeSkimItem`s hold. Set once in `on_skeleton` (all-loading), then+ /// overwritten by `on_update` from the row's `ListItem` as the list pipeline+ /// lands, so the `working_tree` / `branch_diff` / `upstream` tabs dim once+ /// their diff is known empty.+ pub(super) local_content_slots: OnceLock<Box<[LocalContentSlot]>>,pub(super) preview_cache: PreviewCache,pub(super) orchestrator: Arc<PreviewOrchestrator>,pub(super) preview_dims: (usize, usize),@@ -128,6 +148,52 @@ impl PickerHandler {}let _ = tx.try_send(Event::Render);}++ /// Spawn row `idx`'s `comments` background fetch if its branch has an open+ /// PR and that PR's thread hasn't been fetched yet. The `comments` tab on a+ /// worktree row shows the same forge-fetched thread a `--prs` row's tab does+ /// (see `items::WorktreeSkimItem::render_comments_pane`); the PR number comes+ /// from the row's live status, which arrives asynchronously, so this fires+ /// from both the skeleton prime and `on_update`. The per-row+ /// [`Self::comments_fetched`] slot records which PR number was fetched, so+ /// 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>>,+ ) {+ let Some(Some(status)) = pr_status else {+ return;+ };+ let Some(pr_ref) = status.number else { return };+ let Some(slots) = self.comments_fetched.get() else {+ return;+ };+ let Some(slot) = slots.get(idx) else { return };+ let number = pr_ref.number;+ let previous = slot.swap(number, Ordering::Relaxed);+ if previous == number {+ return; // this PR's comments are already fetched (or in flight)+ }+ 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));+ }+ super::prs::spawn_worktree_comments_fetch(+ &self.orchestrator,+ branch_name.to_string(),+ number as u32,+ self.preview_dims.0,+ );+ }}impl PickerProgressHandler for PickerHandler {@@ -143,6 +209,8 @@ impl PickerProgressHandler for PickerHandler {let mut slots: Vec<Arc<Mutex<String>>> = Vec::with_capacity(items.len());let mut pr_slots: Vec<PrStatusSlot> = Vec::with_capacity(items.len());+ let mut comments_slots: Vec<Arc<AtomicU64>> = Vec::with_capacity(items.len());+ let mut local_content_slots: Vec<LocalContentSlot> = Vec::with_capacity(items.len());let mut skim_items: Vec<Arc<dyn SkimItem>> = Vec::with_capacity(items.len() + 1);let mut list_items: Vec<Arc<ListItem>> = Vec::with_capacity(items.len());@@ -247,6 +315,16 @@ impl PickerProgressHandler for PickerHandler {// task reports.let pr_status_arc: PrStatusSlot = Arc::new(Mutex::new(item_arc.pr_status.clone()));pr_slots.push(Arc::clone(&pr_status_arc));+ comments_slots.push(Arc::new(AtomicU64::new(0)));++ // Prime the diff-content slot from the skeleton snapshot. Its async+ // fields are still `None` here (every diff tab reads as loading →+ // available), except a branch-only row, which has no working tree and+ // so resolves `working_tree` to empty immediately. `on_update`+ // overwrites it as the pipeline lands.+ let local_content_arc: LocalContentSlot =+ Arc::new(Mutex::new(LocalContent::from_item(&item_arc)));+ local_content_slots.push(Arc::clone(&local_content_arc));skim_items.push(Arc::new(WorktreeSkimItem {search_text,@@ -257,6 +335,7 @@ impl PickerProgressHandler for PickerHandler {has_upstream,summaries_enabled,pr_status: pr_status_arc,+ local_content: local_content_arc,}) as Arc<dyn SkimItem>);}@@ -265,6 +344,10 @@ impl PickerProgressHandler for PickerHandler {// skim calls `CommandCollector::invoke`.let _ = self.rendered_slots.set(slots.into_boxed_slice());let _ = self.pr_status_slots.set(pr_slots.into_boxed_slice());+ let _ = self.comments_fetched.set(comments_slots.into_boxed_slice());+ let _ = self+ .local_content_slots+ .set(local_content_slots.into_boxed_slice());*self.shared_items.lock().unwrap() = skim_items.clone();// skim 4.x's item channel carries Vec batches; the skeleton is a single@@ -286,6 +369,12 @@ impl PickerProgressHandler for PickerHandler {self.preview_dims,self.llm_command.as_deref(),);+ // A row whose CI status was primed from cache already knows its PR at+ // 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);+ }// Static Summary hint is a synchronous in-memory insert, no// contention concern. Pre-fill every row at skeleton time so the// Summary tab is usable for any selection immediately.@@ -316,6 +405,19 @@ impl PickerProgressHandler for PickerHandler {self.preview_cache.remove(&(item.branch_name().to_string(), 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.+ // Cheap copy; the snapshot starts all-loading and resolves field-by-field+ // as the pipeline lands.+ if let Some(slots) = self.local_content_slots.get()+ && let Some(slot) = slots.get(idx)+ {+ *slot.lock().unwrap() = LocalContent::from_item(item);+ }+ // 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.request_render(false);}@@ -371,6 +473,8 @@ mod tests {shared_items,rendered_slots: OnceLock::new(),pr_status_slots: OnceLock::new(),+ comments_fetched: OnceLock::new(),+ local_content_slots: OnceLock::new(),preview_cache,orchestrator,preview_dims: (80, 24),@@ -423,10 +527,23 @@ mod tests {assert!(pr_slots[0].lock().unwrap().is_none());assert!(pr_slots[1].lock().unwrap().is_none());+ // local_content slots start primed from the skeleton snapshots — these are+ // branch-only rows (no worktree), so `working_tree` already resolves empty+ // while the rest stays loading.+ let lc_slots = handler.local_content_slots.get().unwrap();+ let skeleton_lc =+ LocalContent::from_item(&ListItem::new_branch("aaa".into(), "one".into()));+ assert_eq!(*lc_slots[0].lock().unwrap(), skeleton_lc);+ assert_eq!(*lc_slots[1].lock().unwrap(), skeleton_lc);+// on_update rewrites a single render slot (the second item here) and- // mirrors that item's CI status into its pr_status slot.+ // mirrors that item's CI status and diff-content into its live slots.let mut updated = ListItem::new_branch("bbb".into(), "two".into());updated.pr_status = Some(None);+ updated.counts = Some(crate::commands::list::model::AheadBehind {+ ahead: 1,+ behind: 0,+ });handler.on_update(1, "updated-two".into(), &updated);assert_eq!(*slots[0].lock().unwrap(), "skel-one", "row 0 untouched");assert_eq!(*slots[1].lock().unwrap(), "updated-two");@@ -438,6 +555,16 @@ mod tests {pr_slots[0].lock().unwrap().is_none(),"row 0 pr status untouched");+ assert_eq!(+ *lc_slots[1].lock().unwrap(),+ LocalContent::from_item(&updated),+ "row 1 diff-content mirrored from the updated item"+ );+ assert_eq!(+ *lc_slots[0].lock().unwrap(),+ skeleton_lc,+ "row 0 diff-content untouched"+ );// on_reveal rewrites every slot — slot writes are idempotent// through `Mutex<String>`, so unconditional updates are safe.@@ -446,6 +573,88 @@ mod tests {assert_eq!(*slots[1].lock().unwrap(), "rev-two");}+ /// A row's `comments` fetch is once-per-PR, keyed by branch name — 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+ /// `make_handler` repo has no forge, so the fetch caches a terminal pane+ /// synchronously; the test watches the cache key being invalidated and+ /// repopulated across the number change.+ #[test]+ fn comments_refetch_on_pr_number_change() {+ use crate::commands::list::ci_status::{CiSource, CiStatus, PrRef, PrStatus};++ let (handler, _test, rx) = make_handler();+ handler.on_skeleton(+ vec![ListItem::new_branch("aaa".into(), "feature".into())],+ vec!["s".into()],+ header("hdr"),+ grid(),+ );+ let _ = rx.recv();++ let with_pr = |number: u64| {+ let mut item = ListItem::new_branch("aaa".into(), "feature".into());+ item.pr_status = Some(Some(PrStatus {+ ci_status: CiStatus::Passed,+ source: CiSource::PullRequest,+ is_stale: false,+ is_priming: false,+ url: None,+ number: Some(PrRef::pr(number)),+ review_state: None,+ title: None,+ body: None,+ comment_count: None,+ }));+ item+ };+ let key = ("feature".to_string(), 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"+ );++ // A repeat update with the SAME number must not re-fetch: overwrite with a+ // sentinel and confirm it survives.+ handler+ .preview_cache+ .insert(key.clone(), "SENTINEL-41".into());+ handler.on_update(0, "r".into(), &with_pr(41));+ handler.orchestrator.wait_for_idle();+ assert_eq!(+ handler+ .preview_cache+ .get(&key)+ .map(|v| v.clone())+ .as_deref(),+ Some("SENTINEL-41"),+ "same PR number short-circuits — no re-fetch"+ );++ // The live fetch corrects the number to #42 → the stale #41 thread is+ // dropped and a fresh fetch repopulates the key.+ handler.on_update(0, "r".into(), &with_pr(42));+ handler.orchestrator.wait_for_idle();+ assert_ne!(+ handler+ .preview_cache+ .get(&key)+ .map(|v| v.clone())+ .as_deref(),+ Some("SENTINEL-41"),+ "a corrected PR number drops the stale thread and re-fetches"+ );+ assert!(+ handler.preview_cache.contains_key(&key),+ "the re-fetch repopulated the comments cache for #42"+ );+ }+/// Header + items get published in order. `output()` of the/// WorktreeSkimItem is the branch name so skim returns the correct/// identifier when the user hits Enter.diff --git a/src/commands/picker/prs.rs b/src/commands/picker/prs.rsindex 686d297ae..5c576a176 100644--- a/src/commands/picker/prs.rs+++ b/src/commands/picker/prs.rs@@ -295,6 +295,11 @@ fn fetch_and_stream(/// a duplicate fetch on every repaint. `COLLECT_POOL` bounds how many run at once,/// and the picker's lifetime is user-bounded, so a slow forge call never blocks/// the command (see the "Network Access" notes in CLAUDE.md).+///+/// The comments fetch goes through [`spawn_comments_fetch`], the same entry point+/// a worktree row uses once its CI fetch surfaces a PR — so the two row types+/// fetch and cache comments identically. Only the `log` fetch is `--prs`-specific+/// (a worktree row renders its `log` tab from the local object store instead).fn spawn_pr_previews(orchestrator: &PreviewOrchestrator,entry: &PrEntry,@@ -319,7 +324,28 @@ fn spawn_pr_previews(.unwrap_or_else(|| pr_unavailable_pane("commit log")),)});- orchestrator.spawn_compute((token, PreviewMode::Comments), move |repo| {+ spawn_comments_fetch(orchestrator, token, entry.kind, entry.number, width);+}++/// Spawn the background `comments` fetch keyed by `key_token`, 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+/// 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`]+/// (not `None`), so the tab never strands on its loading placeholder — see+/// [`spawn_pr_previews`] and [`PreviewOrchestrator::spawn_compute`].+fn spawn_comments_fetch(+ orchestrator: &PreviewOrchestrator,+ key_token: String,+ kind: RefKind,+ number: u32,+ width: usize,+) {+ orchestrator.spawn_compute((key_token, PreviewMode::Comments), move |repo| {Some(compute_pr_comments(repo, kind, number, width).unwrap_or_else(|| pr_unavailable_pane("comments")),@@ -327,6 +353,46 @@ fn spawn_pr_previews(});}+/// Spawn the `comments` fetch for a worktree row whose branch has an open PR,+/// keyed by branch name.+///+/// 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+/// sigil can't pick `gh` vs `glab`. GitHub fetches via `gh`, GitLab via `glab`;+/// on any other forge comments aren't listable (the same forges `--prs` declines+/// in [`fetch_open_prs`]), so the tab caches a terminal "not available" pane+/// rather than shelling out to the wrong CLI or spinning on a loading placeholder+/// forever. `ci_platform` reads the cached remote URL — no network.+pub(super) fn spawn_worktree_comments_fetch(+ orchestrator: &PreviewOrchestrator,+ branch: String,+ number: u32,+ width: usize,+) {+ let kind = match orchestrator.repo().ci_platform(None) {+ Some(CiPlatform::GitHub) => RefKind::Pr,+ Some(CiPlatform::GitLab) => RefKind::Mr,+ _ => {+ orchestrator.cache.insert(+ (branch, PreviewMode::Comments),+ comments_unsupported_forge_pane(),+ );+ return;+ }+ };+ spawn_comments_fetch(orchestrator, branch, kind, number, width);+}++/// The `comments` tab pane for a worktree row whose branch has a PR on a forge+/// with no comments-listing support (Gitea, Azure DevOps, or an unrecognized+/// remote — the forges `--prs` declines). A terminal pane, so the tab shows a+/// clear state instead of spinning on a loading placeholder or shelling out to+/// the wrong forge CLI.+fn comments_unsupported_forge_pane() -> String {+ let reset = Reset;+ cformat!("{INFO_SYMBOL}{reset} Comments aren't available for this repository's forge\n")+}+/// Plural noun for the forge's change-request — "PRs" on GitHub, "MRs" on/// GitLab. Used for the empty-list message and the header "loading…" marker,/// where there's no entry to read the kind from.@@ -666,14 +732,16 @@ fn pr_row_empty_placeholder() -> String {)}-/// Placeholder for a `--prs` row's deferred tab while its background fetch is-/// still in flight. skim can't re-query a preview on its own, so the hint points-/// at the accelerator that re-reads the cache once the fetch lands — the same-/// contract as the worktree rows' `loading_placeholder`. Shown only during the-/// in-flight window: once the fetch resolves, a terminal pane replaces it — the-/// rendered content or [`pr_unavailable_pane`] on failure — so it never persists-/// past the fetch.-fn pr_deferred_loading(mode: PreviewMode) -> String {+/// Placeholder for a deferred forge-fetch tab while its background fetch is still+/// in flight. skim can't re-query a preview on its own, so the hint points at the+/// accelerator that re-reads the cache once the fetch lands — the same contract+/// as the worktree rows' `loading_placeholder`. Shown only during the in-flight+/// window: once the fetch resolves, a terminal pane replaces it — the rendered+/// content or [`pr_unavailable_pane`] on failure — so it never persists past the+/// fetch. Shared with worktree rows' `comments` tab (see+/// [`super::items::WorktreeSkimItem::render_comments_pane`]) so both row types+/// show the identical in-flight pane.+pub(super) fn pr_deferred_loading(mode: PreviewMode) -> String {let reset = Reset;let (label, key) = match mode {PreviewMode::Log => ("commit log", 2u8),@@ -1121,7 +1189,7 @@ impl SkimItem for PrSkimItem {// show a placeholder. The active tab is the same global digit, so an// empty tab shows its placeholder until the user switches with alt-N / Tab.let mode = PreviewStateData::read_mode();- let mut result = render_preview_tabs(mode, TabAvailability::pull_request(), context.width);+ let mut result = render_preview_tabs(mode, TabAvailability::listed_pr(), context.width);match mode {PreviewMode::Pr => result.push_str(&self.pr_pane),PreviewMode::Log | PreviewMode::Comments => result.push_str(&self.cached_pane(mode)),diff --git a/src/commands/picker/snapshots/wt__commands__picker__items__tests__empty_all_local_diffs.snap b/src/commands/picker/snapshots/wt__commands__picker__items__tests__empty_all_local_diffs.snapnew file mode 100644index 000000000..bbf39a298--- /dev/null+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__empty_all_local_diffs.snap@@ -0,0 +1,6 @@+---+source: src/commands/picker/items.rs+expression: "render_preview_tabs(PreviewMode::WorkingTree,\nTabAvailability::worktree(CONTENT_EMPTY, true, false, false), WIDE,)"+---+[2m1:[22m [1mHEAD±[22m[0m | 2: [2mlog[22m[0m | [2m3:[22m [2mmain…±[22m[0m | [2m4:[22m [2mremote⇅[22m[0m | [2m5:[22m [2msummary[22m[0m | [2m6:[22m [2mpr[22m[0m | [2m7:[22m [2mcomments[22m[0m+[33m[2mEnter: switch | Tab/alt-1…7: preview | alt-c: create | Esc: cancel | ctrl-u/d: scroll | alt-p: toggle[39m[22m[0mdiff --git a/src/commands/picker/snapshots/wt__commands__picker__items__tests__pr_row.snap b/src/commands/picker/snapshots/wt__commands__picker__items__tests__pr_row.snapindex 0c3213103..4a7d70013 100644--- a/src/commands/picker/snapshots/wt__commands__picker__items__tests__pr_row.snap+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__pr_row.snap@@ -1,6 +1,6 @@---source: src/commands/picker/items.rs-expression: "render_preview_tabs(PreviewMode::Pr, TabAvailability::pull_request(), WIDE)"+expression: "render_preview_tabs(PreviewMode::Pr, TabAvailability::listed_pr(), WIDE)"---[2m1:[22m [2mHEAD±[22m[0m | 2: [2mlog[22m[0m | [2m3:[22m [2mmain…±[22m[0m | [2m4:[22m [2mremote⇅[22m[0m | [2m5:[22m [2msummary[22m[0m | 6: [1mpr[22m[0m | 7: [2mcomments[22m[0m[33m[2mEnter: switch | Tab/alt-1…7: preview | alt-c: create | Esc: cancel | ctrl-u/d: scroll | alt-p: toggle[39m[22m[0mdiff --git a/tests/integration_tests/switch_picker.rs b/tests/integration_tests/switch_picker.rsindex ab9e1c9a4..c317b92b9 100644--- a/tests/integration_tests/switch_picker.rs+++ b/tests/integration_tests/switch_picker.rs@@ -27,7 +27,7 @@//! - **Content expectations** wait for async preview content to load (e.g., "diff --git")use crate::common::mock_commands::{MockConfig, MockResponse};-use crate::common::{TestRepo, repo, wt_bin};+use crate::common::{TEST_EPOCH, TestRepo, repo, wt_bin};use insta::assert_snapshot;use portable_pty::CommandBuilder;use rstest::rstest;@@ -1066,6 +1066,24 @@ fn test_switch_picker_preview_panel_summary(mut repo: TestRepo) {});}+/// Seed a fresh CI-status cache entry for `branch` so the picker primes the+/// row's `pr_status` at skeleton time (`populate_from_cache`) — making the `pr`+/// and `comments` tabs resolve deterministically with no dependence on the live+/// forge fetch's timing. `status_json` is the cached `status` value: `"null"`+/// for "CI checked, no PR", or a PR object (e.g.+/// `{"ci_status":"passed","source":"pr","is_stale":false,"number":{"number":42,"sigil":"#"}}`).+/// `branch` must be a checked-out worktree — its current HEAD is the cache key.+fn seed_ci_status(repo: &TestRepo, branch: &str, status_json: &str) {+ let head = repo.git_output(&["rev-parse", branch]);+ let cache_dir = repo.path().join(".git/wt/cache/ci-status");+ std::fs::create_dir_all(&cache_dir).unwrap();+ let entry = format!(+ r#"{{"status":{status_json},"checked_at":{TEST_EPOCH},"head":"{head}","branch":"{branch}"}}"#,+ head = head.trim(),+ );+ std::fs::write(cache_dir.join(format!("{branch}.json")), entry).unwrap();+}+/// Install a mock forge CLI (`gh`/`glab`) that answers the `--prs` list call/// from a canned JSON file, and return env vars (mock on PATH + MOCK_CONFIG_DIR)/// for a `wt switch --prs` PTY run. No network is touched. `list_delay_ms`@@ -1232,6 +1250,120 @@ fn test_switch_picker_prs_shows_loading_marker(mut repo: TestRepo) {assert!(!list.contains("#42"), "rows not yet streamed in:\n{list}");}+/// A plain `wt switch` (no `--prs`) worktree row whose branch has an open PR+/// shows the real comment thread in its `comments` tab — the same background+/// `gh pr view <n> --json comments` fetch and render a `--prs` row makes. This+/// is the crux of the unification: the comments tab no longer points a worktree+/// row at `--prs`; it loads the thread directly. The PR is primed from a fresh+/// CI cache so the row resolves to "has PR" at skeleton with no `gh pr list`,+/// and the conversation comes from a mocked `gh pr view`.+#[rstest]+fn test_switch_picker_worktree_row_comments_tab_shows_thread(mut repo: TestRepo) {+ repo.remove_fixture_worktrees();+ repo.run_git(&[+ "remote",+ "set-url",+ "origin",+ "https://github.com/owner/test-repo.git",+ ]);+ let feature_path = repo.add_worktree("feature");+ // Commit a file, then leave an uncommitted edit so `feature`'s HEAD± tab+ // shows a `diff --git` — a preview-only sync anchor (it never appears in the+ // list) that confirms the cursor landed on `feature` before reading comments.+ std::fs::write(feature_path.join("file.txt"), "content\n").unwrap();+ let add = repo+ .git_command()+ .args(["-C", feature_path.to_str().unwrap(), "add", "."])+ .run()+ .unwrap();+ assert!(add.status.success(), "Failed to add file");+ let commit = repo+ .git_command()+ .args([+ "-C",+ feature_path.to_str().unwrap(),+ "commit",+ "-m",+ "Commit for comments tab",+ ])+ .run()+ .unwrap();+ assert!(commit.status.success(), "Failed to commit");+ std::fs::write(feature_path.join("file.txt"), "content\nmore\n").unwrap();++ // Prime a fresh CI status carrying an open PR (#42) so the row resolves to+ // "has PR" at skeleton — detect reads this same fresh entry, so no `gh pr+ // list`. The comments thread still needs a live `gh pr view`, mocked below.+ seed_ci_status(+ &repo,+ "feature",+ r##"{"ci_status":"passed","source":"pr","is_stale":false,"number":{"number":42,"sigil":"#"}}"##,+ );++ // Mock the only forge call a worktree row makes — `gh pr view 42 --json+ // comments` (the `log` tab is local; the `pr` tab rides the cached CI). Any+ // other gh invocation falls through to `_default` exit 1.+ let mock_bin = repo.root_path().join("mock-bin");+ std::fs::create_dir_all(&mock_bin).unwrap();+ let comments_json = r#"{"comments":[{"author":{"login":"octocat"},"body":"Looks solid, shipping it.","createdAt":"2024-12-01T00:00:00Z"}]}"#;+ std::fs::write(mock_bin.join("comments.json"), comments_json).unwrap();+ MockConfig::new("gh")+ .version("gh version 1.0.0 (mock)")+ .command("pr view", MockResponse::file("comments.json"))+ .command("_default", MockResponse::exit(1))+ .write(&mock_bin);+ let mut env_vars = repo.test_env_vars();+ env_vars.push((+ "MOCK_CONFIG_DIR".to_string(),+ mock_bin.display().to_string(),+ ));+ // Prepend mock-bin to PATH using the OS separator (`;` on Windows, `:` on+ // Unix) — a hardcoded `:` corrupts the PATH on Windows, so the mock `gh.exe`+ // is never found and the comments fetch fails ("Couldn't load comments").+ let base_path = std::env::var_os("PATH").unwrap_or_default();+ let mut paths = vec![mock_bin.clone()];+ paths.extend(std::env::split_paths(&base_path));+ let joined = std::env::join_paths(paths).expect("mock-bin joins into PATH");+ env_vars.push(("PATH".to_string(), joined.to_string_lossy().into_owned()));++ let result = exec_in_pty_capture_before_abort(+ wt_bin().to_str().unwrap(),+ &["switch"],+ repo.root_path(),+ &env_vars,+ &[+ // Cursor-navigation select: see test_switch_picker_preview_panel_uncommitted+ // for the matcher-lag rationale.+ ("\x1b[B", None), // Down: move cursor to `feature`+ // Alt-1: HEAD± panel. `feature`'s uncommitted diff (`diff --git`) is a+ // preview-only anchor — it confirms the cursor landed on `feature`+ // (not `main`) and gives the skeleton-spawned comments fetch time to+ // land before we read its tab.+ ("\x1b1", Some("diff --git")),+ // Alt-7: jump to comments (7). The thread was fetched in the+ // background at skeleton time (the PR was primed), so it's cached by+ // now — wait for the comment body to confirm the real thread renders.+ ("\x1b7", Some("Looks solid")),+ ],+ );++ assert_valid_abort_exit_code(result.exit_code);+ let (_list, preview) = result.panels();+ assert!(+ preview.contains("octocat"),+ "comment author renders on a worktree row's comments tab:\n{preview}"+ );+ assert!(+ preview.contains("Looks solid"),+ "comment body renders on a worktree row's comments tab:\n{preview}"+ );+ // No `--prs` pointer — the worktree row loads the thread itself.+ assert!(+ !preview.contains("--prs"),+ "comments tab must not point at --prs:\n{preview}"+ );+}+#[rstest]fn test_switch_picker_preview_cycle_tab_forward(mut repo: TestRepo) {// Tab cycles the preview tab forward. From the default HEAD± tab (1), one@@ -1319,6 +1451,8 @@ fn test_switch_picker_preview_cycle_tab_forward_wraps(mut repo: TestRepo) {.unwrap();assert!(commit.status.success(), "Failed to commit");+ seed_ci_status(&repo, "feature", "null");+let env_vars = repo.test_env_vars();let result = exec_in_pty_capture_before_abort(wt_bin().to_str().unwrap(),@@ -1329,9 +1463,10 @@ fn test_switch_picker_preview_cycle_tab_forward_wraps(mut repo: TestRepo) {// Cursor-navigation select: see test_switch_picker_preview_panel_uncommitted// for the matcher-lag rationale.("\x1b[B", None), // Down: move cursor to `feature`- // Alt-7: jump to comments (7). On a worktree row the comments tab- // points at `--prs` rows (it's fetched only there).- ("\x1b7", Some("--prs")),+ // Alt-7: jump to comments (7). The comments tab behaves the same on a+ // worktree row as on a `--prs` row — with no PR (seeded above) it shows+ // "has no PR", matching the `pr` tab.+ ("\x1b7", Some("has no PR")),("\t", Some("no uncommitted changes")), // Tab: wrap 7 → HEAD± (1)],);@@ -1374,6 +1509,8 @@ fn test_switch_picker_preview_cycle_shift_tab_wraps(mut repo: TestRepo) {.unwrap();assert!(commit.status.success(), "Failed to commit");+ seed_ci_status(&repo, "feature", "null");+let env_vars = repo.test_env_vars();let result = exec_in_pty_capture_before_abort(wt_bin().to_str().unwrap(),@@ -1384,9 +1521,9 @@ fn test_switch_picker_preview_cycle_shift_tab_wraps(mut repo: TestRepo) {// Cursor-navigation select: see test_switch_picker_preview_panel_uncommitted// for the matcher-lag rationale.("\x1b[B", None), // Down: move cursor to `feature`- // Shift-Tab: HEAD± (1) → comments (7), the 1 → 7 wraparound. The- // comments tab on a worktree row points at `--prs` rows.- ("\x1b[Z", Some("--prs")),+ // Shift-Tab: HEAD± (1) → comments (7), the 1 → 7 wraparound. With no PR+ // (seeded above) the comments tab shows "has no PR", like the `pr` tab.+ ("\x1b[Z", Some("has no PR")),],);@@ -1394,7 +1531,7 @@ fn test_switch_picker_preview_cycle_shift_tab_wraps(mut repo: TestRepo) {let (_list, preview) = result.panels();assert!(- preview.contains("Comments show on"),+ preview.contains("has no PR"),"Shift-Tab should wrap to the comments tab; preview was:\n{preview}");}diff --git a/tests/integration_tests/switch_picker_dry_run.rs b/tests/integration_tests/switch_picker_dry_run.rsindex fbff5f557..d0e1f5abe 100644--- a/tests/integration_tests/switch_picker_dry_run.rs+++ b/tests/integration_tests/switch_picker_dry_run.rs@@ -121,6 +121,28 @@ fn test_picker_dry_run_shows_cached_pr_numbers(mut repo: TestRepo) {!other_row.contains('#'),"uncached branch renders an empty CI cell, got: {other_row}");++ // The worktree row with a PR spawns a `comments` background fetch keyed by+ // its branch name (PreviewMode::Comments == 7) — 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"]+ .as_array()+ .expect("top-level `entries` array")+ .iter()+ .filter(|e| e["mode"] == 7)+ .map(|e| e["branch"].as_str().expect("branch is a string"))+ .collect();+ assert!(+ comments_branches.contains(&"feature-a"),+ "the PR-bearing worktree row spawns a branch-keyed comments fetch, got: {comments_branches:?}"+ );+ assert!(+ !comments_branches.contains(&"feature-b"),+ "the PR-less worktree row spawns no comments fetch, got: {comments_branches:?}"+ );}/// Verifies that warnings collect emits while running on the picker's bg