Batch mouse wheel scrolling in the TUI (#62146)

## Why

Rapid wheel input can trigger a synchronous transcript redraw for each tick, even when the current layout can still be used.

## What changed

Accumulate wheel movement in the main transcript and side panes until the next frame when the rendered layout is safe to reuse. Refresh first when the transcript has changed, cached content can change height, or the side pane has buffered reply text. Refresh immediately when toggling side-pane zoom so subsequent mouse events use the new layout.

Start composer scrolling from the caret-adjusted viewport after an edit so wheel ticks can accumulate before the next frame.

## Testing

Cover wheel bursts while the plan menu is open, composer scrolling after edits, refresh requirements for mutable history and buffered side replies, and immediate layout updates when toggling side-pane zoom.

GitOrigin-RevId: 342d4d4c014d8a41b2e690b91622197ee97fc059
This commit is contained in:
Benjamin Carlsson
2026-11-18 00:58:27 +00:00
committed by copyberry
parent 67d8266e06
commit 2f5c413e19
12 changed files with 157 additions and 19 deletions
+9 -1
View File
@@ -12,6 +12,7 @@ use crossterm::event::MouseEventKind::ScrollUp;
use crossterm::event::MouseEventKind::Up;
use super::App;
use super::side_companion::SideCompanion;
use crate::transcript_view::ViewAction;
use crate::tui::PointerShape;
use crate::tui::Tui;
@@ -107,7 +108,14 @@ impl App {
TuiEvent::Mouse(mouse)
if matches!(mouse.kind, Drag(Left) | Up(Left) | ScrollUp | ScrollDown) =>
{
self.refresh_owned_transcript(tui)?;
if !matches!(mouse.kind, ScrollUp | ScrollDown)
|| !self
.side_companions
.get(&id)
.is_some_and(SideCompanion::can_scroll_without_refresh)
{
self.refresh_owned_transcript(tui)?;
}
if self
.conversation_frame
.side_pane()
+18 -1
View File
@@ -1009,7 +1009,24 @@ impl App {
}
if let TuiEvent::Mouse(mouse) = event {
let composer_ready = self.chat_widget.prepare_composer_mouse(*mouse);
if mouse.kind != crossterm::event::MouseEventKind::Moved {
// Apply wheel bursts against painted geometry and schedule their accumulated movement.
let wheel_ready = is_vertical_wheel && {
let passive = self
.conversation_frame
.side_pane()
.filter(|panes| panes.passive.contains((mouse.column, mouse.row).into()));
if let Some(pane) =
passive.and_then(|panes| self.side_companions.get(&panes.passive_thread))
{
pane.can_scroll_without_refresh()
} else {
self.transcript_view.can_scroll_without_refresh(
&self.transcript_cells,
self.chat_widget.active_cell_transcript_key(),
)
}
};
if mouse.kind != MouseEventKind::Moved && !wheel_ready {
self.refresh_owned_transcript(tui)?;
}
if self
@@ -322,18 +322,24 @@ async fn plan_menu_allows_transcript_wheel_scrolling_and_keeps_keyboard_ownershi
let bottom = app.render_owned_transcript(&mut tui, size)?;
let latest = screen(&tui);
let menu = render_bottom_popup(&app.chat_widget, /*width*/ 80);
for kind in [
MouseEventKind::ScrollUp,
MouseEventKind::ScrollDown,
MouseEventKind::ScrollUp,
let mut screens = Vec::new();
for (kind, ticks) in [
(MouseEventKind::ScrollUp, 2),
(MouseEventKind::ScrollDown, 2),
(MouseEventKind::ScrollUp, 1),
] {
app.handle_tui_event(
&mut tui,
&mut server,
pointer_event(kind, /*column*/ 1, /*row*/ 1),
)
.await?;
let painted = screen(&tui);
for _ in 0..ticks {
app.handle_tui_event(
&mut tui,
&mut server,
pointer_event(kind, /*column*/ 1, /*row*/ 1),
)
.await?;
assert_eq!(screen(&tui), painted);
}
app.render_owned_transcript(&mut tui, size)?;
screens.push(screen(&tui));
assert_eq!(render_bottom_popup(&app.chat_widget, /*width*/ 80), menu);
if kind == MouseEventKind::ScrollDown {
assert_eq!(screen(&tui), latest);
@@ -344,6 +350,7 @@ async fn plan_menu_allows_transcript_wheel_scrolling_and_keeps_keyboard_ownershi
}
}
let scrolled = screen(&tui);
assert_ne!(screens[0], scrolled);
if close == KeyCode::Esc {
insta::assert_snapshot!("plan_prompt_scrolled", scrolled);
}
+13
View File
@@ -50,6 +50,15 @@ impl SideAnswer {
}
impl SideCompanion {
pub(super) fn can_scroll_without_refresh(&self) -> bool {
self.answer
.as_ref()
.is_none_or(|answer| answer.pending.is_empty())
&& self
.view
.can_scroll_without_refresh(&self.cells, /*live_key*/ None)
}
pub(super) fn empty(cwd: AbsolutePathBuf) -> Self {
Self {
display: CapturedSideDisplay {
@@ -321,3 +330,7 @@ impl SideCompanion {
}
}
}
#[cfg(test)]
#[path = "side_companion_tests.rs"]
mod tests;
@@ -0,0 +1,27 @@
#![cfg(test)]
use super::*;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
#[test]
fn buffered_answer_requires_a_paint_before_wheel_input() {
let cwd = AbsolutePathBuf::try_from(std::env::current_dir().unwrap()).unwrap();
let mut pane = SideCompanion::empty(cwd);
let area = Rect::new(
/*x*/ 0, /*y*/ 0, /*width*/ 20, /*height*/ 4,
);
pane.view
.render(area, &mut Buffer::empty(area), &pane.cells);
assert!(pane.can_scroll_without_refresh());
let mut answer = SideAnswer::new(("turn".into(), "item".into()), /*index*/ 0);
answer.pending = "new reply".into();
pane.answer = Some(answer);
assert!(!pane.can_scroll_without_refresh());
pane.flush_answer();
pane.view
.render(area, &mut Buffer::empty(area), &pane.cells);
assert!(pane.can_scroll_without_refresh());
}
+1 -1
View File
@@ -749,7 +749,7 @@ impl App {
} else if let Some(target) = zoom_target {
self.zoomed_thread = (self.zoomed_thread != Some(target)).then_some(target);
tui.frame_requester().schedule_frame();
Ok(())
self.refresh_owned_transcript(tui)
} else if panel_focus.is_some() {
if hide || (sidebar && panel_focus == Some(PaneFocus::Sidebar)) {
self.zoomed_thread = None;
+2
View File
@@ -4991,8 +4991,10 @@ async fn handle_start_side_seeds_navigation_before_thread_started() -> Result<()
}
let zoom = KeyEvent::from(KeyCode::Char('z'));
keys!(prefix, zoom);
assert!(app.conversation_frame.side_pane().is_none());
let zoomed = side_frame(&mut app, &mut tui, wide)?;
keys!(prefix, zoom);
assert!(app.conversation_frame.side_pane().is_some());
let restored = side_frame(&mut app, &mut tui, wide)?;
assert_eq!(divider_at(&tui, 0), 197);
keys!(prefix, zoom);
@@ -86,12 +86,12 @@ impl TextArea {
if lines.len() <= height {
return false;
}
let scroll = state
.scroll
let baseline = self.effective_scroll(area, &lines, *state);
let scroll = baseline
.saturating_add_signed(isize::from(rows))
.min(lines.len() - height);
if scroll != state.scroll {
state.scroll = scroll;
state.scroll = scroll;
if scroll != baseline {
state.manual_cursor = Some(self.cursor_pos);
}
true
@@ -84,6 +84,34 @@ fn wheel_at_edges_preserves_caret_following_or_browsing_after_resize() {
insta::assert_snapshot!("wheel_at_edges_after_resize", frames.join("\n\n"));
}
#[test]
fn wheel_after_edit_starts_at_the_caret_and_accumulates_without_painting() {
let area = Rect::new(
/*x*/ 0, /*y*/ 0, /*width*/ 12, /*height*/ 3,
);
let up = MouseEvent {
kind: MouseEventKind::ScrollUp,
column: area.x,
row: area.y,
modifiers: KeyModifiers::NONE,
};
let mut t = TextArea::new();
t.insert_str("one\ntwo\nthree\nfour\nfive");
let mut state = TextAreaState::default();
render(&t, area, &mut state);
assert!(t.scroll_mouse(up, &mut state));
t.insert_str("\nsix\nseven\neight");
state.follow_cursor();
let mut painted = state;
render(&t, area, &mut painted);
for _ in 0..2 {
assert!(t.scroll_mouse(up, &mut state));
assert!(t.scroll_mouse(up, &mut painted));
}
assert_eq!(render(&t, area, &mut state), render(&t, area, &mut painted));
}
#[test]
fn mouse_click_maps_wrapping_unicode_tabs_and_empty_lines() {
let area = Rect::new(
+12 -2
View File
@@ -179,6 +179,17 @@ impl Default for TranscriptView {
}
impl TranscriptView {
pub(crate) fn can_scroll_without_refresh(
&self,
cells: &[Arc<dyn HistoryCell>],
live_key: Option<ActiveCellTranscriptKey>,
) -> bool {
!self.area.is_empty()
&& !self.cache.has_mutable_source()
&& self.last_tail == cells.last().map(EntryKey::cell)
&& self.live_key.map(|(_, key)| key) == live_key
}
/// Rows left after the last render, including all startup notices and live entries.
/// Callers can paint temporary UI here without changing selection or saved history.
pub(crate) fn remaining_area(&self) -> Rect {
@@ -688,8 +699,7 @@ impl TranscriptView {
}
// Anchor visible content, not a hidden header that stays ahead of every older page.
let index = self.next_nonempty(cells, index).unwrap_or(index);
let bottom = self.bottom_start(cells);
if rows > 0 && (index, row) >= bottom {
if rows > 0 && (index, row) >= self.bottom_start(cells) {
if self.selection.is_none() && !self.search.is_active() {
self.jump_to_latest();
} else {
@@ -325,6 +325,15 @@ impl TranscriptView {
}
impl LayoutCache {
pub(super) fn has_mutable_source(&self) -> bool {
self.entries.iter().any(|entry| {
entry
.source
.upgrade()
.is_some_and(|cell| !cell.has_stable_transcript_height())
})
}
pub(super) fn begin_frame(&mut self) {
self.frame = self.frame.wrapping_add(/*rhs*/ 1);
let state = RenderState {
+17
View File
@@ -983,6 +983,23 @@ impl HistoryCell for MutableHistoryCell {
}
}
#[test]
fn cached_mutable_history_prevents_reusing_painted_geometry() {
let mutable: Arc<dyn HistoryCell> = Arc::new(MutableHistoryCell {
version: Arc::new(AtomicUsize::new(/*v*/ 1)),
renders: Arc::default(),
});
let cells = vec![mutable, cell("static tail")];
let mut view = TranscriptView::default();
render(&mut view, &cells, /*width*/ 24, /*height*/ 16);
assert!(!view.can_scroll_without_refresh(&cells, /*live_key*/ None));
drop(cells);
let cells = vec![cell("static tail")];
render(&mut view, &cells, /*width*/ 24, /*height*/ 16);
assert!(view.can_scroll_without_refresh(&cells, /*live_key*/ None));
}
#[test]
fn mutable_history_formats_once_per_frame_and_refreshes_the_next_frame() {
let version = Arc::new(AtomicUsize::new(/*v*/ 1));