Skip to content

perf(switch): disk-cache the picker comments tab, keyed by PR updatedAt - #3294

Merged
max-sixty merged 4 commits into
mainfrom
pr-comments-disk-cache
Jun 28, 2026
Merged

max-sixty merged 4 commits into
mainfrom
pr-comments-disk-cache

Conversation

@max-sixty

@max-sixty max-sixty commented Jun 28, 2026 •

Copy link
Copy Markdown
Owner

What

The wt switch picker's preview pane has a two-tier cache: a session-scoped in-memory tier, and an on-disk tier (in .git/wt/cache/picker-preview/) that survives across runs and keys the diff tabs by git SHA. The comments tab (tab 7) had no disk tier — every fresh wt switch re-fetched each row's thread from the forge (gh pr view <n> --json comments), up to ~50 calls on a --prs open and one per worktree-row-with-PR otherwise. Unlike a git diff there was no obvious content hash to key on.

This adds the missing disk tier for GitHub PRs. A GitHub PR's updatedAt is the content signature: it bumps on comment add, edit, review, and review-comment, and rides for free on the gh pr list / gh pr view call the picker already makes for the CI column (PrStatus.updated_at) and the --prs list. Keying the cache by (number, updatedAt) lets a repeat wt switch skip the per-row comments fetch entirely when the thread is unchanged — no extra network, fewer forge calls, and the tab paints instantly on a repeat open instead of showing "Loading comments…".

How to navigate the diff

  • src/commands/picker/preview_cache.rs — the new CommentEntry type plus comments_key / read_comments / write_comments, under the existing picker-preview KIND. Module docstring updated.
  • src/commands/picker/prs.rs — compute_pr_comments reads the disk cache first (a hit re-renders with no forge call), and the gh/glab comment parsing is split from rendering (parse_github_comments / parse_gitlab_notes → render_comment_blocks).
  • src/commands/list/ci_status/ + picker/progressive_handler.rs — thread updated_at from the forge call through PrStatus / PrEntry to the comments-fetch gate.

Key design decisions

Cache raw comments, re-render on read (mirrors LogCacheEntry). The rendered pane folds in pane width (body wrapping) and epoch_now()-relative times (· 2h), neither of which is stable. Caching the rendered string would freeze both — a comment posted "2h" ago would still read "2h" days later. So the cache stores the parsed CommentEntrys and re-renders at the live width and current time on every read; width drops out of the key.

GitHub-only. GitLab's MR updated_at is throttled to once per minute for note activity (so it misses a quick reply) and never moves on note deletion (confirmed from the GitLab Rails ThrottledTouch / Notes::DestroyService source), so it can't reliably signal "unchanged." MRs pass updated_at: None and keep fetching every open, exactly as before — never disk-cached.

One accepted best-effort gap: GitHub comment deletion. GitHub doesn't reflect a comment deletion in the PR's updatedAt (add/edit/review all do). A deleted comment can therefore linger in the cached thread until the next add/edit/review bumps the timestamp. This is documented at PrStatus::updated_at and comments_key, and is the same shape of bounded best-effort staleness as the Log tab's documented ref-decoration drift. There's no free fix — the comment count that would catch a deletion isn't carried by the --prs list call (it omits comments to keep the 50-PR payload light), and fetching to learn it defeats the cache.

Freshness is bounded by the CI cache. --prs rows read a live updated_at from each list call. Worktree rows read it from the CI-status cache — and maybe_spawn_comments skips the expired-cache prime (is_priming), so the comments fetch always keys off a within-TTL or live updated_at rather than the unbounded age of an expired prime. Worktree staleness is thus bounded to the CI column's own 30–60s freshness, consistent with the rest of the picker.

Investigation

This grew out of a forge-semantics investigation (verified empirically against real GitHub PRs and from the GitLab source) into whether a reliable "most recently modified" signal exists for PR/MR comments. The short answer: cleanly yes for GitHub, not viable as a free key for GitLab — hence the GitHub-only scope.

Testing

