Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
perf(switch): disk-cache the picker comments tab, keyed by PR updatedAt (#3294)
Maximilian Roos2def84484309
diff --git a/src/commands/list/ci_status/azure.rs b/src/commands/list/ci_status/azure.rsindex 0dbdd327f..66c81ae24 100644--- a/src/commands/list/ci_status/azure.rs+++ b/src/commands/list/ci_status/azure.rs@@ -146,6 +146,7 @@ pub(super) fn detect_azure_pr(// would need a separate per-PR threads call, which this fetch avoids.author: None,comment_count: None,+ updated_at: None,})}@@ -233,6 +234,7 @@ pub(super) fn detect_azure_pipeline(body: None,author: None,comment_count: None,+ updated_at: None,})}diff --git a/src/commands/list/ci_status/gitea.rs b/src/commands/list/ci_status/gitea.rsindex bbdace1ee..d14cef389 100644--- a/src/commands/list/ci_status/gitea.rs+++ b/src/commands/list/ci_status/gitea.rs@@ -126,6 +126,7 @@ pub(super) fn detect_gitea_pr(body: pr.body.clone(),author: None,comment_count: pr.comment_count(),+ updated_at: None,})}@@ -152,6 +153,7 @@ pub(super) fn detect_gitea_commit_status(body: None,author: None,comment_count: None,+ updated_at: None,})}diff --git a/src/commands/list/ci_status/github.rs b/src/commands/list/ci_status/github.rsindex 5633d3af3..51be16bfa 100644--- a/src/commands/list/ci_status/github.rs+++ b/src/commands/list/ci_status/github.rs@@ -73,8 +73,9 @@ pub(super) fn detect_github(// the picker's `pr` preview pane and matcher text can use them — no// extra round-trip. `gh pr list` has no comment-count field, so we// request the array and count it; for a `--head <branch>` call that's- // typically one PR.- "number,title,body,author,comments,headRefOid,mergeStateStatus,statusCheckRollup,url,headRepositoryOwner,reviewDecision,isDraft",+ // typically one PR. `updatedAt` rides too: it keys the picker's+ // on-disk comments cache (see `PrStatus::updated_at`).+ "number,title,body,author,comments,headRefOid,mergeStateStatus,statusCheckRollup,url,headRepositoryOwner,reviewDecision,isDraft,updatedAt",]).current_dir(&repo_root).run()@@ -146,6 +147,7 @@ pub(super) fn detect_github(body: pr_info.body.clone(),author: pr_info.author.as_ref().map(|a| a.login.clone()),comment_count: pr_info.comment_count(),+ updated_at: pr_info.updated_at.clone(),})}@@ -220,6 +222,7 @@ pub(super) fn detect_github_commit_checks(body: None,author: None,comment_count: None,+ updated_at: None,})}@@ -264,6 +267,11 @@ pub(crate) struct GitHubPrInfo {pub review_decision: Option<String>,#[serde(rename = "isDraft")]pub is_draft: Option<bool>,+ /// PR `updatedAt` — the forge's "last modified" timestamp (RFC 3339). Rides+ /// both the worktree-row [`detect_github`] call and the `--prs` list call;+ /// keys the picker's on-disk comments cache (see [`PrStatus::updated_at`]).+ #[serde(rename = "updatedAt", default)]+ pub updated_at: Option<String>,}/// Owner info for the head repository of a PR.@@ -364,6 +372,10 @@ impl GitHubPrInfo {body: None,author: None,comment_count: None,+ // Unlike title/body/comment_count, `updated_at` IS read off this+ // status: it keys the `--prs` row's on-disk comments cache, so it+ // rides through here from the same `gh pr list` call.+ updated_at: self.updated_at.clone(),}}}@@ -449,6 +461,7 @@ mod tests {comments: Vec::new(),review_decision: None,is_draft: None,+ updated_at: None,author: None,};assert_eq!(pr.open_pr_status().ci_status, CiStatus::Conflicts);@@ -469,6 +482,7 @@ mod tests {comments: Vec::new(),review_decision: None,is_draft: None,+ updated_at: None,author: None,};assert_eq!(pr.ci_status(), CiStatus::NoCI);@@ -486,6 +500,7 @@ mod tests {comments: Vec::new(),review_decision: None,is_draft: None,+ updated_at: None,author: None,};assert_eq!(pr.ci_status(), CiStatus::NoCI);@@ -508,6 +523,7 @@ mod tests {comments: Vec::new(),review_decision: None,is_draft: None,+ updated_at: None,author: None,};assert_eq!(pr.ci_status(), CiStatus::Running, "status={status}");@@ -530,6 +546,7 @@ mod tests {comments: Vec::new(),review_decision: None,is_draft: None,+ updated_at: None,author: None,};assert_eq!(pr.ci_status(), CiStatus::Running);@@ -552,6 +569,7 @@ mod tests {comments: Vec::new(),review_decision: None,is_draft: None,+ updated_at: None,author: None,};assert_eq!(pr.ci_status(), CiStatus::Failed, "conclusion={conclusion}");@@ -575,6 +593,7 @@ mod tests {comments: Vec::new(),review_decision: None,is_draft: None,+ updated_at: None,author: None,};assert_eq!(pr.ci_status(), CiStatus::Failed, "state={state}");@@ -597,6 +616,7 @@ mod tests {comments: Vec::new(),review_decision: None,is_draft: None,+ updated_at: None,author: None,};assert_eq!(pr.ci_status(), CiStatus::Passed);@@ -616,6 +636,7 @@ mod tests {comments: Vec::new(),review_decision: review_decision.map(Into::into),is_draft,+ updated_at: None,author: None,};@@ -658,6 +679,7 @@ mod tests {.collect(),review_decision: None,is_draft: None,+ updated_at: None,author: None,};diff --git a/src/commands/list/ci_status/gitlab.rs b/src/commands/list/ci_status/gitlab.rsindex 1c791d0b2..b24ba45db 100644--- a/src/commands/list/ci_status/gitlab.rs+++ b/src/commands/list/ci_status/gitlab.rs@@ -198,6 +198,7 @@ pub(super) fn detect_gitlab(body: mr_entry.description.clone(),author: mr_entry.author.as_ref().map(|a| a.username.clone()),comment_count: mr_entry.comment_count(),+ updated_at: None,});};@@ -215,6 +216,7 @@ pub(super) fn detect_gitlab(body: mr_entry.description.clone(),author: mr_entry.author.as_ref().map(|a| a.username.clone()),comment_count: mr_entry.comment_count(),+ updated_at: None,})}@@ -290,6 +292,7 @@ pub(super) fn detect_gitlab_pipeline(body: None,author: None,comment_count: None,+ updated_at: None,})}diff --git a/src/commands/list/ci_status/mod.rs b/src/commands/list/ci_status/mod.rsindex fc67280a5..62e2c5a5b 100644--- a/src/commands/list/ci_status/mod.rs+++ b/src/commands/list/ci_status/mod.rs@@ -411,6 +411,23 @@ pub struct PrStatus {/// for cache entries written before this field existed.#[serde(default, skip_serializing_if = "Option::is_none")]pub comment_count: Option<u32>,+ /// PR `updatedAt` (GitHub) — the forge's "last modified" timestamp, an+ /// RFC-3339 string. Rides the same `gh pr list` / `gh pr view` call as+ /// `title` / `body`, and keys the picker's on-disk `comments` cache+ /// (`picker::preview_cache::comments_key`): a GitHub PR's `updatedAt` bumps+ /// on comment add, edit, review, and review-comment, so a stable value means+ /// the thread is unchanged and a later `wt switch` can skip the per-row+ /// `gh pr view --json comments` fetch. Comment *deletion* is the one event+ /// GitHub doesn't reflect here, so a deleted comment can linger in the cache+ /// until the next bump — an accepted best-effort gap for a read-only preview.+ ///+ /// `None` for GitLab MRs — their `updated_at` is throttled to once per minute+ /// for note activity (so it misses a quick reply) *and* never moves on note+ /// deletion, so it can't key a comments cache; the MR comments tab stays+ /// uncached. Also `None` for branch workflows (no PR) and for cache entries+ /// written before this field existed.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub updated_at: Option<String>,}impl CiStatus {@@ -534,6 +551,7 @@ impl PrStatus {body: None,author: None,comment_count: None,+ updated_at: None,}}@@ -756,6 +774,7 @@ mod tests {body: None,author: None,comment_count: None,+ updated_at: None,};assert_eq!(pr_passed.indicator(), "#");@@ -771,6 +790,7 @@ mod tests {body: None,author: None,comment_count: None,+ updated_at: None,};assert_eq!(branch_running.indicator(), "#");@@ -786,6 +806,7 @@ mod tests {body: None,author: None,comment_count: None,+ updated_at: None,};assert_eq!(error_status.indicator(), "⚠");}@@ -806,6 +827,7 @@ mod tests {body: None,author: None,comment_count: None,+ updated_at: None,};// Number fits → PR reference, hyperlinked when supported@@ -903,6 +925,7 @@ mod tests {body: None,author: None,comment_count: None,+ updated_at: None,};let green = "\u{1b}[32m";let dim = "\u{1b}[2m";@@ -945,6 +968,7 @@ mod tests {body: None,author: None,comment_count: None,+ updated_at: None,};// Changes-requested outranks running and passed — waiting can't clear it@@ -1060,6 +1084,7 @@ mod tests {body: None,author: None,comment_count: None,+ updated_at: None,}}diff --git a/src/commands/list/json_output.rs b/src/commands/list/json_output.rsindex 7af70fa68..03497e81e 100644--- a/src/commands/list/json_output.rs+++ b/src/commands/list/json_output.rs@@ -647,6 +647,7 @@ mod tests {body: None,author: None,comment_count: None,+ updated_at: None,},None,);@@ -689,6 +690,7 @@ mod tests {body: None,author: None,comment_count: None,+ updated_at: None,},None,);@@ -721,6 +723,7 @@ mod tests {body: None,author: None,comment_count: None,+ updated_at: None,},None,);@@ -745,6 +748,7 @@ mod tests {body: None,author: None,comment_count: None,+ updated_at: None,};let without = JsonCi::from_pr_status(&pr, None);diff --git a/src/commands/picker/items.rs b/src/commands/picker/items.rsindex 1a6dbdb23..562cf8093 100644--- a/src/commands/picker/items.rs+++ b/src/commands/picker/items.rs@@ -554,10 +554,11 @@ pub(super) fn pr_presence(pr_status: &Option<Option<PrStatus>>) -> PrPresence {}/// Whether two live `pr_status` slot values render the *same* `pr` pane. Equal-/// under the `PrStatus` derive means identical; the only field the pane ignores-/// is `is_priming` — a list-cell dim hint [`render_pr_pane_body`] never reads —-/// so a cache-prime→live flip that merely clears it is not a pane change and-/// must not re-run the preview (which would reset its scroll). Every other field+/// under the `PrStatus` derive means identical; the pane ignores two fields —+/// `is_priming` (a list-cell dim hint [`render_pr_pane_body`] never reads) and+/// `updated_at` (the comments-cache key, also never shown in the pane) — so a+/// cache-prime→live flip that only changes those is not a pane change and must+/// not re-run the preview (which would reset its scroll). Every other field/// (CI badge, title, body, review, comment count, …) shows in the pane, so any/// of them differing is a real change. The lone change-path clone keeps the/// no-change case (the common repeated `on_update`) allocation-free.@@ -570,6 +571,7 @@ pub(super) fn pr_status_pane_eq(x == y|| PrStatus {is_priming: y.is_priming,+ updated_at: y.updated_at.clone(),..x.clone()} == *y}@@ -2178,6 +2180,7 @@ mod tests {body: None,author: None,comment_count: None,+ updated_at: None,};let with_url: PrStatusSlot = Arc::new(Mutex::new(Some(Some(status))));assert_eq!(@@ -2205,6 +2208,7 @@ mod tests {body: body.map(String::from),author: None,comment_count: None,+ updated_at: None,};// 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.@@ -2305,6 +2309,7 @@ mod tests {body: None,author: None,comment_count: None,+ updated_at: None,}))};let row = |slot: Option<Option<PrStatus>>, cache: PreviewCache| {@@ -2363,6 +2368,7 @@ mod tests {body: None,author: None,comment_count,+ updated_at: None,};// A PR with comments adds a cyan all-caps `COMMENTS` metadata line@@ -2406,6 +2412,7 @@ mod tests {body: None,author: author.map(str::to_owned),comment_count: None,+ updated_at: None,};let with = render_pr_pane_body("feature", PrRef::pr(7), &status(Some("bob")), 80)@@ -2446,6 +2453,7 @@ mod tests {body: Some("Adds a **bounded** retry.".into()),author: None,comment_count: None,+ updated_at: None,})),);@@ -2513,6 +2521,7 @@ mod tests {body: Some("body".into()),author: None,comment_count: None,+ updated_at: None,}))};// Share the cache and slot Arcs so the test can mutate the slot anddiff --git a/src/commands/picker/preview_cache.rs b/src/commands/picker/preview_cache.rsindex 53c092065..8645505b0 100644--- a/src/commands/picker/preview_cache.rs+++ b/src/commands/picker/preview_cache.rs@@ -1,4 +1,5 @@-//! Persistent cache for picker preview content, keyed by SHA + dimensions.+//! Persistent cache for picker preview content, keyed by a stable content+//! signature + dimensions.//!//! This is the on-disk tier for three of the modes; the in-memory tier above it//! and the system-wide invalidation rules live in [`super::preview_orchestrator`].@@ -12,7 +13,22 @@//! cached — its inputs include the mutable working tree, which has no cheap//! stable hash. Summary has its own cache (`crate::summary`).//!-//! Layout: `.git/wt/cache/picker-preview/{mode}-{sha}[-{sha}]-{w}[-{h}].json`.+//! The Comments mode has no git SHA, but a GitHub PR's `updatedAt` is the+//! equivalent content signature: it bumps on comment add, edit, review, and+//! review-comment (not deletion — see [`comments_key`]). So a matching key lets+//! a later `wt switch` skip the per-row `gh pr view --json comments` fetch.+//! `updatedAt` rides the `gh pr list` / `gh pr view` call the picker already+//! makes (CI column / `--prs` list), so the signal costs no extra network. Like+//! Log (and unlike the diff modes), Comments caches the *raw* parsed thread+//! ([`CommentEntry`]s) rather than the rendered pane, and re-renders on read —+//! the pane folds in width-dependent wrapping and `epoch_now()`-relative times,+//! so baking those into the cache would freeze them. Only GitHub PRs are cached;+//! see [`comments_key`] and `PrStatus::updated_at` for why GitLab MRs are not.+//! The repo-scoped cache dir isolates by repository, so the PR number alone+//! disambiguates within it.+//!+//! Layout: `.git/wt/cache/picker-preview/{mode}-{sig}[-{sig}][-{w}[-{h}]].json`+//! (the Comments key carries no width — its entry is width-independent raw data).//! The diff modes cache the pre-pager rendered string; the pager step in//! `compute_and_page_preview` runs on every read, so changing the//! configured pager invalidates nothing — the cache is pager-agnostic.@@ -35,6 +51,7 @@ use std::collections::HashMap;use serde::{Deserialize, Serialize};use worktrunk::cache;use worktrunk::git::Repository;+use worktrunk::path::sanitize_for_filename;const KIND: &str = "picker-preview";@@ -74,7 +91,12 @@ pub(super) struct LogCacheEntry {}/// 500 entries × tens-of-KB rendered diffs ≈ tens of MB. Tunable; the-/// user-visible knob is `wt config state clear`.+/// user-visible knob is `wt config state clear`. Comments entries share this+/// single count-based bound and KIND with the diff/log entries (so one+/// `clear_all`/`count_all` covers them), but are small raw-comment JSON; the+/// mtime sweep can evict either type to hold the count, which is benign — an+/// evicted entry is just recomputed (a git subprocess for a diff, a forge fetch+/// for comments) on its next visit.const MAX_ENTRIES: usize = 500;fn log_key(sha: &str, w: usize, h: usize) -> String {@@ -147,6 +169,65 @@ pub(super) fn write_upstream_diff();}+/// One cached PR comment — the deterministic, render-independent fields parsed+/// from the forge (`gh pr view --json comments`). Stored as a `Vec` and+/// re-rendered on every read, mirroring [`LogCacheEntry`]: the rendered pane+/// folds in the pane *width* (body wrapping) and *relative time* ("2h", "3d",+/// against `epoch_now()`), neither of which is stable, so caching the rendered+/// string would freeze both. Caching the raw comments instead keeps width and+/// relative time out of the key and correct as the terminal resizes and+/// wall-clock advances.+#[derive(Serialize, Deserialize)]+pub(super) struct CommentEntry {+ pub author: String,+ pub body: String,+ /// RFC-3339 timestamp; rendered as relative time at display.+ pub created_at: String,+}++/// Cache key for a PR's comment thread: PR `number` + the GitHub PR's+/// `updated_at` content signature. The timestamp is `sanitize_for_filename`'d+/// because RFC-3339 strings carry `:`. The repo-scoped cache dir isolates by+/// repository, so `number` alone disambiguates the PR within it. Width is+/// deliberately absent — the entry holds raw [`CommentEntry`]s re-rendered at+/// the live width on read, so one entry serves every pane width.+///+/// Only GitHub PRs reach this path: a GitHub PR's `updated_at` bumps on comment+/// add, edit, review, and review-comment, so a stable key means the thread is+/// unchanged — *except* deletion, which GitHub does not reflect in `updated_at`+/// (the same delete-blindness, plus a 1-minute throttle, that excludes GitLab+/// MRs entirely; see `PrStatus::updated_at`). A deleted GitHub comment can+/// therefore linger in the cached thread until the next add/edit/review bumps+/// the timestamp — an accepted best-effort gap for a read-only preview, matching+/// the Log tab's documented ref-decoration drift.+fn comments_key(number: u32, updated_at: &str) -> String {+ let ts = sanitize_for_filename(updated_at);+ format!("comments-{number}-{ts}.json")+}++pub(super) fn read_comments(+ repo: &Repository,+ number: u32,+ updated_at: &str,+) -> Option<Vec<CommentEntry>> {+ cache::read(repo, KIND, &comments_key(number, updated_at))+}++pub(super) fn write_comments(+ repo: &Repository,+ number: u32,+ updated_at: &str,+ value: &[CommentEntry],+) {+ cache::write_with_lru(+ repo,+ KIND,+ &comments_key(number, updated_at),+ &value,+ MAX_ENTRIES,+ );+}+/// Clear all cached preview entries, returning the count of `.json` files/// removed. Called by `wt config state clear`; see/// [`worktrunk::cache::clear_json_files`] for the missing-dir /@@ -262,6 +343,59 @@ mod tests {assert_eq!(count_all(&repo), 3);}+ fn sample_comments() -> Vec<CommentEntry> {+ vec![CommentEntry {+ author: "alice".to_string(),+ body: "looks good".to_string(),+ created_at: "2026-06-28T18:30:00Z".to_string(),+ }]+ }++ #[test]+ fn comments_roundtrip_and_keyed_by_signature() {+ let test = TestRepo::with_initial_commit();+ let repo = Repository::at(test.root_path()).unwrap();++ let ts = "2026-06-28T18:36:07Z";+ assert!(read_comments(&repo, 42, ts).is_none());+ write_comments(&repo, 42, ts, &sample_comments());+ let read = read_comments(&repo, 42, ts).expect("entry exists");+ assert_eq!(read.len(), 1);+ assert_eq!(read[0].author, "alice");+ assert_eq!(read[0].created_at, "2026-06-28T18:30:00Z");++ // A different `updated_at` (a new/edited comment) misses, so the next+ // visit re-fetches rather than serving a stale thread.+ assert!(read_comments(&repo, 42, "2026-06-28T19:00:00Z").is_none());+ // A different number is a different key. Width is NOT in the key — the+ // raw entry is re-rendered at the live width on read.+ assert!(read_comments(&repo, 43, ts).is_none());+ }++ #[test]+ fn comments_share_kind_without_colliding_with_diffs() {+ // Comments live under the same `picker-preview` kind as the diff modes+ // (so `clear_all`/`count_all` cover them) but the `comments-` filename+ // prefix keeps them distinct from `log-`/`branch-diff-`/`upstream-diff-`.+ let test = TestRepo::with_initial_commit();+ let repo = Repository::at(test.root_path()).unwrap();++ write_log(&repo, "x", 80, 24, &sample_log_entry());+ write_comments(&repo, 1, "2026-06-28T00:00:00Z", &sample_comments());++ assert_eq!(+ read_log(&repo, "x", 80, 24).unwrap().raw_log,+ "raw log content"+ );+ assert_eq!(+ read_comments(&repo, 1, "2026-06-28T00:00:00Z")+ .expect("entry exists")+ .len(),+ 1+ );+ assert_eq!(count_all(&repo), 2);+ }+#[test]fn clear_all_removes_entries() {let test = TestRepo::with_initial_commit();diff --git a/src/commands/picker/preview_orchestrator.rs b/src/commands/picker/preview_orchestrator.rsindex 35963595c..fbef09e56 100644--- a/src/commands/picker/preview_orchestrator.rs+++ b/src/commands/picker/preview_orchestrator.rs@@ -42,7 +42,7 @@//! | Log / BranchDiff / UpstreamDiff | [`super::preview_cache`], SHA-keyed | `git`, then write disk |//! | Summary | [`crate::summary`], diff-hash-keyed | LLM, then write disk |//! | Pr | none | render from the already-fetched CI/PR data |-//! | Comments | none | one background forge fetch per PR |+//! | Comments | [`super::preview_cache`], `updatedAt`-keyed (GitHub PRs only) | forge fetch, then write disk |//!//! # Invalidation//!diff --git a/src/commands/picker/progressive_handler.rs b/src/commands/picker/progressive_handler.rsindex 68a3a8d1f..5acfa72cf 100644--- a/src/commands/picker/progressive_handler.rs+++ b/src/commands/picker/progressive_handler.rs@@ -195,6 +195,17 @@ impl PickerHandler {return;};let Some(pr_ref) = status.number else { return };+ // Skip the expired-cache prime: `populate_from_cache` carries an+ // unbounded-stale `updated_at` on a `is_priming` placeholder, and since+ // the fetch is deduped by PR number, keying off it here would lock the+ // comments cache to a wrong signature for the whole session (a stale+ // disk hit, or a mis-keyed write) — the live `CiStatus` fetch+ // (`is_priming: false`, within-TTL/fresh `updated_at`) re-runs this and+ // spawns with the right key. A valid (within-TTL) prime is not priming,+ // so it still warms the tab at skeleton.+ if status.is_priming {+ return;+ }let Some(slots) = self.comments_fetched.get() else {return;};@@ -214,6 +225,7 @@ impl PickerHandler {&self.orchestrator,branch_name.to_string(),number as u32,+ status.updated_at.clone(),self.preview_dims.0,);}@@ -848,6 +860,7 @@ mod tests {body: None,author: None,comment_count: None,+ updated_at: None,}));item};@@ -982,6 +995,7 @@ mod tests {body: None,author: None,comment_count: None,+ updated_at: None,}));item};@@ -1031,6 +1045,63 @@ mod tests {);}+ /// An expired-cache prime (`is_priming: true`) carries an unbounded-stale+ /// `updated_at`; spawning the comments fetch off it would lock the disk cache+ /// to a wrong signature for the whole session. The prime is skipped, so the+ /// comments cache stays empty until the live (`is_priming: false`) fetch+ /// lands and spawns with a fresh timestamp.+ #[test]+ fn comments_skip_priming_prime_until_live() {+ use crate::commands::list::ci_status::{CiSource, CiStatus, PrRef, PrStatus};++ let (handler, _test, rx) = make_handler();+ handler.on_skeleton(+ vec![ListItem::new_branch("aaa".into(), "feature".into())],+ vec!["s".into()],+ header("hdr"),+ grid(),+ );+ let _ = rx.recv();++ let status = |is_priming: bool, updated_at: &str| {+ let mut item = ListItem::new_branch("aaa".into(), "feature".into());+ item.pr_status = Some(Some(PrStatus {+ ci_status: CiStatus::Passed,+ source: CiSource::PullRequest,+ is_stale: false,+ is_priming,+ url: None,+ number: Some(PrRef::pr(7)),+ review_state: None,+ title: None,+ body: None,+ author: None,+ comment_count: None,+ updated_at: Some(updated_at.to_string()),+ }));+ item+ };+ let key = ("feature".to_string(), PreviewMode::Comments);++ // Expired prime → skipped: no comments fetch, cache stays empty. (The+ // prime also must not consume the dedup slot, or the live update below+ // would short-circuit.)+ handler.on_update(0, "r".into(), &status(true, "2020-01-01T00:00:00Z"));+ handler.orchestrator.wait_for_idle();+ assert!(+ !handler.preview_cache.contains_key(&key),+ "an is_priming prime must not spawn the comments fetch"+ );++ // Live fetch (not priming) with a fresh timestamp → spawns and caches.+ handler.on_update(0, "r".into(), &status(false, "2026-06-28T00:00:00Z"));+ handler.orchestrator.wait_for_idle();+ assert!(+ handler.preview_cache.contains_key(&key),+ "the live fetch spawns the comments fetch with a fresh signature"+ );+ }+/// Header + items get published in order. `output()` of the/// PickerRow is the branch name so skim returns the correct/// identifier when the user hits Enter.@@ -1154,6 +1225,7 @@ mod tests {body: None,author: Some("alice".into()),comment_count: None,+ updated_at: None,}));handler.on_skeleton(vec![item], vec!["skel".into()], header("hdr"), grid());@@ -1211,6 +1283,7 @@ mod tests {body: None,author: Some("bob".into()),comment_count: None,+ updated_at: None,}));handler.on_update(0, "rendered".into(), &updated);diff --git a/src/commands/picker/prs.rs b/src/commands/picker/prs.rsindex 35b93f904..e0051dbb2 100644--- a/src/commands/picker/prs.rs+++ b/src/commands/picker/prs.rs@@ -59,6 +59,7 @@ use super::super::list::layout::ColumnGrid;use super::items::{PickerRow, PreviewCache, RowShortcutData, RowUrl, ShortcutTable};use super::pr_pane;use super::preview::PreviewMode;+use super::preview_cache::CommentEntry;use super::preview_notify::PreviewNotifier;use super::preview_orchestrator::PreviewOrchestrator;@@ -165,6 +166,12 @@ struct PrEntry {/// `None` when the forge can't supply it in one call (the row then keeps/// its `#N` in the title instead of the CI column).status: Option<PrStatus>,+ /// GitHub PR `updatedAt`, riding the one list call — keys the row's on-disk+ /// comments cache so a repeat `--prs` open skips the per-row comments fetch+ /// when nothing changed (see [`compute_pr_comments`]). `None` for GitLab MRs+ /// (their `updated_at` is throttled and delete-blind, so MR comments aren't+ /// disk-cached).+ updated_at: Option<String>,}impl PrEntry {@@ -205,6 +212,7 @@ impl PrEntry {body: None,author: None,comment_count: None,+ updated_at: None,});status.number = status.number.or_else(|| Some(self.pr_ref()));status.title = Some(self.title.clone()).filter(|t| !t.is_empty());@@ -509,7 +517,14 @@ fn spawn_pr_previews(.unwrap_or_else(|| pr_unavailable_pane("commit log")),)});- spawn_comments_fetch(orchestrator, token, entry.kind, entry.number, width);+ spawn_comments_fetch(+ orchestrator,+ token,+ entry.kind,+ entry.number,+ entry.updated_at.clone(),+ width,+ );}/// Spawn the background `comments` fetch keyed by `key_token`, fetching through@@ -523,16 +538,23 @@ fn spawn_pr_previews(/// keyspaces can't collide. A failed fetch caches a terminal [`pr_unavailable_pane`]/// (not `None`), so the tab never strands on its loading placeholder — see/// [`spawn_pr_previews`] and [`PreviewOrchestrator::spawn_compute`].+///+/// `updated_at` is the GitHub PR's `updatedAt` content signature (riding the+/// forge call the picker already made), used to disk-cache the rendered pane so+/// a later `wt switch` skips this fetch when it's unchanged. `None` for GitLab+/// (or any forge whose timestamp can't key the cache) means the fetch always+/// runs and nothing is written to disk — see [`compute_pr_comments`].fn spawn_comments_fetch(orchestrator: &PreviewOrchestrator,key_token: String,kind: RefKind,number: u32,+ updated_at: Option<String>,width: usize,) {orchestrator.spawn_compute((key_token, PreviewMode::Comments), move |repo| {Some(- compute_pr_comments(repo, kind, number, width)+ compute_pr_comments(repo, kind, number, updated_at.as_deref(), width).unwrap_or_else(|| pr_unavailable_pane("comments")),)});@@ -552,6 +574,7 @@ pub(super) fn spawn_worktree_comments_fetch(orchestrator: &PreviewOrchestrator,branch: String,number: u32,+ updated_at: Option<String>,width: usize,) {let kind = match orchestrator.repo().ci_platform(None) {@@ -565,7 +588,7 @@ pub(super) fn spawn_worktree_comments_fetch(return;}};- spawn_comments_fetch(orchestrator, branch, kind, number, width);+ spawn_comments_fetch(orchestrator, branch, kind, number, updated_at, width);}/// The `comments` tab pane for a worktree row whose branch has a PR on a forge@@ -614,11 +637,11 @@ struct GhPr {head_ref_oid: String,/// CI/review and display fields reused via the shared `gh pr list` mapping:/// number, `title`, `body`, `author`, `isDraft`, `url`, `statusCheckRollup`,- /// `reviewDecision`, `mergeStateStatus`. Flattened so one parse feeds the- /// row display, the `pr` preview pane, and the CI-column status. `title`/- /// `body`/`author` live on [`GitHubPrInfo`] (not here) so the worktree-row- /// fetch, which parses `GitHubPrInfo` directly, gets them from the same- /// widened call.+ /// `reviewDecision`, `mergeStateStatus`, `updatedAt`. Flattened so one parse+ /// feeds the row display, the `pr` preview pane, the CI-column status, and the+ /// comments-cache key. `title`/`body`/`author` 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,}@@ -644,7 +667,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,headRefOid,author,isDraft,url,body,statusCheckRollup,reviewDecision,mergeStateStatus",+ "number,title,headRefName,headRefOid,author,isDraft,url,body,statusCheckRollup,reviewDecision,mergeStateStatus,updatedAt",]).current_dir(repo_root).run()@@ -680,6 +703,7 @@ fn parse_github_prs(stdout: &[u8]) -> anyhow::Result<Vec<PrEntry>> {url: pr.info.url.clone(),kind: RefKind::Pr,body: pr.info.body.clone().unwrap_or_default(),+ updated_at: pr.info.updated_at.clone(),status: Some(pr.info.open_pr_status()),}).collect())@@ -765,6 +789,9 @@ fn parse_gitlab_mrs(stdout: &[u8]) -> anyhow::Result<Vec<PrEntry>> {url: mr.web_url,kind: RefKind::Mr,body: mr.description,+ // GitLab's MR `updated_at` is throttled and delete-blind, so it+ // can't key a comments cache — MR comments stay uncached.+ updated_at: None,status: Some(status),}})@@ -808,6 +835,7 @@ fn gitlab_mr_status(body: None,author: None,comment_count: None,+ updated_at: None,}}@@ -1032,34 +1060,56 @@ fn render_commit_lines(commits: &[(String, String)], width: usize) -> String {/// `--paginate` follows every page so a long thread isn't capped at GitLab's/// default page size. Returns `None` on any failure; the caller maps that to a/// terminal [`pr_unavailable_pane`] (see [`spawn_pr_previews`]).+///+/// `updated_at` is the GitHub PR's `updatedAt` content signature. When present+/// (GitHub only), the parsed thread is read from / written to the on-disk+/// comments cache keyed by `(number, updated_at)` — a hit re-renders the cached+/// [`CommentEntry`]s at the live width with no forge call, so a repeat+/// `wt switch` skips the `gh pr view --json comments` fetch when nothing changed.+/// `None` (GitLab, whose `updated_at` can't key a cache) takes the always-fetch+/// path and writes nothing to disk. See [`super::preview_cache::read_comments`].fn compute_pr_comments(repo: &Repository,kind: RefKind,number: u32,+ updated_at: Option<&str>,width: usize,) -> Option<String> {- let number = number.to_string();- let endpoint = format!("projects/:fullpath/merge_requests/{number}/notes?sort=asc");+ // Disk cache hit: the cached entry is the raw parsed thread, re-rendered+ // here at the live width and current relative time (the pane folds in both),+ // so a hit returns with no forge call.+ if let Some(ts) = updated_at+ && let Some(cached) = super::preview_cache::read_comments(repo, number, ts)+ {+ return Some(render_comment_blocks(&cached, width));+ }++ let number_str = number.to_string();+ let endpoint = format!("projects/:fullpath/merge_requests/{number_str}/notes?sort=asc");let stdout = fetch_forge_json(repo,kind,- &["pr", "view", &number, "--json", "comments"],+ &["pr", "view", &number_str, "--json", "comments"],&["api", "--paginate", &endpoint],)?;- match kind {- RefKind::Pr => render_github_comments(&stdout, width),- RefKind::Mr => render_gitlab_notes(&stdout, width),- }-}+ let comments = match kind {+ RefKind::Pr => parse_github_comments(&stdout),+ RefKind::Mr => parse_gitlab_notes(&stdout),+ }?;-/// 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,+ // Persist the raw thread for the next session, keyed by the content+ // signature. Only GitHub PRs carry a usable `updated_at`; GitLab skips it.+ if let Some(ts) = updated_at {+ super::preview_cache::write_comments(repo, number, ts, &comments);+ }+ Some(render_comment_blocks(&comments, width))}+// The normalized per-comment type is [`CommentEntry`] (author/body/created_at):+// the parse functions below produce it, the disk cache stores it, and+// `render_comment_blocks` renders it. Caching the raw fields (not the rendered+// pane) keeps width and relative time out of the cache, so the thread re-renders+// correctly at the live width and current time on every read.#[derive(Deserialize)]struct GhCommentsResponse {#[serde(default)]@@ -1076,20 +1126,21 @@ struct GhComment {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> {+/// Parse `gh pr view <n> --json comments` into the normalized thread. gh returns+/// the comments oldest-first, which reads top-to-bottom; the order is preserved.+fn parse_github_comments(stdout: &[u8]) -> Option<Vec<CommentEntry>> {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))+ Some(+ parsed+ .comments+ .into_iter()+ .map(|c| CommentEntry {+ author: c.author.login,+ body: c.body,+ created_at: c.created_at,+ })+ .collect(),+ )}#[derive(Deserialize)]@@ -1106,20 +1157,21 @@ struct GlabNote {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> {+/// Parse `glab api …/notes` into the normalized thread, dropping system notes+/// (label changes, description edits, …) so only human comments show.+fn parse_gitlab_notes(stdout: &[u8]) -> Option<Vec<CommentEntry>> {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))+ Some(+ notes+ .into_iter()+ .filter(|n| !n.system)+ .map(|n| CommentEntry {+ author: n.author.username,+ body: n.body,+ created_at: n.created_at,+ })+ .collect(),+ )}/// Render the `comments` pane: each comment as a header line (author + relative@@ -1127,7 +1179,7 @@ fn render_gitlab_notes(stdout: &[u8], width: usize) -> Option<String> {/// [`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 {+fn render_comment_blocks(comments: &[CommentEntry], width: usize) -> String {let reset = Reset;if comments.is_empty() {return cformat!("{INFO_SYMBOL}{reset} No comments\n");@@ -1308,6 +1360,7 @@ mod tests {url: Some("https://github.com/owner/repo/pull/123".to_string()),kind,body: String::new(),+ updated_at: None,status: Some(PrStatus {ci_status: CiStatus::Passed,source: CiSource::PullRequest,@@ -1320,6 +1373,7 @@ mod tests {body: None,author: None,comment_count: None,+ updated_at: None,}),}}@@ -2105,6 +2159,19 @@ mod tests {assert!(stripped.contains('▲'), "warning glyph: {stripped:?}");}+ /// Test helpers composing the parse + render split the production path now+ /// runs in two steps (parse to cache, render on read): these exercise both+ /// at once so the existing end-to-end assertions stay unchanged.+ fn render_github_comments(stdout: &[u8], width: usize) -> Option<String> {+ Some(render_comment_blocks(+ &parse_github_comments(stdout)?,+ width,+ ))+ }+ fn render_gitlab_notes(stdout: &[u8], width: usize) -> Option<String> {+ Some(render_comment_blocks(&parse_gitlab_notes(stdout)?, width))+ }+#[test]fn render_github_comments_threads_author_time_and_body() {// Each comment renders an author + relative-time header and its body in