Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat(switch): show PR/MR title and description in the worktree pr preview pane (#3167)
Maximilian Roosedeba1b8bbab
diff --git a/src/commands/list/ci_status/azure.rs b/src/commands/list/ci_status/azure.rsindex 735d892ed..869709b71 100644--- a/src/commands/list/ci_status/azure.rs+++ b/src/commands/list/ci_status/azure.rs@@ -138,6 +138,8 @@ pub(super) fn detect_azure_pr(url,number: Some(PrRef::pr(u64::from(pr.pull_request_id))),review_state: None,+ title: pr.title.clone(),+ body: pr.description.clone(),})}@@ -219,6 +221,8 @@ pub(super) fn detect_azure_pipeline(url: web_url,number: None,review_state: None,+ title: None,+ body: None,})}@@ -246,6 +250,12 @@ struct AzPrListEntry {#[serde(default)]last_merge_source_commit: Option<AzCommitRef>,repository: AzPrRepository,+ /// PR title; shown in the picker's `pr` preview pane. Rides this call.+ #[serde(default)]+ title: Option<String>,+ /// PR description; rendered as markdown in the `pr` preview pane.+ #[serde(default)]+ description: Option<String>,}impl AzPrListEntry {diff --git a/src/commands/list/ci_status/gitea.rs b/src/commands/list/ci_status/gitea.rsindex 22408c714..9fe1302ac 100644--- a/src/commands/list/ci_status/gitea.rs+++ b/src/commands/list/ci_status/gitea.rs@@ -122,6 +122,8 @@ pub(super) fn detect_gitea_pr(url: Some(pr.html_url.clone()),number: pr.number.map(PrRef::pr),review_state: None,+ title: pr.title.clone(),+ body: pr.body.clone(),})}@@ -144,6 +146,8 @@ pub(super) fn detect_gitea_commit_status(url: None,number: None,review_state: None,+ title: None,+ body: None,})}@@ -181,6 +185,12 @@ struct GiteaPr {mergeable: Option<bool>,html_url: String,head: GiteaPrBranch,+ /// PR title; shown in the picker's `pr` preview pane. Rides this call.+ #[serde(default)]+ title: Option<String>,+ /// PR description; rendered as markdown in the `pr` preview pane.+ #[serde(default)]+ body: Option<String>,}#[derive(Debug, Deserialize)]diff --git a/src/commands/list/ci_status/github.rs b/src/commands/list/ci_status/github.rsindex 0d36e7619..eb569d68d 100644--- a/src/commands/list/ci_status/github.rs+++ b/src/commands/list/ci_status/github.rs@@ -68,7 +68,9 @@ pub(super) fn detect_github("--limit",&MAX_PRS_TO_FETCH.to_string(),"--json",- "number,headRefOid,mergeStateStatus,statusCheckRollup,url,headRepositoryOwner,reviewDecision,isDraft",+ // title,body ride this existing call so the picker's `pr` preview+ // pane can show them — no extra round-trip.+ "number,title,body,headRefOid,mergeStateStatus,statusCheckRollup,url,headRepositoryOwner,reviewDecision,isDraft",]).current_dir(&repo_root).run()@@ -131,6 +133,8 @@ pub(super) fn detect_github(url: pr_info.url.clone(),number: pr_info.number.map(PrRef::pr),review_state: pr_info.review_state(),+ title: pr_info.title.clone(),+ body: pr_info.body.clone(),})}@@ -199,6 +203,8 @@ pub(super) fn detect_github_commit_checks(url: None,number: None,review_state: None,+ title: None,+ body: None,})}@@ -211,6 +217,10 @@ pub(super) fn detect_github_commit_checks(#[derive(Debug, Deserialize)]pub(crate) struct GitHubPrInfo {pub number: Option<u64>,+ /// PR title; shown in the picker's `pr` preview pane. Rides this call.+ pub title: Option<String>,+ /// PR description; shown in the `pr` preview pane. Rides this call.+ pub body: Option<String>,#[serde(rename = "headRefOid")]pub head_ref_oid: Option<String>,#[serde(rename = "mergeStateStatus")]@@ -307,6 +317,13 @@ impl GitHubPrInfo {url: self.url.clone(),number: self.number.map(PrRef::pr),review_state: self.review_state(),+ // TODO(prs-status-title-body): the `--prs` pane reads title/body from+ // the `PrEntry`, not from this status (which feeds only the CI column),+ // so these clones are dead data here. GitLab's `gitlab_mr_status` sets+ // both `None` for this reason — unify the two `--prs` status builders+ // (drop them here to match, or have both read from the status).+ title: self.title.clone(),+ body: self.body.clone(),}}}@@ -388,6 +405,8 @@ mod tests {status_check_rollup: None,url: None,head_repository_owner: None,+ title: None,+ body: None,review_decision: None,is_draft: None,};@@ -404,6 +423,8 @@ mod tests {status_check_rollup: None,url: None,head_repository_owner: None,+ title: None,+ body: None,review_decision: None,is_draft: None,};@@ -417,6 +438,8 @@ mod tests {status_check_rollup: Some(vec![]),url: None,head_repository_owner: None,+ title: None,+ body: None,review_decision: None,is_draft: None,};@@ -435,6 +458,8 @@ mod tests {}]),url: None,head_repository_owner: None,+ title: None,+ body: None,review_decision: None,is_draft: None,};@@ -453,6 +478,8 @@ mod tests {}]),url: None,head_repository_owner: None,+ title: None,+ body: None,review_decision: None,is_draft: None,};@@ -471,6 +498,8 @@ mod tests {}]),url: None,head_repository_owner: None,+ title: None,+ body: None,review_decision: None,is_draft: None,};@@ -490,6 +519,8 @@ mod tests {}]),url: None,head_repository_owner: None,+ title: None,+ body: None,review_decision: None,is_draft: None,};@@ -508,6 +539,8 @@ mod tests {}]),url: None,head_repository_owner: None,+ title: None,+ body: None,review_decision: None,is_draft: None,};@@ -523,6 +556,8 @@ mod tests {status_check_rollup: None,url: None,head_repository_owner: None,+ title: None,+ body: None,review_decision: review_decision.map(Into::into),is_draft,};diff --git a/src/commands/list/ci_status/gitlab.rs b/src/commands/list/ci_status/gitlab.rsindex 6f6668e3a..208101243 100644--- a/src/commands/list/ci_status/gitlab.rs+++ b/src/commands/list/ci_status/gitlab.rs@@ -187,6 +187,8 @@ pub(super) fn detect_gitlab(url: mr_entry.web_url.clone(),number: Some(PrRef::mr(mr_entry.iid)),review_state: mr_entry.review_state(),+ title: mr_entry.title.clone(),+ body: mr_entry.description.clone(),});};@@ -200,6 +202,8 @@ pub(super) fn detect_gitlab(url: mr_entry.web_url.clone(),number: Some(PrRef::mr(mr_entry.iid)),review_state: mr_entry.review_state(),+ title: mr_entry.title.clone(),+ body: mr_entry.description.clone(),})}@@ -269,6 +273,8 @@ pub(super) fn detect_gitlab_pipeline(url: pipeline.web_url.clone(),number: None,review_state: None,+ title: None,+ body: None,})}@@ -292,6 +298,12 @@ struct GitLabMrListEntry {pub web_url: Option<String>,/// Draft/WIP flag (absent in older glab versions)pub draft: Option<bool>,+ /// MR title; shown in the picker's `pr` preview pane. Rides this call.+ #[serde(default)]+ pub title: Option<String>,+ /// MR description; rendered as markdown in the `pr` preview pane.+ #[serde(default)]+ pub description: Option<String>,}impl GitLabMrListEntry {@@ -402,6 +414,8 @@ mod tests {source_project_id: None,web_url: None,draft,+ title: None,+ description: None,};// Draft wins over the approval gapdiff --git a/src/commands/list/ci_status/mod.rs b/src/commands/list/ci_status/mod.rsindex 9f4a3bdf4..745cc0def 100644--- a/src/commands/list/ci_status/mod.rs+++ b/src/commands/list/ci_status/mod.rs@@ -389,6 +389,15 @@ pub struct PrStatus {/// Review state of the PR/MR (absent when the forge reports no review signal)#[serde(skip_serializing_if = "Option::is_none")]pub review_state: Option<ReviewState>,+ /// PR/MR title. Absent for branch workflows (no PR) and for cache entries+ /// written before this field existed. Shown in the picker's worktree-row+ /// `pr` preview pane, riding the same forge call the CI column already makes.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub title: Option<String>,+ /// PR/MR description (GitHub `body`, GitLab/Azure/Gitea `description`/`body`),+ /// rendered as markdown in the `pr` preview pane. Absent as for `title`.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub body: Option<String>,}impl CiStatus {@@ -508,6 +517,8 @@ impl PrStatus {url: None,number: None,review_state: None,+ title: None,+ body: None,}}@@ -714,6 +725,8 @@ mod tests {url: None,number: None,review_state: None,+ title: None,+ body: None,};assert_eq!(pr_passed.indicator(), "#");@@ -725,6 +738,8 @@ mod tests {url: None,number: None,review_state: None,+ title: None,+ body: None,};assert_eq!(branch_running.indicator(), "#");@@ -736,6 +751,8 @@ mod tests {url: None,number: None,review_state: None,+ title: None,+ body: None,};assert_eq!(error_status.indicator(), "⚠");}@@ -752,6 +769,8 @@ mod tests {url: Some("https://github.com/owner/repo/pull/123".to_string()),number: Some(PrRef::pr(123)),review_state: None,+ title: None,+ body: None,};// Number fits → PR reference, hyperlinked when supported@@ -845,6 +864,8 @@ mod tests {url: None,number: Some(PrRef::pr(12)),review_state: None,+ title: None,+ body: None,};let green = "\u{1b}[32m";let dim = "\u{1b}[2m";@@ -883,6 +904,8 @@ mod tests {url: None,number: None,review_state,+ title: None,+ body: None,};// Changes-requested outranks running and passed — waiting can't clear it@@ -994,6 +1017,8 @@ mod tests {url: None,number: number.map(PrRef::pr),review_state: None,+ title: None,+ body: None,}}diff --git a/src/commands/list/json_output.rs b/src/commands/list/json_output.rsindex 39f5749df..3ab5b8b78 100644--- a/src/commands/list/json_output.rs+++ b/src/commands/list/json_output.rs@@ -500,6 +500,12 @@ impl JsonCi {repo,url: pr.url.clone(),review_state: pr.review_state,+ // TODO(json-pr-title-body): `PrStatus` now carries `title`/`body`+ // (for the picker's `pr` preview pane), but they're deliberately not+ // surfaced here — `wt list --json` stays scoped to CI/review status.+ // Add them (with `skip_serializing_if = "Option::is_none"` plus a row+ // in the docs/content/list.md ci-object table) if a JSON consumer+ // needs them.}}}@@ -637,6 +643,8 @@ mod tests {url: Some("https://github.com/org/repo/pull/123".to_string()),number: Some(PrRef::pr(123)),review_state: None,+ title: None,+ body: None,},None,);@@ -675,6 +683,8 @@ mod tests {url: None,number: None,review_state: None,+ title: None,+ body: None,},None,);@@ -703,6 +713,8 @@ mod tests {url: None,number: None,review_state: None,+ title: None,+ body: None,},None,);@@ -723,6 +735,8 @@ mod tests {url: Some("https://git.example.com/org/repo/pull/7".to_string()),number: Some(PrRef::pr(7)),review_state: None,+ title: None,+ body: None,};let without = JsonCi::from_pr_status(&pr, None);diff --git a/src/commands/picker/items.rs b/src/commands/picker/items.rsindex f57164c40..7345faad9 100644--- a/src/commands/picker/items.rs+++ b/src/commands/picker/items.rs@@ -22,6 +22,7 @@ use super::log_formatter::{FIELD_DELIM, batch_fetch_stats, format_log_output, process_log_with_dimming, strip_hash_markers,};use super::pager::{diff_pager, pipe_through_pager};+use super::pr_pane;use super::preview::{PreviewMode, PreviewStateData};use super::preview_cache;@@ -217,27 +218,12 @@ impl SkimItem for WorktreeSkimItem {}fn preview(&self, context: PreviewContext<'_>) -> ItemPreview {+ // The mode is the only render input that comes from outside the item+ // (it's per-process picker state); everything else is derived in+ // `render_preview`, which takes the mode explicitly so it's testable+ // without touching that global state.let mode = PreviewStateData::read_mode();-- // Build preview: tabs header + content. `has_upstream` and- // `summaries_enabled` are synchronous skeleton-time facts (see- // `TabAvailability`); `pr` reads the row's live status slot, refreshed as- // the `CiStatus` task streams in, so it can change between selections.- // The `pr` tab dims only once the fetch reports no PR — while loading or- // with a PR it stays available.- let pr = self.pr_preview();- let avail = TabAvailability::worktree(- self.has_upstream,- self.summaries_enabled,- !matches!(pr, PrPreview::NoPr),- );- let mut result = render_preview_tabs(mode, avail);- result.push_str(&match mode {- PreviewMode::Pr => self.render_pr_pane(pr),- _ => self.preview_for_mode(mode, context.width, context.height),- });-- ItemPreview::AnsiText(result)+ ItemPreview::AnsiText(self.render_preview(mode, context.width, context.height))}}@@ -387,25 +373,55 @@ pub(super) fn render_preview_tabs(mode: PreviewMode, avail: TabAvailability) ->)}-/// The `pr` pane for a worktree row whose branch has a PR/MR. Renders the-/// reference and URL from the async CI fetch. The `url` label pads to the same-/// width as the `--prs` rows' pane (`PrSkimItem::pr_pane`) so the two read-/// alike.+/// The `pr` pane for a worktree row whose branch has a PR/MR. Renders the same+/// shape as the `--prs` rows' pane (`PrSkimItem::pr_pane`) — reference + title+/// header, dim-labeled metadata, and the description as markdown — via the+/// shared [`pr_pane`] helpers, so the two read alike. The title and body ride+/// the same CI fetch the column already makes (see [`PrStatus`]); a status+/// without them (an older cache entry, a forge that doesn't expose them) falls+/// back to a reference-only header and skips the description.///-/// TODO(pr-preview-worktree-body): the CI-column fetch doesn't pull the PR-/// title or description (just number/status/url), so this pane can't show them-/// the way the `--prs` rows' pane does. Widen that fetch's `--json` (or add a-/// per-row PR fetch) to fold them in.-fn render_worktree_pr(branch: &str, pr_ref: PrRef, status: &PrStatus) -> String {- let reset = Reset;- let mut out = cformat!("<bold>{pr_ref}</>{reset} {branch}\n\n");+/// `width` is the live preview-pane width, used to wrap the markdown body.+fn render_worktree_pr(branch: &str, pr_ref: PrRef, status: &PrStatus, width: usize) -> String {+ let title = status.title.as_deref().filter(|t| !t.is_empty());+ let mut out = pr_pane::header(pr_ref, title);+ out.push_str(&pr_pane::metadata_line("branch", branch));if let Some(url) = &status.url {- out.push_str(&cformat!("<dim>url</>{reset} {url}\n"));+ out.push_str(&pr_pane::metadata_line("url", url));+ }+ if let Some(body) = status.body.as_deref() {+ out.push_str(&pr_pane::description(body, width));}out}impl WorktreeSkimItem {+ /// Render the full preview pane (tab bar + mode content) for an explicit+ /// `mode`. Split out of [`SkimItem::preview`] so the dispatch — including+ /// the `pr` tab's `render_pr_pane` call — is testable with a given mode+ /// rather than the per-process picker-state file.+ fn render_preview(&self, mode: PreviewMode, width: usize, height: usize) -> String {+ // Build preview: tabs header + content. `has_upstream` and+ // `summaries_enabled` are synchronous skeleton-time facts (see+ // `TabAvailability`); `pr` reads the row's live status slot, refreshed as+ // the `CiStatus` task streams in, so it can change between selections.+ // The `pr` tab dims only once the fetch reports no PR — while loading or+ // with a PR it stays available. `pr_tab_available` is a cheap+ // discriminant read (no body clone); the pane itself is rendered once and+ // memoized in `render_pr_pane_cached`.+ let avail = TabAvailability::worktree(+ self.has_upstream,+ self.summaries_enabled,+ self.pr_tab_available(),+ );+ let mut result = render_preview_tabs(mode, avail);+ result.push_str(&match mode {+ PreviewMode::Pr => self.render_pr_pane_cached(width),+ _ => self.preview_for_mode(mode, width, height),+ });+ result+ }+/// Derive the `pr` tab's state from the row's live `pr_status` slot. The/// slot is primed from the CI cache at skeleton time and overwritten as the/// `CiStatus` task reports: `None` = no result yet (Loading); `Some(None)`,@@ -422,8 +438,40 @@ impl WorktreeSkimItem {}}- /// Render the `pr` tab's pane from the derived [`PrPreview`] state.- fn render_pr_pane(&self, pr: PrPreview) -> String {+ /// Whether the `pr` tab has content for this row — it dims only once the+ /// live fetch reports no PR. A cheap discriminant read of the `pr_status`+ /// slot (no `PrStatus` clone, unlike [`Self::pr_preview`]), so the tab bar+ /// can be drawn on every `preview()` call without re-cloning the+ /// possibly-large body that [`Self::render_pr_pane_cached`] already memoizes.+ fn pr_tab_available(&self) -> bool {+ match &*self.pr_status.lock().unwrap() {+ None => true, // still fetching+ Some(None) => false, // fetch reported no PR+ Some(Some(status)) => status.number.is_some(), // a bare branch workflow is "no PR"+ }+ }++ /// Render the `pr` pane, memoized in the shared `preview_cache` so repeated+ /// `preview()` calls (every keystroke while the tab is active) don't re-run+ /// the markdown render of the body. The other modes are pre-computed into+ /// this same cache by the orchestrator; the `pr` pane is filled lazily here+ /// instead because its inputs aren't known at skeleton time — they stream in+ /// on the `CiStatus` task. The collect handler's `on_update` removes this+ /// entry whenever the live `pr_status` slot changes (fetch lands, manual+ /// refresh), so a cache hit is always consistent with the current slot.+ fn render_pr_pane_cached(&self, width: usize) -> String {+ let key = (self.branch_name.clone(), PreviewMode::Pr);+ if let Some(cached) = self.preview_cache.get(&key) {+ return cached.value().clone();+ }+ let rendered = self.render_pr_pane(self.pr_preview(), width);+ self.preview_cache.insert(key, rendered.clone());+ rendered+ }++ /// Render the `pr` tab's pane from the derived [`PrPreview`] state. `width`+ /// is the live preview-pane width, threaded to wrap the description markdown.+ fn render_pr_pane(&self, pr: PrPreview, width: usize) -> String {let reset = Reset;let branch = self.item.branch_name();match pr {@@ -433,7 +481,7 @@ impl WorktreeSkimItem {PrPreview::NoPr => {cformat!("{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} has no PR\n")}- PrPreview::HasPr(pr_ref, status) => render_worktree_pr(branch, pr_ref, &status),+ PrPreview::HasPr(pr_ref, status) => render_worktree_pr(branch, pr_ref, &status, width),}}@@ -1059,7 +1107,10 @@ mod tests {fn worktree_pr_tab_reflects_live_status() {use crate::commands::list::ci_status::{CiSource, CiStatus, PrRef, ReviewState};- let status = |number: Option<PrRef>, url: Option<&str>| PrStatus {+ let status = |number: Option<PrRef>,+ url: Option<&str>,+ title: Option<&str>,+ body: Option<&str>| PrStatus {ci_status: CiStatus::Passed,source: CiSource::PullRequest,is_stale: false,@@ -1067,6 +1118,8 @@ mod tests {url: url.map(String::from),number,review_state: Some(ReviewState::Approved),+ title: title.map(String::from),+ body: body.map(String::from),};// Build a row whose live `pr_status` slot carries a given state — what// the picker primes from the cache and then overwrites as the fetch lands.@@ -1089,7 +1142,7 @@ mod tests {assert!(matches!(loading.pr_preview(), PrPreview::Loading));assert!(loading- .render_pr_pane(loading.pr_preview())+ .render_pr_pane(loading.pr_preview(), 80).contains("Fetching PR status"));@@ -1098,28 +1151,178 @@ mod tests {assert!(matches!(no_pr.pr_preview(), PrPreview::NoPr));assert!(no_pr- .render_pr_pane(no_pr.pr_preview())+ .render_pr_pane(no_pr.pr_preview(), 80).contains("has no PR"));- // A cached PR carries a `number` → the pane shows the reference and URL.- let has_pr = row(Some(Some(status(+ // A cached PR with no title/body (an older cache entry) → the pane still+ // shows the reference, branch, and URL, with no description block.+ let bare = row(Some(Some(status(Some(PrRef::pr(42)),Some("https://github.com/o/r/pull/42"),+ None,+ None,))));- assert!(matches!(has_pr.pr_preview(), PrPreview::HasPr(..)));- let pane = has_pr.render_pr_pane(has_pr.pr_preview());+ assert!(matches!(bare.pr_preview(), PrPreview::HasPr(..)));+ let pane = bare.render_pr_pane(bare.pr_preview(), 80);assert!(pane.contains("#42"), "reference: {pane:?}");+ assert!(pane.contains("feature"), "branch: {pane:?}");assert!(pane.contains("https://github.com/o/r/pull/42"),"url: {pane:?}");+ assert!(+ !pane.contains("\x1b[107m"),+ "no description gutter without a body: {pane:?}"+ );++ // A PR carrying title + body → the title rides the header and the body+ // renders as markdown in the house gutter, matching the `--prs` pane.+ let full = row(Some(Some(status(+ Some(PrRef::pr(7)),+ Some("https://github.com/o/r/pull/7"),+ Some("Fix the flaky retry"),+ Some("Adds a **bounded** retry."),+ ))));+ let pane = full.render_pr_pane(full.pr_preview(), 80);+ assert!(pane.contains("#7"), "reference: {pane:?}");+ assert!(pane.contains("Fix the flaky retry"), "title: {pane:?}");+ assert!(pane.contains("\x1b[107m"), "description gutter: {pane:?}");+ assert!(pane.contains("\x1b[1m"), "markdown bold rendered: {pane:?}");+ assert!(!pane.contains("**"), "markdown markers consumed: {pane:?}");// Cached branch CI with no PR `number` → NoPr.- let branch_ci = row(Some(Some(status(None, None))));+ let branch_ci = row(Some(Some(status(None, None, None, None))));assert!(matches!(branch_ci.pr_preview(), PrPreview::NoPr));}+ #[test]+ fn preview_assembles_tab_bar_and_pr_pane() {+ use crate::commands::list::ci_status::{CiSource, CiStatus, PrRef, ReviewState};++ // A worktree row whose live status carries a PR with title + body.+ let item = ListItem::new_branch("abc".into(), "feature".into());+ let row = WorktreeSkimItem {+ search_text: String::new(),+ rendered: Arc::new(Mutex::new(String::new())),+ branch_name: "feature".into(),+ item: Arc::new(item),+ preview_cache: Arc::new(DashMap::new()),+ has_upstream: false,+ summaries_enabled: false,+ pr_status: Arc::new(Mutex::new(Some(Some(PrStatus {+ ci_status: CiStatus::Passed,+ source: CiSource::PullRequest,+ is_stale: false,+ is_priming: false,+ url: Some("https://github.com/o/r/pull/7".into()),+ number: Some(PrRef::pr(7)),+ review_state: Some(ReviewState::Approved),+ title: Some("Fix the flaky retry".into()),+ body: Some("Adds a **bounded** retry.".into()),+ })))),+ };++ // In Pr mode, `render_preview` assembles the tab bar plus the worktree PR+ // 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:?}");+ assert!(+ pr_pane.contains("Fix the flaky retry"),+ "title: {pr_pane:?}"+ );+ assert!(+ pr_pane.contains("\x1b[107m"),+ "description gutter: {pr_pane:?}"+ );++ // `SkimItem::preview` reads the default mode (no per-process state file in+ // tests → WorkingTree) and delegates to `render_preview`, exercising the+ // wrapper and the non-pr dispatch arm (cache miss → loading placeholder).+ let ctx = PreviewContext {+ query: "",+ cmd_query: "",+ width: 80,+ height: 24,+ current_index: 0,+ current_selection: "",+ selected_indices: &[],+ selections: &[],+ };+ let ItemPreview::AnsiText(text) = row.preview(ctx) else {+ panic!("expected AnsiText preview");+ };+ assert!(text.contains("HEAD"), "tab bar present: {text:?}");+ assert!(+ text.contains("Loading working-tree diff"),+ "non-pr arm placeholder: {text:?}"+ );+ }++ #[test]+ fn pr_pane_is_memoized_until_the_slot_is_invalidated() {+ use crate::commands::list::ci_status::{CiSource, CiStatus, PrRef, ReviewState};++ let status = |title: &str| {+ Some(Some(PrStatus {+ ci_status: CiStatus::Passed,+ source: CiSource::PullRequest,+ is_stale: false,+ is_priming: false,+ url: Some("https://github.com/o/r/pull/7".into()),+ number: Some(PrRef::pr(7)),+ review_state: Some(ReviewState::Approved),+ title: Some(title.into()),+ body: Some("body".into()),+ }))+ };+ // Share the cache and slot Arcs so the test can mutate the slot and+ // invalidate the entry the way the collect handler's `on_update` does.+ let cache: PreviewCache = Arc::new(DashMap::new());+ let slot: PrStatusSlot = Arc::new(Mutex::new(status("First title")));+ let key = ("feature".to_string(), PreviewMode::Pr);+ let row = WorktreeSkimItem {+ search_text: String::new(),+ rendered: Arc::new(Mutex::new(String::new())),+ branch_name: "feature".into(),+ item: Arc::new(ListItem::new_branch("abc".into(), "feature".into())),+ preview_cache: Arc::clone(&cache),+ has_upstream: false,+ summaries_enabled: false,+ pr_status: Arc::clone(&slot),+ };++ // First render populates the shared cache.+ assert!(+ row.render_preview(PreviewMode::Pr, 80, 24)+ .contains("First title")+ );+ assert!(cache.contains_key(&key), "render populates the cache");++ // The slot changes but the entry is NOT invalidated → the cached render+ // is reused, proving the markdown render didn't re-run.+ *slot.lock().unwrap() = status("Second title");+ let served = row.render_preview(PreviewMode::Pr, 80, 24);+ assert!(+ served.contains("First title"),+ "served from cache: {served:?}"+ );+ assert!(+ !served.contains("Second title"),+ "not re-rendered: {served:?}"+ );++ // Invalidating the entry (what `on_update` does on a slot change) makes+ // the next render reflect the new slot.+ cache.remove(&key);+ let refreshed = row.render_preview(PreviewMode::Pr, 80, 24);+ assert!(+ refreshed.contains("Second title"),+ "re-rendered after invalidation: {refreshed:?}"+ );+ }+/// Helper: build a test repo with `main` at the initial commit, then a/// second commit so branches can diverge from it.fn repo_with_main() -> (worktrunk::testing::TestRepo, Repository) {diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex 77121f30d..e313064cb 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -91,6 +91,7 @@mod items;mod log_formatter;mod pager;+mod pr_pane;mod preview;pub(crate) mod preview_cache;mod preview_orchestrator;diff --git a/src/commands/picker/pr_pane.rs b/src/commands/picker/pr_pane.rsnew file mode 100644index 000000000..a84edf9ca--- /dev/null+++ b/src/commands/picker/pr_pane.rs@@ -0,0 +1,167 @@+//! Shared rendering for the picker's `pr` preview pane.+//!+//! Two rows show a PR/MR: a worktree row whose branch has one+//! (`render_worktree_pr` in [`super::items`]) and a `--prs` row+//! ([`super::prs::PrSkimItem`]). Both render the same shape — a bold reference ++//! title header, dim-labeled metadata lines whose values share one column, and+//! the description as markdown inside the house gutter — so they read alike.+//! They build from these shared pieces rather than each formatting their own.++use anstyle::Reset;+use color_print::cformat;+use worktrunk::styling::format_with_gutter;++use super::super::list::ci_status::PrRef;++/// Column (in cells) where a metadata line's value begins, after its dim label.+/// The widest labels (`branch`/`author`, 6) plus a 3-space gap; shorter labels+/// (`url`, `state`) pad out to the same column so every value lines up — across+/// lines and across the two panes.+const VALUE_COLUMN: usize = 9;++/// The pane header: a bold PR/MR reference, the title when known, then a blank+/// line. A title-less status (an old cache entry, or a fetch that didn't carry+/// one) renders just the reference.+pub(super) fn header(pr_ref: PrRef, title: Option<&str>) -> String {+ let reset = Reset;+ match title {+ Some(title) => cformat!("<bold>{pr_ref}</>{reset} {title}\n\n"),+ None => cformat!("<bold>{pr_ref}</>{reset}\n\n"),+ }+}++/// One dim-labeled metadata line (`branch`, `author`, `url`, …). The label pads+/// so the value starts at [`VALUE_COLUMN`], aligning values down the pane and+/// between the two panes. `value` may carry its own styling (e.g. a yellow+/// `draft`) and must close its own spans. A full `{reset}` after the label keeps+/// the dim from bleeding into the value (skim's ANSI parser drops color_print's+/// `</>`); see [`super::items::render_preview_tabs`].+pub(super) fn metadata_line(label: &str, value: &str) -> String {+ let reset = Reset;+ let pad = " ".repeat(VALUE_COLUMN.saturating_sub(label.len()));+ let label = cformat!("<dim>{label}</>{reset}");+ format!("{label}{pad}{value}\n")+}++/// The description block: `body` rendered as markdown (bold headers, styled+/// lists and inline code — the same renderer the `summary` tab uses) and quoted+/// in the house gutter ([`format_with_gutter`], a bg-color bar that closes each+/// line with a full `\x1b[0m`, skim-safe). The whole body renders; the preview+/// pane scrolls (`ctrl-u`/`ctrl-d`) through a long one. Empty body → empty+/// string, so the block is skipped. The leading `\x1b[0m` is a defensive+/// boundary so the first gutter line renders clean regardless of what precedes+/// it (the metadata lines already reset their own spans).+///+/// `width` is the preview-pane width. The `--prs` pane is built before skim+/// renders, so it passes the list width as a close proxy (Right splits ~50/50;+/// Down gives list and preview the full width); the worktree pane reads the live+/// preview width. 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 description(body: &str, width: usize) -> String {+ let body = body.trim();+ if body.is_empty() {+ return String::new();+ }+ let reset = Reset;+ 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")+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn header_with_and_without_title() {+ let with = header(PrRef::pr(42), Some("Fix the flaky test"));+ assert!(with.contains("#42"), "reference: {with:?}");+ assert!(with.contains("Fix the flaky test"), "title: {with:?}");+ assert!(with.ends_with("\n\n"), "blank line after header: {with:?}");++ // A title-less status renders just the reference: the styled `#42`+ // closes with a full reset, then the blank line — no trailing spaces+ // where the title would be.+ let without = header(PrRef::pr(42), None);+ assert!(without.contains("#42"), "reference: {without:?}");+ assert!(+ without.ends_with("\x1b[0m\n\n"),+ "ends right after the styled reference: {without:?}"+ );+ use ansi_str::AnsiStr;+ assert_eq!(+ without.ansi_strip(),+ "#42\n\n",+ "no title slot: {without:?}"+ );+ }++ #[test]+ fn metadata_line_aligns_values_to_one_column() {+ use ansi_str::AnsiStr;+ // The value column is fixed regardless of label length, so a short label+ // (`url`) and a long one (`branch`) put their values at the same column.+ let url = metadata_line("url", "https://example.com")+ .ansi_strip()+ .to_string();+ let branch = metadata_line("branch", "feature/auth")+ .ansi_strip()+ .to_string();+ assert_eq!(+ url.find("https"),+ Some(VALUE_COLUMN),+ "url value at the shared column: {url:?}"+ );+ assert_eq!(+ branch.find("feature"),+ Some(VALUE_COLUMN),+ "branch value at the shared column: {branch:?}"+ );+ }++ #[test]+ fn description_empty_or_blank_renders_nothing() {+ // No body, or whitespace-only — the block is skipped entirely so the+ // pane doesn't show an empty gutter.+ assert_eq!(description("", 80), "");+ assert_eq!(description(" \n\t \n", 80), "");+ }++ #[test]+ fn description_wraps_into_the_house_gutter() {+ let out = description("Fixes the flaky retry logic.", 80);+ // Leading full reset clears inherited style; the house gutter sets a+ // bg color and closes each line with a skim-safe `\x1b[0m`.+ assert!(out.starts_with("\n\x1b[0m"), "leading reset: {out:?}");+ assert!(out.contains("\x1b[107m"), "house gutter bg: {out:?}");+ assert!(+ out.contains("Fixes the flaky retry logic."),+ "body: {out:?}"+ );+ }++ #[test]+ fn description_renders_the_whole_body() {+ // One item per line so each survives as its own gutter line; the pane+ // scrolls, so the full body renders with no truncation hint.+ let body = (0..50)+ .map(|i| format!("- word{i}"))+ .collect::<Vec<_>>()+ .join("\n");+ let out = description(&body, 80);+ assert!(!out.contains("more line"), "no truncation hint: {out:?}");+ assert!(out.contains("word0"), "head kept: {out:?}");+ assert!(out.contains("word49"), "tail kept: {out:?}");+ }++ #[test]+ fn description_renders_markdown() {+ // Markdown is styled, not shown verbatim: a bold span carries the SGR-1+ // termimad emits, and the literal `**` markers are gone.+ let out = description("Fixes the **flaky** retry.", 80);+ assert!(out.contains("\x1b[1m"), "bold rendered: {out:?}");+ assert!(!out.contains("**"), "markers consumed: {out:?}");+ }+}diff --git a/src/commands/picker/progressive_handler.rs b/src/commands/picker/progressive_handler.rsindex a907e6763..ff44b69cb 100644--- a/src/commands/picker/progressive_handler.rs+++ b/src/commands/picker/progressive_handler.rs@@ -48,6 +48,7 @@ use worktrunk::styling::{StyledLine, strip_osc8_hyperlinks};const RENDER_THROTTLE: Duration = Duration::from_millis(16);use super::items::{HeaderLoading, HeaderSkimItem, PrStatusSlot, PreviewCache, WorktreeSkimItem};+use super::preview::PreviewMode;use super::preview_orchestrator::PreviewOrchestrator;use crate::commands::list::collect::PickerProgressHandler;use crate::commands::list::model::ListItem;@@ -277,6 +278,11 @@ impl PickerProgressHandler for PickerHandler {&& let Some(slot) = slots.get(idx){*slot.lock().unwrap() = item.pr_status.clone();+ // Drop the memoized `pr` pane for this row so the next `preview()`+ // re-renders from the status just mirrored — see+ // `WorktreeSkimItem::render_pr_pane_cached`.+ self.preview_cache+ .remove(&(item.branch_name().to_string(), PreviewMode::Pr));}self.request_render(false);}diff --git a/src/commands/picker/prs.rs b/src/commands/picker/prs.rsindex d2e718a1e..c4564178f 100644--- a/src/commands/picker/prs.rs+++ b/src/commands/picker/prs.rs@@ -49,7 +49,7 @@ use serde::Deserialize;use skim::prelude::*;use unicode_width::UnicodeWidthStr;use worktrunk::git::{CiPlatform, Repository};-use worktrunk::styling::{INFO_SYMBOL, StyledLine, format_with_gutter, warning_message};+use worktrunk::styling::{INFO_SYMBOL, StyledLine, warning_message};use super::super::list::ci_status::{CiSource, CiStatus, GitHubPrInfo, PrRef, PrStatus, ReviewState, non_interactive_cmd,@@ -58,6 +58,7 @@ 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::pr_pane;use super::preview::{PreviewMode, PreviewStateData};/// One-shot handoff of the picker's column geometry from the collect thread@@ -260,18 +261,16 @@ fn fetch_open_prs(repo: &Repository) -> anyhow::Result<Vec<PrEntry>> {#[derive(Deserialize)]struct GhPr {- title: String,#[serde(rename = "headRefName")]head_ref_name: String,#[serde(default)]author: GhAuthor,- /// PR description; shown in the `pr` preview tab. Rides the one list call.- #[serde(default)]- body: String,- /// CI/review fields reused via the shared `gh pr list` mapping: number,- /// `isDraft`, `url`, `statusCheckRollup`, `reviewDecision`,- /// `mergeStateStatus`. Flattened so one parse feeds both display and the- /// CI-column status.+ /// CI/review and display fields reused via the shared `gh pr list` mapping:+ /// number, `title`, `body`, `isDraft`, `url`, `statusCheckRollup`,+ /// `reviewDecision`, `mergeStateStatus`. Flattened so one parse feeds the+ /// row display, the `pr` preview pane, and the CI-column status. `title`/+ /// `body` live on [`GitHubPrInfo`] (not here) so the worktree-row fetch,+ /// which parses `GitHubPrInfo` directly, gets them from the same widened call.#[serde(flatten)]info: GitHubPrInfo,}@@ -320,13 +319,13 @@ fn parse_github_prs(stdout: &[u8]) -> anyhow::Result<Vec<PrEntry>> {.into_iter().map(|pr| PrEntry {number: pr.info.number.unwrap_or(0) as u32,- title: pr.title,+ title: pr.info.title.clone().unwrap_or_default(),head_branch: pr.head_ref_name,author: pr.author.login,is_draft: pr.info.is_draft == Some(true),url: pr.info.url.clone(),kind: RefKind::Pr,- body: pr.body,+ body: pr.info.body.clone().unwrap_or_default(),status: Some(pr.info.open_pr_status()),}).collect())@@ -445,6 +444,10 @@ fn gitlab_mr_status(url,number: Some(PrRef::mr(u64::from(iid))),review_state,+ // The `--prs` pane reads title/body from the `PrEntry`, not this status+ // (which feeds only the CI column), so they stay absent here.+ title: None,+ body: None,}}@@ -495,24 +498,25 @@ impl PrSkimItem {body,..} = entry;- // A full `{reset}` (\x1b[0m) closes every styled span: skim's ANSI- // parser drops color_print's `</>` (SGR 22/39), so without it the- // header's bold and each label's dim bleed across the values and on- // down the pane. Same workaround as `pr_row_empty_placeholder` and the- // `compute_*` preview helpers; see `render_preview_tabs` for the why.+ // The shared `pr_pane` helpers build the same header / metadata / body+ // shape as the worktree-row pane (see `items::render_worktree_pr`), so+ // the two read alike. They close each styled span with a full `{reset}`+ // (\x1b[0m) because skim's ANSI parser drops color_print's `</>` (SGR+ // 22/39); the `draft` value below does the same.let reset = Reset;- let mut pr_pane = cformat!(- "<bold>{pr_ref}</>{reset} {title}\n\n<dim>branch</>{reset} {head_branch}\n<dim>author</>{reset} @{author}\n"- );+ let mut pr_pane = pr_pane::header(pr_ref, Some(&title));+ pr_pane.push_str(&pr_pane::metadata_line("branch", &head_branch));+ pr_pane.push_str(&pr_pane::metadata_line("author", &format!("@{author}")));if is_draft {- pr_pane.push_str(&cformat!(- "<dim>state</>{reset} <yellow>draft</>{reset}\n"+ pr_pane.push_str(&pr_pane::metadata_line(+ "state",+ &cformat!("<yellow>draft</>{reset}"),));}if let Some(url) = url {- pr_pane.push_str(&cformat!("<dim>url</>{reset} {url}\n"));+ pr_pane.push_str(&pr_pane::metadata_line("url", &url));}- pr_pane.push_str(&render_pr_description(&body, list_width));+ pr_pane.push_str(&pr_pane::description(&body, list_width));Self {search_text,@@ -523,33 +527,6 @@ impl PrSkimItem {}}-/// The PR/MR description block for the `pr` preview pane: the body rendered as-/// markdown (bold headers, styled lists and inline code — the same renderer the-/// `summary` tab uses) and quoted in the house gutter ([`format_with_gutter`],-/// a bg-color bar that closes each line with a full `\x1b[0m`, skim-safe). The-/// whole body renders; the preview pane scrolls (`ctrl-u`/`ctrl-d`) through a-/// long one. Empty body → empty string, so the block is skipped. The leading-/// `\x1b[0m` is a defensive boundary so the first gutter line renders clean-/// regardless of what precedes it (the metadata lines already reset their own-/// spans).-///-/// `width` is the list width, a close proxy for the preview pane width in both-/// layouts (Right splits ~50/50; Down gives list and preview the full width).-/// 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.-fn render_pr_description(body: &str, width: usize) -> String {- let body = body.trim();- if body.is_empty() {- return String::new();- }- let reset = Reset;- 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")-}-/// 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.@@ -659,7 +636,7 @@ fn render_freeform_row(entry: &PrEntry, list_width: usize) -> String {//// TODO(pr-preview-comments): add a `7: comments` tab showing the PR/MR// discussion, rendered with the house gutter per comment (author + body, like-// `render_pr_description`). Needs the same background per-row fetch as the log+// `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@@ -719,6 +696,8 @@ mod tests {url: None,number: Some(number_ref),review_state: None,+ title: None,+ body: None,}),}}@@ -1187,50 +1166,6 @@ mod tests {assert!(parse_gitlab_mrs(b"not json").is_err());}- #[test]- fn description_empty_or_blank_renders_nothing() {- // No body, or whitespace-only — the block is skipped entirely so the- // pane doesn't show an empty gutter.- assert_eq!(render_pr_description("", 80), "");- assert_eq!(render_pr_description(" \n\t \n", 80), "");- }-- #[test]- fn description_wraps_into_the_house_gutter() {- let out = render_pr_description("Fixes the flaky retry logic.", 80);- // Leading full reset clears inherited style; the house gutter sets a- // bg color and closes each line with a skim-safe `\x1b[0m`.- assert!(out.starts_with("\n\x1b[0m"), "leading reset: {out:?}");- assert!(out.contains("\x1b[107m"), "house gutter bg: {out:?}");- assert!(- out.contains("Fixes the flaky retry logic."),- "body: {out:?}"- );- }-- #[test]- fn description_renders_the_whole_body() {- // One word per line so each survives as its own gutter line; the pane- // scrolls, so the full body renders with no truncation hint.- let body = (0..50)- .map(|i| format!("- word{i}"))- .collect::<Vec<_>>()- .join("\n");- let out = render_pr_description(&body, 80);- assert!(!out.contains("more line"), "no truncation hint: {out:?}");- assert!(out.contains("word0"), "head kept: {out:?}");- assert!(out.contains("word49"), "tail kept: {out:?}");- }-- #[test]- fn description_renders_markdown() {- // Markdown is styled, not shown verbatim: a bold span carries the SGR-1- // termimad emits, and the literal `**` markers are gone.- let out = render_pr_description("Fixes the **flaky** retry.", 80);- assert!(out.contains("\x1b[1m"), "bold rendered: {out:?}");- assert!(!out.contains("**"), "markers consumed: {out:?}");- }-#[test]fn pr_pane_shows_description_only_when_present() {let mut with_body = entry(RefKind::Pr, 1, "t");