New preview_cache unit tests cover the comments round-trip and signature keying (a changed timestamp misses); a progressive_handler test covers the is_priming guard (an expired prime doesn't spawn/mis-key the fetch; the live update does). The existing prs.rs comment-rendering tests are retained via thin parse-then-render helpers. cargo run -- hook pre-merge and cargo clippy --all-targets --features shell-integration-tests are green.

This was written by Claude Code on behalf of max

The `wt switch` picker's `comments` preview tab (tab 7) had no disk tier:
every fresh `wt switch` re-fetched each row's thread from the forge
(`gh pr view <n> --json comments`), up to ~50 calls on a `--prs` open.
Unlike the diff tabs there was no obvious content hash to key on.

A GitHub PR's `updatedAt` is that signature: it bumps on comment add,
edit, review, and review-comment, and rides for free on the `gh pr list` /
`gh pr view` call the picker already makes for the CI column / `--prs`
list. Keying an on-disk cache by `(number, updatedAt)` lets a repeat
`wt switch` skip the per-row comments fetch when the thread is unchanged.

Mirroring `LogCacheEntry`, the cache stores the raw parsed comments
(`CommentEntry`) and re-renders on read, so pane width and
`epoch_now()`-relative times stay live and drop out of the key.

GitHub-only: GitLab's MR `updated_at` is throttled (once/minute for note
activity) and never moves on note deletion, so MRs pass `updated_at:
None` and keep fetching every open — never disk-cached. GitHub comment
*deletion* is the one event `updatedAt` misses; a deleted comment can
linger until the next bump — an accepted best-effort gap for a read-only
preview, matching the Log tab's documented ref-decoration drift.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lint and code-coverage are both red on the same root cause: the test build doesn't compile. Adding updated_at to PrStatus requires every struct literal to set it, and one test helper outside this diff was missed — the row closure in on_update_pokes_run_preview_only_when_the_visible_pane_changes (src/commands/picker/progressive_handler.rs), the PrStatus { ci_status, source: CiSource::PullRequest, … number: Some(PrRef::pr(7)), … comment_count: None } literal:

error[E0063]: missing field `updated_at` in initializer of `commands::list::ci_status::PrStatus`

The fix is to add updated_at: None, after the comment_count: None, line in that closure — the same one-liner already applied to the sibling PrStatus literals in this file. (The PR body notes pre-merge was green locally; this literal is only present in the pull/3294/merge tree, so it slipped past the branch-tip build.)

Since the line is outside the diff, I can't attach it as an inline suggestion. Want me to push the one-line fix to the branch?

The rest of the change reads cleanly — keying the comments cache off GitHub's updatedAt, caching raw CommentEntrys and re-rendering on read (mirroring LogCacheEntry), the GitHub-only scope with the documented deletion/GitLab gaps, and reuse of sanitize_for_filename / the existing picker-preview KIND are all consistent with the surrounding code. No other findings.

max-sixty and others added 2 commits June 28, 2026 12:50
Merging main (which landed #3293 alt-r preview refresh) brought in a new
PrStatus test literal in progressive_handler.rs that predates the
`updated_at` field this branch adds — a semantic conflict git's text merge
couldn't catch, so it broke the `shell-integration-tests`-gated build (CI
lint + code-coverage). Add the missing `updated_at: None`, and update the
preview_orchestrator cache-tier table so the Comments row reflects its new
`updatedAt`-keyed disk tier instead of "none".

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One correctness concern on the freshness of the new comments cache for worktree rows (the --prs path is fine — it always reads a live updated_at from each list call).

Worktree rows primed from an expired CI cache key the comments cache to a stale updated_at

The comments fetch is spawned once per PR per session, deduped by PR number in maybe_spawn_comments (previous == number → return). The updated_at it captures is whatever the row's first pr_status carried — and for a worktree row that's the skeleton prime, which can be an expired CI cache entry:

  • populate_from_cache (in src/commands/list/ci_status/mod.rs, the else if let Some(stale) = cached.status.filter(|s| s.number.is_some()) branch) keeps an expired entry that names a PR, carrying its old updated_at through ..stale and marking it is_priming: true. There's no TTL bound on how old this entry is.
  • on_skeleton then calls maybe_spawn_comments for that primed row, spawning the comments fetch keyed by the stale updated_at (T_old).
  • When the live CiStatus fetch lands in on_update with a fresh updated_at (T_new ≠ T_old), maybe_spawn_comments runs again but dedups by number and returns early — it never re-keys the fetch to T_new.

