Skip to content

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

perf(switch): prime the picker comments tab from the worktree CI fetch (#3299)

Maximilian Roosa5231f57b7d2
diff --git a/src/commands/list/ci_status/github.rs b/src/commands/list/ci_status/github.rs
index 51be16bfa..d838340f1 100644
--- a/src/commands/list/ci_status/github.rs
+++ b/src/commands/list/ci_status/github.rs
@@ -9,6 +9,11 @@ use super::{
CiBranchName, CiSource, CiStatus, MAX_PRS_TO_FETCH, PrRef, PrStatus, ReviewState,
branch_owner_repo, non_interactive_cmd, parse_json, retriable_pr_error,
};
+// CI detection primes the picker's on-disk comments cache: this `gh pr list`
+// call already transfers the comment thread (we count it for `comment_count`),
+// so feeding it to the cache the picker's `comments` tab reads spares that tab
+// its own `gh pr view --json comments` fetch. See `prime_comments_cache`.
+use crate::commands::picker::preview_cache::{self, CommentEntry};
/// Detect GitHub PR CI status for a branch.
///
@@ -135,6 +140,10 @@ pub(super) fn detect_github(
.map(|pr_head| pr_head != local_head)
.unwrap_or(false);
+ // The comment thread is already in hand from the call above — hand it to the
+ // picker's comments cache so its `comments` tab need not re-fetch it.
+ prime_comments_cache(repo, pr_info);
+
Some(PrStatus {
ci_status,
source: CiSource::PullRequest,
@@ -151,6 +160,38 @@ pub(super) fn detect_github(
})
}
+/// `gh pr list` returns at most one page (100) of a PR's `comments` connection
+/// and does *not* paginate nested connections (unlike `gh pr view`, which
+/// follows every page). A returned full page may therefore be truncated.
+const GH_LIST_COMMENTS_PAGE: usize = 100;
+
+/// Prime the picker's on-disk `comments` cache from the thread this `gh pr list`
+/// call already transferred (the same array [`GitHubPrInfo::comment_count`]
+/// counts). The picker's worktree-row `comments` tab keys off the PR's
+/// `updatedAt`, so a matching prime turns its per-row `gh pr view --json
+/// comments` fetch into a cache hit — including the common zero-comment PR (an
+/// empty thread is cached, so the tab resolves to "No comments" with no fetch).
+///
+/// GitHub only: the key needs `updatedAt`, the content signature GitLab's
+/// throttled, delete-blind timestamp can't provide (see [`PrStatus::updated_at`]).
+/// A PR with no resolved number or no `updatedAt` is skipped — there's no key to
+/// write under, and the tab falls back to its own fetch.
+///
+/// A full page of comments ([`GH_LIST_COMMENTS_PAGE`]) is also skipped: it may be
+/// truncated, and caching a partial thread would stop the tab's *paginating*
+/// `gh pr view` fetch (which gets all of them) from ever running. Sub-page
+/// threads — the overwhelming majority — are known-complete and cached.
+fn prime_comments_cache(repo: &Repository, pr_info: &GitHubPrInfo) {
+ let (Some(number), Some(updated_at)) = (pr_info.number, pr_info.updated_at.as_deref()) else {
+ return;
+ };
+ if pr_info.comments.len() >= GH_LIST_COMMENTS_PAGE {
+ return;
+ }
+ let entries: Vec<CommentEntry> = pr_info.comments.iter().map(CommentEntry::from).collect();
+ preview_cache::write_comments(repo, number as u32, updated_at, &entries);
+}
+
/// Detect CI status for a commit using GitHub's check-runs API.
///
/// This queries all check runs for the commit SHA, giving us the same data
@@ -244,12 +285,14 @@ pub(crate) struct GitHubPrInfo {
#[serde(default)]
pub author: Option<GitHubAuthor>,
/// Conversation comments on the PR. Requested only on the worktree-row
- /// [`detect_github`] call to count them for the `pr` pane; the `--prs` call
- /// omits `comments` to keep its 50-PR payload light, so this stays empty
- /// there (`#[serde(default)]`). Only the count is needed, so each element
- /// deserializes as [`serde::de::IgnoredAny`] rather than a comment struct.
+ /// [`detect_github`] call; the `--prs` call omits `comments` to keep its
+ /// 50-PR payload light, so this stays empty there (`#[serde(default)]`). Its
+ /// length feeds [`comment_count`](Self::comment_count) (the `pr` pane's
+ /// `comments` line), and the bodies prime the picker's on-disk comments cache
+ /// via [`prime_comments_cache`] — the same thread the `comments` tab would
+ /// otherwise re-fetch with `gh pr view --json comments`.
#[serde(default)]
- pub comments: Vec<serde::de::IgnoredAny>,
+ pub comments: Vec<GitHubComment>,
#[serde(rename = "headRefOid")]
pub head_ref_oid: Option<String>,
#[serde(rename = "mergeStateStatus")]
@@ -288,6 +331,32 @@ pub(crate) struct GitHubAuthor {
pub login: String,
}
+/// A single GitHub conversation comment. The per-element shape is identical for
+/// `gh pr list --json comments` (the worktree CI call, which primes the cache —
+/// see [`prime_comments_cache`]) and `gh pr view --json comments` (the picker's
+/// lazy fetch in `commands::picker::prs`), so both parse into this one type. Only
+/// the fields the picker's `comments` pane renders are kept — author,
+/// body, and timestamp; the rest of GitHub's comment object is ignored.
+#[derive(Debug, Default, Deserialize)]
+pub(crate) struct GitHubComment {
+ #[serde(default)]
+ pub author: GitHubAuthor,
+ #[serde(default)]
+ pub body: String,
+ #[serde(rename = "createdAt", default)]
+ pub created_at: String,
+}
+
+impl From<&GitHubComment> for CommentEntry {
+ fn from(c: &GitHubComment) -> Self {
+ CommentEntry {
+ author: c.author.login.clone(),
+ body: c.body.clone(),
+ created_at: c.created_at.clone(),
+ }
+ }
+}
+
/// A single check from `statusCheckRollup`.
///
/// This is a union of two GitHub API types with different field structures:
@@ -674,7 +743,7 @@ mod tests {
head_repository_owner: None,
title: None,
body: None,
- comments: std::iter::repeat_with(|| serde::de::IgnoredAny)
+ comments: std::iter::repeat_with(GitHubComment::default)
.take(n)
.collect(),
review_decision: None,
@@ -689,6 +758,132 @@ mod tests {
assert_eq!(with(4).comment_count(), Some(4));
}
+ /// `gh pr list --json comments` carries each comment's author, body, and
+ /// `createdAt` (note the rename) — parsing them is what lets the worktree CI
+ /// call prime the picker's comments cache. Pins the JSON shape.
+ #[test]
+ fn github_pr_info_parses_comment_bodies() {
+ let json = br#"[{
+ "number": 1,
+ "comments": [
+ {"author": {"login": "bob"}, "body": "ship it", "createdAt": "2026-06-28T00:00:00Z"}
+ ],
+ "updatedAt": "2026-06-28T01:00:00Z"
+ }]"#;
+ let prs: Vec<GitHubPrInfo> = serde_json::from_slice(json).expect("parse");
+ let pr = &prs[0];
+ assert_eq!(pr.comments.len(), 1);
+ assert_eq!(pr.comments[0].author.login, "bob");
+ assert_eq!(pr.comments[0].body, "ship it");
+ assert_eq!(pr.comments[0].created_at, "2026-06-28T00:00:00Z");
+ assert_eq!(pr.updated_at.as_deref(), Some("2026-06-28T01:00:00Z"));
+ }
+
+ /// `prime_comments_cache` writes the thread under `(number, updatedAt)`, the
+ /// key the picker's `comments` tab reads — so the tab serves it without its
+ /// own `gh pr view --json comments` fetch.
+ #[test]
+ fn prime_comments_cache_writes_under_signature() {
+ use worktrunk::testing::TestRepo;
+
+ let test = TestRepo::with_initial_commit();
+ let repo = Repository::at(test.root_path()).unwrap();
+
+ let json = br#"[{
+ "number": 42,
+ "comments": [
+ {"author": {"login": "alice"}, "body": "lgtm", "createdAt": "2026-06-28T18:00:00Z"}
+ ],
+ "updatedAt": "2026-06-28T18:30:00Z"
+ }]"#;
+ let prs: Vec<GitHubPrInfo> = serde_json::from_slice(json).expect("parse");
+ prime_comments_cache(&repo, &prs[0]);
+
+ let cached = preview_cache::read_comments(&repo, 42, "2026-06-28T18:30:00Z")
+ .expect("primed entry exists");
+ assert_eq!(cached.len(), 1);
+ assert_eq!(cached[0].author, "alice");
+ assert_eq!(cached[0].body, "lgtm");
+ assert_eq!(cached[0].created_at, "2026-06-28T18:00:00Z");
+ }
+
+ /// A zero-comment PR is primed too (an empty thread), so the common
+ /// no-comments case skips the fetch as well.
+ #[test]
+ fn prime_comments_cache_caches_empty_thread() {
+ use worktrunk::testing::TestRepo;
+
+ let test = TestRepo::with_initial_commit();
+ let repo = Repository::at(test.root_path()).unwrap();
+
+ let json = br#"[{"number": 7, "comments": [], "updatedAt": "2026-06-28T00:00:00Z"}]"#;
+ let prs: Vec<GitHubPrInfo> = serde_json::from_slice(json).expect("parse");
+ prime_comments_cache(&repo, &prs[0]);
+
+ let cached =
+ preview_cache::read_comments(&repo, 7, "2026-06-28T00:00:00Z").expect("empty entry");
+ assert!(cached.is_empty());
+ }
+
+ /// A full page of comments may be truncated (`gh pr list` doesn't paginate
+ /// nested connections), so the prime skips it — the comments tab's own
+ /// paginating `gh pr view` fetch gets the complete thread instead.
+ #[test]
+ fn prime_comments_cache_skips_a_possibly_truncated_full_page() {
+ use worktrunk::testing::TestRepo;
+
+ let test = TestRepo::with_initial_commit();
+ let repo = Repository::at(test.root_path()).unwrap();
+
+ let pr = GitHubPrInfo {
+ number: Some(5),
+ comments: std::iter::repeat_with(GitHubComment::default)
+ .take(GH_LIST_COMMENTS_PAGE)
+ .collect(),
+ updated_at: Some("2026-06-28T00:00:00Z".to_string()),
+ head_ref_oid: None,
+ merge_state_status: None,
+ status_check_rollup: None,
+ url: None,
+ head_repository_owner: None,
+ title: None,
+ body: None,
+ review_decision: None,
+ is_draft: None,
+ author: None,
+ };
+ prime_comments_cache(&repo, &pr);
+
+ assert_eq!(
+ preview_cache::count_all(&repo),
+ 0,
+ "a full (possibly truncated) page is not cached"
+ );
+ }
+
+ /// No `updatedAt` means no cache key, so nothing is written — the tab falls
+ /// back to its own fetch rather than caching under a missing signature.
+ #[test]
+ fn prime_comments_cache_skips_without_updated_at() {
+ use worktrunk::testing::TestRepo;
+
+ let test = TestRepo::with_initial_commit();
+ let repo = Repository::at(test.root_path()).unwrap();
+
+ let json = br#"[{
+ "number": 9,
+ "comments": [{"author": {"login": "x"}, "body": "y", "createdAt": "z"}]
+ }]"#;
+ let prs: Vec<GitHubPrInfo> = serde_json::from_slice(json).expect("parse");
+ prime_comments_cache(&repo, &prs[0]);
+
+ assert_eq!(
+ preview_cache::count_all(&repo),
+ 0,
+ "no updatedAt → no key → nothing written"
+ );
+ }
+
#[test]
fn test_aggregate_github_checks() {
// Helper to create a check without state field (like check-runs API)
diff --git a/src/commands/list/ci_status/mod.rs b/src/commands/list/ci_status/mod.rs
index 62e2c5a5b..cfaef12a1 100644
--- a/src/commands/list/ci_status/mod.rs
+++ b/src/commands/list/ci_status/mod.rs
@@ -83,8 +83,10 @@ impl CiBranchName {
// Re-export public types
pub(crate) use cache::{CachedCiStatus, MaxPrNumber};
-// Only the `--prs` picker consumes this re-export.
-pub(crate) use github::GitHubPrInfo;
+// Only the `--prs` picker consumes these re-exports: `GitHubPrInfo` to parse the
+// `gh pr list` payload, `GitHubComment` to parse `gh pr view --json comments`
+// into the shared comment shape (the worktree CI call reuses the same type).
+pub(crate) use github::{GitHubComment, GitHubPrInfo};
/// Maximum number of PRs/MRs to fetch when filtering by source repository.
///
diff --git a/src/commands/picker/preview_cache.rs b/src/commands/picker/preview_cache.rs
index 8645505b0..673c49cd1 100644
--- a/src/commands/picker/preview_cache.rs
+++ b/src/commands/picker/preview_cache.rs
@@ -18,7 +18,14 @@
//! 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
+//! makes (CI column / `--prs` list), so the signal costs no extra network. The
+//! worktree-row CI call (`gh pr list --head`) goes one better: it already
+//! transfers the whole comment thread (it counts it for the `pr` pane's
+//! `comments` line), so [`list::ci_status`](crate::commands::list::ci_status)
+//! *primes* this cache from that otherwise-discarded data — turning even the
+//! *first* `wt switch`'s comments fetch into a hit, including the common
+//! zero-comment PR (an empty thread is cached, so the tab resolves to
+//! "No comments" with no fetch). 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,
@@ -170,15 +177,16 @@ 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.
+/// from the forge (`gh pr view --json comments`, or the same thread riding the
+/// worktree-row `gh pr list --head` call — see [`write_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(crate) struct CommentEntry {
pub author: String,
pub body: String,
/// RFC-3339 timestamp; rendered as relative time at display.
@@ -205,7 +213,7 @@ fn comments_key(number: u32, updated_at: &str) -> String {
format!("comments-{number}-{ts}.json")
}
-pub(super) fn read_comments(
+pub(crate) fn read_comments(
repo: &Repository,
number: u32,
updated_at: &str,
@@ -213,7 +221,14 @@ pub(super) fn read_comments(
cache::read(repo, KIND, &comments_key(number, updated_at))
}
-pub(super) fn write_comments(
+/// Write a PR's comment thread to the on-disk cache. Called from two places:
+/// the picker's own lazy `gh pr view --json comments` fetch ([`super::prs`]),
+/// and [`list::ci_status`](crate::commands::list::ci_status), which primes it
+/// from the thread the worktree-row `gh pr list --head` CI call already
+/// transferred — so the lazy fetch never has to run for a worktree row whose
+/// `updatedAt` matches. An empty `value` is a valid entry (a zero-comment PR),
+/// and writing it lets that common case skip the fetch too.
+pub(crate) fn write_comments(
repo: &Repository,
number: u32,
updated_at: &str,
diff --git a/src/commands/picker/prs.rs b/src/commands/picker/prs.rs
index e0051dbb2..4e1334662 100644
--- a/src/commands/picker/prs.rs
+++ b/src/commands/picker/prs.rs
@@ -51,8 +51,8 @@ use worktrunk::git::{CiPlatform, Repository};
use worktrunk::styling::{HINT_SYMBOL, INFO_SYMBOL, StyledLine, WARNING_SYMBOL, warning_message};
use super::super::list::ci_status::{
- CiSource, CiStatus, GitHubPrInfo, PrRef, PrStatus, ReviewState, non_interactive_cmd,
- tool_available,
+ CiSource, CiStatus, GitHubComment, GitHubPrInfo, PrRef, PrStatus, ReviewState,
+ non_interactive_cmd, tool_available,
};
use super::super::list::columns::ColumnKind;
use super::super::list::layout::ColumnGrid;
@@ -646,12 +646,6 @@ struct GhPr {
info: GitHubPrInfo,
}
-#[derive(Deserialize, Default)]
-struct GhAuthor {
- #[serde(default)]
- login: String,
-}
-
fn fetch_github(repo_root: &Path) -> anyhow::Result<Vec<PrEntry>> {
if !tool_available("gh", &["--version"]) {
anyhow::bail!("gh CLI not found; install gh to browse PRs with --prs");
@@ -1077,13 +1071,21 @@ fn compute_pr_comments(
) -> Option<String> {
// 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.
+ // so a hit returns with no forge call. GitHub worktree rows usually hit even
+ // on the first `wt switch` of a session — the CI call primed this entry from
+ // the thread it already carried (see `ci_status::github::prime_comments_cache`).
if let Some(ts) = updated_at
&& let Some(cached) = super::preview_cache::read_comments(repo, number, ts)
{
return Some(render_comment_blocks(&cached, width));
}
+ // TODO(gitlab-comments-cache): GitLab MRs always reach the fetch below —
+ // their `updated_at` can't key the cache (throttled to ~1/min and blind to
+ // note deletion). If MR comment fetches become a quota concern, synthesize a
+ // signature from a cheap `notes?per_page=1` probe — the `X-Total` header plus
+ // the newest note's `updated_at` both move on any add/edit/delete — and
+ // disk-cache MRs the same way GitHub PRs are cached here.
let number_str = number.to_string();
let endpoint = format!("projects/:fullpath/merge_requests/{number_str}/notes?sort=asc");
let stdout = fetch_forge_json(
@@ -1113,34 +1115,16 @@ fn compute_pr_comments(
#[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,
+ comments: Vec<GitHubComment>,
}
/// 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.
+/// The per-comment shape is shared with the worktree CI call, so this reuses
+/// [`GitHubComment`] rather than a parallel struct (see its `From<&_>` impl).
fn parse_github_comments(stdout: &[u8]) -> Option<Vec<CommentEntry>> {
let parsed: GhCommentsResponse = serde_json::from_slice(stdout).ok()?;
- Some(
- parsed
- .comments
- .into_iter()
- .map(|c| CommentEntry {
- author: c.author.login,
- body: c.body,
- created_at: c.created_at,
- })
- .collect(),
- )
+ Some(parsed.comments.iter().map(CommentEntry::from).collect())
}
#[derive(Deserialize)]