Skip to content

fix(switch): auto-refresh picker preview when a background compute lands - #3247

Merged
max-sixty merged 2 commits into
mainfrom
picker-preview-auto-refresh
Jun 25, 2026
Merged

max-sixty merged 2 commits into
mainfrom
picker-preview-auto-refresh

Conversation

@max-sixty

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

Copy link
Copy Markdown
Owner

Problem

The wt switch picker's preview pane is served from a DashMap cache filled by background workers on COLLECT_POOL (a git diff HEAD, a git log, a forge gh pr view). skim 4.8 re-reads that cache only inside run_preview, which fires only on Event::RunPreview — produced by a selection change or a preview-tab keystroke. The cache-insert path didn't poke skim, so a compute that finished after the single RunPreview the keystroke produced sat in the cache with no event to surface it: the pane stayed on its Loading… placeholder until the user pressed a key again. That Press alt-N again to refresh text was the manual workaround for exactly this gap, and it was a Windows-CI flake (PR #3238 papered over it test-side by re-issuing the tab keystroke).

The skim mechanism this uses

skim 4.8 hands the embedder its event sender at TUI init: Skim::event_sender() returns the tokio::sync::mpsc::Sender<Event> that drives the loop. The picker already captures it (as render_tx, a shared Arc<OnceLock<…>>) and pushes Event::Render through it for in-place row repaints. Pushing Event::RunPreview through the same channel forces run_preview to re-read the cache for the currently-selected row + current mode — the external injection point the orchestrator needed. The channel is 1024*1024-capacity, so the try_send poke is never dropped.

Approach

New PreviewNotifier (src/commands/picker/preview_notify.rs) closes the producer → consumer loop:

  • Consumer side: every *SkimItem::preview() records the selected row's awaited (row-key, mode) via note_awaiting — before it reads the cache. That ordering makes the hand-off race-free: if the read misses, the fill that satisfies it necessarily lands after the read, so it observes the awaited key already set.
  • Producer side: the orchestrator routes every cache fill through a single PreviewOrchestrator::fill / fill_external path, which calls notify_filled(key). That injects Event::RunPreview iff the filled key matches what the selected row is awaiting. A fill for an off-screen row or a tab the user isn't on matches nothing and injects nothing — so background pre-compute never thrashes the visible preview.

preview() is only ever called for the selected row, so the single shared awaiting slot always reflects what's on screen; when the selection changes, the next RunPreview updates it.

Two producers feed the panes, both now covered:

  • Orchestrator cache fills (diff / log / summary / the --prs comments & log fetch) → notify_filled(key), exact-key match.
  • The collect handler's on_update mirrors a row's live pr_status (the pr / comments panes) and local_content (the diff tabs' dim state) — not cache fills → notify_row_changed(row_key), which re-runs the selected row's preview on any tab when that row's data lands. This is what flips the pr tab from "Fetching PR status…" to the resolved PR on its own.

Wiring: render_tx is constructed before the orchestrator in handle_picker and handed in; it's still published once, inside run_skim after init_tui. generate_and_cache_summary became generate_summary_for_item (returns the pane; the orchestrator inserts via fill).

User-visible change

The placeholders drop the now-obsolete "press alt-N … to refresh" wording — the pane fills in on its own:

○ Loading working-tree diff…       (was: ○ Loading working-tree diff. Press alt-1 again to refresh.)
○ Generating summary…
○ Fetching PR status for feature…  (was: … press alt-6 to refresh)
ⓘ Loading comments…                (--prs deferred tabs; was: … press alt-2 again to refresh)

Testing

  • test_switch_picker_preview_auto_refreshes_when_compute_lands (PTY): mocks gh pr view --json comments behind a 3 s delay, opens a --prs row's comments tab mid-fetch — the comment surfaces with no further input (the orchestrator-fill path).
  • test_switch_picker_pr_tab_auto_resolves_from_fetching (PTY): the per-row CI fetch (gh pr list --head) is delayed 3 s and unseeded, so the pr tab opens on "Fetching PR status…" and resolves to the live PR on its own (the on_update path).
  • Both verified to time out (stay stranded) when the poke is disabled, so they genuinely exercise the mechanism rather than passing on a cache hit.
  • fill_notifies_only_awaited_key / notify_row_changed_pokes_only_the_selected_row (unit): the poke fires for the visible row+mode (resp. row, any mode) and nothing for off-screen / other-tab keys — the no-thrash guarantee.
  • The PTY driver's keystroke re-issue (nudge / is_alt_digit_tab / PREVIEW_REISSUE_INTERVAL, PR test(switch): deflake comments-tab preview wait by re-issuing the tab key #3238) is removed — the product now auto-refreshes, so the tests genuinely verify it rather than papering over a strand. All 37 switch_picker PTY tests pass; full cargo run -- hook pre-merge --yes green.

🤖 Generated with Claude Code

The preview pane is served from a DashMap cache filled by background
COLLECT_POOL workers; skim 4.8 re-reads it only on Event::RunPreview
(selection/tab change). A compute that finished after the keystroke's
single preview-run sat in the cache with no event to surface it, leaving
a "Loading…" placeholder stranded until the next keystroke.

PreviewNotifier closes the loop: the selected row records its awaited
(row-key, mode) in preview() before reading the cache; every cache fill
routes through PreviewOrchestrator::fill, which injects RunPreview through
skim's event sender iff the filled key matches the awaited one. The
finished preview auto-surfaces with no keystroke, scoped to the visible
row+mode so off-screen fills don't thrash the preview.

The loading placeholders drop the now-obsolete "Press alt-N again to
refresh" wording, and the PTY test driver's keystroke re-issue (the
workaround for this exact gap, PR #3238) is removed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@worktrunk-bot

Copy link
Copy Markdown
Collaborator

Heads-up on the one red check: affected tests (windows, advisory) (non-required) failed on test_switch_picker_worktree_row_comments_tab_shows_thread, but the required test (windows) leg ran the same test and passed — so this reads as a non-deterministic Windows PTY timing flake, not a regression. Approval stands; I've kicked a rerun of the advisory leg.

One thing worth a glance, since Windows reliability is the whole point here: the strand was at the Alt-1 diff --git step (the working-tree diff surfacing on its own), not the comments fetch — Timed out after 30s waiting for expected content "diff --git". That's the new orchestrator-computed auto-refresh path. With the test-side nudge re-issue gone, this test now genuinely gates on the product poke landing within 30s, and on a loaded Windows runner it didn't here. It passed on the required leg, so the mechanism works; I just can't rule out that the auto-refresh is a touch more timing-sensitive on Windows under load than the old keystroke-reissue masking. If it recurs, the git diff compute losing the race (rather than a lost poke) would be the first place I'd look.

The orchestrator-cache path (diff/log/summary/comments) already poked a
RunPreview on fill, but the `pr`/`comments` panes are fed by the collect
handler's `on_update` mirroring the row's live `pr_status` — not a cache
fill — and that path only sent `Event::Render` (a list redraw), so the
tab stayed on "Fetching PR status…" until the next keystroke. Add
`notify_row_changed` to PreviewNotifier and call it from `on_update`, so
the selected row's preview re-runs when its live data lands; drop the now
obsolete "press alt-6/7 to refresh" wording.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@max-sixty
max-sixty merged commit e3ca4c2 into main Jun 25, 2026
37 checks passed
@max-sixty
max-sixty deleted the picker-preview-auto-refresh branch June 25, 2026 19:24
max-sixty added a commit that referenced this pull request Jun 26, 2026
…3251)

Fast producer-site regression guard for the on_update → Event::RunPreview poke that #3247 wired. Unlike the orchestrator cache-fill path (self-guarding via the single PreviewOrchestrator::fill choke point), the on_update poke is a separate call, so this locks it: the test fails when the poke is removed. Also shares one render_tx between the orchestrator's notifier and the handler in make_handler, matching handle_picker. Test-only.
worktrunk-bot added a commit that referenced this pull request Jun 26, 2026
Resolves the conflict in tests/integration_tests/switch_picker.rs. main
(#3247) added PreviewNotifier, which auto-repaints a late preview when its
background compute lands, and removed the test-side Alt-<digit> keystroke
re-issue that #3238 used to paper over stranded "Loading…" placeholders.

The two de-flakes in this PR are orthogonal to that:

- Flake #1 (alt-x sticky exit code) — a separate region, auto-merged cleanly.
- Flake #2 (comments-tab cursor reset) — kept. PreviewNotifier re-runs only
  the *preview* for the selected row (notify_row_changed); it does not stop
  on_update's request_render from resetting skim's cursor to the top after an
  async row decoration lands. So the cursor-confirmed Down is still needed.

Resolution keeps the cursor-arrow re-issue (restored wait_for_stable_until's
nudge param, now scoped to cursor recovery and renamed PREVIEW_REISSUE_INTERVAL
-> CURSOR_REISSUE_INTERVAL) and drops the obsolete Alt-<digit> re-issue branch
(is_alt_digit_tab deleted) in favor of main's PreviewNotifier path. Full
switch_picker suite passes locally on Linux.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
social4hyq pushed a commit to social4hyq/homebrew-core that referenced this pull request Sep 20, 2026
worktrunk 0.62.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

- **Browse open PRs/MRs in the `wt switch` picker, with live CI**: The picker now streams a live CI/review-status column per row — priming from the local cache, then fetching live (it previously showed only cached numbers with no network). A new `--prs` flag adds the repository's open PRs (GitHub) / MRs (GitLab) as rows alongside your worktrees, each with `pr` / `comments` / `log` preview tabs loaded from the forge in the background; selecting one fetches its branch and switches. Rows whose branch is already shown aren't duplicated, so `--prs` differs from plain `wt switch` only by the extra rows. [Docs](https://worktrunk.dev/switch/) ([#3128](max-sixty/worktrunk#3128), [#3169](max-sixty/worktrunk#3169), [#3189](max-sixty/worktrunk#3189), [#3252](max-sixty/worktrunk#3252))

- **`main…±` diff column shows by default in `wt list`**: The `main…±` column (lines changed since the merge-base with the default branch) now renders in the default `wt list` and picker, served from a persistent cache rather than a history walk. `--full` now adds only the columns that reach off-machine — CI status and LLM branch summaries — and `wt list --format=json` populates `main.diff` for every item, not just under `--full`. ([#3236](max-sixty/worktrunk#3236))

- **`[list] columns` selects and orders the columns `wt list` shows**: A new `[list] columns` user-config key (also settable via `--config-set`) takes an ordered array of column names — built-in (`branch`, `status`, `ci`, `path`, …) and `[list.custom-columns]` headers alike — and renders exactly those, in that order. Where v0.61.0's custom columns *add* columns, this *selects and reorders* the whole set; omit the key for the default layout. (`WORKTRUNK__LIST__COLUMNS` isn't supported yet and warns if set.) ([#3141](max-sixty/worktrunk#3141))

- **Picker PR preview shows full PR/MR detail**: The `pr` tab now renders the PR/MR title, markdown description, author, draft state, comment count, bold branch name, and underlined URL for any row whose branch has an open PR — not just `--prs` rows — and the `comments` tab fetches the real thread. The title and description ride the CI fetch the picker already makes; the comment thread is fetched lazily in the background, once per row. ([#3167](max-sixty/worktrunk#3167), [#3197](max-sixty/worktrunk#3197), [#3223](max-sixty/worktrunk#3223), [#3195](max-sixty/worktrunk#3195), [#3231](max-sixty/worktrunk#3231))

- **Interactive picker runs on Windows**: The `wt switch` picker was Unix-only because its preview-tab keys shelled out through a per-process state file `cmd.exe` lacks; tab state moved to an in-memory atomic with native skim callbacks, lifting the platform gate. ([#3217](max-sixty/worktrunk#3217))

- **Picker keyboard shortcuts**: `Alt-y` copies the selected branch name, `Alt-o` opens the row's PR/MR in the browser, and `Alt-r` refreshes the list (picking up worktrees created or removed elsewhere). (Breaking: in the picker, remove moved from `Alt-r` to `Alt-x`) ([#3233](max-sixty/worktrunk#3233))

- **Picker uses the full terminal**: List height scales with the terminal (a roughly even split with the preview, minimum 3 rows) instead of a fixed 12-row cap, the table lays out at full width so toggling the preview off with `Alt-p` reveals the freed columns with no reflow, and a scrollbar appears when the list overflows. ([#3205](max-sixty/worktrunk#3205), [#3214](max-sixty/worktrunk#3214), [#3198](max-sixty/worktrunk#3198))

- **Picker filters on more of each row**: Typing a gutter sigil filters by row kind (`+` for linked worktrees, `@` for the current one), the fuzzy matcher ranks on the distinguishing path segment rather than the shared parent prefix, and rows with a PR/MR also match on its number, title, and author. ([#3143](max-sixty/worktrunk#3143), [#3208](max-sixty/worktrunk#3208), [#3252](max-sixty/worktrunk#3252))

- **Picker visual polish**: The legend recolored to dim-cyan and reordered so navigation leads, and preview loading placeholders moved to the dim-hint style (`↳` transient, `○` settled, `▲` failed). ([#3237](max-sixty/worktrunk#3237), [#3253](max-sixty/worktrunk#3253))

- **"Still waiting" status for slow commit-message generation**: A configured `commit.generation` command captures stdout, so a slow or hung LLM previously showed nothing while `wt step commit`/`squash` waited. After a 2s delay worktrunk now shows a dim, in-place `○ Waiting for the commit message (Ns)` status, escalating at 10s to reveal the exact shell-escaped invocation in a gutter beneath it; the block clears on completion, mirroring `wt list`'s stall footer. ([#3178](max-sixty/worktrunk#3178))

- **"Still waiting" status extended to more slow commands**: The same waiting status now covers three more foreground commands that were silent while a captured subprocess ran — the `wt config show --full` commit-generation self-test, the `wt switch pr:`/`mr:` host lookup, and the `wt config show --full` version check. The version check no longer caps its fetch at an aggressive 5s, instead showing the status while a slow-but-working request completes (with a generous ceiling so a non-interactive run can't hang). ([#3183](max-sixty/worktrunk#3183))

- **`wt config state logs profile` performance profiler**: A new subcommand turns a `-vv` `[wt-trace]` capture (a path argument, `-` for stdin, or the default `trace.log`) into a performance profile: subprocess time by command shape, the slowest calls, parallelism and peak concurrency, redundant cache-miss re-runs, and — for `wt list`/picker captures — derived latencies and a collect timeline. `--format=json` emits the same data, and every `-vv` bug-report bundle now inlines a rendered profile. ([#3184](max-sixty/worktrunk#3184), [#3186](max-sixty/worktrunk#3186))

- **`WORKTRUNK_VERBOSE` env var**: `WORKTRUNK_VERBOSE=0|1|2` mirrors `-v`/`-vv`, combined with any flag via `max` (the env sets a floor the flag can raise). Unlike the flags it's honored on the shell-completion path, which returns before flag parsing — so a slow tab-completion can be profiled for the first time. ([#3166](max-sixty/worktrunk#3166))

- **Aliases inherit the wrapped command's completion**: An alias that forwards `{{ args }}` to a single `wt` command (`co = "wt switch {{ args }}"`) now completes that command's arguments and flags — `wt co <Tab>` completes branches like `wt switch <Tab>` — instead of a generic stub. Bare dispatchers and multi-`{{ args }}` aliases keep the stub. ([#3172](max-sixty/worktrunk#3172), thanks @yzx9)

- **`wt step copy-ignored --require-include`**: A new `--require-include` flag makes the copy a no-op unless a `.worktreeinclude` file exists in the source worktree (matching Claude Code desktop, where that file is required), reporting why it skipped as a hint in text mode and a `reason` field in `--format=json`. ([#3196](max-sixty/worktrunk#3196), thanks @yzx9)

- **`wt step tether` honors `-C`**: The global `-C <path>` flag now sets the tethered command's working directory (`wt step tether -C frontend -- npm run dev`); teardown still watches the worktree root, so the command is reaped when the worktree is removed. ([#3207](max-sixty/worktrunk#3207))

- **Statusline rate-limit pace color grades by severity**: The pace segment's color now deepens (dim → dim-yellow → yellow) with the projected throttling severity, so an early-window burst stays muted while a costly projected lockout stands out. The displayed pace number is unchanged. ([#3229](max-sixty/worktrunk#3229))

### Fixed

- **Picker `Alt-x` removal updates the row in place**: Removing a worktree no longer re-collects the whole list (a flicker that reset the cursor to the top): an unmerged worktree's row morphs into a branch-only row while the worktree is removed in the background, and a merged worktree's row drops with the cursor landing on the row that slid up. A removal that can't safely happen — the current or main worktree, or a dirty or locked one — is declined with the same diagnostic `wt remove` prints, rather than a dead keypress or a disruptive `cd` home. The post-removal cursor lands by row identity, so it stays correct even under an active filter. ([#3262](max-sixty/worktrunk#3262), [#3199](max-sixty/worktrunk#3199), [#3211](max-sixty/worktrunk#3211), [#3225](max-sixty/worktrunk#3225))

- **Picker preview refreshes when its background fetch lands**: A diff/log/PR-view fetch that completed after its triggering keystroke used to sit unshown until the next keypress; the pane now updates on its own when the fetch lands. ([#3247](max-sixty/worktrunk#3247))

- **Picker rows stay aligned while filtering**: Typing a filter no longer slides the matched row left and drops its leading sigil, and `Alt-l`/`Alt-h` no longer scroll the list off its gutter. ([#3213](max-sixty/worktrunk#3213), [#3226](max-sixty/worktrunk#3226))

- **fish completions no longer recurse to the call-stack limit**: With worktrunk's fish lazy-load wrapper installed, co

See merge request: Harmonybrew/homebrew-core!12862
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