So for an expired-primed worktree row the comments tab is locked to T_old for the whole session:

  • If comments-{number}-{T_old}.json exists on disk (written in a prior session), it's a hit → the stale thread is served with no forge call, missing any comment added/edited since.
  • If it doesn't exist, the live thread is fetched but written under the stale key T_old — a mis-keyed entry whose filename no longer reflects its content signature, which then becomes the stale-serving entry for a future expired-primed session.

This is the case the PR body says doesn't happen: "For worktree rows the updated_at comes from the CI-status cache (30–60s TTL), so the comments tab inherits the CI column's freshness bound." That holds for a valid (within-TTL) prime, but the expired-prime branch has no such bound, so the staleness is unbounded rather than 30–60s. Before this PR the once-per-session fetch always hit the forge and returned the live thread regardless of updated_at, so this is a net-new staleness window.

A clean, targeted fix: skip the comments spawn for the priming placeholder so it keys off the live (or within-TTL) updated_at instead — is_priming (#[serde(skip)], set only by populate_from_cache) exactly identifies the expired prime:

// in maybe_spawn_comments, before reserving the comments_fetched slot:
let Some(pr_ref) = status.number else { return };
if status.is_priming {
    // Expired-prime placeholder: its `updated_at` is unbounded-stale and
    // would lock the comments cache to a wrong signature. Let the live
    // CiStatus fetch spawn this with a fresh timestamp.
    return;
}

Valid primes keep warming the tab at skeleton; expired-primed rows just wait a beat for the live fetch. Alternatively, have the live on_update re-spawn when updated_at changed (more involved, since comments_fetched only stores the number). Happy to push the is_priming guard if you want it — flagging rather than pushing since whether this staleness is even worth closing is a judgment call given the PR's documented best-effort posture.

Minor: pr_status_pane_eq now compares a pane-invisible field

Adding updated_at to PrStatus (which derives Eq and is compared in pr_status_pane_eq) means an updated_at-only change now reports pane_changed = true and re-renders the pr pane (resetting its scroll) on the prime→live transition, even though the pr pane never renders updated_at. Its docstring ("Every other field … shows in the pane, so any of them differing is a real change") is also now inaccurate. The one-line fix mirrors the is_priming exclusion:

PrStatus {
    is_priming: y.is_priming,
    updated_at: y.updated_at.clone(),
    ..x.clone()
} == *y

Both are cosmetic-to-low severity (read-only preview), but the first is a real divergence from the stated freshness contract and worth a decision before this lands.

… priming

Two fixes from review of the comments disk cache:

1. Skip the comments fetch for an expired-cache prime (`is_priming`) in
   `maybe_spawn_comments`. `populate_from_cache` carries an unbounded-stale
   `updated_at` on the priming placeholder; since the fetch is deduped by PR
   number, keying off it 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
   it with the right key, so worktree staleness is bounded to the CI column's
   30–60s freshness rather than the age of an expired prime. A valid prime is
   not priming, so it still warms the tab at skeleton.

2. Exclude `updated_at` from `pr_status_pane_eq`. It's the comments-cache key,
   never shown in the `pr` pane, so an `updated_at`-only change (the prime→live
   flip) must not report a pane change and reset the pane's scroll. Mirrors the
   existing `is_priming` exclusion; docstring updated.

Adds a `progressive_handler` regression test for the priming guard.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@max-sixty
max-sixty merged commit 2def844 into main Jun 28, 2026
36 checks passed
@max-sixty
max-sixty deleted the pr-comments-disk-cache branch June 28, 2026 22:17
social4hyq pushed a commit to social4hyq/homebrew-core that referenced this pull request Sep 20, 2026
worktrunk 0.63.0

Created-by: HarmonybrewBot
Commit-by: HarmonybrewBot
Merged-by: HarmonybrewBot
Description: Created by `brew bump`

---

Created with `brew bump-formula-pr`.<details>
  <summary>release notes</summary>
  <pre>## Release Notes

### Improved

- **`[list] columns` can force a column on past `--full`**: Listing a column now overrides the `--full` / `[list] summary` presets — `columns = ["branch", "ci"]` shows the CI column without `--full`. Hard data-source prerequisites still apply: a listed `summary` with no `[commit.generation]` command, or `url` with no template, stays hidden, since listing can't conjure data that isn't configured. ([#3295](max-sixty/worktrunk#3295))

- **`Alt-r` in the picker refreshes the preview panes, not just the rows**: `Alt-r` re-collected the rows but kept serving cached preview content, so editing a tracked file and refreshing still showed the pre-edit diff. It now clears the preview cache too, recomputing the working-tree / log / branch-diff / upstream / summary tabs and re-fetching `pr` / `comments`. Unchanged branches re-read from the content-keyed on-disk cache, so only genuinely changed content pays a recompute. ([#3293](max-sixty/worktrunk#3293))

- **A narrowed `wt list` is now actually faster**: A narrowed `[list] columns` selection (e.g. `["branch", "path"]`) now runs only the git work its columns need. It previously ran every per-worktree `git status`, diff, and ahead/behind walk regardless, then discarded the unselected results — so a trimmed view was no faster than the full table, and on a repo with many dirty worktrees that discarded work was the bulk of the wall-clock cost. ([#3274](max-sixty/worktrunk#3274), thanks @jtaby for reporting)

- **Fewer duplicate git calls in `wt list --full`**: The two integration probes per row (the conflict bit for `main-state` and the clean-merge tree for the integration column) issued a byte-identical `git merge-tree`, and the shared default-branch tip was peeled to its tree once per row. Both are now deduplicated through the in-memory cache, so each resolves once per run instead of once per worktree. ([#3288](max-sixty/worktrunk#3288), [#3289](max-sixty/worktrunk#3289))

- **Picker `comments` tab avoids redundant forge fetches**: The picker's `comments` preview tab gained an on-disk cache keyed by the PR's `updatedAt` (which rides for free on the CI fetch the picker already makes), so a repeat `wt switch` skips the per-row `gh pr view --json comments` fetch when the thread is unchanged and paints the tab instantly instead of showing "Loading comments…". The cache is also primed from the `gh pr list` call the picker already makes, so the tab skips its own fetch even on a session's first open (including PRs with no comments). GitHub only. ([#3294](max-sixty/worktrunk#3294), [#3299](max-sixty/worktrunk#3299))

- **Statusline width comes from `COLUMNS`, not a parent-process walk**: `wt list statusline` used to spawn up to 10 `ps` calls plus `stty` per render to recover a terminal width, because Claude Code piped the subprocess with no inherited TTY. Claude Code now sets `COLUMNS`/`LINES` to the terminal dimensions before running the script (since v2.1.153), so the width comes straight from there — less a fixed 5-column margin for Claude Code's own UI — and the `ps`/`stty` walk is gone. On an older Claude Code that doesn't set `COLUMNS`, the line renders untruncated rather than walking the process tree. ([#3286](max-sixty/worktrunk#3286), closes [#2950](max-sixty/worktrunk#2950))

### Fixed

- **`wt list` diff and ahead/behind columns use the upstream default tip**: The `main↕` (ahead/behind) and `main…±` (diff) columns measured every branch against the *local* default-branch tip, so in a fork whose local `main` lagged its upstream they reported inflated counts — one fork branch showed `↑44` and `+∞ / -5K` when it was ~2 commits past the real upstream tip. They now diff against the same upstream-aware base the integration column already uses. ([#3280](max-sixty/worktrunk#3280))

- **Integrated branches no longer flash `✗` in `wt list`**: A squash-merged branch whose default branch later re-edited the same lines showed `✗` (would-conflict), even though `wt step prune` classified it as `⊂` (fully integrated) and removed it. The list now ranks the integration verdict above the downstream conflict, matching prune; a genuinely un-integrated conflict still shows `✗`. ([#3278](max-sixty/worktrunk#3278))

- **`wt list` divergence-overflow marker uses one emphasis level**: When an ahead/behind count overflows its digit budget, the `main↕` column's compact `C`/`K`/`∞` marker rendered the "behind" subcolumn as dim + bold (reading as bold red) instead of a clean one-level step. It now steps exactly one level — dim red → normal red — matching the "ahead" subcolumn, across `wt list` and the picker. ([#3303](max-sixty/worktrunk#3303))

- **Branch deletion on removal is atomic**: `wt remove` and prune now delete a branch with a compare-and-swap (`git update-ref -d <ref> <expected-sha>`) against the SHA the integration check already read, closing the window where a branch whose tip moved in between (e.g. a hook landing a commit) could be deleted. Such a branch is now retained with a clear message and a `wt remove -D <branch>` recovery hint. This also unifies the previously divergent safe-delete paths; explicit force-delete still uses `git branch -D`. ([#2903](max-sixty/worktrunk#2903))

- **`wt list` and picker Age/Message columns paint as soon as the commit batch lands**: These columns carry no async task — their data arrives with the initial `git log` batch — but stayed on the `·` placeholder until some slower task happened to redraw the row, so the commit message lagged behind a cache-warm Summary preview. They now paint the moment the batch lands. ([#3287](max-sixty/worktrunk#3287))

- **Picker `Alt-x` removal: no cursor flash, `--prs` rows preserved**: Removing a row with `Alt-x` flashed the `>` pointer to the top of the list for a frame, and in `--prs` mode made the streamed PR/MR rows vanish until the next `Alt-r`. Removal is now a synchronous in-place pool resync: the cursor lands on the row that slid up with no flash, and the PR/MR rows survive. ([#3268](max-sixty/worktrunk#3268), [#3275](max-sixty/worktrunk#3275))

- **Removable rows stay gray when selected in the picker**: A safe-to-delete worktree (integrated, or clean and even with the default branch) renders its row gray, but the gray vanished under the selection highlight — exactly when you're about to act on it. The gray now survives selection (selected row only; `wt list` and unselected rows are unchanged). ([#3267](max-sixty/worktrunk#3267))

- **Picker preview keeps its scroll when CI status arrives**: Scrolling down a diff and waiting a couple of seconds snapped it back to the top when the live CI fetch landed and re-rendered the pane. The re-render is now precise — a tab re-runs only when its own content would actually change — so a CI update no longer throws away the scroll position of an unrelated tab. ([#3292](max-sixty/worktrunk#3292))

- **Picker summary tab dims when there's nothing to summarize**: The summary preview tab (`5`) stayed lit on a clean branch with no commits ahead, unlike the diff tabs (1/3/4), which dim once their diff is known empty. It now dims in concert with them once both the branch diff and working tree are known empty. ([#3291](max-sixty/worktrunk#3291))

- **Picker default view keeps collect order**: With no query typed, the `wt switch` picker reordered rows by where each name's last `/` falls, so slash-bearing branches (`feature/…`, `perf/…`) sank toward the bottom and intermixed with other row kinds. The default view now preserves collect order. ([#3301](max-sixty/worktrunk#3301))

- **Picker branch-diff preview and summary use the upstream-aware base**: Like the `wt list` columns above, the picker's branch-diff preview pane and the LLM branch summary diffed against the raw local default branch, so a fork whose local default lagged upstream made them describe dozens of already-merged commits. They now use the same upstream-aware comparison base. ([#3305](max-sixty/worktrunk#3305))

- **Picker comment previews render fenced code blocks cleanly**: A fenced code block inside a PR/MR comment rendered as a garbled double gutter in the `wt switch` comments preview — alternating bar/no-bar lines with broken alignment. The code block now renders without the nested gutter. ([#3306](max-sixty/worktrunk#3306))

- **First-run hints show the config path wt actually loads from**: The picker's disabled-summary tab and the commit-generation setup prompt hardcoded `~/.config/worktrunk/config.toml`, so a user with `--config`, `WORKTRUNK_CONFIG_PATH`, or a non-default `$XDG_CONFIG_HOME` was told to edit a file wt never reads. Both now show the resolved path. ([#3290](max-sixty/worktrunk#3290), [#3298](max-sixty/worktrunk#3298))

### Internal

- **`-vv` trace and profiler accuracy**: `trace.log` is now purely human-readable, with the machine-parseable `[wt-trace]` fields living only in `trace.jsonl`; and the performance profile's cache analysis no longer reports stdin-driven commands (LLM `claude -p` calls, `git patch-id`) as duplicate re-runs, since their real input isn't captured in the command string. ([#3296](max-sixty/worktrunk#3296), [#3297](max-sixty/worktrunk#3297))

## Install worktrunk 0.63.0

### Install prebuilt binaries via shell script

`

See merge request: Harmonybrew/homebrew-core!13092
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants