Batch native scrollback replays during history refill (#64005)

## Why

Refilling terminal scrollback can take several history pages. Replaying
scrollback after each page rebuilds it while more history is still loading.

## What changed

Buffer older pages while the next page is loading, then replay them together
when the refill finishes. Flush buffered history if a page request fails,
the transcript overlay opens during the refill, or the five-second deadline
from the first buffered page expires. The overlay still updates page by page.

## Testing

Extend the scrollback refill test to cover batching across pages, replay
after a page failure, and replay at the deadline with a request still pending.

GitOrigin-RevId: 577b9f7394e2741267099e4595f69345a6a70a21
This commit is contained in:
Eric Traut
2026-11-25 22:48:50 +00:00
committed by copyberry
parent 9b6a7e3d0e
commit 897d47ac95
5 changed files with 100 additions and 21 deletions
+3
View File
@@ -611,6 +611,9 @@ impl App {
app_server.cancel_older_history_page(thread_id, &cursor);
if self.chat_widget.thread_id() == Some(thread_id) {
self.transcript_view.history = TranscriptHistoryState::Failed;
if self.transcript_reflow.refill_deadline.is_some() {
self.transcript_reflow.schedule_immediate();
}
if let Some(Overlay::Transcript(overlay)) = self.overlay.as_mut() {
overlay.set_history_state(TranscriptHistoryState::Failed);
}
+16 -2
View File
@@ -18,6 +18,8 @@ use codex_app_server_protocol::ThreadItemsListResponse;
#[path = "history_completion.rs"]
mod completion;
const SCROLLBACK_REFILL_MAX_WAIT: Duration = Duration::from_secs(5);
impl App {
/// Start one bounded page request shared by scrollback refill and the transcript overlay.
pub(crate) fn request_older_history_page(
@@ -472,7 +474,7 @@ impl App {
tui.frame_requester().schedule_frame();
}
/// Preserve the legacy overlay and inline scrollback refill behavior.
/// Update the overlay per page and batch native scrollback replays.
fn finish_inline_history_page(
&mut self,
tui: &mut tui::Tui,
@@ -489,18 +491,30 @@ impl App {
});
continue_to_start = previous_state == TranscriptHistoryState::LoadingBeginning
&& self.scrollback_has_older_history;
// Finish a deferred refill if the overlay opened between pages.
if self.transcript_reflow.refill_deadline.take().is_some() {
self.schedule_immediate_resize_reflow(tui);
}
} else {
let wrap_width = self.chat_widget.history_wrap_width(width);
let rendered_rows = self
.render_transcript_lines_for_reflow(wrap_width)
.lines
.len();
self.schedule_immediate_resize_reflow(tui);
if self.scrollback_history_needs_top_up(rendered_rows)
&& self.request_older_history_page(app_server, thread_id)
{
// Bound the wait from the first buffered page, even if later requests stall.
if self.transcript_reflow.refill_deadline.is_none() {
self.transcript_reflow.refill_deadline =
Some(Instant::now() + SCROLLBACK_REFILL_MAX_WAIT);
tui.frame_requester()
.schedule_frame_in(SCROLLBACK_REFILL_MAX_WAIT);
}
return;
}
self.transcript_reflow.refill_deadline = None;
self.schedule_immediate_resize_reflow(tui);
}
if continue_to_start
&& self.request_older_history_page(app_server, thread_id)
+13 -2
View File
@@ -471,7 +471,13 @@ impl App {
self.discard_scrollback_render_work(tui);
return Ok(());
}
let Some(deadline) = self.transcript_reflow.pending_until() else {
let Some(deadline) = self
.transcript_reflow
.pending_until()
.into_iter()
.chain(self.transcript_reflow.refill_deadline)
.min()
else {
return Ok(());
};
let now = Instant::now();
@@ -519,6 +525,7 @@ impl App {
tui.frame_requester().schedule_frame();
return Ok(terminal_width);
}
let flushing_refill = self.transcript_reflow.refill_deadline.take().is_some();
let width = self.chat_widget.history_wrap_width(terminal_width.0);
if self.transcript_cells.is_empty() {
// Drop any queued pre-resize/pre-consolidation inserts before rebuilding from cells.
@@ -558,7 +565,10 @@ impl App {
if self.pending_thread_usage_history_refresh {
self.refresh_thread_usage_history_tail(tui)?;
}
self.request_scrollback_history_top_up(reflowed_rows);
// When flushing a partial refill, the next request is in flight or just failed.
if !flushing_refill {
self.request_scrollback_history_top_up(reflowed_rows);
}
Ok(terminal_width)
}
@@ -607,6 +617,7 @@ impl App {
return Ok(());
}
self.native_history.replayed();
self.transcript_reflow.refill_deadline = None;
let width = self.chat_widget.history_wrap_width(terminal_width.0);
let reflowed_lines = if self.transcript_cells.is_empty() {
self.reset_history_emission_state();
@@ -5071,7 +5071,7 @@ async fn underfilled_scrollback_fetches_older_pages_without_opening_the_transcri
model_context_window: None,
collaboration_mode_kind: Default::default(),
}))
.chain((0..120).map(|index| {
.chain((0..420).map(|index| {
EventMsg::ItemCompleted(ItemCompletedEvent {
content_token_count: None,
thread_id,
@@ -5144,7 +5144,7 @@ async fn underfilled_scrollback_fetches_older_pages_without_opening_the_transcri
.await?;
app.transcript_cells = initial_cells;
app.scrollback_has_older_history = app_server.has_older_history(thread_id);
app.local_settings.tui.terminal_resize_reflow_max_rows = Some(32);
app.local_settings.tui.terminal_resize_reflow_max_rows = Some(650);
let initial_cell_count = app.transcript_cells.len();
let initial_page_requests = recorded_params(&requests, "thread/items/list").len();
let mut tui = crate::tui::test_support::make_test_tui()?;
@@ -5206,27 +5206,76 @@ async fn underfilled_scrollback_fetches_older_pages_without_opening_the_transcri
};
// Keep the large dispatcher future off the Windows test thread's stack.
Box::pin(app.handle_event(&mut tui, &mut app_server, request)).await?;
let loaded = loop {
match app_event_rx.recv().await {
Some(event @ AppEvent::OlderThreadHistoryLoaded { .. }) => break event,
Some(_) => {}
None => panic!("older history page channel closed"),
// Fail the second page, retry it, then hold the next response past the replay deadline.
let size = tui.terminal.last_known_screen_size;
for attempt in 1..=5 {
let mut loaded = loop {
match app_event_rx.recv().await {
Some(event @ AppEvent::OlderThreadHistoryLoaded { .. }) => break event,
Some(_) => {}
None => panic!("older history page channel closed"),
}
};
if attempt == 2
&& let AppEvent::OlderThreadHistoryLoaded { result, .. } = &mut loaded
{
*result = Err("page unavailable".to_string());
}
};
Box::pin(app.handle_event(&mut tui, &mut app_server, loaded)).await?;
Box::pin(app.handle_event(&mut tui, &mut app_server, loaded)).await?;
assert_eq!(
app.transcript_reflow.has_pending_reflow(),
matches!(attempt, 2 | 5),
"after page request {attempt}"
);
if attempt == 3 {
*app.transcript_reflow
.refill_deadline
.as_mut()
.expect("buffered page") = Instant::now();
}
if matches!(attempt, 2 | 3) {
app.maybe_run_resize_reflow(&mut tui, size)?;
let oldest = tui
.pending_history_lines_for_test()
.into_iter()
.map(|row| row.line.to_string())
.find(|line| line.contains("scrollback output"))
.expect("queued history");
if attempt == 2 {
insta::assert_snapshot!(oldest, @"• scrollback output 312");
while let Ok(event) = app_event_rx.try_recv() {
assert!(!matches!(
event,
AppEvent::RequestOlderScrollbackHistory { .. }
));
}
assert!(app.request_older_history_page(&mut app_server, thread_id));
} else {
insta::assert_snapshot!(oldest, @"• scrollback output 212");
assert!(app_server.pending_older_history_cursor(thread_id).is_some());
}
}
}
assert!(app.overlay.is_none());
assert!(app.transcript_cells.len() > initial_cell_count);
assert_eq!(app.transcript_cells.len(), initial_cell_count + 400);
assert_eq!(
recorded_params(&requests, "thread/items/list").len(),
initial_page_requests + 1
);
assert_eq!(
app.render_transcript_lines_for_reflow(/*width*/ 80)
.lines
.len(),
32
initial_page_requests + 5
);
app.maybe_run_resize_reflow(&mut tui, size)?;
let queued = tui.pending_history_lines_for_test();
assert_eq!(queued.len(), 650);
let oldest_rows = queued[..4]
.iter()
.map(|row| row.line.to_string())
.collect::<Vec<_>>();
insta::assert_snapshot!(oldest_rows.join("\n"), @"
Earlier messages are available — press ⌃t to view the full transcript
• scrollback output 95
• scrollback output 96
");
app_server.shutdown().await?;
proxy.await??;
+2
View File
@@ -25,6 +25,8 @@ pub(crate) const TRANSCRIPT_REFLOW_DEBOUNCE: Duration = Duration::from_millis(75
/// final rebuild instead of assuming the latest observed size has already been repaired.
#[derive(Debug, Default)]
pub(crate) struct TranscriptReflowState {
/// Latest replay time for older pages buffered while another page is fetched.
pub(crate) refill_deadline: Option<Instant>,
last_observed_width: Option<u16>,
last_reflow_width: Option<u16>,
pending_reflow_width: Option<u16>,