refactor(tui): simplify deferred history replay

This commit is contained in:
Felipe Coury
2026-06-05 12:48:51 -03:00
parent 85fd78fe6d
commit 3f49d7706b
6 changed files with 38 additions and 236 deletions
+3 -5
View File
@@ -471,11 +471,9 @@ struct SessionSummary {
resume_hint: Option<String>,
}
#[derive(Debug, Default)]
struct InitialHistoryReplayBuffer {
retained_lines: VecDeque<crate::terminal_hyperlinks::HyperlinkLine>,
render_from_transcript_tail: bool,
}
/// Marks replay whose terminal writes are deferred until `transcript_cells` is complete.
#[derive(Debug)]
struct InitialHistoryReplayBuffer;
pub(crate) struct App {
model_catalog: Arc<ModelCatalog>,
+3 -9
View File
@@ -197,13 +197,7 @@ impl App {
tui.frame_requester().schedule_frame();
}
self.transcript_cells.push(cell.clone());
if self.initial_history_replay_buffer.as_ref().is_some() {
self.insert_history_cell_lines_with_initial_replay_buffer(
cell.as_ref(),
self.chat_widget
.history_wrap_width(tui.terminal.last_known_screen_size.width),
);
} else {
if self.initial_history_replay_buffer.is_none() {
self.insert_history_cell_lines(
tui,
cell.as_ref(),
@@ -212,8 +206,8 @@ impl App {
);
}
}
AppEvent::EndInitialHistoryReplayBuffer => {
self.finish_initial_history_replay_buffer(tui);
AppEvent::EndHistoryReplay => {
self.finish_history_replay(tui);
}
AppEvent::ConsolidateAgentMessage {
source,
+19 -110
View File
@@ -113,107 +113,38 @@ impl App {
self.config.features.enabled(Feature::TerminalResizeReflow)
}
/// Start retaining initial resume replay rows before they are written to scrollback.
///
/// Resume replay can insert thousands of already-finalized history cells before the first draw.
/// When resize reflow is enabled, buffering here lets the same row cap used by resize rebuilds
/// apply to the startup write. Starting this buffer while an overlay owns rendering would split
/// transcript ownership, so overlay replay continues through the normal deferred-history path.
pub(super) fn begin_initial_history_replay_buffer(&mut self) {
/// Defer resume or thread-switch history writes until replay has rebuilt `transcript_cells`.
pub(super) fn begin_history_replay(&mut self) {
if self.terminal_resize_reflow_enabled() && self.overlay.is_none() {
self.transcript_reflow.clear_pending_reflow();
self.initial_history_replay_buffer = Some(Default::default());
self.initial_history_replay_buffer = Some(InitialHistoryReplayBuffer);
}
}
/// Start retaining a thread-switch transcript replay without rendering each historical cell.
///
/// Thread switches already rebuild `transcript_cells` from source. When a row cap exists, we can
/// defer terminal writes until the replay is complete and reuse the resize-reflow tail renderer
/// so only the rows the terminal would retain are formatted and inserted.
pub(super) fn begin_thread_switch_history_replay_buffer(&mut self) {
if self.terminal_resize_reflow_enabled() && self.overlay.is_none() {
self.transcript_reflow.clear_pending_reflow();
self.initial_history_replay_buffer = Some(InitialHistoryReplayBuffer {
retained_lines: VecDeque::new(),
render_from_transcript_tail: true,
});
}
}
/// Fold stream-consolidation repair into the source-backed render that ends startup replay.
pub(super) fn absorb_reflow_into_initial_history_replay(&mut self) -> bool {
let Some(buffer) = &mut self.initial_history_replay_buffer else {
/// Fold stream-consolidation repair into the source-backed render that ends history replay.
pub(super) fn absorb_reflow_into_history_replay(&mut self) -> bool {
if self.initial_history_replay_buffer.is_none() {
return false;
};
}
buffer.retained_lines.clear();
buffer.render_from_transcript_tail = true;
self.transcript_reflow.clear_pending_reflow();
self.transcript_reflow.clear_stream_flags();
true
}
/// Flush retained initial resume replay rows into terminal scrollback.
///
/// The buffer stores display lines, not cells, because the cap is measured in terminal rows.
/// This mirrors terminal scrollback behavior and avoids making startup replay cheaper or more
/// expensive than a later resize rebuild of the same transcript.
pub(super) fn finish_initial_history_replay_buffer(&mut self, tui: &mut tui::Tui) {
let Some(buffer) = self.initial_history_replay_buffer.take() else {
return;
};
if buffer.render_from_transcript_tail {
let width = tui.terminal.last_known_screen_size.width;
let reflowed_lines = self.render_transcript_lines_for_reflow(width).lines;
if !reflowed_lines.is_empty() {
tui.insert_history_hyperlink_lines_with_wrap_policy(
reflowed_lines,
self.history_line_wrap_policy(),
);
}
/// Render replayed history once from source after all replay events have been applied.
pub(super) fn finish_history_replay(&mut self, tui: &mut tui::Tui) {
if self.initial_history_replay_buffer.take().is_none() {
return;
}
if buffer.retained_lines.is_empty() {
return;
}
let retained_lines = buffer.retained_lines.into_iter().collect::<Vec<_>>();
tui.insert_history_hyperlink_lines_with_wrap_policy(
retained_lines,
self.history_line_wrap_policy(),
);
}
pub(super) fn insert_history_cell_lines_with_initial_replay_buffer(
&mut self,
cell: &dyn HistoryCell,
width: u16,
) {
if self
.initial_history_replay_buffer
.as_ref()
.is_some_and(|buffer| buffer.render_from_transcript_tail)
{
return;
}
let display = self.display_lines_for_history_insert(cell, width);
if display.is_empty() {
return;
}
let max_rows = self.resize_reflow_max_rows();
let overlay_active = self.overlay.is_some();
if let Some(buffer) = &mut self.initial_history_replay_buffer {
if overlay_active {
self.deferred_history_lines.extend(display);
} else {
Self::buffer_initial_history_replay_display_lines(buffer, display, max_rows);
}
let width = tui.terminal.last_known_screen_size.width;
let reflowed_lines = self.render_transcript_lines_for_reflow(width).lines;
if !reflowed_lines.is_empty() {
tui.insert_history_hyperlink_lines_with_wrap_policy(
reflowed_lines,
self.history_line_wrap_policy(),
);
}
}
@@ -225,24 +156,6 @@ impl App {
}
}
/// Retain only the newest rendered rows for initial resume replay.
///
/// The oldest rows are dropped first because terminal scrollback caps preserve the tail of the
/// transcript. Keeping this policy local to display lines is important: trimming source cells
/// here would make copy, transcript overlay, and future replay paths disagree about history.
pub(super) fn buffer_initial_history_replay_display_lines(
buffer: &mut InitialHistoryReplayBuffer,
display: Vec<HyperlinkLine>,
max_rows: Option<usize>,
) {
buffer.retained_lines.extend(display);
if let Some(max_rows) = max_rows {
while buffer.retained_lines.len() > max_rows {
buffer.retained_lines.pop_front();
}
}
}
fn schedule_resize_reflow(&mut self, target_width: Option<u16>) -> bool {
debug_assert!(self.terminal_resize_reflow_enabled());
self.transcript_reflow.schedule_debounced(target_width)
@@ -264,7 +177,7 @@ impl App {
self.transcript_reflow.clear();
return Ok(());
}
if self.absorb_reflow_into_initial_history_replay() {
if self.absorb_reflow_into_history_replay() {
return Ok(());
}
@@ -296,7 +209,7 @@ impl App {
self.transcript_reflow.clear();
return Ok(());
}
if self.absorb_reflow_into_initial_history_replay() {
if self.absorb_reflow_into_history_replay() {
return Ok(());
}
self.schedule_immediate_resize_reflow(tui);
@@ -328,10 +241,6 @@ impl App {
if width.changed || width.initialized {
self.chat_widget.on_terminal_resize(size.width);
}
if resize_requires_rebuild && let Some(buffer) = &mut self.initial_history_replay_buffer {
buffer.retained_lines.clear();
buffer.render_from_transcript_tail = true;
}
if should_rebuild_transcript {
if self.terminal_resize_reflow_enabled() {
if reflow_needed && self.should_mark_reflow_as_stream_time() {
+7 -104
View File
@@ -4019,103 +4019,18 @@ async fn uncapped_resize_reflow_renders_all_cells_under_row_limit() {
}
#[tokio::test]
async fn initial_replay_buffer_keeps_recent_rows_when_row_cap_present() {
let (mut app, _rx, _op_rx) = make_test_app_with_channels().await;
enable_terminal_resize_reflow(&mut app);
app.config.terminal_resize_reflow.max_rows = TerminalResizeReflowMaxRows::Limit(3);
app.begin_initial_history_replay_buffer();
for index in 0..5 {
App::buffer_initial_history_replay_display_lines(
app.initial_history_replay_buffer
.as_mut()
.expect("initial replay buffer active"),
vec![Line::from(format!("line {index}")).into()],
/*max_rows*/ Some(3),
);
}
let buffer = app
.initial_history_replay_buffer
.as_ref()
.expect("initial replay buffer should remain active");
assert_eq!(
buffer
.retained_lines
.iter()
.map(rendered_line_text)
.collect::<Vec<_>>(),
vec![
"line 2".to_string(),
"line 3".to_string(),
"line 4".to_string(),
]
);
}
#[tokio::test]
async fn thread_switch_replay_buffer_uses_transcript_tail_mode_when_row_cap_present() {
let (mut app, _rx, _op_rx) = make_test_app_with_channels().await;
enable_terminal_resize_reflow(&mut app);
app.config.terminal_resize_reflow.max_rows = TerminalResizeReflowMaxRows::Limit(3);
app.begin_thread_switch_history_replay_buffer();
let buffer = app
.initial_history_replay_buffer
.as_ref()
.expect("thread switch replay buffer should be active");
assert!(buffer.render_from_transcript_tail);
assert!(buffer.retained_lines.is_empty());
}
#[tokio::test]
async fn thread_switch_replay_buffer_uses_transcript_tail_without_row_cap() {
async fn history_replay_activates_without_row_cap() {
let (mut app, _rx, _op_rx) = make_test_app_with_channels().await;
enable_terminal_resize_reflow(&mut app);
app.config.terminal_resize_reflow.max_rows = TerminalResizeReflowMaxRows::Disabled;
app.begin_thread_switch_history_replay_buffer();
app.begin_history_replay();
let buffer = app
.initial_history_replay_buffer
.as_ref()
.expect("thread switch replay buffer should be active");
assert!(buffer.render_from_transcript_tail);
assert!(buffer.retained_lines.is_empty());
assert!(app.initial_history_replay_buffer.is_some());
}
#[tokio::test]
async fn uncapped_initial_replay_buffer_keeps_all_rows() {
let (mut app, _rx, _op_rx) = make_test_app_with_channels().await;
enable_terminal_resize_reflow(&mut app);
app.config.terminal_resize_reflow.max_rows = TerminalResizeReflowMaxRows::Disabled;
app.begin_initial_history_replay_buffer();
App::buffer_initial_history_replay_display_lines(
app.initial_history_replay_buffer
.as_mut()
.expect("initial replay buffer active"),
vec![Line::from("first").into(), Line::from("second").into()],
/*max_rows*/ None,
);
let buffer = app
.initial_history_replay_buffer
.as_ref()
.expect("initial replay buffer should remain active");
assert_eq!(
buffer
.retained_lines
.iter()
.map(rendered_line_text)
.collect::<Vec<_>>(),
vec!["first".to_string(), "second".to_string()]
);
}
#[tokio::test]
async fn initial_replay_defers_resize_reflow_and_switches_to_tail_render() {
async fn history_replay_defers_resize_and_consolidation_reflows() {
let (mut app, _rx, _op_rx) = make_test_app_with_channels().await;
enable_terminal_resize_reflow(&mut app);
app.config.terminal_resize_reflow.max_rows = TerminalResizeReflowMaxRows::Disabled;
@@ -4123,20 +4038,13 @@ async fn initial_replay_defers_resize_reflow_and_switches_to_tail_render() {
.schedule_debounced(/*target_width*/ Some(118));
assert!(app.transcript_reflow.has_pending_reflow());
app.begin_initial_history_replay_buffer();
app.begin_history_replay();
let frame_requester = crate::tui::FrameRequester::test_dummy();
assert!(!app.transcript_reflow.has_pending_reflow());
App::buffer_initial_history_replay_display_lines(
app.initial_history_replay_buffer
.as_mut()
.expect("initial replay buffer active"),
vec![Line::from("stale stream row").into()],
/*max_rows*/ None,
);
app.transcript_reflow
.schedule_debounced(/*target_width*/ Some(118));
assert!(app.absorb_reflow_into_initial_history_replay());
assert!(app.absorb_reflow_into_history_replay());
assert!(!app.transcript_reflow.has_pending_reflow());
assert!(!app.handle_draw_size_change(
ratatui::layout::Size::new(/*width*/ 118, /*height*/ 24),
@@ -4145,12 +4053,7 @@ async fn initial_replay_defers_resize_reflow_and_switches_to_tail_render() {
));
assert!(!app.transcript_reflow.has_pending_reflow());
let buffer = app
.initial_history_replay_buffer
.as_ref()
.expect("initial replay buffer should remain active");
assert!(buffer.render_from_transcript_tail);
assert!(buffer.retained_lines.is_empty());
assert!(app.initial_history_replay_buffer.is_some());
}
#[tokio::test]
+4 -6
View File
@@ -1074,13 +1074,12 @@ impl App {
let should_buffer_initial_replay =
self.terminal_resize_reflow_enabled() && !turns.is_empty();
if should_buffer_initial_replay {
self.begin_initial_history_replay_buffer();
self.begin_history_replay();
}
self.chat_widget
.replay_thread_turns(turns, ReplayKind::ResumeInitialMessages);
if should_buffer_initial_replay {
self.app_event_tx
.send(AppEvent::EndInitialHistoryReplayBuffer);
self.app_event_tx.send(AppEvent::EndHistoryReplay);
}
let pending = std::mem::take(&mut self.pending_primary_events);
for pending_event in pending {
@@ -1263,7 +1262,7 @@ impl App {
let should_buffer_replay = self.terminal_resize_reflow_enabled()
&& (!snapshot.turns.is_empty() || !snapshot.events.is_empty());
if should_buffer_replay {
self.begin_thread_switch_history_replay_buffer();
self.begin_history_replay();
}
let suppress_replay_notices =
replay_filter::snapshot_has_pending_interactive_request(&snapshot);
@@ -1291,8 +1290,7 @@ impl App {
self.handle_thread_event_replay(event);
}
if should_buffer_replay {
self.app_event_tx
.send(AppEvent::EndInitialHistoryReplayBuffer);
self.app_event_tx.send(AppEvent::EndHistoryReplay);
}
self.chat_widget
.set_queue_autosend_suppressed(/*suppressed*/ false);
+2 -2
View File
@@ -577,8 +577,8 @@ pub(crate) enum AppEvent {
InsertHistoryCell(Box<dyn HistoryCell>),
/// Finish buffering initial resume replay after all replay events have been queued.
EndInitialHistoryReplayBuffer,
/// Render deferred history after all resume or thread-switch replay events have been queued.
EndHistoryReplay,
/// Replace the contiguous run of streaming `AgentMessageCell`s at the end of
/// the transcript with a single `AgentMarkdownCell` that stores the raw