Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat(switch): log + comments preview tabs for --prs picker rows (#3169)
Maximilian Roosb3e1fc06b480
diff --git a/CLAUDE.md b/CLAUDE.mdindex 50090aba0..8b2a5799c 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -106,7 +106,7 @@ What currently reaches the wire:- 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 branch-- `wt switch --prs` — one `gh pr list` / `glab mr list` to populate the interactive picker (streamed in after the frame paints)+- `wt switch --prs` — one `gh pr list` / `glab mr list` to populate the interactive picker (streamed in after the frame paints), then a per-row background `gh pr view <n> --json comments` (`glab api …/notes` on GitLab) to fill each row's `comments` preview tab, plus a `gh pr view <n> --json commits` / `glab api …/commits` for the `log` tab **only when the head commit isn't already local** — a `--prs` row whose `headRefOid`/`sha` resolves in the object store renders the `log` tab from a local `git log` with no network (off the pool, once per row when the rows land — see `picker::prs::spawn_pr_previews`)- `wt config show --full` — version check against GitHub- the first `Repository::default_branch()` per repo — `git ls-remote` (above)diff --git a/docs/content/switch.md b/docs/content/switch.mdindex 19d44ca85..310f75b8b 100644--- a/docs/content/switch.md+++ b/docs/content/switch.md@@ -76,7 +76,7 @@ The CI column shows each row's PR/MR CI and review status, the same as [`wt list| `Enter` | Switch to selected worktree || `Alt-c` | Create new worktree named as entered text || `Esc` | Cancel |-| `Alt-1`–`Alt-6` | Jump to a preview tab |+| `Alt-1`–`Alt-7` | Jump to a preview tab || `Tab`/`Shift-Tab` | Cycle preview tabs forward/backward || `Alt-p` | Toggle preview panel || `Ctrl-u`/`Ctrl-d` | Scroll preview up/down |@@ -94,6 +94,9 @@ Typing a gutter sigil filters by row kind: `+` narrows to linked worktrees and `4. **remote⇅** — Ahead/behind diff vs upstream tracking branch5. **summary** — LLM-generated branch summary; requires `[list] summary = true` and [`commit.generation`](@/config.md#commit)6. **pr** — The selected row's PR/MR, for any row whose branch has one+7. **comments** — The PR/MR's comment thread, fetched from the forge on `--prs` rows++On narrow previews the tab bar compacts to digits — only the active tab keeps its label — so every `Alt-N` accelerator stays visible.**Pager configuration:** The preview panel pipes diff output through git's pager. Override in user config:@@ -114,7 +117,7 @@ Both work anywhere a branch is accepted, including `--base`. The `--create` flagIf the PR or MR is on a fork, the local branch uses its branch name directly, so `git push` works normally. A pre-existing local branch with that name tracking something else requires renaming first.-The `--prs` flag adds the repository's open PRs (GitHub) or MRs (GitLab) to the interactive picker. Each row resolves to the same `pr:`/`mr:` shortcut, so selecting one fetches the ref and switches to its branch.+The `--prs` flag adds the repository's open PRs (GitHub) or MRs (GitLab) to the interactive picker. Each row resolves to the same `pr:`/`mr:` shortcut, so selecting one fetches the ref and switches to its branch. A `--prs` row has no local worktree, so its `pr` and `comments` preview tabs load the PR/MR's metadata and comments from the forge in the background. The `log` tab uses a local `git log` — graph and merge-base dimming included — whenever the head commit is already in the object store (a same-repo PR off a fetched remote), falling back to a flat forge-fetched commit list otherwise.Requires `gh` (GitHub), `glab` (GitLab), or an equivalent CLI installed and authenticated; see [forge platform](@/config.md#forge-platform) for Gitea, Azure DevOps, and other supported platforms.diff --git a/skills/worktrunk/reference/switch.md b/skills/worktrunk/reference/switch.mdindex 7a71cab4a..9a00efab6 100644--- a/skills/worktrunk/reference/switch.md+++ b/skills/worktrunk/reference/switch.md@@ -72,7 +72,7 @@ The CI column shows each row's PR/MR CI and review status, the same as [`wt list| `Enter` | Switch to selected worktree || `Alt-c` | Create new worktree named as entered text || `Esc` | Cancel |-| `Alt-1`–`Alt-6` | Jump to a preview tab |+| `Alt-1`–`Alt-7` | Jump to a preview tab || `Tab`/`Shift-Tab` | Cycle preview tabs forward/backward || `Alt-p` | Toggle preview panel || `Ctrl-u`/`Ctrl-d` | Scroll preview up/down |@@ -90,6 +90,9 @@ Typing a gutter sigil filters by row kind: `+` narrows to linked worktrees and `4. **remote⇅** — Ahead/behind diff vs upstream tracking branch5. **summary** — LLM-generated branch summary; requires `[list] summary = true` and [`commit.generation`](https://worktrunk.dev/config/#commit)6. **pr** — The selected row's PR/MR, for any row whose branch has one+7. **comments** — The PR/MR's comment thread, fetched from the forge on `--prs` rows++On narrow previews the tab bar compacts to digits — only the active tab keeps its label — so every `Alt-N` accelerator stays visible.**Pager configuration:** The preview panel pipes diff output through git's pager. Override in user config:@@ -116,7 +119,7 @@ Both work anywhere a branch is accepted, including `--base`. The `--create` flagIf the PR or MR is on a fork, the local branch uses its branch name directly, so `git push` works normally. A pre-existing local branch with that name tracking something else requires renaming first.-The `--prs` flag adds the repository's open PRs (GitHub) or MRs (GitLab) to the interactive picker. Each row resolves to the same `pr:`/`mr:` shortcut, so selecting one fetches the ref and switches to its branch.+The `--prs` flag adds the repository's open PRs (GitHub) or MRs (GitLab) to the interactive picker. Each row resolves to the same `pr:`/`mr:` shortcut, so selecting one fetches the ref and switches to its branch. A `--prs` row has no local worktree, so its `pr` and `comments` preview tabs load the PR/MR's metadata and comments from the forge in the background. The `log` tab uses a local `git log` — graph and merge-base dimming included — whenever the head commit is already in the object store (a same-repo PR off a fetched remote), falling back to a flat forge-fetched commit list otherwise.Requires `gh` (GitHub), `glab` (GitLab), or an equivalent CLI installed and authenticated; see [forge platform](https://worktrunk.dev/config/#forge-platform) for Gitea, Azure DevOps, and other supported platforms.diff --git a/src/cli/mod.rs b/src/cli/mod.rsindex f8c387124..0187de6bb 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -666,7 +666,7 @@ The CI column shows each row's PR/MR CI and review status, the same as [`wt list| `Enter` | Switch to selected worktree || `Alt-c` | Create new worktree named as entered text || `Esc` | Cancel |-| `Alt-1`–`Alt-6` | Jump to a preview tab |+| `Alt-1`–`Alt-7` | Jump to a preview tab || `Tab`/`Shift-Tab` | Cycle preview tabs forward/backward || `Alt-p` | Toggle preview panel || `Ctrl-u`/`Ctrl-d` | Scroll preview up/down |@@ -684,6 +684,9 @@ Typing a gutter sigil filters by row kind: `+` narrows to linked worktrees and `4. **remote⇅** — Ahead/behind diff vs upstream tracking branch5. **summary** — LLM-generated branch summary; requires `[list] summary = true` and [`commit.generation`](@/config.md#commit)6. **pr** — The selected row's PR/MR, for any row whose branch has one+7. **comments** — The PR/MR's comment thread, fetched from the forge on `--prs` rows++On narrow previews the tab bar compacts to digits — only the active tab keeps its label — so every `Alt-N` accelerator stays visible.**Pager configuration:** The preview panel pipes diff output through git's pager. Override in user config:@@ -710,7 +713,7 @@ Both work anywhere a branch is accepted, including `--base`. The `--create` flagIf the PR or MR is on a fork, the local branch uses its branch name directly, so `git push` works normally. A pre-existing local branch with that name tracking something else requires renaming first.-The `--prs` flag adds the repository's open PRs (GitHub) or MRs (GitLab) to the interactive picker. Each row resolves to the same `pr:`/`mr:` shortcut, so selecting one fetches the ref and switches to its branch.+The `--prs` flag adds the repository's open PRs (GitHub) or MRs (GitLab) to the interactive picker. Each row resolves to the same `pr:`/`mr:` shortcut, so selecting one fetches the ref and switches to its branch. A `--prs` row has no local worktree, so its `pr` and `comments` preview tabs load the PR/MR's metadata and comments from the forge in the background. The `log` tab uses a local `git log` — graph and merge-base dimming included — whenever the head commit is already in the object store (a same-repo PR off a fetched remote), falling back to a flat forge-fetched commit list otherwise.Requires `gh` (GitHub), `glab` (GitLab), or an equivalent CLI installed and authenticated; see [forge platform](@/config.md#forge-platform) for Gitea, Azure DevOps, and other supported platforms.diff --git a/src/commands/picker/items.rs b/src/commands/picker/items.rsindex 7345faad9..dd4d9e096 100644--- a/src/commands/picker/items.rs+++ b/src/commands/picker/items.rs@@ -14,7 +14,7 @@ use dashmap::DashMap;use ratatui::text::{Line, Span};use skim::prelude::*;use worktrunk::git::Repository;-use worktrunk::styling::INFO_SYMBOL;+use worktrunk::styling::{INFO_SYMBOL, visual_width};use super::super::list::ci_status::{PrRef, PrStatus};use super::super::list::model::ListItem;@@ -264,13 +264,15 @@ pub(super) struct TabAvailability {upstream: bool,summary: bool,pr: bool,+ comments: bool,}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`]).+ /// 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 {Self {working_tree: true,@@ -279,98 +281,188 @@ impl TabAvailability {upstream: has_upstream,summary: summaries_enabled,pr,+ comments: false,}}- /// A `--prs` row: it carries no local worktree, so only the PR tab has- /// content; tabs 1-5 are empty.+ /// 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: false,+ log: true,branch_diff: false,upstream: false,summary: false,pr: true,+ comments: true,}}}+/// One preview tab's identity: its `alt-N` digit, label, and whether it's the+/// active mode / has content for the current row. Built once, then rendered+/// full or compact depending on the pane width.+struct Tab {+ number: u8,+ label: &'static str,+ is_active: bool,+ has_content: bool,+}+/// Render the preview tab bar, shared by worktree rows and `--prs` rows.///-/// Every tab always keeps its `N: label` text — only the formatting varies, so-/// the accelerators stay discoverable. Two **orthogonal** signals carry through-/// the styling: the **number's** brightness says whether the tab is selectable-/// (normal = has content, dim = empty for this row — see `TabAvailability`),-/// and the **label's** weight says whether it's the active mode (bold = active,-/// dim = inactive). The two compose independently: an empty tab dims its number-/// whether or not it's selected, but the active tab's label still bolds — so an-/// active-but-empty tab (dim number, bold label) stays distinct from an-/// inactive-empty one (dim number, dim label), and the selected tab is always-/// identifiable even when it has nothing to show (its pane, e.g. "… has no PR",-/// says the rest).-pub(super) fn render_preview_tabs(mode: PreviewMode, avail: TabAvailability) -> String {- // Full SGR reset (\x1b[0m) after each styled span. color_print's `</>`- // emits only \x1b[22m (intensity reset); pairing it with an explicit [0m- // keeps dim/bold from bleeding across the dividers and into the rest of the- // line in the list and preview panels. Same reason the `compute_*_preview`- // helpers below scatter `{reset}` after each styled span.+/// Every full-form tab keeps its `N: label` text — only the formatting varies,+/// so the accelerators stay discoverable. Two **orthogonal** signals carry+/// through the styling: the **number's** brightness says whether the tab is+/// selectable (normal = has content, dim = empty for this row — see+/// `TabAvailability`), and the **label's** weight says whether it's the active+/// mode (bold = active, dim = inactive). The two compose independently: an empty+/// tab dims its number whether or not it's selected, but the active tab's label+/// still bolds — so an active-but-empty tab (dim number, bold label) stays+/// distinct from an inactive-empty one (dim number, dim label), and the selected+/// tab is always identifiable even when it has nothing to show (its pane, e.g.+/// "… has no PR", says the rest).+///+/// **Width adaptation.** skim renders previews with wrapping off (its default),+/// so a tab bar wider than `width` would truncate on the right — and the `pr` /+/// `comments` tabs, exactly the ones with content on a `--prs` row, sit at that+/// end. When the seven full-form tabs don't fit, the bar falls back to a compact+/// form (`1 2: log 3 …`): every accelerator digit stays visible, but only the+/// active tab keeps its label. The two style signals survive — empty digits dim,+/// the active digit+label bolds — so navigation works at any width. `width` is+/// the preview pane width skim reports.+pub(super) fn render_preview_tabs(+ mode: PreviewMode,+ avail: TabAvailability,+ width: usize,+) -> String {let reset = Reset;- /// Format one tab, keeping the `N: label` text in every state so the- /// accelerator never disappears. The number and label carry the two- /// orthogonal signals independently: the number dims when the tab is empty- /// (not selectable), and the label bolds on the active tab. They compose,- /// so an active-but-empty tab is dim-number + bold-label — distinct from an- /// inactive-empty one (dim-number + dim-label).- fn format_tab(number: u8, label: &str, is_active: bool, has_content: bool) -> String {- let number = if has_content {- format!("{number}:")- } else {- cformat!("<dim>{number}:</>")- };- let label = if is_active {- cformat!("<bold>{label}</>")- } else {- cformat!("<dim>{label}</>")- };- format!("{number} {label}")- }-- let tab1 = format_tab(- 1,- "HEAD±",- mode == PreviewMode::WorkingTree,- avail.working_tree,- );- let tab2 = format_tab(2, "log", mode == PreviewMode::Log, avail.log);- let tab3 = format_tab(- 3,- "main…±",- mode == PreviewMode::BranchDiff,- avail.branch_diff,- );- let tab4 = format_tab(- 4,- "remote⇅",- mode == PreviewMode::UpstreamDiff,- avail.upstream,- );- let tab5 = format_tab(5, "summary", mode == PreviewMode::Summary, avail.summary);- let tab6 = format_tab(6, "pr", mode == PreviewMode::Pr, avail.pr);+ let tabs = [+ Tab {+ number: 1,+ label: "HEAD±",+ is_active: mode == PreviewMode::WorkingTree,+ has_content: avail.working_tree,+ },+ Tab {+ number: 2,+ label: "log",+ is_active: mode == PreviewMode::Log,+ has_content: avail.log,+ },+ Tab {+ number: 3,+ label: "main…±",+ is_active: mode == PreviewMode::BranchDiff,+ has_content: avail.branch_diff,+ },+ Tab {+ number: 4,+ label: "remote⇅",+ is_active: mode == PreviewMode::UpstreamDiff,+ has_content: avail.upstream,+ },+ Tab {+ number: 5,+ label: "summary",+ is_active: mode == PreviewMode::Summary,+ has_content: avail.summary,+ },+ Tab {+ number: 6,+ label: "pr",+ is_active: mode == PreviewMode::Pr,+ has_content: avail.pr,+ },+ Tab {+ number: 7,+ label: "comments",+ is_active: mode == PreviewMode::Comments,+ has_content: avail.comments,+ },+ ];++ // Prefer the full bar; fall back to compact only when it would overflow the+ // pane (`visual_width` measures the styled string with ANSI stripped).+ let full = render_tab_row_full(&tabs, reset);+ let bar = if visual_width(&full) <= width {+ full+ } else {+ render_tab_row_compact(&tabs, reset)+ };// Controls use dim yellow to distinguish from dimmed (white) tabs.// The tab numbers above are the alt-N accelerators (bare digits type// into the query); Tab/shift-tab cycle the same tabs.+ //+ // The controls line is intentionally NOT width-managed: skim clips it on the+ // right on a narrow pane, but it's only a reminder — the accelerators it+ // names live in the tab bar above, which IS width-managed, so nothing+ // navigable is lost when the tail clips.let controls = cformat!(- "<dim,yellow>Enter: switch | Tab/alt-1…6: preview | alt-c: create | Esc: cancel | ctrl-u/d: scroll | alt-p: toggle</>"+ "<dim,yellow>Enter: switch | Tab/alt-1…7: preview | alt-c: create | Esc: cancel | ctrl-u/d: scroll | alt-p: toggle</>");- // End each tab and controls with full reset to prevent style bleeding- // into dividers and preview content- format!(- "{tab1}{reset} | {tab2}{reset} | {tab3}{reset} | {tab4}{reset} | {tab5}{reset} | {tab6}{reset}\n{controls}{reset}\n\n"- )+ // Each tab/segment already ends with a full reset (so styling never bleeds+ // into the dividers or preview content); `{reset}` here only closes the+ // controls line's dim-yellow span.+ format!("{bar}\n{controls}{reset}\n\n")+}++/// Full tab bar: `N: label` per tab, ` | `-separated. The number dims when the+/// tab is empty (not selectable), and the label bolds on the active tab — two+/// orthogonal signals that compose (see [`render_preview_tabs`]).+fn render_tab_row_full(tabs: &[Tab], reset: Reset) -> String {+ tabs.iter()+ .map(|t| {+ let number = if t.has_content {+ format!("{}:", t.number)+ } else {+ cformat!("<dim>{}:</>", t.number)+ };+ let label = if t.is_active {+ cformat!("<bold>{}</>", t.label)+ } else {+ cformat!("<dim>{}</>", t.label)+ };+ format!("{number} {label}{reset}")+ })+ .collect::<Vec<_>>()+ .join(" | ")+}++/// Compact tab bar for narrow panes: just the digits, space-separated, with the+/// active tab keeping its label (`1 2: log 3 …`). The number still dims when+/// empty and the active digit+label bolds, so both style signals survive and+/// every accelerator stays visible — only the inactive labels drop.+fn render_tab_row_compact(tabs: &[Tab], reset: Reset) -> String {+ tabs.iter()+ .map(|t| {+ if t.is_active {+ // Active: `N: label`, with the number bold (and dim too when empty).+ let number = if t.has_content {+ cformat!("<bold>{}:</>", t.number)+ } else {+ cformat!("<dim,bold>{}:</>", t.number)+ };+ format!("{number} {}{reset}", cformat!("<bold>{}</>", t.label))+ } else {+ // Inactive: just the digit, dim when empty.+ let number = if t.has_content {+ t.number.to_string()+ } else {+ cformat!("<dim>{}</>", t.number)+ };+ format!("{number}{reset}")+ }+ })+ .collect::<Vec<_>>()+ .join(" ")}/// The `pr` pane for a worktree row whose branch has a PR/MR. Renders the same@@ -414,9 +506,12 @@ impl WorktreeSkimItem {self.summaries_enabled,self.pr_tab_available(),);- let mut result = render_preview_tabs(mode, avail);+ 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(),_ => self.preview_for_mode(mode, width, height),});result@@ -485,6 +580,15 @@ 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 {+ let reset = Reset;+ cformat!("{INFO_SYMBOL}{reset} Comments show on <bold>wt switch --prs</>{reset} rows\n")+ }+/// Render preview for the given mode with specified dimensions.////// Pure cache read: skim invokes `preview()` synchronously while drawing@@ -521,9 +625,14 @@ impl WorktreeSkimItem {PreviewMode::BranchDiff => ("Loading", "branch diff"),PreviewMode::UpstreamDiff => ("Loading", "upstream diff"),PreviewMode::Summary => ("Generating", "summary"),- // The `pr` tab has no background task — `preview()` renders it from- // the row's cached `pr_status` via `render_pr_pane`, never here.+ // 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.PreviewMode::Pr => unreachable!("pr tab renders via render_pr_pane"),+ PreviewMode::Comments => {+ unreachable!("comments tab renders via comments_unavailable_pane")+ }};let key = mode as u8;format!("○ {verb} {label}. Press alt-{key} again to refresh.\n")@@ -562,10 +671,12 @@ impl WorktreeSkimItem {false,),PreviewMode::Summary => (Self::loading_placeholder(PreviewMode::Summary), false),- // PR previews never precompute (no git/LLM work) — the orchestrator- // never spawns this mode, and `preview()` renders the `pr` pane from- // the row's cached `pr_status`.+ // PR and comments previews never precompute on worktree rows (no+ // git/LLM work) — the orchestrator never spawns these modes, and+ // `preview()` renders them directly (cached `pr_status` / the+ // `--prs`-only pointer).PreviewMode::Pr => unreachable!("pr tab is never precomputed"),+ PreviewMode::Comments => unreachable!("comments tab is never precomputed"),}}@@ -764,7 +875,7 @@ impl WorktreeSkimItem {width: usize,height: usize,) -> (String, bool) {- Self::compute_log_preview_inner(repo, item, width, height, false)+ Self::compute_log_preview_inner(repo, item.head(), item.branch_name(), width, height, false)}/// Force-recompute the Log preview, bypassing the disk-cache read but@@ -777,12 +888,31 @@ impl WorktreeSkimItem {width: usize,height: usize,) -> String {- Self::compute_log_preview_inner(repo, item, width, height, true).0+ Self::compute_log_preview_inner(repo, item.head(), item.branch_name(), width, height, true)+ .0+ }++ /// Render the rich local `git log` for an arbitrary `(head, branch)` pair —+ /// the same graph + dim/bright merge-base split + timestamps the worktree+ /// rows show. Used by the `--prs` `log` tab for a row whose head commit is+ /// already in the local object store (a same-repo PR off a fetched+ /// `origin`); see `prs::compute_pr_log`. Discards the disk-hit flag — a+ /// `--prs` row's preview renders once with no background-refresh loop, so+ /// there's nothing to reschedule.+ pub(super) fn compute_log_for_head(+ repo: &Repository,+ head: &str,+ branch: &str,+ width: usize,+ height: usize,+ ) -> String {+ Self::compute_log_preview_inner(repo, head, branch, width, height, false).0}fn compute_log_preview_inner(repo: &Repository,- item: &ListItem,+ head: &str,+ branch: &str,width: usize,height: usize,force_recompute: bool,@@ -796,8 +926,6 @@ impl WorktreeSkimItem {let show_timestamps = width >= TIMESTAMP_WIDTH_THRESHOLD;// Calculate how many log lines fit in preview (height minus header)let log_limit = height.saturating_sub(HEADER_LINES).max(1);- let head = item.head();- let branch = item.branch_name();let reset = Reset;let Some(default_branch) = repo.default_branch() else {return (@@ -958,13 +1086,18 @@ impl WorktreeSkimItem {#[cfg(test)]mod tests {use super::*;+ use ansi_str::AnsiStr;use insta::assert_snapshot;+ /// Width at which all seven full-form tabs fit, so the snapshots capture the+ /// full bar (the compact fallback has its own test).+ const WIDE: usize = 200;+#[test]fn test_render_preview_tabs() {- // Each mode active, on a worktree row with upstream + summaries- // enabled but no PR (tabs 1-5 available; tab 6 dim). The active- // mode's label is bold, inactive available labels dim, and on the+ // 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);@@ -976,21 +1109,73 @@ mod tests {("summary", PreviewMode::Summary),("pr", PreviewMode::Pr),] {- assert_snapshot!(name, render_preview_tabs(mode, wt));+ 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 tabs 1-5.+ // 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.assert_snapshot!("empty_upstream_and_summary",render_preview_tabs(PreviewMode::WorkingTree,- TabAvailability::worktree(false, false, false)+ TabAvailability::worktree(false, false, false),+ WIDE,));assert_snapshot!("pr_row",- render_preview_tabs(PreviewMode::Pr, TabAvailability::pull_request())+ render_preview_tabs(PreviewMode::Pr, TabAvailability::pull_request(), WIDE)+ );+ }++ /// Narrow panes can't fit the full bar (skim renders previews with wrapping+ /// off, so it would truncate the `pr` / `comments` tabs — exactly the ones+ /// with content on a `--prs` row). The compact fallback keeps every+ /// accelerator digit visible and labels only the active tab.+ #[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 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 {+ assert!(+ plain.contains(&n.to_string()),+ "digit {n} present: {plain:?}"+ );+ }+ assert!(plain.contains("6: pr"), "active tab labeled: {plain:?}");+ assert!(+ !plain.contains("comments"),+ "inactive label dropped: {plain:?}"+ );+ assert!(!plain.contains("HEAD"), "inactive label dropped: {plain:?}");+ // The compact bar fits a narrow pane where the full bar would not.+ 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);+ assert!(+ full.contains("7: ") && full.contains("comments"),+ "wide pane keeps full labels"+ );++ // Boundary: the switch is `visual_width(full) <= width`. Measure the full+ // 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 full_w = visual_width(full.lines().next().unwrap());+ let at_fit = render_preview_tabs(PreviewMode::Pr, avail, full_w);+ assert!(+ at_fit.contains("comments"),+ "full bar at exact-fit width: {at_fit:?}"+ );+ let one_under = render_preview_tabs(PreviewMode::Pr, avail, full_w - 1);+ assert!(+ !one_under.contains("comments"),+ "compacts one column under: {one_under:?}");}@@ -1227,7 +1412,12 @@ mod tests {// pane — the dispatch arm `SkimItem::preview` reaches once the picker-state// file selects mode 6. The pane shows the title and the markdown body.let pr_pane = row.render_preview(PreviewMode::Pr, 80, 24);- assert!(pr_pane.contains("6: pr"), "tab bar: {pr_pane:?}");+ // Strip ANSI before checking the tab labels: the active `pr` tab is bold,+ // so `6: pr` is split by an SGR escape in the raw string (the bar's own+ // test, `test_render_preview_tabs`, snapshots the styled form).+ let bar = pr_pane.ansi_strip().to_string();+ assert!(bar.contains("6: pr"), "pr tab: {bar:?}");+ assert!(bar.contains("7: comments"), "comments tab: {bar:?}");assert!(pr_pane.contains("Fix the flaky retry"),"title: {pr_pane:?}"@@ -1617,13 +1807,15 @@ mod tests {#[test]fn test_render_preview_tabs_ansi_codes() {// Test that ANSI escape sequences properly reset to prevent style bleeding.- // The per-tab `{reset}` is appended in the outer format regardless of a+ // The per-tab `{reset}` is appended in the full bar regardless of a// tab's internal styling, so the reset/divider counts hold whether a tab// is active (bold label), inactive-available (dim label), or empty (dim- // number + label — here tab 6, pr).+ // number + label — here tabs 6 pr and 7 comments). WIDE forces the full+ // (not compact) bar.let output = render_preview_tabs(PreviewMode::WorkingTree,TabAvailability::worktree(true, true, false),+ WIDE,);let first_line = output.lines().next().unwrap();@@ -1633,13 +1825,13 @@ mod tests {// This prevents bold/dim from bleeding into the " | " dividerslet full_reset = "\x1b[0m";- // Count resets - should have one after each of the 6 tabs- assert_eq!(first_line.matches(full_reset).count(), 6);+ // Count resets - should have one after each of the 7 tabs+ assert_eq!(first_line.matches(full_reset).count(), 7);// The sequence should be: style + text + [22m + [0m + divider// Check that dividers come after full resetslet parts: Vec<&str> = first_line.split(" | ").collect();- assert_eq!(parts.len(), 6);+ assert_eq!(parts.len(), 7);assert!(parts.iter().all(|part| part.ends_with(full_reset)));// Controls line should end with full reset to ensure clean state for preview contentdiff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex e313064cb..60cc0e133 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -686,11 +686,11 @@ pub fn handle_picker(.color("fg:-1,bg:-1,header:-1,matched:108,current:237,current_bg:251,current_match:108").cmd_collector(Rc::new(RefCell::new(collector)) as Rc<RefCell<dyn CommandCollector>>).bind(vec![- // Preview-tab switching. Bare digits 1-6 are intentionally NOT+ // Preview-tab switching. Bare digits 1-7 are intentionally NOT// bound — they flow to the query input so a number can be typed// (a PR number, or digits within a branch name). Two ways to// switch tabs remain:- // * alt-1..alt-6 jump straight to a tab. skim 4.x parses+ // * alt-1..alt-7 jump straight to a tab. skim 4.x parses// `alt-<digit>` natively via crossterm; an unparsable bind is// just logged and dropped.// * tab / shift-tab cycle forward / backward (below).@@ -718,10 +718,14 @@ pub fn handle_picker("alt-6:execute-silent(echo 6 > {0})+refresh-preview",state_path_str),+ format!(+ "alt-7:execute-silent(echo 7 > {0})+refresh-preview",+ state_path_str+ ),// Cycle tabs with tab / shift-tab. The state file holds the current- // digit; `tr` rotates it (1→2→3→4→5→6→1 forward, the reverse for- // btab) with wraparound, via a temp file + rename so the read and- // write don't race on one path. Two hard constraints shape this:+ // digit; `tr` rotates it (1→2→…→7→1 forward, the reverse for btab)+ // with wraparound, via a temp file + rename so the read and write+ // don't race on one path. Two hard constraints shape this:// * Paren-free — skim 4.x parses an `execute-silent(…)` body by// splitting at the first `(` and trimming the trailing `)`, and// splits the action chain on `+`. So the body must contain no@@ -746,19 +750,19 @@ pub fn handle_picker(// report (`btab` / `shift-btab` / `shift-tab`) so the override holds// regardless of terminal. (Plain Tab is unambiguous — `Tab+NONE`.)format!(- "tab:execute-silent(tr 123456 234561 < {0} > {0}.tmp; mv {0}.tmp {0})+refresh-preview",+ "tab:execute-silent(tr 1234567 2345671 < {0} > {0}.tmp; mv {0}.tmp {0})+refresh-preview",state_path_str),format!(- "btab:execute-silent(tr 123456 612345 < {0} > {0}.tmp; mv {0}.tmp {0})+refresh-preview",+ "btab:execute-silent(tr 1234567 7123456 < {0} > {0}.tmp; mv {0}.tmp {0})+refresh-preview",state_path_str),format!(- "shift-btab:execute-silent(tr 123456 612345 < {0} > {0}.tmp; mv {0}.tmp {0})+refresh-preview",+ "shift-btab:execute-silent(tr 1234567 7123456 < {0} > {0}.tmp; mv {0}.tmp {0})+refresh-preview",state_path_str),format!(- "shift-tab:execute-silent(tr 123456 612345 < {0} > {0}.tmp; mv {0}.tmp {0})+refresh-preview",+ "shift-tab:execute-silent(tr 1234567 7123456 < {0} > {0}.tmp; mv {0}.tmp {0})+refresh-preview",state_path_str),// Create new worktree with query as branch name (alt-c for "create")@@ -869,6 +873,7 @@ pub fn handle_picker(let prs_repo = repo.clone();let prs_warnings = Arc::clone(&stashed_warnings);let prs_grid = Arc::clone(&grid_slot);+ let prs_orchestrator = Arc::clone(&orchestrator);let prs_render_tx = Arc::clone(&render_tx);Some(std::thread::Builder::new()@@ -876,12 +881,18 @@ pub fn handle_picker(.spawn(move || {prs::stream_open_prs(&prs_repo,- skim_list_width,+ &prs::PrsLayout {+ list_width: skim_list_width,+ preview_dims,+ },&prs_tx,&prs_warnings,&prs_grid,- &prs_loading,- &prs_render_tx,+ &prs_orchestrator,+ &prs::PrsStreamSignal {+ pending: &prs_loading,+ render_tx: &prs_render_tx,+ },);}).context("Failed to spawn picker-prs thread")?,diff --git a/src/commands/picker/pr_pane.rs b/src/commands/picker/pr_pane.rsindex a84edf9ca..d69eeae0a 100644--- a/src/commands/picker/pr_pane.rs+++ b/src/commands/picker/pr_pane.rs@@ -64,10 +64,19 @@ pub(super) fn description(body: &str, width: usize) -> String {return String::new();}let reset = Reset;+ format!("\n{reset}{}\n", markdown_in_gutter(body, width))+}++/// Render `body` as markdown and quote it in the house gutter, returning no+/// leading/trailing newline — the shared inner form behind [`description`] and+/// the `--prs` comments pane (`prs::render_comment_blocks`), so the PR/MR body+/// and each comment read alike. The markdown wraps to the gutter's inner width+/// (the bar plus its pad take two columns) so the gutter's own wrap is a no-op+/// rather than re-breaking the already-styled lines.+pub(super) fn markdown_in_gutter(body: &str, width: usize) -> String {let rendered =crate::md_help::render_markdown_in_help_with_width(body, Some(width.saturating_sub(2)));- let gutter = format_with_gutter(&rendered, Some(width));- format!("\n{reset}{gutter}\n")+ format_with_gutter(&rendered, Some(width))}#[cfg(test)]diff --git a/src/commands/picker/preview.rs b/src/commands/picker/preview.rsindex c7c1266b2..a0c5c9bad 100644--- a/src/commands/picker/preview.rs+++ b/src/commands/picker/preview.rs@@ -14,12 +14,15 @@ use std::path::PathBuf;/// 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)////// 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,-/// tabs 1-5 on a `--prs` row (no local worktree), and tab 6 on a worktree row-/// (PR previews render only on `--prs` rows).+/// 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).////// Loosely aligned with `wt list` columns, though not a perfect match:/// - Tab 1 corresponds to "HEAD±" column@@ -35,6 +38,7 @@ pub(super) enum PreviewMode {UpstreamDiff = 4,Summary = 5,Pr = 6,+ Comments = 7,}impl PreviewMode {@@ -45,6 +49,7 @@ impl PreviewMode {4 => Self::UpstreamDiff,5 => Self::Summary,6 => Self::Pr,+ 7 => Self::Comments,_ => Self::WorkingTree,}}@@ -235,6 +240,7 @@ mod tests {assert_eq!(PreviewMode::from_u8(4), PreviewMode::UpstreamDiff);assert_eq!(PreviewMode::from_u8(5), PreviewMode::Summary);assert_eq!(PreviewMode::from_u8(6), PreviewMode::Pr);+ assert_eq!(PreviewMode::from_u8(7), PreviewMode::Comments);// Invalid values default to WorkingTreeassert_eq!(PreviewMode::from_u8(0), PreviewMode::WorkingTree);assert_eq!(PreviewMode::from_u8(99), PreviewMode::WorkingTree);diff --git a/src/commands/picker/preview_orchestrator.rs b/src/commands/picker/preview_orchestrator.rsindex be55d2284..55840fb33 100644--- a/src/commands/picker/preview_orchestrator.rs+++ b/src/commands/picker/preview_orchestrator.rs@@ -23,7 +23,7 @@ use std::time::Duration;use dashmap::DashMap;use worktrunk::git::Repository;-use super::items::{PreviewCache, WorktreeSkimItem};+use super::items::{PreviewCache, PreviewCacheKey, WorktreeSkimItem};use super::preview::PreviewMode;use super::summary;use crate::commands::list::collect::COLLECT_POOL;@@ -146,6 +146,43 @@ impl PreviewOrchestrator {});}+ /// Spawn a preview-compute task whose value comes from a caller-supplied+ /// closure. Returns immediately.+ ///+ /// The general-purpose companion to [`Self::spawn_preview`]: that method+ /// computes a worktree `ListItem`'s preview via the local-git+ /// `compute_and_page_preview`, whereas `--prs` rows (`PrSkimItem`) have no+ /// local worktree, so they fetch their `log` / `comments` panes through a+ /// forge CLI and pass that work in as `compute`. Both share the same+ /// [`PreviewCache`], the same `COLLECT_POOL` routing, and the same+ /// pending-counter accounting (so the dry-run path's `wait_for_idle` and+ /// the cache dump cover PR-row fetches too).+ ///+ /// Idempotent on `key` (short-circuits on a cache hit) and runs `compute`+ /// outside any DashMap lock, like `spawn_preview`. A `None` or empty result+ /// is deliberately NOT cached: the slot stays empty rather than pinning a+ /// blank pane, so a later `spawn_compute` with the same key recomputes. The+ /// `--prs` callers spawn once per row and never re-invoke, so in practice an+ /// uncached failure leaves the tab on its loading placeholder until the+ /// picker reopens.+ pub(super) fn spawn_compute<F>(&self, key: PreviewCacheKey, compute: F)+ where+ F: FnOnce(&Repository) -> Option<String> + Send + 'static,+ {+ let cache = Arc::clone(&self.cache);+ let repo = self.repo.clone();+ self.spawn_task(move || {+ if cache.contains_key(&key) {+ return;+ }+ if let Some(value) = compute(&repo)+ && !value.is_empty()+ {+ cache.insert(key, value);+ }+ });+ }+/// Spawn the skeleton-time pre-compute tier.////// Fires at `on_skeleton`. Two layers of priority:@@ -460,6 +497,61 @@ mod tests {);}+ /// `spawn_compute` fills the shared cache from a closure, short-circuits a+ /// duplicate key, and refuses to cache a `None` or empty result (so a+ /// transient forge failure doesn't pin a blank pane). One test covers the+ /// belief "the generic spawn path behaves like spawn_preview's caching".+ #[test]+ fn spawn_compute_fills_caches_once_and_skips_empty() {+ let t = TestRepo::new();+ let orch = orch_for(&t);++ // A populated value lands in the cache under its key.+ orch.spawn_compute(("pr:7".to_string(), PreviewMode::Log), |_| {+ Some("commit list".to_string())+ });+ orch.wait_for_idle();+ assert_eq!(+ orch.cache+ .get(&("pr:7".to_string(), 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(("pr:7".to_string(), PreviewMode::Log), |_| {+ Some("REPLACED".to_string())+ });+ orch.wait_for_idle();+ assert_eq!(+ orch.cache+ .get(&("pr:7".to_string(), 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(("pr:9".to_string(), PreviewMode::Log), |_| None);+ orch.spawn_compute(("pr:8".to_string(), PreviewMode::Log), |_| {+ Some(String::new())+ });+ orch.wait_for_idle();+ assert!(+ !orch+ .cache+ .contains_key(&("pr:9".to_string(), PreviewMode::Log)),+ "None is not cached"+ );+ assert!(+ !orch+ .cache+ .contains_key(&("pr:8".to_string(), PreviewMode::Log)),+ "empty string is not cached"+ );+ }+#[test]fn cache_entries_json_format() {let t = TestRepo::new();diff --git a/src/commands/picker/prs.rs b/src/commands/picker/prs.rsindex c4564178f..d1f6eb977 100644--- a/src/commands/picker/prs.rs+++ b/src/commands/picker/prs.rs@@ -57,9 +57,12 @@ use super::super::list::ci_status::{};use super::super::list::columns::ColumnKind;use super::super::list::layout::ColumnGrid;-use super::items::{TabAvailability, ansi_to_line, render_preview_tabs};+use super::items::{+ PreviewCache, TabAvailability, WorktreeSkimItem, ansi_to_line, render_preview_tabs,+};use super::pr_pane;use super::preview::{PreviewMode, PreviewStateData};+use super::preview_orchestrator::PreviewOrchestrator;/// One-shot handoff of the picker's column geometry from the collect thread/// (which computes the layout at skeleton time) to the `--prs` thread (which@@ -134,6 +137,12 @@ struct PrEntry {number: u32,title: String,head_branch: String,+ /// The head commit SHA, when the forge list call supplies it (GitHub+ /// `headRefOid`, GitLab `sha`). Lets the `log` tab render the rich local+ /// `git log` when the commit is already in the object store, falling back+ /// to the forge API otherwise — see [`compute_pr_log`]. `None` when the+ /// forge omits it; the row then always takes the API path.+ head_oid: Option<String>,author: String,is_draft: bool,url: Option<String>,@@ -157,6 +166,33 @@ impl PrEntry {RefKind::Mr => PrRef::mr(u64::from(self.number)),}}++ /// 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.+ fn output_token(&self) -> String {+ format!("{}:{}", self.kind.shortcut(), self.number)+ }+}++/// How the `--prs` thread reports that its forge call has resolved: drop the+/// header's "loading…" marker (`pending`) and poke skim to repaint (`render_tx`).+/// Bundled so `stream_open_prs` stays within the argument budget and the two+/// always travel together.+pub(super) struct PrsStreamSignal<'a> {+ pub pending: &'a AtomicBool,+ pub render_tx: &'a OnceLock<tokio::sync::mpsc::Sender<Event>>,+}++/// The two widths a `--prs` row renders against: `list_width` for the row's own+/// column cell (matching the worktree rows' grid), and `preview_dims` for the+/// deferred preview panes — the preview window is sized differently from the+/// list column in both layouts, and the local `git log` path also needs the+/// pane *height* for its line budget. Bundled so the streaming entry points stay+/// within the argument budget.+pub(super) struct PrsLayout {+ pub list_width: usize,+ pub preview_dims: (usize, usize),}/// Stream the open PRs/MRs into the picker, then clear the header's "loading…"@@ -169,17 +205,17 @@ impl PrEntry {/// keystroke.pub(super) fn stream_open_prs(repo: &Repository,- list_width: usize,+ layout: &PrsLayout,tx: &SkimItemSender,stashed_warnings: &Mutex<Vec<String>>,grid_slot: &GridSlot,- prs_loading: &AtomicBool,- render_tx: &OnceLock<tokio::sync::mpsc::Sender<Event>>,+ orchestrator: &PreviewOrchestrator,+ signal: &PrsStreamSignal,) {- fetch_and_stream(repo, list_width, tx, stashed_warnings, grid_slot);+ fetch_and_stream(repo, layout, tx, stashed_warnings, grid_slot, orchestrator);- prs_loading.store(false, Ordering::Relaxed);- if let Some(tx) = render_tx.get() {+ signal.pending.store(false, Ordering::Relaxed);+ if let Some(tx) = signal.render_tx.get() {let _ = tx.try_send(Event::Render);}}@@ -191,10 +227,11 @@ pub(super) fn stream_open_prs(/// picker stays usable with its worktree rows.fn fetch_and_stream(repo: &Repository,- list_width: usize,+ layout: &PrsLayout,tx: &SkimItemSender,stashed_warnings: &Mutex<Vec<String>>,grid_slot: &GridSlot,+ orchestrator: &PreviewOrchestrator,) {let entries = match fetch_open_prs(repo) {Ok(entries) => entries,@@ -222,16 +259,66 @@ fn fetch_and_stream(let grid = grid_slot.wait(Duration::from_secs(5));// skim 4.x takes a batch per send; the forge call already returned every- // row, so stream them in one shot.+ // row, so stream them in one shot. As each row is built, kick off its+ // deferred preview fetches (commit log) on `COLLECT_POOL` — the row-list+ // call carries only the cheap description, so the heavier per-PR panes load+ // off-thread and `preview()` reads them from the shared cache.let items: Vec<Arc<dyn SkimItem>> = entries.into_iter().map(|entry| {- Arc::new(PrSkimItem::new(entry, list_width, grid.as_ref())) as Arc<dyn SkimItem>+ spawn_pr_previews(orchestrator, &entry, layout.preview_dims);+ Arc::new(PrSkimItem::new(+ entry,+ layout.list_width,+ grid.as_ref(),+ &orchestrator.cache,+ )) as Arc<dyn SkimItem>}).collect();let _ = tx.send(items);}+/// Spawn the deferred per-row preview fetches for one `--prs` row, keyed by the+/// row's `pr:{N}` / `mr:{N}` token so [`PrSkimItem::preview`] reads them back.+/// Each is fire-and-forget on `COLLECT_POOL`, spawned once per row. `preview()`+/// only reads the cache, so a forge failure leaves the slot empty and the tab+/// keeps its loading placeholder until the picker reopens — there's no in-session+/// retry (see [`PreviewOrchestrator::spawn_compute`]).+///+/// Both tabs are spawned eagerly, once per row, for all rows — so a `--prs` open+/// queues up to `2 × MAX_PRS` (~100) per-PR forge calls. This is deliberate and+/// mirrors how the picker already fetches per-row CI status: spawning once here+/// (not from `preview()`) keeps [`PrSkimItem::preview`] a pure cache read with no+/// in-flight bookkeeping, so skim's UI thread never blocks and a row can't spawn+/// 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).+fn spawn_pr_previews(+ orchestrator: &PreviewOrchestrator,+ entry: &PrEntry,+ preview_dims: (usize, usize),+) {+ let token = entry.output_token();+ 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((token.clone(), PreviewMode::Log), move |repo| {+ compute_pr_log(+ repo,+ kind,+ number,+ head_oid.as_deref(),+ &head_branch,+ width,+ height,+ )+ });+ orchestrator.spawn_compute((token, PreviewMode::Comments), move |repo| {+ compute_pr_comments(repo, kind, number, width)+ });+}+/// 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.@@ -263,6 +350,9 @@ fn fetch_open_prs(repo: &Repository) -> anyhow::Result<Vec<PrEntry>> {struct GhPr {#[serde(rename = "headRefName")]head_ref_name: String,+ /// Head commit SHA; lets the `log` tab use a local `git log` when present.+ #[serde(rename = "headRefOid", default)]+ head_ref_oid: String,#[serde(default)]author: GhAuthor,/// CI/review and display fields reused via the shared `gh pr list` mapping:@@ -296,7 +386,7 @@ fn fetch_github(repo_root: &Path) -> anyhow::Result<Vec<PrEntry>> {&MAX_PRS.to_string(),"--json",// CI/review fields and the description ride the one call; no extra round-trip.- "number,title,headRefName,author,isDraft,url,body,statusCheckRollup,reviewDecision,mergeStateStatus",+ "number,title,headRefName,headRefOid,author,isDraft,url,body,statusCheckRollup,reviewDecision,mergeStateStatus",]).current_dir(repo_root).run()@@ -321,6 +411,7 @@ fn parse_github_prs(stdout: &[u8]) -> anyhow::Result<Vec<PrEntry>> {number: pr.info.number.unwrap_or(0) as u32,title: pr.info.title.clone().unwrap_or_default(),head_branch: pr.head_ref_name,+ head_oid: Some(pr.head_ref_oid).filter(|s| !s.is_empty()),author: pr.author.login,is_draft: pr.info.is_draft == Some(true),url: pr.info.url.clone(),@@ -337,6 +428,9 @@ struct GlabMr {title: String,#[serde(default)]source_branch: String,+ /// Diff head SHA; lets the `log` tab use a local `git log` when present.+ #[serde(default)]+ sha: String,#[serde(default)]author: GlabAuthor,#[serde(default)]@@ -402,6 +496,7 @@ fn parse_gitlab_mrs(stdout: &[u8]) -> anyhow::Result<Vec<PrEntry>> {number: mr.iid,title: mr.title,head_branch: mr.source_branch,+ head_oid: Some(mr.sha).filter(|s| !s.is_empty()),author: mr.author.username,is_draft: mr.draft,url: mr.web_url,@@ -465,14 +560,26 @@ pub(super) struct PrSkimItem {output_token: String,/// The tab-6 (`pr`) pane: PR/MR metadata and web URL, built once at/// construction from already-fetched data. A `--prs` row has no local- /// worktree, so tabs 1-5 render an empty placeholder instead.+ /// worktree, so the working-tree/branch-diff/upstream tabs render an empty+ /// placeholder instead.pr_pane: String,+ /// Shared preview cache (same map the worktree rows use), read by the+ /// deferred `log` tab. Keyed by `(output_token, mode)`; the background+ /// fetch spawned in [`spawn_pr_previews`] populates it off-thread, and a+ /// miss falls back to a loading placeholder (skim re-queries on the next+ /// selection/tab change).+ preview_cache: PreviewCache,}impl PrSkimItem {- fn new(entry: PrEntry, list_width: usize, grid: Option<&ColumnGrid>) -> Self {+ fn new(+ entry: PrEntry,+ list_width: usize,+ grid: Option<&ColumnGrid>,+ preview_cache: &PreviewCache,+ ) -> Self {let label = entry.kind.shortcut();- let output_token = format!("{label}:{}", entry.number);+ let output_token = entry.output_token();// Trailing gutter glyph (the `#` from `PR_GUTTER_SIGIL`, sans pad) so// typing `#` filters to PR/MR rows, matching how the worktree/branch@@ -523,13 +630,26 @@ impl PrSkimItem {rendered,output_token,pr_pane,+ preview_cache: Arc::clone(preview_cache),}}++ /// Read a deferred tab's pane from the shared cache, or a loading+ /// placeholder on a miss. The background fetch (see [`spawn_pr_previews`])+ /// keys by this row's `output_token`, the same as [`PrEntry::output_token`].+ fn cached_pane(&self, mode: PreviewMode) -> String {+ self.preview_cache+ .get(&(self.output_token.clone(), mode))+ .map(|v| v.value().clone())+ .unwrap_or_else(|| pr_deferred_loading(mode))+ }}-/// The pane for tabs 1-5 on a `--prs` row. The head branch isn't checked out-/// locally, so there's no working tree / log / diff to show — point the user-/// at the `pr` tab, which holds the PR/MR metadata.+/// The pane for the tabs a `--prs` row leaves empty — working-tree (1),+/// branch-diff (3), upstream (4), summary (5). The head branch isn't checked+/// out locally, so there's no working tree or diff to show; point the user at+/// the `pr` tab, which holds the PR/MR metadata. The `log` tab (2) is *not*+/// empty — it loads commits in the background (see [`compute_pr_log`]).fn pr_row_empty_placeholder() -> String {let reset = Reset;cformat!(@@ -537,6 +657,337 @@ 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`. A failed fetch (spawned+/// once per row) leaves the slot empty, so this placeholder persists until the+/// picker reopens; the refresh hint is a no-op then.+fn pr_deferred_loading(mode: PreviewMode) -> String {+ let reset = Reset;+ let (label, key) = match mode {+ PreviewMode::Log => ("commit log", 2u8),+ PreviewMode::Comments => ("comments", 7u8),+ // Only the deferred tabs reach here; other modes render synchronously.+ _ => ("preview", mode as u8),+ };+ cformat!(+ "{INFO_SYMBOL}{reset} Loading {label}… press <bold>alt-{key}</>{reset} again to refresh\n"+ )+}++/// Run a forge CLI and return its stdout, or `None` on any failure (root+/// unresolvable, spawn error, non-zero exit). Shared by the deferred `log` /+/// `comments` fetches: a PR runs `gh <gh_args>`, an MR runs `glab <glab_args>`.+/// Runs off-thread on `COLLECT_POOL`, never on skim's UI thread; a `None` result+/// leaves the cache slot empty so the tab keeps its loading placeholder (see+/// [`PreviewOrchestrator::spawn_compute`]).+fn fetch_forge_json(+ repo: &Repository,+ kind: RefKind,+ gh_args: &[&str],+ glab_args: &[&str],+) -> Option<Vec<u8>> {+ let repo_root = repo.current_worktree().root().ok()?;+ let (program, args) = match kind {+ RefKind::Pr => ("gh", gh_args),+ RefKind::Mr => ("glab", glab_args),+ };+ let output = non_interactive_cmd(program)+ .args(args.iter().copied())+ .current_dir(&repo_root)+ .run()+ .ok()?;+ output.status.success().then_some(output.stdout)+}++/// Fetch and render the commit log for a `--prs` row's `log` tab.+///+/// When the PR/MR head commit (`head_oid`, from the forge list call) is already+/// in the local object store — a same-repo PR off a fetched `origin` — the tab+/// renders the rich local `git log`: graph, dim/bright merge-base split, and+/// relative timestamps, identical to a worktree row's `log` tab and sharing its+/// SHA-keyed disk cache. No network for that row.+///+/// Otherwise (a fork PR, an unfetched head, or a forge that omits the SHA) the+/// commit isn't local, so the commits come from the forge API instead: `gh pr+/// view <n> --json commits` (GitHub) or `glab api+/// projects/:fullpath/merge_requests/<n>/commits` (GitLab). That path renders a+/// flat `git log --oneline`-style list — no graph or merge-base coloring, since+/// the objects aren't present to compute them. `glab`'s `--paginate` follows+/// every page so a long PR isn't capped at GitLab's default page size, matching+/// `gh`'s complete `--json` result.+fn compute_pr_log(+ repo: &Repository,+ kind: RefKind,+ number: u32,+ head_oid: Option<&str>,+ head_branch: &str,+ width: usize,+ height: usize,+) -> Option<String> {+ if let Some(oid) = head_oid+ && let Some(local) = local_log(repo, oid, head_branch, width, height)+ {+ return Some(local);+ }++ let number = number.to_string();+ let endpoint = format!("projects/:fullpath/merge_requests/{number}/commits");+ let stdout = fetch_forge_json(+ repo,+ kind,+ &["pr", "view", &number, "--json", "commits"],+ &["api", "--paginate", &endpoint],+ )?;+ match kind {+ RefKind::Pr => render_github_commits(&stdout, width),+ RefKind::Mr => render_gitlab_commits(&stdout, width),+ }+}++/// Render the local `git log` for `oid` when it's present in the object store,+/// else `None` so [`compute_pr_log`] falls back to the forge API. The+/// `^{commit}` peel both confirms the object exists locally and rejects a SHA+/// that resolves to a non-commit (a stray blob/tree), and `--quiet` keeps a+/// miss to a silent exit-1 rather than a `fatal:` on stderr.+fn local_log(+ repo: &Repository,+ oid: &str,+ head_branch: &str,+ width: usize,+ height: usize,+) -> Option<String> {+ let spec = format!("{oid}^{{commit}}");+ if !repo+ .run_command_check(&[+ "rev-parse",+ "--verify",+ "--quiet",+ "--end-of-options",+ &spec,+ ])+ .unwrap_or(false)+ {+ return None;+ }+ let rendered = WorktreeSkimItem::compute_log_for_head(repo, oid, head_branch, width, height);+ (!rendered.is_empty()).then_some(rendered)+}++#[derive(Deserialize)]+struct GhCommitsResponse {+ #[serde(default)]+ commits: Vec<GhCommit>,+}++#[derive(Deserialize)]+struct GhCommit {+ #[serde(default)]+ oid: String,+ #[serde(rename = "messageHeadline", default)]+ message_headline: String,+}++/// Map `gh pr view <n> --json commits` to the `log` pane. gh returns commits+/// oldest-first; the log reads newest-first like `git log`, so reverse.+fn render_github_commits(stdout: &[u8], width: usize) -> Option<String> {+ let parsed: GhCommitsResponse = serde_json::from_slice(stdout).ok()?;+ let lines: Vec<(String, String)> = parsed+ .commits+ .into_iter()+ .rev()+ .map(|c| (short_hash(&c.oid), c.message_headline))+ .collect();+ Some(render_commit_lines(&lines, width))+}++#[derive(Deserialize)]+struct GlabCommit {+ #[serde(default)]+ short_id: String,+ #[serde(default)]+ title: String,+}++/// Map `glab api …/merge_requests/<n>/commits` to the `log` pane. GitLab's+/// commits endpoint returns newest-first already, so keep the order.+fn render_gitlab_commits(stdout: &[u8], width: usize) -> Option<String> {+ let commits: Vec<GlabCommit> = serde_json::from_slice(stdout).ok()?;+ let lines: Vec<(String, String)> = commits.into_iter().map(|c| (c.short_id, c.title)).collect();+ Some(render_commit_lines(&lines, width))+}++/// Abbreviate a full commit hash to the conventional short form. GitLab already+/// supplies a `short_id`; GitHub's `oid` is the full SHA.+fn short_hash(oid: &str) -> String {+ oid.chars().take(8).collect()+}++/// Render a `git log --oneline`-style list for the `log` pane: a dim short hash,+/// then the subject. The preview pane doesn't wrap, so each subject truncates to+/// the pane width rather than letting skim clip mid-escape. An empty list (a PR+/// with no commits the API returned) renders an info line so `spawn_compute`+/// caches a terminal value rather than leaving the slot empty (an empty string+/// is skipped, which would keep the loading placeholder).+fn render_commit_lines(commits: &[(String, String)], width: usize) -> String {+ let reset = Reset;+ if commits.is_empty() {+ return cformat!("{INFO_SYMBOL}{reset} No commits\n");+ }+ let mut out = String::new();+ for (short, headline) in commits {+ let budget = width.saturating_sub(short.width() + 2).max(8);+ let headline = crate::display::truncate_to_width(headline, budget);+ out.push_str(&cformat!("<dim>{short}</>{reset} {headline}\n"));+ }+ out+}++/// Fetch and render the comments on a `--prs` row's `comments` tab:+/// `gh pr view <n> --json comments` (GitHub, the conversation-level comments) or+/// `glab api …/merge_requests/<n>/notes?sort=asc` (GitLab, human notes). `sort=asc`+/// matches GitHub's oldest-first order (GitLab defaults to newest-first), and+/// `--paginate` follows every page so a long thread isn't capped at GitLab's+/// default page size. Returns `None` on any failure, leaving the slot empty so+/// the tab keeps its loading placeholder.+fn compute_pr_comments(+ repo: &Repository,+ kind: RefKind,+ number: u32,+ width: usize,+) -> Option<String> {+ let number = number.to_string();+ let endpoint = format!("projects/:fullpath/merge_requests/{number}/notes?sort=asc");+ let stdout = fetch_forge_json(+ repo,+ kind,+ &["pr", "view", &number, "--json", "comments"],+ &["api", "--paginate", &endpoint],+ )?;+ match kind {+ RefKind::Pr => render_github_comments(&stdout, width),+ RefKind::Mr => render_gitlab_notes(&stdout, width),+ }+}++/// One PR/MR comment, normalized across forges for the `comments` pane.+struct Comment {+ author: String,+ body: String,+ /// RFC 3339 timestamp; rendered as relative time when parseable.+ created_at: String,+}++#[derive(Deserialize)]+struct GhCommentsResponse {+ #[serde(default)]+ comments: Vec<GhComment>,+}++#[derive(Deserialize)]+struct GhComment {+ #[serde(default)]+ author: GhAuthor,+ #[serde(default)]+ body: String,+ #[serde(rename = "createdAt", default)]+ created_at: String,+}++/// Map `gh pr view <n> --json comments` to the `comments` pane. gh returns the+/// thread oldest-first, which reads top-to-bottom.+fn render_github_comments(stdout: &[u8], width: usize) -> Option<String> {+ let parsed: GhCommentsResponse = serde_json::from_slice(stdout).ok()?;+ let comments: Vec<Comment> = parsed+ .comments+ .into_iter()+ .map(|c| Comment {+ author: c.author.login,+ body: c.body,+ created_at: c.created_at,+ })+ .collect();+ Some(render_comment_blocks(&comments, width))+}++#[derive(Deserialize)]+struct GlabNote {+ #[serde(default)]+ body: String,+ #[serde(default)]+ author: GlabAuthor,+ #[serde(default)]+ created_at: String,+ /// GitLab tags activity events (label changes, "changed the description") as+ /// system notes; only human comments belong in the pane.+ #[serde(default)]+ system: bool,+}++/// Map `glab api …/notes` to the `comments` pane, dropping system notes (label+/// changes, description edits, …) so only human comments show.+fn render_gitlab_notes(stdout: &[u8], width: usize) -> Option<String> {+ let notes: Vec<GlabNote> = serde_json::from_slice(stdout).ok()?;+ let comments: Vec<Comment> = notes+ .into_iter()+ .filter(|n| !n.system)+ .map(|n| Comment {+ author: n.author.username,+ body: n.body,+ created_at: n.created_at,+ })+ .collect();+ Some(render_comment_blocks(&comments, width))+}++/// Render the `comments` pane: each comment as a header line (author + relative+/// time) followed by its body as markdown in the house gutter — the same+/// [`pr_pane::markdown_in_gutter`] the PR/MR body uses. An empty thread renders+/// an info line so `spawn_compute` caches a terminal value rather than leaving+/// the slot empty (an empty string is skipped, which would keep the loading placeholder).+fn render_comment_blocks(comments: &[Comment], width: usize) -> String {+ let reset = Reset;+ if comments.is_empty() {+ return cformat!("{INFO_SYMBOL}{reset} No comments\n");+ }+ let mut out = String::new();+ for comment in comments {+ let author = if comment.author.is_empty() {+ "unknown"+ } else {+ &comment.author+ };+ let header = match relative_time(&comment.created_at) {+ Some(when) => cformat!("<bold>@{author}</>{reset} <dim>· {when}</>{reset}"),+ None => cformat!("<bold>@{author}</>{reset}"),+ };+ out.push_str(&header);+ out.push('\n');++ let body = comment.body.trim();+ if body.is_empty() {+ out.push_str(&cformat!("<dim>(no body)</>{reset}\n"));+ } else {+ out.push_str(&format!(+ "{reset}{}\n",+ pr_pane::markdown_in_gutter(body, width)+ ));+ }+ // Blank line between comments.+ out.push('\n');+ }+ out+}++/// Parse an RFC 3339 timestamp to abbreviated relative time ("2h", "3d"),+/// honoring `WORKTRUNK_TEST_EPOCH` via `format_relative_time_short`. `None` when+/// the forge omits or malforms the date, so the header just drops the time.+fn relative_time(iso: &str) -> Option<String> {+ let ts = chrono::DateTime::parse_from_rfc3339(iso).ok()?.timestamp();+ Some(crate::display::format_relative_time_short(ts))+}+/// Place the PR's cells on the worktree rows' grid so every column lines up:/// a dim `#` gutter sigil (see `PR_GUTTER_SIGIL`), the head branch in the/// Branch column, and the number.@@ -620,27 +1071,23 @@ fn render_freeform_row(entry: &PrEntry, list_width: usize) -> String {// Each needs a field added to the row-list `--json` (cheap, one call) or a// derived value — keep them off the flexible region so the grid stays aligned.//-// TODO(pr-preview-log): give the `log` tab (and ideally `summary`) content on-// `--prs` rows. The body/description rides the one `gh pr list` call cheaply,-// but a commit log does not: for a checked-out branch it's a local `git log`,-// but a `--prs` head branch isn't fetched, so the commits need either a fetch-// or `gh pr view <n> --json commits` / `glab mr view`. That payload is too-// heavy to fold into the row-list call (commits for ~50 PRs), so it must load-// in the background per row — which `--prs` rows don't do yet: today the whole-// row, `pr_pane` included, is built once when the list call returns. The-// mechanism would mirror the worktree rows' `PreviewOrchestrator` cache: a-// shared map the `preview()` callback reads, populated off-thread, with a-// "loading…" placeholder on a miss (skim re-queries on selection/tab change).-// Remote-branch rows (`--remotes`) are the cheap half — their commits are-// already fetched, so their `log` tab is a plain local `git log`.+// TODO(pr-preview-summary): give the `summary` tab content on `--prs` rows.+// The `log` tab now loads commits in the background (see `compute_pr_log`); a+// summary would feed those commits (or the PR body) through the same+// `[commit.generation]` LLM path the worktree `summary` tab uses, keyed and+// cached the same way via `spawn_pr_previews`.//-// TODO(pr-preview-comments): add a `7: comments` tab showing the PR/MR-// discussion, rendered with the house gutter per comment (author + body, like-// `pr_pane::description`). Needs the same background per-row fetch as the log-// (`gh pr view <n> --json comments`), and a 7th tab widens the preview tab bar-// — already ~63 cols with six numbered tabs — so it clips sooner on narrow-// (≤~125-col, Right-layout) previews. Weigh an abbreviated/scrolling tab bar-// alongside it.+// TODO(pr-preview-fetch-error): on a forge-fetch failure the deferred `log` /+// `comments` slot stays empty (`spawn_compute` drops a `None`), and since the+// fetch is spawned once per row and `preview()` only reads the cache, the tab+// shows the "Loading…" placeholder for the rest of the session — there's no+// in-session retry, so the hint to press the key again is a no-op. Cache a+// terminal "couldn't load" pane on failure instead, so the tab distinguishes+// in-flight from failed; this needs the PR-row closures (or `spawn_compute`) to+// signal failure vs. a genuinely-empty result. The same terminal-pane path+// would also give the orphan-root local-head case (a present head sharing no+// merge-base with the default branch, which `compute_log_for_head` renders as+// "has no commits") a clear outcome rather than a misleading one.impl SkimItem for PrSkimItem {fn text(&self) -> Cow<'_, str> {Cow::Borrowed(&self.search_text)@@ -654,17 +1101,19 @@ impl SkimItem for PrSkimItem {Cow::Borrowed(&self.output_token)}- fn preview(&self, _context: PreviewContext<'_>) -> ItemPreview {- // Share the worktree rows' tab bar. A `--prs` row has content only on- // the `pr` tab (tabs 1-5 empty → de-emphasized); the active tab is the- // same global digit, so an empty tab shows the placeholder until the- // user presses alt-6 / Tab.+ fn preview(&self, context: PreviewContext<'_>) -> ItemPreview {+ // Share the worktree rows' tab bar. A `--prs` row has content on the+ // `pr` tab (built at construction) and the `log` / `comments` tabs+ // (fetched in the background, read from the shared cache); the+ // working-tree/branch-diff/upstream/summary tabs are de-emphasized and+ // 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());- if mode == PreviewMode::Pr {- result.push_str(&self.pr_pane);- } else {- result.push_str(&pr_row_empty_placeholder());+ let mut result = render_preview_tabs(mode, TabAvailability::pull_request(), context.width);+ match mode {+ PreviewMode::Pr => result.push_str(&self.pr_pane),+ PreviewMode::Log | PreviewMode::Comments => result.push_str(&self.cached_pane(mode)),+ _ => result.push_str(&pr_row_empty_placeholder()),}ItemPreview::AnsiText(result)}@@ -673,6 +1122,13 @@ impl SkimItem for PrSkimItem {#[cfg(test)]mod tests {use super::*;+ use dashmap::DashMap;++ /// Build a `PrSkimItem` with a throwaway empty preview cache — 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>) -> PrSkimItem {+ PrSkimItem::new(entry, list_width, grid, &Arc::new(DashMap::new()))+ }fn entry(kind: RefKind, number: u32, title: &str) -> PrEntry {let number_ref = match kind {@@ -683,6 +1139,7 @@ mod tests {number,title: title.to_string(),head_branch: "feature/auth".to_string(),+ head_oid: None,author: "alice".to_string(),is_draft: false,url: Some("https://github.com/owner/repo/pull/123".to_string()),@@ -717,16 +1174,16 @@ mod tests {#[test]fn output_token_is_the_switch_shortcut() {- let pr = PrSkimItem::new(entry(RefKind::Pr, 123, "Fix the flaky test"), 120, None);+ let pr = pr_item(entry(RefKind::Pr, 123, "Fix the flaky test"), 120, None);assert_eq!(pr.output(), "pr:123");- let mr = PrSkimItem::new(entry(RefKind::Mr, 7, "Add caching"), 120, None);+ let mr = pr_item(entry(RefKind::Mr, 7, "Add caching"), 120, None);assert_eq!(mr.output(), "mr:7");}#[test]fn search_text_covers_number_title_branch_author() {- let pr = PrSkimItem::new(entry(RefKind::Pr, 42, "Speed up startup"), 120, None);+ let pr = pr_item(entry(RefKind::Pr, 42, "Speed up startup"), 120, None);let text = pr.text();assert!(text.contains("42"));assert!(text.contains("Speed up startup"));@@ -754,7 +1211,7 @@ mod tests {.is_some()};- let pr = PrSkimItem::new(entry(RefKind::Pr, 42, "Speed up startup"), 120, None);+ let pr = pr_item(entry(RefKind::Pr, 42, "Speed up startup"), 120, None);assert!(matches(&pr), "# selects the PR row");// A worktree-style row carries no `#` in its folded search_text.assert!(@@ -768,7 +1225,7 @@ mod tests {// No grid: the freeform fallback shows reference and branch. The title// and author have no column, so they stay off the row — but the title// still feeds `search_text`.- let pr = PrSkimItem::new(entry(RefKind::Pr, 1, "Retry the flaky test"), 80, None);+ let pr = pr_item(entry(RefKind::Pr, 1, "Retry the flaky test"), 80, None);let row = plain(&pr.rendered);assert!(row.contains("feature/auth"), "branch on the row: {row:?}");assert!(row.contains("#1"), "reference on the row: {row:?}");@@ -789,7 +1246,7 @@ mod tests {// truncates so the row stays inside the pane.let mut e = entry(RefKind::Pr, 1, "Title");e.head_branch = "a-very-long-branch-name-that-would-otherwise-overflow".to_string();- let pr = PrSkimItem::new(e, 40, None);+ let pr = pr_item(e, 40, None);let row = plain(&pr.rendered);assert!(row.contains("#1"), "reference survives: {row:?}");assert!(row.contains('…'), "branch truncated: {row:?}");@@ -803,7 +1260,7 @@ mod tests {// `grid_row_with_ci_dims_drafts_instead_of_flagging_them`).let mut e = entry(RefKind::Pr, 9, "WIP refactor");e.is_draft = true;- let pr = PrSkimItem::new(e, 120, None);+ let pr = pr_item(e, 120, None);assert!(pr.pr_pane.contains("draft"));}@@ -846,7 +1303,7 @@ mod tests {// grid() has no CI column, so the number falls back to just after the// Branch column (which ends at 22, so the reference lands at 24). The// title and author stay off the row.- let pr = PrSkimItem::new(+ let pr = pr_item(entry(RefKind::Pr, 123, "Fix the flaky test"),120,Some(&grid()),@@ -871,7 +1328,7 @@ mod tests {fn grid_row_truncates_long_branch_to_its_column() {let mut e = entry(RefKind::Pr, 5, "Title");e.head_branch = "a-very-long-branch-name-overflowing".to_string();- let pr = PrSkimItem::new(e, 120, Some(&grid_with_ci()));+ let pr = pr_item(e, 120, Some(&grid_with_ci()));let text = plain(&pr.rendered);// The branch is shortened to its column; the number still lands in CI.assert!(text.contains('…'));@@ -883,7 +1340,7 @@ mod tests {// GitLab MRs render `!N`, not `#N` — matching `PrRef` everywhere else// (the CI column, `wt list`). The CI-column number, freeform row, and// preview all derive the sigil from `PrEntry::pr_ref`.- let mr = PrSkimItem::new(+ let mr = pr_item(entry(RefKind::Mr, 42, "Add caching"),120,Some(&grid_with_ci()),@@ -896,14 +1353,14 @@ mod tests {);assert!(mr.pr_pane.contains("!42"), "preview uses ! for MRs");- let mr_freeform = PrSkimItem::new(entry(RefKind::Mr, 42, "Add caching"), 120, None);+ let mr_freeform = pr_item(entry(RefKind::Mr, 42, "Add caching"), 120, None);assert!(plain(&mr_freeform.rendered).contains("!42"),"freeform row uses !");// GitHub PRs keep `#N`.- let pr = PrSkimItem::new(+ let pr = pr_item(entry(RefKind::Pr, 42, "Add caching"),120,Some(&grid_with_ci()),@@ -926,7 +1383,7 @@ mod tests {};let mut e = entry(RefKind::Pr, 1, "Title");e.head_branch = "a-very-long-branch-name-that-runs-past-the-edge".to_string();- let pr = PrSkimItem::new(e, 60, Some(&no_flexible));+ let pr = pr_item(e, 60, Some(&no_flexible));let text = plain(&pr.rendered);assert!(text.width() <= 60);// Skim's overflow check uses CJK widths, where the truncation `…`@@ -937,7 +1394,7 @@ mod tests {#[test]fn grid_row_places_the_number_in_the_ci_column() {- let pr = PrSkimItem::new(+ let pr = pr_item(entry(RefKind::Pr, 123, "Fix the flaky test"),120,Some(&grid_with_ci()),@@ -962,7 +1419,7 @@ mod tests {grid_col(ColumnKind::Message, 32, 40),],};- let pr = PrSkimItem::new(+ let pr = pr_item(entry(RefKind::Pr, 42, "Retry the flaky test"),120,Some(&grid),@@ -985,7 +1442,7 @@ mod tests {if let Some(status) = e.status.as_mut() {status.review_state = Some(ReviewState::Draft);}- let pr = PrSkimItem::new(e, 120, Some(&grid_with_ci()));+ let pr = pr_item(e, 120, Some(&grid_with_ci()));let text = plain(&pr.rendered);assert!(!text.contains("draft"),@@ -1046,7 +1503,7 @@ mod tests {// Two PRs: one ready from a fork, one draft. Mirrors the// `gh pr list --json number,title,headRefName,author,isDraft,url` shape.let json = br#"[- {"number":2964,"title":"ci: freshen","headRefName":"fix/ci","author":{"login":"octocat"},"isDraft":false,"url":"https://github.com/o/r/pull/2964","body":"Bumps the CI image and re-pins actions."},+ {"number":2964,"title":"ci: freshen","headRefName":"fix/ci","headRefOid":"abc1234500000000000000000000000000000000","author":{"login":"octocat"},"isDraft":false,"url":"https://github.com/o/r/pull/2964","body":"Bumps the CI image and re-pins actions."},{"number":2969,"title":"wip","headRefName":"wip-branch","author":{"login":"forkuser"},"isDraft":true,"url":"https://github.com/o/r/pull/2969"}]"#;let entries = parse_github_prs(json).unwrap();@@ -1055,6 +1512,11 @@ mod tests {assert_eq!(entries[0].number, 2964);assert_eq!(entries[0].title, "ci: freshen");assert_eq!(entries[0].head_branch, "fix/ci");+ // `headRefOid` feeds the `log` tab's local-`git log` fast path.+ assert_eq!(+ entries[0].head_oid.as_deref(),+ Some("abc1234500000000000000000000000000000000")+ );assert_eq!(entries[0].author, "octocat");assert!(!entries[0].is_draft);assert!(matches!(entries[0].kind, RefKind::Pr));@@ -1063,6 +1525,8 @@ mod tests {assert_eq!(entries[1].number, 2969);assert!(entries[1].is_draft);assert_eq!(entries[1].author, "forkuser");+ // Absent `headRefOid` → `None`, so that row always takes the forge API.+ assert!(entries[1].head_oid.is_none());// Absent `body` defaults to empty — the description block is skipped.assert_eq!(entries[1].body, "");}@@ -1124,12 +1588,27 @@ mod tests {let (tx, _rx): (SkimItemSender, SkimItemReceiver) = unbounded();let warnings = Mutex::new(Vec::new());let grid = GridSlot::new();+ let orchestrator = PreviewOrchestrator::new(test.repo.clone());let loading = AtomicBool::new(true);let (rtx, mut rrx) = tokio::sync::mpsc::channel(8);let render_tx = OnceLock::new();render_tx.set(rtx).unwrap();- stream_open_prs(&test.repo, 80, &tx, &warnings, &grid, &loading, &render_tx);+ stream_open_prs(+ &test.repo,+ &PrsLayout {+ list_width: 80,+ preview_dims: (80, 24),+ },+ &tx,+ &warnings,+ &grid,+ &orchestrator,+ &PrsStreamSignal {+ pending: &loading,+ render_tx: &render_tx,+ },+ );assert!(!loading.load(Ordering::Relaxed), "loading flag cleared");assert!(matches!(rrx.try_recv(), Ok(Event::Render)), "render poked");@@ -1140,7 +1619,7 @@ mod tests {// `glab mr list --output json`: iid (not number), source_branch,// author.username, draft, web_url.let json = br#"[- {"iid":7,"title":"Add caching","source_branch":"feat/cache","author":{"username":"alice"},"draft":false,"web_url":"https://gitlab.com/o/r/-/merge_requests/7","description":"Caches the dependency graph between jobs."},+ {"iid":7,"title":"Add caching","source_branch":"feat/cache","sha":"abc1234500000000000000000000000000000000","author":{"username":"alice"},"draft":false,"web_url":"https://gitlab.com/o/r/-/merge_requests/7","description":"Caches the dependency graph between jobs."},{"iid":8,"title":"WIP","source_branch":"wip","author":{"username":"bob"},"draft":true,"web_url":"https://gitlab.com/o/r/-/merge_requests/8"}]"#;let entries = parse_gitlab_mrs(json).unwrap();@@ -1148,6 +1627,12 @@ mod tests {assert_eq!(entries[0].number, 7);assert_eq!(entries[0].head_branch, "feat/cache");+ // `sha` feeds the `log` tab's local-`git log` fast path; absent → None.+ assert_eq!(+ entries[0].head_oid.as_deref(),+ Some("abc1234500000000000000000000000000000000")+ );+ assert!(entries[1].head_oid.is_none());assert_eq!(entries[0].author, "alice");assert!(matches!(entries[0].kind, RefKind::Mr));assert_eq!(entries[0].body, "Caches the dependency graph between jobs.");@@ -1155,7 +1640,7 @@ mod tests {assert_eq!(entries[1].body, "");// The MR's `output()` shortcut uses the iid.assert_eq!(- PrSkimItem::new(entries.into_iter().next().unwrap(), 120, None).output(),+ pr_item(entries.into_iter().next().unwrap(), 120, None).output(),"mr:7");}@@ -1170,12 +1655,12 @@ mod tests {fn pr_pane_shows_description_only_when_present() {let mut with_body = entry(RefKind::Pr, 1, "t");with_body.body = "A short summary of the change.".to_string();- let pr = PrSkimItem::new(with_body, 120, Some(&grid()));+ let pr = pr_item(with_body, 120, Some(&grid()));assert!(pr.pr_pane.contains("A short summary of the change."));assert!(pr.pr_pane.contains("\x1b[107m"), "gutter present");// The base fixture has an empty body — no gutter, no description.- let plain_pr = PrSkimItem::new(entry(RefKind::Pr, 2, "t"), 120, Some(&grid()));+ let plain_pr = pr_item(entry(RefKind::Pr, 2, "t"), 120, Some(&grid()));assert!(!plain_pr.pr_pane.contains("\x1b[107m"),"no gutter when empty"@@ -1188,9 +1673,9 @@ mod tests {// default (WorkingTree) — empty on a --prs row — so `preview()` renders// the shared tab bar plus the "not checked out" placeholder. Drives the// real `SkimItem::preview` (the `--prs` streaming path is too async to- // exercise it reliably under a PTY); `PreviewContext` is ignored by the- // impl, so a minimal one suffices.- let pr = PrSkimItem::new(entry(RefKind::Pr, 7, "Title"), 120, Some(&grid()));+ // exercise it reliably under a PTY). `context.width` (80) is wide enough+ // for the full tab bar, so the `pr` / `comments` tabs show their labels.+ let pr = pr_item(entry(RefKind::Pr, 7, "Title"), 120, Some(&grid()));let ctx = PreviewContext {query: "",cmd_query: "",@@ -1204,10 +1689,252 @@ mod tests {let ItemPreview::AnsiText(text) = pr.preview(ctx) else {panic!("expected AnsiText preview");};- assert!(text.contains("6: pr"), "tab bar present: {text:?}");+ // Assert on the ANSI-stripped bar so the check targets the tab labels+ // themselves, not a coincidental substring of the styled controls line.+ let bar = plain(&text);+ assert!(bar.contains("6: pr"), "pr tab present: {bar:?}");+ assert!(bar.contains("7: comments"), "comments tab present: {bar:?}");assert!(text.contains("Not checked out locally"),"placeholder present: {text:?}");}++ #[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-2); once the background fetch lands a value under that key, the+ // pane shows it.+ let cache: PreviewCache = Arc::new(DashMap::new());+ let pr = PrSkimItem::new(entry(RefKind::Pr, 42, "t"), 120, None, &cache);++ let miss = pr.cached_pane(PreviewMode::Log);+ assert!(miss.contains("Loading commit log"), "miss: {miss:?}");+ assert!(miss.contains("alt-2"), "refresh hint: {miss:?}");++ cache.insert(+ ("pr:42".to_string(), PreviewMode::Log),+ "abc12345 Fix it\n".to_string(),+ );+ assert_eq!(pr.cached_pane(PreviewMode::Log), "abc12345 Fix it\n");+ }++ #[test]+ fn render_github_commits_oneline_newest_first() {+ // gh returns commits oldest-first; the `log` pane shows them+ // newest-first like `git log`, with a dim 8-char short hash.+ let json = br#"{"commits":[+ {"oid":"aaaaaaaa0000000000000000000000000000aaaa","messageHeadline":"older change"},+ {"oid":"bbbbbbbb1111111111111111111111111111bbbb","messageHeadline":"newer change"}+ ]}"#;+ let out = plain(&render_github_commits(json, 80).unwrap());+ assert!(+ out.find("bbbbbbbb").unwrap() < out.find("aaaaaaaa").unwrap(),+ "newest-first: {out:?}"+ );+ assert!(out.contains("newer change") && out.contains("older change"));+ // Hash abbreviated to 8 chars, not the full 40.+ assert!(!out.contains("bbbbbbbb1"), "short hash only: {out:?}");+ }++ #[test]+ fn render_gitlab_commits_keeps_order_and_uses_short_id() {+ // GitLab's commits endpoint returns newest-first already, and supplies a+ // ready `short_id`, so the order is preserved as-is.+ let json = br#"[+ {"short_id":"deadbeef","title":"newer change"},+ {"short_id":"cafef00d","title":"older change"}+ ]"#;+ let out = plain(&render_gitlab_commits(json, 80).unwrap());+ assert!(out.contains("deadbeef") && out.contains("newer change"));+ assert!(+ out.find("deadbeef").unwrap() < out.find("cafef00d").unwrap(),+ "order preserved: {out:?}"+ );+ }++ #[test]+ fn render_commits_empty_and_truncation() {+ // A PR the API reports with no commits caches an info line (a terminal+ // value) rather than leaving the slot empty.+ assert!(+ plain(&render_github_commits(br#"{"commits":[]}"#, 80).unwrap()).contains("No commits")+ );++ // The preview doesn't wrap, so a long subject truncates to the pane+ // width (after the dim hash + two spaces) rather than clipping mid-escape.+ let commits = vec![("abc12345".to_string(), "subject-".repeat(20))];+ let line = render_commit_lines(&commits, 40);+ let first = plain(&line);+ let first = first.lines().next().unwrap();+ assert!(first.width() <= 40, "within pane: {first:?}");+ assert!(first.contains('…'), "truncated: {first:?}");+ }++ #[test]+ fn render_commits_invalid_json_is_none() {+ // A forge that returns junk yields `None`, so `spawn_compute` leaves the+ // slot empty rather than caching garbage.+ assert!(render_github_commits(b"not json", 80).is_none());+ assert!(render_gitlab_commits(b"not json", 80).is_none());+ }++ #[test]+ fn log_tab_uses_local_git_log_when_head_present() {+ // When the PR head commit is already in the local object store, the+ // `log` tab renders the rich local `git log` — graph marker and full+ // subject — with no forge call, sharing the worktree rows' log path. An+ // absent SHA falls through to `None` so `compute_pr_log` can hit the+ // forge API instead. Both checks are hermetic: `local_log` never shells+ // out to a forge CLI.+ let t = worktrunk::testing::TestRepo::with_initial_commit();+ let repo = Repository::at(t.path()).unwrap();+ std::fs::write(t.path().join("feature.txt"), "x\n").unwrap();+ repo.run_command(&["add", "feature.txt"]).unwrap();+ repo.run_command(&["commit", "-m", "Add the retry"])+ .unwrap();+ let oid = repo+ .run_command(&["rev-parse", "HEAD"])+ .unwrap()+ .trim()+ .to_string();++ // Present locally → the local git-log render (graph `*` + subject).+ let local = local_log(&repo, &oid, "feature", 80, 24).expect("head present → local log");+ let plain_local = plain(&local);+ assert!(+ plain_local.contains("Add the retry"),+ "subject present: {plain_local:?}"+ );+ assert!(plain_local.contains('*'), "graph marker: {plain_local:?}");++ // Absent locally → `None`, leaving the forge API path to the caller.+ assert!(+ local_log(&repo, &"0".repeat(40), "feature", 80, 24).is_none(),+ "absent head → no local render"+ );++ // `compute_pr_log` takes the local path for a present head without+ // touching the forge.+ let via_compute = compute_pr_log(&repo, RefKind::Pr, 42, Some(&oid), "feature", 80, 24)+ .expect("compute_pr_log renders the local log");+ assert!(plain(&via_compute).contains("Add the retry"));+ }++ #[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-7) on a miss.+ let cache: PreviewCache = Arc::new(DashMap::new());+ let pr = PrSkimItem::new(entry(RefKind::Mr, 7, "t"), 120, None, &cache);++ let miss = pr.cached_pane(PreviewMode::Comments);+ assert!(miss.contains("Loading comments"), "miss: {miss:?}");+ assert!(miss.contains("alt-7"), "refresh hint: {miss:?}");++ cache.insert(+ ("mr:7".to_string(), PreviewMode::Comments),+ "rendered thread".to_string(),+ );+ assert_eq!(pr.cached_pane(PreviewMode::Comments), "rendered thread");+ }++ #[test]+ fn render_github_comments_threads_author_time_and_body() {+ // Each comment renders an author + relative-time header and its body in+ // the house gutter. The timestamps are old, so a relative-time suffix+ // renders; we assert the separator's presence, not the exact value, so+ // the test is stable regardless of the wall clock.+ let json = br#"{"comments":[+ {"author":{"login":"octocat"},"body":"Looks **good** to me.","createdAt":"2024-12-01T00:00:00Z"},+ {"author":{"login":"hubot"},"body":"Reran CI.","createdAt":"2024-11-01T00:00:00Z"}+ ]}"#;+ let out = render_github_comments(json, 80).unwrap();+ let plain = plain(&out);+ assert!(+ plain.contains("@octocat") && plain.contains("@hubot"),+ "authors: {plain:?}"+ );+ // Body rendered as markdown (the `**` markers are consumed) in the gutter.+ assert!(out.contains("\x1b[107m"), "house gutter bg: {out:?}");+ assert!(+ plain.contains("good") && !plain.contains("**good**"),+ "markdown: {plain:?}"+ );+ // A relative-time suffix is present (e.g. "1mo" / "2mo").+ assert!(plain.contains('·'), "time separator: {plain:?}");+ }++ #[test]+ fn render_gitlab_notes_drops_system_notes() {+ // GitLab `/notes` interleaves human comments with system activity+ // ("changed the description", label events); only the human comment+ // survives.+ let json = br#"[+ {"body":"changed the description","author":{"username":"alice"},"created_at":"2024-12-01T00:00:00Z","system":true},+ {"body":"Nice cleanup.","author":{"username":"bob"},"created_at":"2024-12-02T00:00:00Z","system":false}+ ]"#;+ let plain = plain(&render_gitlab_notes(json, 80).unwrap());+ assert!(+ plain.contains("@bob") && plain.contains("Nice cleanup."),+ "human note: {plain:?}"+ );+ assert!(+ !plain.contains("changed the description"),+ "system note dropped: {plain:?}"+ );+ assert!(+ !plain.contains("@alice"),+ "system author dropped: {plain:?}"+ );+ }++ #[test]+ fn render_comments_empty_and_missing_fields() {+ // No comments (or only system notes filtered out) → an info line, so the+ // slot caches a terminal value rather than staying empty.+ assert!(+ plain(&render_github_comments(br#"{"comments":[]}"#, 80).unwrap())+ .contains("No comments")+ );+ // A comment missing author/date still renders: "@unknown", no time, body.+ let json = br#"{"comments":[{"body":"orphaned"}]}"#;+ let missing = plain(&render_github_comments(json, 80).unwrap());+ assert!(missing.contains("@unknown"), "fallback author: {missing:?}");+ assert!(missing.contains("orphaned"), "body kept: {missing:?}");+ assert!(+ !missing.contains('·'),+ "no time when date absent: {missing:?}"+ );++ // An empty-body comment keeps its header and shows a "(no body)" marker+ // (a reaction-only or deleted comment), rather than a blank gutter.+ let empty_body = br#"{"comments":[{"author":{"login":"octocat"},"body":"","createdAt":"2024-12-01T00:00:00Z"}]}"#;+ let rendered = plain(&render_github_comments(empty_body, 80).unwrap());+ assert!(+ rendered.contains("@octocat"),+ "header survives: {rendered:?}"+ );+ assert!(+ rendered.contains("(no body)"),+ "empty-body marker: {rendered:?}"+ );+ }++ #[test]+ fn render_comments_invalid_json_is_none() {+ assert!(render_github_comments(b"not json", 80).is_none());+ assert!(render_gitlab_notes(b"not json", 80).is_none());+ }++ #[test]+ fn relative_time_parses_rfc3339_else_none() {+ // A parseable timestamp yields a short relative string; junk yields None+ // so the comment header just drops the time.+ assert!(relative_time("2024-12-01T00:00:00Z").is_some());+ assert!(relative_time("not a date").is_none());+ assert!(relative_time("").is_none());+ }}diff --git a/src/commands/picker/snapshots/wt__commands__picker__items__tests__branch_diff.snap b/src/commands/picker/snapshots/wt__commands__picker__items__tests__branch_diff.snapindex b2bf037a5..729669f78 100644--- a/src/commands/picker/snapshots/wt__commands__picker__items__tests__branch_diff.snap+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__branch_diff.snap@@ -1,6 +1,6 @@---source: src/commands/picker/items.rs-expression: "render_preview_tabs(mode, wt)"+expression: "render_preview_tabs(mode, wt, WIDE)"----1: [2mHEAD±[22m[0m | 2: [2mlog[22m[0m | 3: [1mmain…±[22m[0m | 4: [2mremote⇅[22m[0m | 5: [2msummary[22m[0m | [2m6:[22m [2mpr[22m[0m-[33m[2mEnter: switch | Tab/alt-1…6: preview | alt-c: create | Esc: cancel | ctrl-u/d: scroll | alt-p: toggle[39m[22m[0m+1: [2mHEAD±[22m[0m | 2: [2mlog[22m[0m | 3: [1mmain…±[22m[0m | 4: [2mremote⇅[22m[0m | 5: [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__empty_upstream_and_summary.snap b/src/commands/picker/snapshots/wt__commands__picker__items__tests__empty_upstream_and_summary.snapindex ad4bbc3a9..bf623d1e7 100644--- a/src/commands/picker/snapshots/wt__commands__picker__items__tests__empty_upstream_and_summary.snap+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__empty_upstream_and_summary.snap@@ -1,6 +1,6 @@---source: src/commands/picker/items.rs-expression: "render_preview_tabs(PreviewMode::WorkingTree,\nTabAvailability::worktree(false, false, false))"+expression: "render_preview_tabs(PreviewMode::WorkingTree,\nTabAvailability::worktree(false, false, false), WIDE,)"----1: [1mHEAD±[22m[0m | 2: [2mlog[22m[0m | 3: [2mmain…±[22m[0m | [2m4:[22m [2mremote⇅[22m[0m | [2m5:[22m [2msummary[22m[0m | [2m6:[22m [2mpr[22m[0m-[33m[2mEnter: switch | Tab/alt-1…6: preview | alt-c: create | Esc: cancel | ctrl-u/d: scroll | alt-p: toggle[39m[22m[0m+1: [1mHEAD±[22m[0m | 2: [2mlog[22m[0m | 3: [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__log.snap b/src/commands/picker/snapshots/wt__commands__picker__items__tests__log.snapindex 97cd24349..1ed9b7222 100644--- a/src/commands/picker/snapshots/wt__commands__picker__items__tests__log.snap+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__log.snap@@ -1,6 +1,6 @@---source: src/commands/picker/items.rs-expression: "render_preview_tabs(mode, wt)"+expression: "render_preview_tabs(mode, wt, WIDE)"----1: [2mHEAD±[22m[0m | 2: [1mlog[22m[0m | 3: [2mmain…±[22m[0m | 4: [2mremote⇅[22m[0m | 5: [2msummary[22m[0m | [2m6:[22m [2mpr[22m[0m-[33m[2mEnter: switch | Tab/alt-1…6: preview | alt-c: create | Esc: cancel | ctrl-u/d: scroll | alt-p: toggle[39m[22m[0m+1: [2mHEAD±[22m[0m | 2: [1mlog[22m[0m | 3: [2mmain…±[22m[0m | 4: [2mremote⇅[22m[0m | 5: [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.snap b/src/commands/picker/snapshots/wt__commands__picker__items__tests__pr.snapindex 566a4283d..270efe459 100644--- a/src/commands/picker/snapshots/wt__commands__picker__items__tests__pr.snap+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__pr.snap@@ -1,6 +1,6 @@---source: src/commands/picker/items.rs-expression: "render_preview_tabs(mode, wt)"+expression: "render_preview_tabs(mode, wt, WIDE)"----1: [2mHEAD±[22m[0m | 2: [2mlog[22m[0m | 3: [2mmain…±[22m[0m | 4: [2mremote⇅[22m[0m | 5: [2msummary[22m[0m | [2m6:[22m [1mpr[22m[0m-[33m[2mEnter: switch | Tab/alt-1…6: preview | alt-c: create | Esc: cancel | ctrl-u/d: scroll | alt-p: toggle[39m[22m[0m+1: [2mHEAD±[22m[0m | 2: [2mlog[22m[0m | 3: [2mmain…±[22m[0m | 4: [2mremote⇅[22m[0m | 5: [2msummary[22m[0m | [2m6:[22m [1mpr[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 eb1373b8b..0c3213103 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())"+expression: "render_preview_tabs(PreviewMode::Pr, TabAvailability::pull_request(), WIDE)"----[2m1:[22m [2mHEAD±[22m[0m | [2m2:[22m [2mlog[22m[0m | [2m3:[22m [2mmain…±[22m[0m | [2m4:[22m [2mremote⇅[22m[0m | [2m5:[22m [2msummary[22m[0m | 6: [1mpr[22m[0m-[33m[2mEnter: switch | Tab/alt-1…6: preview | alt-c: create | Esc: cancel | ctrl-u/d: scroll | alt-p: toggle[39m[22m[0m+[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/src/commands/picker/snapshots/wt__commands__picker__items__tests__summary.snap b/src/commands/picker/snapshots/wt__commands__picker__items__tests__summary.snapindex 1b5d6cca0..bb31f6424 100644--- a/src/commands/picker/snapshots/wt__commands__picker__items__tests__summary.snap+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__summary.snap@@ -1,6 +1,6 @@---source: src/commands/picker/items.rs-expression: "render_preview_tabs(mode, wt)"+expression: "render_preview_tabs(mode, wt, WIDE)"----1: [2mHEAD±[22m[0m | 2: [2mlog[22m[0m | 3: [2mmain…±[22m[0m | 4: [2mremote⇅[22m[0m | 5: [1msummary[22m[0m | [2m6:[22m [2mpr[22m[0m-[33m[2mEnter: switch | Tab/alt-1…6: preview | alt-c: create | Esc: cancel | ctrl-u/d: scroll | alt-p: toggle[39m[22m[0m+1: [2mHEAD±[22m[0m | 2: [2mlog[22m[0m | 3: [2mmain…±[22m[0m | 4: [2mremote⇅[22m[0m | 5: [1msummary[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__upstream_diff.snap b/src/commands/picker/snapshots/wt__commands__picker__items__tests__upstream_diff.snapindex 0c92992fc..d82a5e99a 100644--- a/src/commands/picker/snapshots/wt__commands__picker__items__tests__upstream_diff.snap+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__upstream_diff.snap@@ -1,6 +1,6 @@---source: src/commands/picker/items.rs-expression: "render_preview_tabs(mode, wt)"+expression: "render_preview_tabs(mode, wt, WIDE)"----1: [2mHEAD±[22m[0m | 2: [2mlog[22m[0m | 3: [2mmain…±[22m[0m | 4: [1mremote⇅[22m[0m | 5: [2msummary[22m[0m | [2m6:[22m [2mpr[22m[0m-[33m[2mEnter: switch | Tab/alt-1…6: preview | alt-c: create | Esc: cancel | ctrl-u/d: scroll | alt-p: toggle[39m[22m[0m+1: [2mHEAD±[22m[0m | 2: [2mlog[22m[0m | 3: [2mmain…±[22m[0m | 4: [1mremote⇅[22m[0m | 5: [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__working_tree.snap b/src/commands/picker/snapshots/wt__commands__picker__items__tests__working_tree.snapindex 68ed18b74..96fa4369a 100644--- a/src/commands/picker/snapshots/wt__commands__picker__items__tests__working_tree.snap+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__working_tree.snap@@ -1,6 +1,6 @@---source: src/commands/picker/items.rs-expression: "render_preview_tabs(mode, wt)"+expression: "render_preview_tabs(mode, wt, WIDE)"----1: [1mHEAD±[22m[0m | 2: [2mlog[22m[0m | 3: [2mmain…±[22m[0m | 4: [2mremote⇅[22m[0m | 5: [2msummary[22m[0m | [2m6:[22m [2mpr[22m[0m-[33m[2mEnter: switch | Tab/alt-1…6: preview | alt-c: create | Esc: cancel | ctrl-u/d: scroll | alt-p: toggle[39m[22m[0m+1: [1mHEAD±[22m[0m | 2: [2mlog[22m[0m | 3: [2mmain…±[22m[0m | 4: [2mremote⇅[22m[0m | 5: [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/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rsindex 64500c1de..4a68a6fa0 100644--- a/tests/integration_tests/switch.rs+++ b/tests/integration_tests/switch.rs@@ -2370,6 +2370,184 @@ fn test_switch_prs_dry_run_github(repo: TestRepo) {);}+/// 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",+/// mode:2}` (Log) entry with non-empty bytes proves the whole mechanism end to+/// end: `spawn_compute` → `compute_pr_log` → `render_github_commits` → cache.+///+/// `headRefOid` here is a SHA that isn't in the test repo's object store, so+/// `compute_pr_log`'s local-`git log` fast path misses and falls back to the+/// forge API — exercising that branch (the present-head fast path has its own+/// test, `test_switch_prs_dry_run_github_log_tab_local`).+#[cfg(unix)]+#[rstest]+fn test_switch_prs_dry_run_github_log_tab(repo: TestRepo) {+ repo.write_project_config("[forge]\nplatform = \"github\"\n");+ let pr_json = r#"[{"number":42,"title":"Retry the flaky test","headRefName":"fix/flaky","headRefOid":"1111111111111111111111111111111111111111","author":{"login":"octocat"},"isDraft":false,"url":"https://github.com/owner/test-repo/pull/42"}]"#;+ let commits_json = r#"{"commits":[{"oid":"abc1234500000000000000000000000000000000","messageHeadline":"Wrap the request in a retry"}]}"#;++ let mock_bin = repo.root_path().join("mock-bin");+ fs::create_dir_all(&mock_bin).unwrap();+ fs::write(mock_bin.join("list.json"), pr_json).unwrap();+ fs::write(mock_bin.join("commits.json"), commits_json).unwrap();+ MockConfig::new("gh")+ .version("gh version 1.0.0 (mock)")+ .command("pr list", MockResponse::file("list.json"))+ // `gh pr view 42 --json commits` matches the "pr view" compound key.+ .command("pr view", MockResponse::file("commits.json"))+ .command("_default", MockResponse::exit(1))+ .write(&mock_bin);++ let mut cmd = repo.wt_command();+ cmd.args(["switch", "--prs"]);+ cmd.env("WORKTRUNK_PICKER_DRY_RUN", "1");+ configure_mock_cli_env(&mut cmd, &mock_bin);+ let output = cmd.output().unwrap();+ assert!(+ output.status.success(),+ "dry-run --prs log tab failed:\nstdout: {}\nstderr: {}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr),+ );++ let stdout = String::from_utf8(output.stdout).expect("stdout is utf-8");+ let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("stdout is valid JSON");+ let entries = parsed["entries"].as_array().expect("entries array");+ // Mode 2 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"] == 2)+ .unwrap_or_else(|| panic!("no pr:42 Log cache entry in dump:\n{stdout}"));+ assert!(+ log_entry["bytes"].as_u64().unwrap_or(0) > 0,+ "log pane rendered non-empty: {log_entry}"+ );+}++/// When a `--prs` row's head commit is already in the local object store, the+/// `log` tab renders the rich local `git log` instead of fetching from the+/// forge. Here `gh pr list` reports the repo's own HEAD as `headRefOid` and the+/// mocked `gh pr view` is rigged to fail — so a non-empty `pr:42` Log cache+/// entry can only have come from the local-`git log` fast path, proving the+/// `headRefOid` → `spawn_pr_previews` → `compute_pr_log` wiring short-circuits+/// the API when the commit is present.+///+/// The same run pins the deferred-fetch failure contract: the `comments` tab has+/// no local path, so its forge fetch fails here, and `spawn_compute` leaves the+/// slot empty rather than caching a blank pane (the present Log entry proves the+/// row was built, so the absent Comments entry is a genuine miss, not a row that+/// never streamed). Nothing re-spawns it — the tab keeps its loading placeholder+/// for the session.+#[cfg(unix)]+#[rstest]+fn test_switch_prs_dry_run_github_log_tab_local(repo: TestRepo) {+ repo.write_project_config("[forge]\nplatform = \"github\"\n");+ let head = repo.head_sha();+ let pr_json = format!(+ r#"[{{"number":42,"title":"Local head","headRefName":"fix/flaky","headRefOid":"{head}","author":{{"login":"octocat"}},"isDraft":false,"url":"https://github.com/owner/test-repo/pull/42"}}]"#+ );++ let mock_bin = repo.root_path().join("mock-bin");+ fs::create_dir_all(&mock_bin).unwrap();+ fs::write(mock_bin.join("list.json"), &pr_json).unwrap();+ MockConfig::new("gh")+ .version("gh version 1.0.0 (mock)")+ .command("pr list", MockResponse::file("list.json"))+ // The local fast path must win: a forge `pr view` would fail here, so a+ // non-empty Log entry proves the commits came from the local `git log`.+ .command("pr view", MockResponse::exit(1))+ .command("_default", MockResponse::exit(1))+ .write(&mock_bin);++ let mut cmd = repo.wt_command();+ cmd.args(["switch", "--prs"]);+ cmd.env("WORKTRUNK_PICKER_DRY_RUN", "1");+ configure_mock_cli_env(&mut cmd, &mock_bin);+ let output = cmd.output().unwrap();+ assert!(+ output.status.success(),+ "dry-run --prs local log tab failed:\nstdout: {}\nstderr: {}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr),+ );++ let stdout = String::from_utf8(output.stdout).expect("stdout is utf-8");+ let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("stdout is valid JSON");+ let entries = parsed["entries"].as_array().expect("entries array");+ let log_entry = entries+ .iter()+ .find(|e| e["branch"] == "pr:42" && e["mode"] == 2)+ .unwrap_or_else(|| panic!("no pr:42 Log cache entry in dump:\n{stdout}"));+ assert!(+ log_entry["bytes"].as_u64().unwrap_or(0) > 0,+ "local log pane rendered non-empty: {log_entry}"+ );++ // The comments tab has no local path, so its forge fetch failed (pr view →+ // exit 1) and `spawn_compute` cached nothing — the failure leaves the slot+ // empty rather than pinning a blank pane. Mode 7 is Comments.+ assert!(+ !entries+ .iter()+ .any(|e| e["branch"] == "pr:42" && e["mode"] == 7),+ "failed comments fetch must leave the slot empty, not cache a blank pane:\n{stdout}"+ );+}++/// The `comments` tab (7) 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",+/// mode:7}` 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+/// canned response carries both arrays; serde ignores the one each renderer+/// doesn't read.)+#[cfg(unix)]+#[rstest]+fn test_switch_prs_dry_run_github_comments_tab(repo: TestRepo) {+ repo.write_project_config("[forge]\nplatform = \"github\"\n");+ let pr_json = r#"[{"number":42,"title":"Retry the flaky test","headRefName":"fix/flaky","author":{"login":"octocat"},"isDraft":false,"url":"https://github.com/owner/test-repo/pull/42"}]"#;+ let view_json = r#"{"commits":[{"oid":"abc1234500000000000000000000000000000000","messageHeadline":"Wrap the request in a retry"}],"comments":[{"author":{"login":"reviewer"},"body":"Nice fix.","createdAt":"2024-12-01T00:00:00Z"}]}"#;++ let mock_bin = repo.root_path().join("mock-bin");+ fs::create_dir_all(&mock_bin).unwrap();+ fs::write(mock_bin.join("list.json"), pr_json).unwrap();+ fs::write(mock_bin.join("view.json"), view_json).unwrap();+ MockConfig::new("gh")+ .version("gh version 1.0.0 (mock)")+ .command("pr list", MockResponse::file("list.json"))+ .command("pr view", MockResponse::file("view.json"))+ .command("_default", MockResponse::exit(1))+ .write(&mock_bin);++ let mut cmd = repo.wt_command();+ cmd.args(["switch", "--prs"]);+ cmd.env("WORKTRUNK_PICKER_DRY_RUN", "1");+ configure_mock_cli_env(&mut cmd, &mock_bin);+ let output = cmd.output().unwrap();+ assert!(+ output.status.success(),+ "dry-run --prs comments tab failed:\nstdout: {}\nstderr: {}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr),+ );++ let stdout = String::from_utf8(output.stdout).expect("stdout is utf-8");+ let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("stdout is valid JSON");+ let entries = parsed["entries"].as_array().expect("entries array");+ // Mode 7 is Comments; the row keys its cache by `pr:42`.+ let comments_entry = entries+ .iter()+ .find(|e| e["branch"] == "pr:42" && e["mode"] == 7)+ .unwrap_or_else(|| panic!("no pr:42 Comments cache entry in dump:\n{stdout}"));+ assert!(+ comments_entry["bytes"].as_u64().unwrap_or(0) > 0,+ "comments pane rendered non-empty: {comments_entry}"+ );+}+/// GitLab counterpart of [`test_switch_prs_dry_run_github`], covering the/// `fetch_gitlab` / `parse_gitlab_mrs` / `gitlab_mr_status` path via a mocked/// `glab mr list`.@@ -2393,6 +2571,65 @@ 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:2` (Log) and `mode:7`+/// (Comments) cache entries with non-empty bytes prove `compute_pr_log` /+/// `compute_pr_comments` → `render_gitlab_commits` / `render_gitlab_notes` →+/// cache for the GitLab forge — the half the unit tests (canned JSON straight+/// into the renderers) can't reach, pinning the endpoint/arg construction.+///+/// Both `glab api …/commits` and `…/notes` match the mock's `api --paginate`+/// compound key, so one canned response carries all fields each renderer reads+/// (`short_id`/`title` for commits; `body`/`author`/`created_at`/`system` for+/// notes) — serde ignores the rest.+#[cfg(unix)]+#[rstest]+fn test_switch_prs_dry_run_gitlab_deferred_tabs(repo: TestRepo) {+ repo.write_project_config("[forge]\nplatform = \"gitlab\"\n");+ let mr_json = r#"[{"iid":7,"title":"Cache the dependency graph","source_branch":"feat/cache","author":{"username":"alice"},"draft":false,"web_url":"https://gitlab.com/owner/test-repo/-/merge_requests/7"}]"#;+ let api_json = r#"[{"short_id":"abc12345","title":"Cache deps between jobs","body":"Looks good.","author":{"username":"reviewer"},"created_at":"2024-12-01T00:00:00Z","system":false}]"#;++ let mock_bin = repo.root_path().join("mock-bin");+ fs::create_dir_all(&mock_bin).unwrap();+ fs::write(mock_bin.join("list.json"), mr_json).unwrap();+ fs::write(mock_bin.join("api.json"), api_json).unwrap();+ MockConfig::new("glab")+ .version("glab version 1.0.0 (mock)")+ .command("mr list", MockResponse::file("list.json"))+ // `glab api --paginate <endpoint>` for both commits and notes.+ .command("api --paginate", MockResponse::file("api.json"))+ .command("_default", MockResponse::exit(1))+ .write(&mock_bin);++ let mut cmd = repo.wt_command();+ cmd.args(["switch", "--prs"]);+ cmd.env("WORKTRUNK_PICKER_DRY_RUN", "1");+ configure_mock_cli_env(&mut cmd, &mock_bin);+ let output = cmd.output().unwrap();+ assert!(+ output.status.success(),+ "dry-run --prs gitlab deferred tabs failed:\nstdout: {}\nstderr: {}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr),+ );++ let stdout = String::from_utf8(output.stdout).expect("stdout is utf-8");+ let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("stdout is valid JSON");+ let entries = parsed["entries"].as_array().expect("entries array");+ for (mode, label) in [(2, "Log"), (7, "Comments")] {+ let entry = entries+ .iter()+ .find(|e| e["branch"] == "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,+ "{label} pane rendered non-empty: {entry}"+ );+ }+}+/// An empty forge list still runs `stream_open_prs` to completion, exercising/// the empty-list branch and `forge_noun` (`_ => "PRs"` on GitHub).#[cfg(unix)]diff --git a/tests/integration_tests/switch_picker.rs b/tests/integration_tests/switch_picker.rsindex 85fd50407..283b95af5 100644--- a/tests/integration_tests/switch_picker.rs+++ b/tests/integration_tests/switch_picker.rs@@ -1153,9 +1153,9 @@ fn test_switch_picker_preview_cycle_tab_forward(mut repo: TestRepo) {#[rstest]fn test_switch_picker_preview_cycle_tab_forward_wraps(mut repo: TestRepo) {- // Forward cycling wraps 6 → 1: from the pr tab (reached via Alt-6), one Tab- // returns to the HEAD± tab. This covers the `6 → 1` end of the- // `tr 123456 234561` map, the half most easily typo'd away.+ // Forward cycling wraps 7 → 1: from the comments tab (reached via Alt-7), one+ // Tab returns to the HEAD± tab. This covers the `7 → 1` end of the+ // `tr 1234567 2345671` map, the half most easily typo'd away.repo.remove_fixture_worktrees();repo.run_git(&["remote", "remove", "origin"]);let feature_path = repo.add_worktree("feature");@@ -1192,9 +1192,11 @@ 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`- ("\x1b6", Some("PR")), // Alt-6: jump to pr (6); "Fetching PR status"/"has no PR"- ("\t", Some("no uncommitted changes")), // Tab: wrap 6 → HEAD± (1)+ ("\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")),+ ("\t", Some("no uncommitted changes")), // Tab: wrap 7 → HEAD± (1)],);@@ -1203,15 +1205,15 @@ fn test_switch_picker_preview_cycle_tab_forward_wraps(mut repo: TestRepo) {let (_list, preview) = result.panels();assert!(preview.contains("no uncommitted changes"),- "Tab from the pr tab should wrap to the HEAD± tab; preview was:\n{preview}"+ "Tab from the comments tab should wrap to the HEAD± tab; preview was:\n{preview}");}#[rstest]fn test_switch_picker_preview_cycle_shift_tab_wraps(mut repo: TestRepo) {// Shift-Tab cycles backward and wraps: from the default HEAD± tab (1), one- // Shift-Tab lands on the pr tab (6), exercising the reverse rotation- // `tr 123456 612345` including the 1 → 6 wraparound.+ // Shift-Tab lands on the comments tab (7), exercising the reverse rotation+ // `tr 1234567 7123456` including the 1 → 7 wraparound.repo.remove_fixture_worktrees();repo.run_git(&["remote", "remove", "origin"]);let feature_path = repo.add_worktree("feature");@@ -1245,21 +1247,19 @@ 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`- ("\x1b[Z", Some("PR")), // Shift-Tab: HEAD± → pr (wrap); "Fetching PR status"/"has no PR"+ ("\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")),],);assert_valid_abort_exit_code(result.exit_code);let (_list, preview) = result.panels();- // The worktree row has no remote and no CI cache, so its `pr` pane is either- // "Fetching PR status …" (the live fetch hasn't reported yet) or "feature- // has no PR" (it reported nothing) — both confirm Shift-Tab wrapped to the- // pr tab.assert!(- preview.contains("Fetching PR status") || preview.contains("has no PR"),- "Shift-Tab should wrap to the pr tab; preview was:\n{preview}"+ preview.contains("Comments show on"),+ "Shift-Tab should wrap to the comments tab; preview was:\n{preview}");}diff --git a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap b/tests/snapshots/integration__integration_tests__help__help_switch_long.snapindex 8bf72a5db..af9c2f94b 100644--- a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_switch_long.snap@@ -185,7 +185,7 @@ The CI column shows each row's PR/MR CI and review status, the same as [2mwt li[2mEnter[0m Switch to selected worktree[2mAlt-c[0m Create new worktree named as entered text[2mEsc[0m Cancel- [2mAlt-1[0m–[2mAlt-6[0m Jump to a preview tab+ [2mAlt-1[0m–[2mAlt-7[0m Jump to a preview tab[2mTab[0m/[2mShift-Tab[0m Cycle preview tabs forward/backward[2mAlt-p[0m Toggle preview panel[2mCtrl-u[0m/[2mCtrl-d[0m Scroll preview up/down@@ -202,6 +202,9 @@ Typing a gutter sigil filters by row kind: [36m+[0m narrows to linked worktree4. [1mremote⇅[0m — Ahead/behind diff vs upstream tracking branch5. [1msummary[0m — LLM-generated branch summary; requires [2m[list] summary = true[0m and [2mcommit.generation[0m6. [1mpr[0m — The selected row's PR/MR, for any row whose branch has one+7. [1mcomments[0m — The PR/MR's comment thread, fetched from the forge on [2m--prs[0m rows++On narrow previews the tab bar compacts to digits — only the active tab keeps its label — so every [2mAlt-N[0m accelerator stays visible.[1mPager configuration:[0m The preview panel pipes diff output through git's pager. Override in user config:@@ -224,7 +227,8 @@ Both work anywhere a branch is accepted, including [2m--base[0m. The [2m--creIf the PR or MR is on a fork, the local branch uses its branch name directly, so [2mgit push[0m works normally. A pre-existing local branch with that name tracking something else requires renaming first.-The [2m--prs[0m flag adds the repository's open PRs (GitHub) or MRs (GitLab) to the interactive picker. Each row resolves to the same [2mpr:[0m/[2mmr:[0m shortcut, so selecting one fetches the ref and switches to its branch.+The [2m--prs[0m flag adds the repository's open PRs (GitHub) or MRs (GitLab) to the interactive picker. Each row resolves to the same [2mpr:[0m/[2mmr:[0m shortcut, so selecting one fetches the ref and switches to its branch. A [2m--prs[0m row has no local worktree, so its [2mpr[0m and [2mcomments[0m preview tabs load the PR/MR's metadata and comments from the forge in the background. The [2mlog[0m tab uses a local [2mgit log[0m — graph and merge-base dimming included — whenever the head commit is already in the object store (a same-repo PR+off a fetched remote), falling back to a flat forge-fetched commit list otherwise.Requires [2mgh[0m (GitHub), [2mglab[0m (GitLab), or an equivalent CLI installed and authenticated; see forge platform for Gitea, Azure DevOps, and other supported platforms.diff --git a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_abort_escape_preview.snap b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_abort_escape_preview.snapindex 65ccf912d..a8619476e 100644--- a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_abort_escape_preview.snap+++ b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_abort_escape_preview.snap@@ -2,7 +2,7 @@source: tests/integration_tests/switch_picker.rsexpression: preview----1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary | 6: pr [N/M]-Enter: switch | Tab/alt-1…6: preview | alt-c: create | Esc:+1: HEAD± 2 3 4 5 6 7+Enter: switch | Tab/alt-1…7: preview | alt-c: create | Esc:○ main has no uncommitted changesdiff --git a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_multiple_worktrees_preview.snap b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_multiple_worktrees_preview.snapindex 65ccf912d..a8619476e 100644--- a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_multiple_worktrees_preview.snap+++ b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_multiple_worktrees_preview.snap@@ -2,7 +2,7 @@source: tests/integration_tests/switch_picker.rsexpression: preview----1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary | 6: pr [N/M]-Enter: switch | Tab/alt-1…6: preview | alt-c: create | Esc:+1: HEAD± 2 3 4 5 6 7+Enter: switch | Tab/alt-1…7: preview | alt-c: create | Esc:○ main has no uncommitted changesdiff --git a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_log_preview.snap b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_log_preview.snapindex 940867780..22469e9c3 100644--- a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_log_preview.snap+++ b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_log_preview.snap@@ -2,8 +2,8 @@source: tests/integration_tests/switch_picker.rsexpression: preview----1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary | 6: pr [N/M]-Enter: switch | Tab/alt-1…6: preview | alt-c: create | Esc:+1 2: log 3 4 5 6 7+Enter: switch | Tab/alt-1…7: preview | alt-c: create | Esc:* [HASH] +1 [TIME] (feature) Add file 5 with content* [HASH] +1 [TIME] Add file 4 with contentdiff --git a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_main_diff_preview.snap b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_main_diff_preview.snapindex 100f86d90..8b40bb5ce 100644--- a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_main_diff_preview.snap+++ b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_main_diff_preview.snap@@ -2,8 +2,8 @@source: tests/integration_tests/switch_picker.rsexpression: preview----1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary | 6: pr [N/M]-Enter: switch | Tab/alt-1…6: preview | alt-c: create | Esc:+1 2 3: main…± 4 5 6 7+Enter: switch | Tab/alt-1…7: preview | alt-c: create | Esc:feature_code.rs | 6 ++++++tests.rs | 4 ++++diff --git a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_summary_preview.snap b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_summary_preview.snapindex 157a39b00..7b6ec8336 100644--- a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_summary_preview.snap+++ b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_summary_preview.snap@@ -2,8 +2,8 @@source: tests/integration_tests/switch_picker.rsexpression: preview----1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary | 6: pr [N/M]-Enter: switch | Tab/alt-1…6: preview | alt-c: create | Esc:+1 2 3 4 5: summary 6 7+Enter: switch | Tab/alt-1…7: preview | alt-c: create | Esc:Configure [commit.generation] command to enable LLM summaridiff --git a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_uncommitted_preview.snap b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_uncommitted_preview.snapindex 3329d6b64..881a3a721 100644--- a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_uncommitted_preview.snap+++ b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_uncommitted_preview.snap@@ -2,8 +2,8 @@source: tests/integration_tests/switch_picker.rsexpression: preview----1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary | 6: pr [N/M]-Enter: switch | Tab/alt-1…6: preview | alt-c: create | Esc:+1: HEAD± 2 3 4 5 6 7+Enter: switch | Tab/alt-1…7: preview | alt-c: create | Esc:tracked.txt | 4 +++-1 file changed, 3 insertions(+), 1 deletion(-)diff --git a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_with_branches_preview.snap b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_with_branches_preview.snapindex 65ccf912d..a8619476e 100644--- a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_with_branches_preview.snap+++ b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_with_branches_preview.snap@@ -2,7 +2,7 @@source: tests/integration_tests/switch_picker.rsexpression: preview----1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary | 6: pr [N/M]-Enter: switch | Tab/alt-1…6: preview | alt-c: create | Esc:+1: HEAD± 2 3 4 5 6 7+Enter: switch | Tab/alt-1…7: preview | alt-c: create | Esc:○ main has no uncommitted changes