Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(picker): keep preview scroll when a CI fetch lands (#3292)
Maximilian Roose5842f03e5a1
diff --git a/src/commands/list/ci_status/mod.rs b/src/commands/list/ci_status/mod.rsindex 166f09760..fc67280a5 100644--- a/src/commands/list/ci_status/mod.rs+++ b/src/commands/list/ci_status/mod.rs@@ -362,7 +362,7 @@ pub enum ReviewState {}/// CI status from PR/MR or branch workflow-#[derive(Debug, Clone, Serialize, Deserialize)]+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct PrStatus {pub ci_status: CiStatus,/// Source of the CI status (PR/MR or branch workflow)diff --git a/src/commands/picker/items.rs b/src/commands/picker/items.rsindex 2be8d3ba5..1a6dbdb23 100644--- a/src/commands/picker/items.rs+++ b/src/commands/picker/items.rs@@ -528,6 +528,55 @@ enum PrPreview {HasPr(PrRef, PrStatus),}+/// The three states the `pr` and `comments` tabs branch on, read from a live+/// `pr_status` slot value without cloning the status. The discriminant mirrors+/// [`PickerRow::pr_preview`] exactly. The `comments` pane is byte-identical+/// within `HasPr` (its thread is branch-keyed and surfaced by `notify_filled`),+/// so the collect handler re-renders that tab on a *presence* change, not on+/// every `pr_status` field — re-running it for an unchanged body would only+/// reset the user's scroll. See [`PreviewNotifier`].+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(super) enum PrPresence {+ Loading,+ NoPr,+ HasPr,+}++/// The [`PrPresence`] a live `pr_status` slot value resolves to — the same+/// three-way split [`PickerRow::pr_preview`] renders.+pub(super) fn pr_presence(pr_status: &Option<Option<PrStatus>>) -> PrPresence {+ match pr_status {+ None => PrPresence::Loading,+ Some(None) => PrPresence::NoPr,+ Some(Some(status)) if status.number.is_some() => PrPresence::HasPr,+ Some(Some(_)) => PrPresence::NoPr,+ }+}++/// 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+/// (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.+pub(super) fn pr_status_pane_eq(+ a: &Option<Option<PrStatus>>,+ b: &Option<Option<PrStatus>>,+) -> bool {+ match (a, b) {+ (Some(Some(x)), Some(Some(y))) => {+ x == y+ || PrStatus {+ is_priming: y.is_priming,+ ..x.clone()+ } == *y+ }+ _ => a == b,+ }+}+/// Live, content-aware availability for the local-checkout tabs whose pane is a/// diff — `working_tree`, `branch_diff`, and `upstream`. Each tab dims once its/// diff is *known* empty, the same way the `pr` tab dims once the fetch reportsdiff --git a/src/commands/picker/preview_notify.rs b/src/commands/picker/preview_notify.rsindex 62d0c5b5e..477a58930 100644--- a/src/commands/picker/preview_notify.rs+++ b/src/commands/picker/preview_notify.rs@@ -18,13 +18,36 @@//! off-screen row, or a tab the user isn't looking at — matches nothing and//! injects nothing, so background pre-compute never re-runs the visible preview.//!-//! Some panes aren't fed by an orchestrator cache fill: the `pr` / `comments`-//! panes read the row's live `pr_status`, and the diff tabs' dim state reads its-//! `local_content` — both mirrored by the collect handler's `on_update` as the-//! list pipeline lands. [`notify_row_changed`](PreviewNotifier::notify_row_changed)-//! covers those: it re-runs the selected row's preview (whatever tab is showing)-//! when that row's live data changes, so e.g. the `pr` tab flips from "Fetching-//! PR status…" to the resolved PR on its own.+//! Two panes are fed by live row data rather than an orchestrator cache fill:+//! the `pr` and `comments` panes render from the row's live `pr_status`,+//! mirrored by the collect handler's `on_update` as the `CiStatus` fetch lands.+//! [`notify_pr_status_changed`](PreviewNotifier::notify_pr_status_changed) covers+//! them: when that row is selected, it re-runs the preview so e.g. the `pr` tab+//! flips from "Fetching PR status…" to the resolved PR on its own.+//!+//! It re-runs only when the *visible* tab's body would actually differ, because+//! a re-run resets the preview scroll to the top (skim clears it on every+//! content swap), and yanking the user out of a scrolled pane to repaint+//! identical bytes is the bug this guards against. That makes the gate+//! per-tab, matching what each body reads:+//!+//! - **diff / log / summary tabs** — body comes from the orchestrator cache, not+//! `pr_status`, so an `on_update` never re-runs them (their fills ride+//! `notify_filled`). `on_update` also mirrors `local_content`, but that only+//! re-dims the diff tabs' tab-bar number — chrome the user can wait a keystroke+//! for, never worth a scroll reset.+//! - **`pr` tab** — body renders every shown `PrStatus` field, so it re-runs on+//! any real change. The collect handler excludes `is_priming` (a list-cell dim+//! hint the pane never draws — see `items::pr_status_pane_eq`) so a+//! cache-prime→live flip that only clears it doesn't reset scroll.+//! - **`comments` tab** — body is the branch-keyed thread (surfaced by+//! `notify_filled`), invariant to `PrStatus` fields once a PR exists, so it+//! re-runs only on a [`PrPresence`](super::items::PrPresence) change+//! (Loading/NoPr/HasPr), not on every field.+//!+//! The collect handler computes those two change signals and passes them as a+//! [`PrStatusDelta`]; this notifier maps the awaited tab to the one it cares+//! about.//!//! ## Why recording happens before the cache read//!@@ -43,6 +66,22 @@ use tokio::sync::mpsc::Sender;use super::items::PreviewCacheKey;use super::preview::PreviewMode;+/// What about a row's live `pr_status` changed, at the granularity each+/// `pr_status`-backed tab's body cares about. The collect handler computes both+/// from the old and new slot values; [`PreviewNotifier::notify_pr_status_changed`]+/// reads the one matching the visible tab.+#[derive(Debug, Clone, Copy)]+pub(super) struct PrStatusDelta {+ /// The rendered `pr` pane would differ — any shown field changed (CI badge,+ /// title, body, review, …), ignoring the `is_priming` dim hint the pane+ /// never draws. Gates the `pr` tab. See `items::pr_status_pane_eq`.+ pub(super) pane_changed: bool,+ /// The [`PrPresence`](super::items::PrPresence) (Loading/NoPr/HasPr) changed.+ /// Gates the `comments` tab, whose body is otherwise the branch-keyed thread+ /// surfaced by [`PreviewNotifier::notify_filled`]. Implies `pane_changed`.+ pub(super) presence_changed: bool,+}+/// Bridges a background [`PreviewCache`](super::items::PreviewCache) fill to/// skim's event loop. See the module docstring for the full contract.///@@ -91,21 +130,25 @@ impl PreviewNotifier {}}- /// Inject an `Event::RunPreview` if the selected row is `row_key` on *any*- /// tab, so a change to that row's live data re-renders its preview without a- /// keystroke. Unlike [`Self::notify_filled`] this matches the row regardless- /// of mode, because the data it covers feeds several panes at once: the- /// collect handler's `on_update` mirrors the live `pr_status` (the `pr` /- /// `comments` panes) and `local_content` (the diff tabs' dim state), none of- /// which is an orchestrator cache fill.- pub(super) fn notify_row_changed(&self, row_key: &str) {- if self- .awaiting- .lock()- .unwrap()- .as_ref()- .is_some_and(|(k, _)| k == row_key)- {+ /// Inject an `Event::RunPreview` if the selected row is `row_key` *and* the+ /// part of `pr_status` its visible tab renders actually changed, so the live+ /// `CiStatus` fetch surfaces on its own without resetting the scroll of an+ /// unchanged pane. `delta` carries the two per-tab change signals the collect+ /// handler computed (see [`PrStatusDelta`]); a diff / log / summary tab reads+ /// neither, so it matches nothing and injects nothing.+ pub(super) fn notify_pr_status_changed(&self, row_key: &str, delta: PrStatusDelta) {+ let relevant = {+ let awaiting = self.awaiting.lock().unwrap();+ awaiting.as_ref().is_some_and(|(k, mode)| {+ k == row_key+ && match mode {+ PreviewMode::Pr => delta.pane_changed,+ PreviewMode::Comments => delta.presence_changed,+ _ => false,+ }+ })+ };+ if relevant {self.poke();}}@@ -131,33 +174,71 @@ impl PreviewNotifier {mod tests {use super::*;- /// `notify_row_changed` re-runs the selected row's preview on *any* tab when- /// that row's live data lands (the `on_update` path), and stays silent for- /// other rows — so a CI-status / diff-content update surfaces on the visible- /// row without thrashing off-screen ones. (`notify_filled`'s exact-key- /// scoping is covered by the orchestrator's `fill_notifies_only_awaited_key`.)+ /// `notify_pr_status_changed` re-runs the selected row's preview only when+ /// the *visible* tab's own change signal fired: the `pr` tab on a pane+ /// change, the `comments` tab on a presence change, and never a diff tab.+ /// It stays silent for other rows. (`notify_filled`'s exact-key scoping is+ /// covered by `fill_notifies_only_awaited_key`.)#[test]- fn notify_row_changed_pokes_only_the_selected_row() {+ fn notify_pr_status_changed_pokes_only_the_visible_tabs_signal() {let (tx, mut rx) = tokio::sync::mpsc::channel::<Event>(8);let render_tx = Arc::new(OnceLock::new());render_tx.set(tx).unwrap();let notifier = PreviewNotifier::new(render_tx);- // The selected row is on the `pr` tab (still "Fetching PR status…").+ let pane_only = PrStatusDelta {+ pane_changed: true,+ presence_changed: false,+ };+ let presence_too = PrStatusDelta {+ pane_changed: true,+ presence_changed: true,+ };+ let drain = |rx: &mut tokio::sync::mpsc::Receiver<Event>| {+ let mut n = 0;+ while let Ok(Event::RunPreview) = rx.try_recv() {+ n += 1;+ }+ n+ };++ // `pr` tab: any pane change re-runs it (e.g. "Fetching…" → resolved PR).notifier.note_awaiting("feature", PreviewMode::Pr);+ notifier.notify_pr_status_changed("feature", pane_only);+ assert_eq!(drain(&mut rx), 1, "a pr-pane change re-runs the pr tab");- // That row's CI status lands → re-run, even though the awaited tab (Pr)- // isn't an orchestrator-filled mode.- notifier.notify_row_changed("feature");- assert!(- matches!(rx.try_recv(), Ok(Event::RunPreview)),- "the selected row's update re-runs its preview"+ // `comments` tab: a pane-only change (no presence flip) does NOT re-run —+ // its body is the unchanged branch-keyed thread, so re-running would only+ // reset the scroll. A presence change (e.g. NoPr → HasPr) does re-run.+ notifier.note_awaiting("feature", PreviewMode::Comments);+ notifier.notify_pr_status_changed("feature", pane_only);+ assert_eq!(+ drain(&mut rx),+ 0,+ "a pane-only change must not reset a scrolled comments thread"+ );+ notifier.notify_pr_status_changed("feature", presence_too);+ assert_eq!(+ drain(&mut rx),+ 1,+ "a presence change re-runs the comments tab"+ );++ // A diff tab reads neither signal → never re-runs (preserves diff scroll).+ notifier.note_awaiting("feature", PreviewMode::WorkingTree);+ notifier.notify_pr_status_changed("feature", presence_too);+ assert_eq!(+ drain(&mut rx),+ 0,+ "a CI update while a diff tab is showing must not reset its scroll");// A different row's update injects nothing.- notifier.notify_row_changed("other");- assert!(- rx.try_recv().is_err(),+ notifier.note_awaiting("feature", PreviewMode::Pr);+ notifier.notify_pr_status_changed("other", presence_too);+ assert_eq!(+ drain(&mut rx),+ 0,"an off-screen row's update doesn't thrash the visible preview");}diff --git a/src/commands/picker/progressive_handler.rs b/src/commands/picker/progressive_handler.rsindex c892a8705..68a3a8d1f 100644--- a/src/commands/picker/progressive_handler.rs+++ b/src/commands/picker/progressive_handler.rs@@ -54,9 +54,10 @@ const RENDER_THROTTLE: Duration = Duration::from_millis(16);use super::items::{HeaderLoading, HeaderSkimItem, LayoutSlot, LocalCheckout, LocalContent, LocalContentSlot,MorphHandle, PickerRow, PrStatusSlot, PreviewCache, RowShortcutData, RowUrl, ShortcutTable,- worktree_output_token,+ pr_presence, pr_status_pane_eq, worktree_output_token,};use super::preview::PreviewMode;+use super::preview_notify::PrStatusDelta;use super::preview_orchestrator::PreviewOrchestrator;use crate::commands::list::collect::PickerProgressHandler;use crate::commands::list::model::{BranchScope, ItemKind, ListItem};@@ -500,13 +501,29 @@ impl PickerProgressHandler for PickerHandler {{*slot.lock().unwrap() = strip_osc8_hyperlinks(&rendered);}- // Mirror the row's current CI status into its live slot so the `pr`- // tab reflects the fetch as it lands. Cheap clone; `pr_status` is- // `None` until the CiStatus task reports, then `Some(..)`.+ // Mirror the row's current CI status into its live slot so the `pr` /+ // `comments` tabs reflect the fetch as it lands. Track change at the+ // granularity each tab's body reads (see `PrStatusDelta`): `pane_changed`+ // (any field the `pr` pane draws, ignoring the `is_priming` dim hint it+ // doesn't) gates the slot write, the `pr` cache eviction, and the `pr`+ // tab re-render; `presence_changed` (Loading/NoPr/HasPr) gates only the+ // `comments` re-render. An unchanged-pane update touches nothing — a+ // re-render would just reset the preview scroll.+ let mut delta = PrStatusDelta {+ pane_changed: false,+ presence_changed: false,+ };if let Some(slots) = self.pr_status_slots.get()&& let Some(slot) = slots.get(idx){- *slot.lock().unwrap() = item.pr_status.clone();+ let mut slot = slot.lock().unwrap();+ delta.pane_changed = !pr_status_pane_eq(&slot, &item.pr_status);+ delta.presence_changed = pr_presence(&slot) != pr_presence(&item.pr_status);+ if delta.pane_changed {+ *slot = item.pr_status.clone();+ }+ }+ if delta.pane_changed {// Drop the memoized `pr` pane for this row so the next `preview()`// re-renders from the status just mirrored — see// `PickerRow::render_pr_pane_cached`.@@ -528,15 +545,20 @@ impl PickerProgressHandler for PickerHandler {self.maybe_spawn_comments(idx, item.branch_name(), &item.pr_status);// `request_render` sends `Event::Render`, which repaints the *list* row// (its CI/status cells just changed) but does NOT re-run the preview.- // The slots just mirrored — `pr_status` (the `pr` / `comments` panes) and- // `local_content` (the diff tabs' dim state) — feed the preview, so if- // this is the selected row also poke a `RunPreview` to re-render it:- // that's what flips its `pr` tab from "Fetching PR status…" to the- // resolved PR without a keystroke. Scoped to the selected row, so- // off-screen updates don't thrash the preview (see `PreviewNotifier`).- self.orchestrator- .notifier()- .notify_row_changed(item.branch_name());+ // When the `pr` pane changed, poke a `RunPreview` so the selected row's+ // `pr` / `comments` tab flips from "Fetching PR status…" to the resolved+ // PR without a keystroke. The notifier scopes the poke to the selected+ // row and to the visible tab's own change signal, so neither an+ // off-screen update nor a CI fetch landing while the user scrolls a diff+ // (or an unchanged `comments` thread) thrashes the preview — each would+ // reset its scroll (see `PreviewNotifier`). The `local_content` mirror+ // above feeds only the diff tabs' tab-bar dim, which refreshes on the+ // next selection change or tab switch rather than re-running here.+ if delta.pane_changed {+ self.orchestrator+ .notifier()+ .notify_pr_status_changed(item.branch_name(), delta);+ }self.request_render(false);}@@ -784,13 +806,17 @@ mod tests {/// re-renders from the new status without a keystroke. This is the loop the/// orchestrator-fill path can't close — `on_update` isn't a cache fill, so it/// can't ride `PreviewOrchestrator::fill`'s notify; the poke is wired- /// separately here. Scoped to the selected row: an update for a row the- /// cursor isn't on repaints the list (`Event::Render`) but must not re-run- /// the visible preview. Fast producer-site guard for that wiring; the- /// end-to-end path is also covered by the PTY test- /// `test_switch_picker_pr_tab_auto_resolves_from_fetching`.+ /// separately here. It re-runs only when the *visible* tab's body would+ /// differ: an update for a row the cursor isn't on, while a diff tab shows,+ /// for an unchanged status, or for an `is_priming`-only flip (which the+ /// `pr` / `comments` panes don't draw) repaints the list (`Event::Render`)+ /// but must not re-run the preview — a re-run resets its scroll. Fast+ /// producer-site guard for that wiring; the end-to-end path is also covered+ /// by the PTY test `test_switch_picker_pr_tab_auto_resolves_from_fetching`.#[test]- fn on_update_pokes_run_preview_for_the_selected_row() {+ fn on_update_pokes_run_preview_only_when_the_visible_pane_changes() {+ use crate::commands::list::ci_status::{CiSource, CiStatus, PrRef, PrStatus};+let (handler, _test, rx) = make_handler();// Publish skim's event sender (shared with the orchestrator's notifier,// as in production) so both the list redraw and the preview re-run land@@ -806,9 +832,30 @@ mod tests {);let _ = rx.recv(); // drain the skeleton batch- // A live-status change for the row: CI reported "no PR".- let mut updated = ListItem::new_branch("aaa".into(), "feature".into());- updated.pr_status = Some(None);+ // A worktree row carrying PR #7, with `is_priming` and `ci_status`+ // controllable so the test can vary just one field at a time.+ let row = |is_priming: bool, ci_status: CiStatus| {+ let mut item = ListItem::new_branch("aaa".into(), "feature".into());+ item.pr_status = Some(Some(PrStatus {+ ci_status,+ 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,+ }));+ item+ };+ let no_pr = || {+ let mut item = ListItem::new_branch("aaa".into(), "feature".into());+ item.pr_status = Some(None);+ item+ };let run_previews = |rx: &mut tokio::sync::mpsc::Receiver<Event>| {let mut n = 0;@@ -819,28 +866,81 @@ mod tests {}n};+ let await_tab = |mode| {+ handler+ .orchestrator+ .notifier()+ .note_awaiting("feature", mode)+ };- // Cursor is on `feature`'s `pr` tab (still loading) → its CI update- // re-runs the preview.- handler- .orchestrator- .notifier()- .note_awaiting("feature", PreviewMode::Pr);- handler.on_update(0, "r".into(), &updated);+ // Cursor on `feature`'s `pr` tab (still loading). The CI fetch lands as a+ // cache-prime placeholder → the pane resolves, so it re-runs.+ await_tab(PreviewMode::Pr);+ handler.on_update(0, "r".into(), &row(true, CiStatus::Passed));assert!(run_previews(&mut render_rx) >= 1,- "the selected row's CI update re-runs its preview"+ "the selected row's first CI report re-runs its pr tab"+ );++ // The live fetch overwrites the prime, clearing only `is_priming`. The+ // pr pane never draws that hint, so the body is byte-identical — it must+ // NOT re-run and reset the scroll of the PR body the user is reading.+ await_tab(PreviewMode::Pr);+ handler.on_update(0, "r".into(), &row(false, CiStatus::Passed));+ assert_eq!(+ run_previews(&mut render_rx),+ 0,+ "an is_priming-only flip leaves the pr pane unchanged — no scroll reset"+ );++ // A real field the pane shows (the CI badge) changes → re-run.+ await_tab(PreviewMode::Pr);+ handler.on_update(0, "r".into(), &row(false, CiStatus::Failed));+ assert_eq!(+ run_previews(&mut render_rx),+ 1,+ "a changed CI badge re-runs the pr tab"+ );++ // Cursor on the `comments` tab: a pr-field change that keeps the PR+ // present (#7, badge flips back) leaves the branch-keyed thread+ // unchanged, so it must NOT re-run a scrolled thread.+ await_tab(PreviewMode::Comments);+ handler.on_update(0, "r".into(), &row(false, CiStatus::Passed));+ assert_eq!(+ run_previews(&mut render_rx),+ 0,+ "a pane-only change must not reset a scrolled comments thread"+ );++ // A presence change (#7 → no PR) flips the comments body, so it re-runs.+ await_tab(PreviewMode::Comments);+ handler.on_update(0, "r".into(), &no_pr());+ assert_eq!(+ run_previews(&mut render_rx),+ 1,+ "a presence change re-runs the comments tab"+ );++ // Cursor on a diff tab: a real status change (a PR surfaces again) feeds+ // the tab bar's dim but not the diff body, so it must NOT re-run.+ await_tab(PreviewMode::WorkingTree);+ handler.on_update(0, "r".into(), &row(false, CiStatus::Passed));+ assert_eq!(+ run_previews(&mut render_rx),+ 0,+ "a CI update while a diff tab is showing must not reset its scroll");- // Cursor is on a different row → `feature`'s update must not re-run the- // preview the cursor is showing (no thrash). `request_render`'s throttle- // may swallow the `Event::Render` too, but the `RunPreview` poke is- // unthrottled, so its absence is the meaningful signal.+ // Cursor on a different row → `feature`'s update must not re-run the+ // preview the cursor is showing. `request_render`'s throttle may swallow+ // the `Event::Render` too, but the `RunPreview` poke is unthrottled, so+ // its absence is the meaningful signal.handler.orchestrator.notifier().note_awaiting("other", PreviewMode::Pr);- handler.on_update(0, "r".into(), &updated);+ handler.on_update(0, "r".into(), &no_pr());assert_eq!(run_previews(&mut render_rx),0,