diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 74eb553909..1405e9080e 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -1132,12 +1132,19 @@ impl App { .start_queued_model_document(tui, app_server, screen_size.width) .await; } - if !matches!( - &event, - TuiEvent::Key(_) | TuiEvent::Mouse(_) | TuiEvent::Paste(_) | TuiEvent::FocusLost - ) { + // Reflow and paint must agree on width. Final inserts still use the last + // painted width until consolidation completes. Offline sessions drop those events. + let defer_inline_draw = draws_history + && self.overlay.is_none() + && !self.reconnect.offline + && !tui.is_owned_screen() + && self.chat_widget.has_pending_stream_consolidation() + && !self.chat_widget.has_active_modal(); + if draws_history { self.expire_pending_key_chord(tui); - self.handle_draw_pre_render(tui, screen_size)?; + if !defer_inline_draw { + self.handle_draw_pre_render(tui, screen_size)?; + } } let dismiss_chord = match &event { @@ -1381,6 +1388,11 @@ impl App { _ => {} } + if defer_inline_draw { + tui.defer_screen_size(screen_size); + tui.frame_requester().schedule_frame(); + return Ok(AppRunControl::Continue); + } if self.overlay.is_some() { let _ = self .handle_backtrack_overlay_event(tui, app_server, event) diff --git a/codex-rs/tui/src/app/resize_reflow.rs b/codex-rs/tui/src/app/resize_reflow.rs index 81a17a6459..a71c2a3ccd 100644 --- a/codex-rs/tui/src/app/resize_reflow.rs +++ b/codex-rs/tui/src/app/resize_reflow.rs @@ -290,23 +290,6 @@ impl App { ); } - fn clear_terminal_for_resize_replay(&mut self, tui: &mut tui::Tui) -> Result<()> { - if tui.is_owned_screen() || tui.has_deferred_thread_switch_clear() { - return Ok(()); - } - 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 @@ -457,7 +440,13 @@ impl App { tui.terminal.last_known_screen_size, &tui.frame_requester(), ); - if should_rebuild_transcript { + if should_rebuild_transcript && tui.has_deferred_replay_clear() { + // The live tail may already be gone. Replace its queued replay at the + // new width in this frame, without waiting for the resize debounce. + if !self.transcript_cells.is_empty() { + self.transcript_reflow.schedule_immediate(); + } + } else if should_rebuild_transcript { // Resize-sensitive history inserts queued before this frame may be wrapped for the old // viewport or targeted at rows no longer visible. Drop them and let resize reflow // rebuild from transcript cells. @@ -543,17 +532,8 @@ impl App { let reflowed_lines = reflow_result.lines; let reflowed_rows = reflowed_lines.len(); - // Drop any queued pre-resize/pre-consolidation inserts before rebuilding from cells. - tui.clear_pending_history_lines(); - self.clear_terminal_for_resize_replay(tui)?; - self.deferred_history_lines.clear(); - if !reflowed_lines.is_empty() { - tui.insert_history_hyperlink_lines_with_wrap_policy( - reflowed_lines, - self.history_line_wrap_policy(), - ); - } + tui.queue_history_replay(reflowed_lines, self.history_line_wrap_policy()); self.last_rendered_history_tail = self .native_history .replayable_cells(&self.transcript_cells) @@ -635,16 +615,8 @@ impl App { self.render_transcript_lines_for_reflow(width).lines }; - tui.clear_pending_history_lines(); - self.clear_terminal_for_resize_replay(tui)?; - self.deferred_history_lines.clear(); - if !reflowed_lines.is_empty() { - tui.insert_history_hyperlink_lines_with_wrap_policy( - reflowed_lines, - self.history_line_wrap_policy(), - ); - } + tui.queue_history_replay(reflowed_lines, self.history_line_wrap_policy()); Ok(()) } diff --git a/codex-rs/tui/src/app/tests/stream_animation_tests.rs b/codex-rs/tui/src/app/tests/stream_animation_tests.rs index e8dbb09f04..e7cfd87e2a 100644 --- a/codex-rs/tui/src/app/tests/stream_animation_tests.rs +++ b/codex-rs/tui/src/app/tests/stream_animation_tests.rs @@ -1,4 +1,7 @@ use super::*; +use crate::app::owned_transcript::tests::buffer_text; +use crate::chatwidget::tests::helpers::complete_assistant_message; +use crate::chatwidget::tests::helpers::handle_agent_message_delta; use futures::FutureExt; use pretty_assertions::assert_eq; @@ -49,3 +52,61 @@ async fn stream_animation_preserves_pacing_and_discards_stopped_ticks() -> Resul time::resume(); Ok(()) } + +#[tokio::test] +async fn inline_streamed_table_stays_visible_until_history_is_painted() -> Result<()> { + let (mut app, mut events, _ops) = make_test_app_with_channels().await; + let mut server = start_config_write_test_app_server(&app).await?; + let mut tui = crate::tui::test_support::make_test_tui()?; + let resized = tui.terminal.last_known_screen_size; + let size = Size::new(/*width*/ 60, resized.height); + let table = "| Pattern | Outcome |\n| --- | --- |\n| Table tail | Preserved |\n"; + handle_agent_message_delta(&mut app.chat_widget, table); + drain_app_events(&mut app, &mut tui, &mut server, &mut events).await?; + let live = side_frame(&mut app, &mut tui, size)?; + assert!(live.contains("Preserved"), "{live}"); + + complete_assistant_message(&mut app.chat_widget, "msg-1", table, /*phase*/ None); + // Postpone the paint without holding typeahead for a later approval prompt. + assert!(app.can_read_terminal_after_thread_switch(&tui, &events)); + app.handle_tui_event(&mut tui, &mut server, TuiEvent::Draw) + .await?; + app.handle_tui_event( + &mut tui, + &mut server, + TuiEvent::Key(KeyCode::Char('é').into()), + ) + .await?; + assert_eq!(app.chat_widget.composer_text_with_pending(), "é"); + drain_app_events(&mut app, &mut tui, &mut server, &mut events).await?; + assert_eq!(buffer_text(tui.terminal.previous_buffer()), live); + // Widen the terminal while the table replay and the next message's final + // insert are both pending. The prose should fit on one line at the new width. + let prose = "This final sentence fits on one line only after the terminal widens."; + app.chat_widget.handle_server_notification( + agent_message_delta_notification(ThreadId::new(), "turn-1", "msg-2", prose), + /*replay_kind*/ None, + ); + complete_assistant_message(&mut app.chat_widget, "msg-2", prose, /*phase*/ None); + app.handle_tui_event(&mut tui, &mut server, TuiEvent::Resize(resized)) + .await?; + drain_app_events(&mut app, &mut tui, &mut server, &mut events).await?; + let resized = tui.screen_size_for_event(&TuiEvent::Draw)?; + app.handle_draw_pre_render(&mut tui, resized)?; + let history = tui.pending_history_lines_for_test(); + assert_snapshot!(history.iter().map(rendered_line_text).collect::>().join("\n"), @r" + • Pattern Outcome + ━━━━━━━━━━━━ ━━━━━━━━━━━ + Table tail Preserved + + • This final sentence fits on one line only after the terminal widens. + "); + app.render_chat_widget_frame(&mut tui, resized)?; + let frame = buffer_text(tui.terminal.previous_buffer()); + assert!( + !frame.contains("Preserved"), + "table should appear only in scrollback" + ); + server.shutdown().await?; + Ok(()) +} diff --git a/codex-rs/tui/src/chatwidget/tests/helpers.rs b/codex-rs/tui/src/chatwidget/tests/helpers.rs index c04a9225fd..b2b1904449 100644 --- a/codex-rs/tui/src/chatwidget/tests/helpers.rs +++ b/codex-rs/tui/src/chatwidget/tests/helpers.rs @@ -637,7 +637,7 @@ pub(super) fn handle_model_verification( ); } -pub(super) fn handle_agent_message_delta(chat: &mut ChatWidget, delta: impl Into) { +pub(crate) fn handle_agent_message_delta(chat: &mut ChatWidget, delta: impl Into) { chat.handle_server_notification( ServerNotification::AgentMessageDelta( codex_app_server_protocol::AgentMessageDeltaNotification { @@ -1087,7 +1087,7 @@ pub(super) fn terminal_interaction( ); } -pub(super) fn complete_assistant_message( +pub(crate) fn complete_assistant_message( chat: &mut ChatWidget, item_id: &str, text: &str, diff --git a/codex-rs/tui/src/chatwidget/usage_history.rs b/codex-rs/tui/src/chatwidget/usage_history.rs index 882211f4ee..462b0665cd 100644 --- a/codex-rs/tui/src/chatwidget/usage_history.rs +++ b/codex-rs/tui/src/chatwidget/usage_history.rs @@ -12,11 +12,15 @@ impl ChatWidget { pub(crate) fn usage_history_insertion_blocked(&self) -> bool { self.stream_controller.is_some() || self.plan_stream_controller.is_some() - || self.pending_stream_consolidations > 0 + || self.has_pending_stream_consolidation() || self.transcript.active_cell.is_some() || self.active_hook_cell.is_some() } + pub(crate) fn has_pending_stream_consolidation(&self) -> bool { + self.pending_stream_consolidations > 0 + } + /// Records a stream consolidation barrier that delays reset hint insertion. /// /// Each queued consolidation should eventually call diff --git a/codex-rs/tui/src/tui.rs b/codex-rs/tui/src/tui.rs index 40b0ca55b6..c4b13d8bae 100644 --- a/codex-rs/tui/src/tui.rs +++ b/codex-rs/tui/src/tui.rs @@ -735,6 +735,12 @@ pub(crate) fn tmux_fullscreen_image_base() -> Option { .map(std::num::NonZeroU32::get) } +#[derive(Clone, Copy, PartialEq, Eq)] +enum DeferredClear { + ThreadSwitch, + Replay, +} + pub struct Tui { pub(crate) link_hover: link_pointer::LinkHover, frame_requester: FrameRequester, @@ -745,7 +751,7 @@ pub struct Tui { pub(crate) terminal_size_tags: crate::terminal_size_telemetry::LaunchTags, pub(crate) terminal: Terminal, pending_history_lines: Vec, - clear_thread_switch_on_draw: bool, + clear_on_draw: Option, screen_size: ScreenSizePolicy, ambient_pet_image_state: crate::pets::PetImageRenderState, pet_picker_preview_image_state: crate::pets::PetImageRenderState, @@ -828,7 +834,7 @@ impl Tui { terminal_size_tags: Vec::new(), terminal, pending_history_lines: vec![], - clear_thread_switch_on_draw: false, + clear_on_draw: None, screen_size: ScreenSizePolicy::default(), ambient_pet_image_state: crate::pets::PetImageRenderState::default(), pet_picker_preview_image_state: crate::pets::PetImageRenderState::default(), @@ -1208,6 +1214,28 @@ impl Tui { Box::pin(stream) } + /// Overlays and in-place history edits can flush a replay before the scheduled draw. + fn flush_history_before_draw(&mut self) -> Result<()> { + let flush = |tui: &mut Self| { + let screen_size = tui.terminal.last_known_screen_size; + Self::flush_pending_history_lines( + &mut tui.terminal, + &mut tui.pending_history_lines, + &mut tui.retained_images, + tui.scrollback, + screen_size, + ) + }; + if self.has_deferred_replay_clear() { + stdout().sync_update(|_| { + self.apply_deferred_clear()?; + flush(self) + })? + } else { + flush(self) + } + } + /// Enter alternate screen and expand the viewport to full terminal size, saving the current /// inline viewport for restoration when leaving. pub fn enter_alt_screen(&mut self) -> Result<()> { @@ -1216,14 +1244,7 @@ impl Tui { } // History queued before opening an overlay belongs to the inline transcript. // Flush before switching screens or expanding an inline overlay's viewport. - let screen_size = self.terminal.last_known_screen_size; - Self::flush_pending_history_lines( - &mut self.terminal, - &mut self.pending_history_lines, - &mut self.retained_images, - self.scrollback, - screen_size, - )?; + self.flush_history_before_draw()?; if !self.alt_screen_enabled { return Ok(()); } @@ -1334,33 +1355,71 @@ impl Tui { pub fn clear_pending_history_lines(&mut self) { self.pending_history_lines.clear(); + if self.has_deferred_replay_clear() { + self.clear_on_draw = None; + } } pub(crate) fn clear_for_thread_switch(&mut self) -> Result<()> { - self.clear_thread_switch_on_draw = false; + self.clear_on_draw = None; if self.is_alt_screen_active() { self.leave_alt_screen()?; } if self.is_owned_screen() { self.terminal.clear()?; + } else { + self.clear_for_replay()?; + } + Ok(()) + } + + fn clear_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); - } + } + let mut area = self.terminal.viewport_area; + if area.y > 0 { + area.y = 0; + self.terminal.set_viewport_area(area); } Ok(()) } /// Keep the current frame visible until the next synchronized draw. pub(crate) fn defer_thread_switch_clear(&mut self) { - self.clear_thread_switch_on_draw = true; + self.clear_on_draw = Some(DeferredClear::ThreadSwitch); } pub(crate) fn has_deferred_thread_switch_clear(&self) -> bool { - self.clear_thread_switch_on_draw + self.clear_on_draw == Some(DeferredClear::ThreadSwitch) + } + + /// Replace queued inserts and clear the screen when the replay is painted. + /// An empty replay still clears rows removed by rollback. + pub(crate) fn queue_history_replay( + &mut self, + lines: Vec, + wrap_policy: HistoryLineWrapPolicy, + ) { + self.pending_history_lines.clear(); + if !self.has_deferred_thread_switch_clear() { + self.clear_on_draw = Some(DeferredClear::Replay); + } + self.insert_history_hyperlink_lines_with_wrap_policy(lines, wrap_policy); + } + + pub(crate) fn has_deferred_replay_clear(&self) -> bool { + self.clear_on_draw == Some(DeferredClear::Replay) + } + + fn apply_deferred_clear(&mut self) -> Result<()> { + match self.clear_on_draw.take() { + Some(DeferredClear::ThreadSwitch) => self.clear_for_thread_switch(), + Some(DeferredClear::Replay) => self.clear_for_replay(), + None => Ok(()), + } } /// Resize the inline viewport for the resize-reflow path. @@ -1520,17 +1579,11 @@ impl Tui { stdout().sync_update(|_| { #[cfg(unix)] if let Some(prepared) = prepared_resume.take() { - self.terminal.invalidate_cursor_state(); - prepared.apply( - &mut self.terminal, - screen_size, - self.owned_screen, - self.mouse_capture.captures_mouse(self.owned_screen), - )?; + prepared.apply(self, screen_size)?; } - if self.clear_thread_switch_on_draw { - self.clear_for_thread_switch()?; + if self.clear_on_draw.is_some() { + self.apply_deferred_clear()?; pending_viewport_area = None; } if self.owned_screen && !self.is_alt_screen_active() { @@ -1679,18 +1732,10 @@ impl Tui { stdout().sync_update(|_| { #[cfg(unix)] if let Some(prepared) = prepared_resume.take() { - self.terminal.invalidate_cursor_state(); - prepared.apply( - &mut self.terminal, - screen_size, - self.owned_screen, - self.mouse_capture.captures_mouse(self.owned_screen), - )?; + prepared.apply(self, screen_size)?; } - if self.clear_thread_switch_on_draw { - self.clear_for_thread_switch()?; - } + self.apply_deferred_clear()?; if self.owned_screen && !self.is_alt_screen_active() { self.enter_alt_screen()?; } diff --git a/codex-rs/tui/src/tui/history_tail.rs b/codex-rs/tui/src/tui/history_tail.rs index 1ccc6c822d..69771f5456 100644 --- a/codex-rs/tui/src/tui/history_tail.rs +++ b/codex-rs/tui/src/tui/history_tail.rs @@ -28,14 +28,7 @@ impl Tui { replacement: &[HyperlinkLine], wrap_policy: HistoryLineWrapPolicy, ) -> io::Result { - let screen_size = self.terminal.last_known_screen_size; - Self::flush_pending_history_lines( - &mut self.terminal, - &mut self.pending_history_lines, - &mut self.retained_images, - self.scrollback, - screen_size, - )?; + self.flush_history_before_draw()?; let mode = self.scrollback.history_insertion_mode(wrap_policy); let replaced = replace_visible_terminal_history_tail( &mut self.terminal, diff --git a/codex-rs/tui/src/tui/job_control.rs b/codex-rs/tui/src/tui/job_control.rs index a74224a612..4b807ccaea 100644 --- a/codex-rs/tui/src/tui/job_control.rs +++ b/codex-rs/tui/src/tui/job_control.rs @@ -18,7 +18,7 @@ use ratatui::layout::Size; use crate::key_hint; -use super::Terminal; +use super::Tui; pub const SUSPEND_KEY: key_hint::KeyBinding = key_hint::ctrl(KeyCode::Char('z')); @@ -181,20 +181,21 @@ pub(crate) enum PreparedResumeAction { } impl PreparedResumeAction { - pub(crate) fn apply( - self, - terminal: &mut Terminal, - screen_size: Size, - owned: bool, - capture_mouse: bool, - ) -> Result<()> { + pub(crate) fn apply(self, tui: &mut Tui, screen_size: Size) -> Result<()> { + tui.terminal.invalidate_cursor_state(); match self { PreparedResumeAction::RealignViewport(area) => { - terminal.set_viewport_area(area); + // A deferred clear resets the origin itself. Realigning to an empty + // viewport first would make the terminal skip the scrollback purge. + if tui.clear_on_draw.is_none() { + tui.terminal.set_viewport_area(area); + } } PreparedResumeAction::RestoreAltScreen => { + let capture_mouse = tui.mouse_capture.captures_mouse(tui.owned_screen); + let terminal = &mut tui.terminal; super::ALTERNATE_SCREEN.enter(terminal.backend_mut(), capture_mouse)?; - if owned { + if tui.owned_screen { terminal.hide_cursor()?; } terminal.set_viewport_area(Rect::from(screen_size)); diff --git a/codex-rs/tui/src/tui/owned_screen_tests.rs b/codex-rs/tui/src/tui/owned_screen_tests.rs index 7e189bdd89..381c8b9156 100644 --- a/codex-rs/tui/src/tui/owned_screen_tests.rs +++ b/codex-rs/tui/src/tui/owned_screen_tests.rs @@ -123,12 +123,7 @@ async fn owned_screen_lifecycle_child() { .leave(tui.terminal.backend_mut()) .expect("suspend static pager"); super::job_control::PreparedResumeAction::RestoreAltScreen - .apply( - &mut tui.terminal, - Size::new(/*width*/ 80, /*height*/ 24), - /*owned*/ false, - tui.mouse_capture.captures_mouse(/*owned_screen*/ false), - ) + .apply(&mut tui, Size::new(/*width*/ 80, /*height*/ 24)) .expect("resume static pager"); pager .handle_event( @@ -173,12 +168,7 @@ async fn owned_screen_lifecycle_child() { .expect("suspend screen"); let resumed = Size::new(/*width*/ 100, /*height*/ 30); super::job_control::PreparedResumeAction::RestoreAltScreen - .apply( - &mut tui.terminal, - resumed, - /*owned*/ true, - /*capture_mouse*/ true, - ) + .apply(&mut tui, resumed) .expect("resume owned screen"); assert_eq!( ( @@ -206,6 +196,14 @@ async fn owned_screen_lifecycle_child() { .expect("release session screen"); assert_eq!(tui.terminal.viewport_area, inline); + // Resuming inline must still purge the old rows before replaying history. + tui.queue_history_replay(Vec::new(), super::HistoryLineWrapPolicy::PreWrap); + super::job_control::PreparedResumeAction::RealignViewport(Rect::default()) + .apply(&mut tui, resumed) + .expect("resume inline"); + tui.apply_deferred_clear().expect("clear before replay"); + assert_eq!(tui.terminal.viewport_area, Rect { y: 0, ..inline }); + // A fresh fullscreen launch defers terminal entry until its first frame. tui.terminal.tmux_kitty_image_base = Some(0x80_0100); let support =