From 3f49d7706b1577f9d9378b3621ac1d264af4e147 Mon Sep 17 00:00:00 2001 From: Felipe Coury Date: Fri, 5 Jun 2026 12:48:51 -0300 Subject: [PATCH] refactor(tui): simplify deferred history replay --- codex-rs/tui/src/app.rs | 8 +- codex-rs/tui/src/app/event_dispatch.rs | 12 +-- codex-rs/tui/src/app/resize_reflow.rs | 129 ++++--------------------- codex-rs/tui/src/app/tests.rs | 111 ++------------------- codex-rs/tui/src/app/thread_routing.rs | 10 +- codex-rs/tui/src/app_event.rs | 4 +- 6 files changed, 38 insertions(+), 236 deletions(-) diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index b1245db3ec..9a9ab04d32 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -471,11 +471,9 @@ struct SessionSummary { resume_hint: Option, } -#[derive(Debug, Default)] -struct InitialHistoryReplayBuffer { - retained_lines: VecDeque, - 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, diff --git a/codex-rs/tui/src/app/event_dispatch.rs b/codex-rs/tui/src/app/event_dispatch.rs index 324385a774..8e3048f96b 100644 --- a/codex-rs/tui/src/app/event_dispatch.rs +++ b/codex-rs/tui/src/app/event_dispatch.rs @@ -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, diff --git a/codex-rs/tui/src/app/resize_reflow.rs b/codex-rs/tui/src/app/resize_reflow.rs index f8675162ff..6a1424f084 100644 --- a/codex-rs/tui/src/app/resize_reflow.rs +++ b/codex-rs/tui/src/app/resize_reflow.rs @@ -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::>(); - 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, - max_rows: Option, - ) { - 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) -> 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() { diff --git a/codex-rs/tui/src/app/tests.rs b/codex-rs/tui/src/app/tests.rs index 92b077350d..f9ef53bb86 100644 --- a/codex-rs/tui/src/app/tests.rs +++ b/codex-rs/tui/src/app/tests.rs @@ -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![ - "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!["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] diff --git a/codex-rs/tui/src/app/thread_routing.rs b/codex-rs/tui/src/app/thread_routing.rs index 3fc198e431..5e9c5b17b9 100644 --- a/codex-rs/tui/src/app/thread_routing.rs +++ b/codex-rs/tui/src/app/thread_routing.rs @@ -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); diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index e8f7219812..bc21185666 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -577,8 +577,8 @@ pub(crate) enum AppEvent { InsertHistoryCell(Box), - /// 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