fix(tui): prevent startup transcript flashes

This commit is contained in:
Felipe Coury
2026-06-05 12:27:45 -03:00
parent a14a73b54a
commit 85fd78fe6d
6 changed files with 263 additions and 68 deletions
-7
View File
@@ -190,12 +190,6 @@ impl App {
tui.frame_requester().schedule_frame();
}
AppEvent::BeginInitialHistoryReplayBuffer => {
self.begin_initial_history_replay_buffer();
}
AppEvent::BeginThreadSwitchHistoryReplayBuffer => {
self.begin_thread_switch_history_replay_buffer();
}
AppEvent::InsertHistoryCell(cell) => {
let cell: Arc<dyn HistoryCell> = cell.into();
if let Some(Overlay::Transcript(t)) = &mut self.overlay {
@@ -205,7 +199,6 @@ impl App {
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(
tui,
cell.as_ref(),
self.chat_widget
.history_wrap_width(tui.terminal.last_known_screen_size.width),
+51 -42
View File
@@ -121,6 +121,7 @@ impl App {
/// transcript ownership, so overlay replay continues through the normal deferred-history path.
pub(super) fn begin_initial_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(Default::default());
}
}
@@ -131,10 +132,8 @@ impl App {
/// 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.resize_reflow_max_rows().is_some()
&& self.overlay.is_none()
{
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,
@@ -142,6 +141,19 @@ impl App {
}
}
/// 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 {
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.
@@ -152,20 +164,22 @@ impl App {
return;
};
if buffer.retained_lines.is_empty() {
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(),
);
}
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(),
);
}
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,
@@ -175,7 +189,6 @@ impl App {
pub(super) fn insert_history_cell_lines_with_initial_replay_buffer(
&mut self,
tui: &mut tui::Tui,
cell: &dyn HistoryCell,
width: u16,
) {
@@ -194,16 +207,12 @@ impl App {
}
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 let Some(max_rows) = max_rows {
Self::buffer_initial_history_replay_display_lines(buffer, display, max_rows);
} else if self.overlay.is_some() {
if overlay_active {
self.deferred_history_lines.extend(display);
} else {
tui.insert_history_hyperlink_lines_with_wrap_policy(
display,
self.history_line_wrap_policy(),
);
Self::buffer_initial_history_replay_display_lines(buffer, display, max_rows);
}
}
}
@@ -224,11 +233,13 @@ impl App {
pub(super) fn buffer_initial_history_replay_display_lines(
buffer: &mut InitialHistoryReplayBuffer,
display: Vec<HyperlinkLine>,
max_rows: usize,
max_rows: Option<usize>,
) {
buffer.retained_lines.extend(display);
while buffer.retained_lines.len() > max_rows {
buffer.retained_lines.pop_front();
if let Some(max_rows) = max_rows {
while buffer.retained_lines.len() > max_rows {
buffer.retained_lines.pop_front();
}
}
}
@@ -241,20 +252,6 @@ impl App {
crate::resize_reflow_cap::resize_reflow_max_rows(self.config.terminal_resize_reflow)
}
fn clear_terminal_for_resize_replay(&mut self, tui: &mut tui::Tui) -> Result<()> {
if tui.is_alt_screen_active() {
tui.terminal.clear_visible_screen()?;
} else {
tui.terminal.clear_scrollback_and_visible_screen_ansi()?;
}
let mut area = tui.terminal.viewport_area;
if area.y > 0 {
area.y = 0;
tui.terminal.set_viewport_area(area);
}
Ok(())
}
/// Finish stream consolidation by repairing any resize work that happened during streaming.
///
/// This is called after agent-message stream cells have either been replaced by an
@@ -267,6 +264,9 @@ impl App {
self.transcript_reflow.clear();
return Ok(());
}
if self.absorb_reflow_into_initial_history_replay() {
return Ok(());
}
if self.transcript_reflow.take_stream_finish_reflow_needed() {
self.schedule_immediate_resize_reflow(tui);
@@ -296,6 +296,9 @@ impl App {
self.transcript_reflow.clear();
return Ok(());
}
if self.absorb_reflow_into_initial_history_replay() {
return Ok(());
}
self.schedule_immediate_resize_reflow(tui);
self.maybe_run_resize_reflow(tui)?;
if !self.transcript_reflow.has_pending_reflow() {
@@ -319,10 +322,16 @@ impl App {
let width = self.transcript_reflow.note_width(size.width);
let reflow_needed = self.transcript_reflow.reflow_needed_for_width(size.width);
let height_changed = size.height != last_known_screen_size.height;
let should_rebuild_transcript = reflow_needed || height_changed;
let resize_requires_rebuild = reflow_needed || height_changed;
let replay_in_progress = self.initial_history_replay_buffer.is_some();
let should_rebuild_transcript = resize_requires_rebuild && !replay_in_progress;
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() {
@@ -446,7 +455,7 @@ impl App {
// Drop any queued pre-resize/pre-consolidation inserts before rebuilding from cells.
tui.clear_pending_history_lines();
self.clear_terminal_for_resize_replay(tui)?;
tui.request_terminal_replay_clear();
self.deferred_history_lines.clear();
if !reflowed_lines.is_empty() {
@@ -475,7 +484,7 @@ impl App {
};
tui.clear_pending_history_lines();
self.clear_terminal_for_resize_replay(tui)?;
tui.request_terminal_replay_clear();
self.deferred_history_lines.clear();
if !reflowed_lines.is_empty() {
+76 -3
View File
@@ -4031,7 +4031,7 @@ async fn initial_replay_buffer_keeps_recent_rows_when_row_cap_present() {
.as_mut()
.expect("initial replay buffer active"),
vec![Line::from(format!("line {index}")).into()],
/*max_rows*/ 3,
/*max_rows*/ Some(3),
);
}
@@ -4070,14 +4070,87 @@ async fn thread_switch_replay_buffer_uses_transcript_tail_mode_when_row_cap_pres
}
#[tokio::test]
async fn thread_switch_replay_buffer_is_disabled_without_row_cap() {
async fn thread_switch_replay_buffer_uses_transcript_tail_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();
assert!(app.initial_history_replay_buffer.is_none());
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 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() {
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.transcript_reflow
.schedule_debounced(/*target_width*/ Some(118));
assert!(app.transcript_reflow.has_pending_reflow());
app.begin_initial_history_replay_buffer();
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.transcript_reflow.has_pending_reflow());
assert!(!app.handle_draw_size_change(
ratatui::layout::Size::new(/*width*/ 118, /*height*/ 24),
ratatui::layout::Size::new(/*width*/ 118, /*height*/ 35),
&frame_requester,
));
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());
}
#[tokio::test]
+2 -4
View File
@@ -1074,8 +1074,7 @@ impl App {
let should_buffer_initial_replay =
self.terminal_resize_reflow_enabled() && !turns.is_empty();
if should_buffer_initial_replay {
self.app_event_tx
.send(AppEvent::BeginInitialHistoryReplayBuffer);
self.begin_initial_history_replay_buffer();
}
self.chat_widget
.replay_thread_turns(turns, ReplayKind::ResumeInitialMessages);
@@ -1264,8 +1263,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.app_event_tx
.send(AppEvent::BeginThreadSwitchHistoryReplayBuffer);
self.begin_thread_switch_history_replay_buffer();
}
let suppress_replay_notices =
replay_filter::snapshot_has_pending_interactive_request(&snapshot);
-7
View File
@@ -575,13 +575,6 @@ pub(crate) enum AppEvent {
result: Result<SkillsListResponse, String>,
},
/// Begin buffering initial resume replay rows before they are written to scrollback.
BeginInitialHistoryReplayBuffer,
/// Begin buffering thread-switch replay cells so the final scrollback write can reuse the
/// resize-reflow tail renderer.
BeginThreadSwitchHistoryReplayBuffer,
InsertHistoryCell(Box<dyn HistoryCell>),
/// Finish buffering initial resume replay after all replay events have been queued.
+134 -5
View File
@@ -84,6 +84,22 @@ fn should_emit_notification(condition: NotificationCondition, terminal_focused:
}
}
fn run_synchronized_draw<W, T>(
writer: &mut W,
replay_clear_pending: &mut bool,
operations: impl FnOnce(&mut W) -> Result<T>,
) -> Result<T>
where
W: Write,
{
let replay_clear_requested = *replay_clear_pending;
let result = writer.sync_update(operations)?;
if replay_clear_requested && result.is_ok() {
*replay_clear_pending = false;
}
result
}
impl Drop for Tui {
fn drop(&mut self) {
if let Err(err) = self.clear_ambient_pet_image() {
@@ -97,10 +113,12 @@ mod tests {
use std::io::Write as _;
use super::clear_for_viewport_change;
use super::run_synchronized_draw;
use super::should_emit_notification;
use crate::custom_terminal::Terminal as CustomTerminal;
use crate::test_backend::VT100Backend;
use codex_config::types::NotificationCondition;
use pretty_assertions::assert_eq;
use ratatui::layout::Position;
use ratatui::layout::Rect;
@@ -168,6 +186,76 @@ mod tests {
"expected stale cells inside the new viewport to be cleared, rows: {rows:?}"
);
}
#[test]
fn synchronized_draw_wraps_replay_clear_and_repaint() {
let mut output = Vec::new();
let mut replay_clear_pending = true;
let replay_clear_requested = replay_clear_pending;
let value = run_synchronized_draw(&mut output, &mut replay_clear_pending, |writer| {
assert!(replay_clear_requested);
writer.write_all(b"clear")?;
writer.write_all(b"replay")?;
Ok(42)
})
.expect("synchronized draw");
assert_eq!(value, 42);
assert!(!replay_clear_pending);
assert_eq!(output, b"\x1b[?2026hclearreplay\x1b[?2026l");
}
#[test]
fn synchronized_draw_retries_replay_clear_after_render_error() {
let mut output = Vec::new();
let mut replay_clear_pending = true;
let replay_clear_requested = replay_clear_pending;
let error = run_synchronized_draw(&mut output, &mut replay_clear_pending, |writer| {
assert!(replay_clear_requested);
writer.write_all(b"clear")?;
Err::<(), _>(std::io::Error::other("render failed"))
})
.expect_err("draw should fail");
assert_eq!(error.kind(), std::io::ErrorKind::Other);
assert!(replay_clear_pending);
assert_eq!(output, b"\x1b[?2026hclear\x1b[?2026l");
}
#[test]
fn synchronized_draw_retries_replay_clear_after_sync_flush_error() {
struct FailOnFlush {
output: Vec<u8>,
}
impl std::io::Write for FailOnFlush {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.output.extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Err(std::io::Error::other("flush failed"))
}
}
let mut writer = FailOnFlush { output: Vec::new() };
let mut replay_clear_pending = true;
let replay_clear_requested = replay_clear_pending;
let error = run_synchronized_draw(&mut writer, &mut replay_clear_pending, |writer| {
assert!(replay_clear_requested);
writer.write_all(b"clear")?;
Ok(())
})
.expect_err("sync flush should fail");
assert_eq!(error.kind(), std::io::ErrorKind::Other);
assert!(replay_clear_pending);
assert_eq!(writer.output, b"\x1b[?2026hclear\x1b[?2026l");
}
}
pub fn set_modes() -> Result<()> {
@@ -498,6 +586,8 @@ pub struct Tui {
suspend_context: SuspendContext,
// True when overlay alt-screen UI is active
alt_screen_active: Arc<AtomicBool>,
// Rebuilds clear the terminal inside the next synchronized draw before replaying history.
terminal_replay_clear_pending: bool,
// True when terminal/tab is focused; updated internally from crossterm events
terminal_focused: Arc<AtomicBool>,
enhanced_keys_supported: bool,
@@ -554,6 +644,7 @@ impl Tui {
#[cfg(unix)]
suspend_context: SuspendContext::new(),
alt_screen_active: Arc::new(AtomicBool::new(false)),
terminal_replay_clear_pending: false,
terminal_focused: Arc::new(AtomicBool::new(true)),
enhanced_keys_supported,
notification_backend: Some(detect_backend(NotificationMethod::default())),
@@ -590,6 +681,10 @@ impl Tui {
self.alt_screen_active.load(Ordering::Relaxed)
}
pub(crate) fn request_terminal_replay_clear(&mut self) {
self.terminal_replay_clear_pending = true;
}
// Drop crossterm EventStream to avoid stdin conflicts with other processes.
pub fn pause_events(&mut self) {
self.event_broker.pause_events();
@@ -768,6 +863,20 @@ impl Tui {
self.pending_history_lines.clear();
}
fn clear_terminal_for_replay(&mut self) -> Result<()> {
if self.is_alt_screen_active() {
self.terminal.clear_visible_screen()?;
} else {
self.terminal.clear_scrollback_and_visible_screen_ansi()?;
}
let mut area = self.terminal.viewport_area;
if area.y > 0 {
area.y = 0;
self.terminal.set_viewport_area(area);
}
Ok(())
}
/// Resize the inline viewport for the resize-reflow path.
///
/// Unlike the legacy draw path, this path does not scroll rows above the viewport when the
@@ -852,16 +961,26 @@ impl Tui {
// Precompute any viewport updates that need a cursor-position query before entering
// the synchronized update, to avoid racing with the event reader.
let mut pending_viewport_area = self.pending_viewport_area()?;
let mut pending_viewport_area = if self.terminal_replay_clear_pending {
None
} else {
self.pending_viewport_area()?
};
ensure_virtual_terminal_processing()?;
stdout().sync_update(|_| {
let mut replay_clear_pending = self.terminal_replay_clear_pending;
let replay_clear_requested = replay_clear_pending;
let result = run_synchronized_draw(&mut stdout(), &mut replay_clear_pending, |_| {
#[cfg(unix)]
if let Some(prepared) = prepared_resume.take() {
prepared.apply(&mut self.terminal)?;
}
if replay_clear_requested {
self.clear_terminal_for_replay()?;
}
let terminal = &mut self.terminal;
if let Some(new_area) = pending_viewport_area.take() {
terminal.set_viewport_area(new_area);
@@ -910,7 +1029,9 @@ impl Tui {
terminal.draw(|frame| {
draw_fn(frame);
})
})?
});
self.terminal_replay_clear_pending = replay_clear_pending;
result
}
pub fn draw_ambient_pet_image(
@@ -988,12 +1109,18 @@ impl Tui {
ensure_virtual_terminal_processing()?;
stdout().sync_update(|_| {
let mut replay_clear_pending = self.terminal_replay_clear_pending;
let replay_clear_requested = replay_clear_pending;
let result = run_synchronized_draw(&mut stdout(), &mut replay_clear_pending, |_| {
#[cfg(unix)]
if let Some(prepared) = prepared_resume.take() {
prepared.apply(&mut self.terminal)?;
}
if replay_clear_requested {
self.clear_terminal_for_replay()?;
}
let terminal = &mut self.terminal;
let needs_full_repaint =
Self::update_inline_viewport_for_resize_reflow(terminal, height)?;
@@ -1024,7 +1151,9 @@ impl Tui {
terminal.draw(|frame| {
draw_fn(frame);
})
})?
});
self.terminal_replay_clear_pending = replay_clear_pending;
result
}
fn pending_viewport_area(&mut self) -> Result<Option<Rect>> {