Repository navigation
perf(switch): disk-cache the picker comments tab, keyed by PR updatedAt - #3294
Conversation
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
left a comment
There was a problem hiding this comment.
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.
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
left a comment
There was a problem hiding this comment.
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(insrc/commands/list/ci_status/mod.rs, theelse if let Some(stale) = cached.status.filter(|s| s.number.is_some())branch) keeps an expired entry that names a PR, carrying its oldupdated_atthrough..staleand marking itis_priming: true. There's no TTL bound on how old this entry is.on_skeletonthen callsmaybe_spawn_commentsfor that primed row, spawning the comments fetch keyed by the staleupdated_at(T_old).- When the live
CiStatusfetch lands inon_updatewith a freshupdated_at(T_new ≠ T_old),maybe_spawn_commentsruns again but dedups by number and returns early — it never re-keys the fetch toT_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}.jsonexists 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()
} == *yBoth 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]>
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
What
The
wt switchpicker'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. Thecommentstab (tab 7) had no disk tier — every freshwt switchre-fetched each row's thread from the forge (gh pr view <n> --json comments), up to ~50 calls on a--prsopen 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
updatedAtis the content signature: it bumps on comment add, edit, review, and review-comment, and rides for free on thegh pr list/gh pr viewcall the picker already makes for the CI column (PrStatus.updated_at) and the--prslist. Keying the cache by(number, updatedAt)lets a repeatwt switchskip 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 newCommentEntrytype pluscomments_key/read_comments/write_comments, under the existingpicker-previewKIND. Module docstring updated.src/commands/picker/prs.rs—compute_pr_commentsreads the disk cache first (a hit re-renders with no forge call), and thegh/glabcomment parsing is split from rendering (parse_github_comments/parse_gitlab_notes→render_comment_blocks).src/commands/list/ci_status/+picker/progressive_handler.rs— threadupdated_atfrom the forge call throughPrStatus/PrEntryto 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) andepoch_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 parsedCommentEntrys 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_atis throttled to once per minute for note activity (so it misses a quick reply) and never moves on note deletion (confirmed from the GitLab RailsThrottledTouch/Notes::DestroyServicesource), so it can't reliably signal "unchanged." MRs passupdated_at: Noneand 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 atPrStatus::updated_atandcomments_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--prslist call (it omitscommentsto keep the 50-PR payload light), and fetching to learn it defeats the cache.Freshness is bounded by the CI cache.
--prsrows read a liveupdated_atfrom each list call. Worktree rows read it from the CI-status cache — andmaybe_spawn_commentsskips the expired-cache prime (is_priming), so the comments fetch always keys off a within-TTL or liveupdated_atrather 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_cacheunit tests cover the comments round-trip and signature keying (a changed timestamp misses); aprogressive_handlertest covers theis_primingguard (an expired prime doesn't spawn/mis-key the fetch; the live update does). The existingprs.rscomment-rendering tests are retained via thin parse-then-render helpers.cargo run -- hook pre-mergeandcargo clippy --all-targets --features shell-integration-testsare green.