diff --git a/codex-rs/tui/src/app/agent_message_consolidation.rs b/codex-rs/tui/src/app/agent_message_consolidation.rs index 52a015c0fc..7b12f21178 100644 --- a/codex-rs/tui/src/app/agent_message_consolidation.rs +++ b/codex-rs/tui/src/app/agent_message_consolidation.rs @@ -3,7 +3,8 @@ //! During streaming, the chat widget emits transient `AgentMessageCell`s so it //! can animate stable lines into scrollback while keeping the active mutable //! tail in the bottom pane. Once the answer finishes, the app replaces that -//! trailing run with a single source-backed `AgentMarkdownCell`. This makes the +//! stream with a single source-backed `AgentMarkdownCell`, keeping interleaved +//! notices after the answer in their original order. This makes the //! transcript the canonical owner of the raw markdown source used for future //! resize re-renders. The retained view preserves its displayed revision before that //! replacement, then repaints without replaying terminal scrollback. @@ -14,7 +15,6 @@ use std::sync::Arc; use color_eyre::eyre::Result; use super::App; -use super::resize_reflow::trailing_run_start; use crate::app_event::ConsolidationScrollbackReflow; use crate::history_cell; use crate::history_cell::HistoryCell; @@ -26,6 +26,7 @@ impl App { &mut self, tui: &mut tui::Tui, source: history_cell::AgentMarkdownCell, + emitted_cells: usize, scrollback_reflow: ConsolidationScrollbackReflow, deferred_history_cell: Option>, ) -> Result<()> { @@ -43,25 +44,56 @@ impl App { self.transcript_cells.push(cell); } - // Walk backward to find the contiguous run of streaming AgentMessageCells that - // belong to the just-finalized stream. - let end = self.transcript_cells.len(); - tracing::debug!( - "ConsolidateAgentMessage: transcript_cells.len()={end}, source_len={}", - source.copy_source().map_or(/*default*/ 0, str::len) - ); - let start = trailing_run_start::(&self.transcript_cells); - self.replace_agent_message(tui, start..end, source, scrollback_reflow) + // A notice may follow the last fragment or separate two fragments. Bound + // the walk by what this controller emitted so an empty stream never + // claims a previous interrupted answer. + let is_fragment = + |cell: &Arc| cell.as_any().is::(); + let mut start = self.transcript_cells.len(); + let mut end = start; + let mut fragments = 0; + for (index, cell) in self.transcript_cells.iter().enumerate().rev() { + if fragments == emitted_cells + || cell.as_any().is::() + || cell.as_any().is::() + || cell.as_any().is::() + { + break; + } + if is_fragment(cell) { + if fragments == 0 { + end = index + 1; + } + start = index; + fragments += 1; + if !cell.is_stream_continuation() { + break; + } + } + } + + if end - start > fragments { + if tui.is_owned_screen() { + self.transcript_view + .retain_before_regroup(&self.transcript_cells, start..end); + } + // Stable partition keeps notices out of the replacement range and + // preserves their identities in the native output queue. + self.transcript_cells[start..end].sort_by_key(|cell| !is_fragment(cell)); + } + self.replace_agent_message(tui, start..end, fragments, source, scrollback_reflow) } pub(super) fn replace_agent_message( &mut self, tui: &mut tui::Tui, range: Range, + fragments: usize, source: history_cell::AgentMarkdownCell, - scrollback_reflow: ConsolidationScrollbackReflow, + mut scrollback_reflow: ConsolidationScrollbackReflow, ) -> Result<()> { - let Range { start, end } = range; + let start = range.start; + let end = start + fragments; if start < end { tracing::debug!( "ConsolidateAgentMessage: replacing cells [{start}..{end}] with AgentMarkdownCell" @@ -69,6 +101,26 @@ impl App { let consolidated: Arc = Arc::new(source); self.native_history .consolidate(&self.transcript_cells[start..end], &consolidated); + let notices = &self.transcript_cells[end..range.end]; + // Replaying native scrollback clears the terminal's history. Hidden + // diagnostics and entirely queued answers never split the printed output. + if !notices.is_empty() + && !tui.is_owned_screen() + && scrollback_reflow == ConsolidationScrollbackReflow::IfResizeReflowRan + && !self.native_history.contains(&consolidated) + { + let width = self + .chat_widget + .history_wrap_width(tui.terminal.last_known_screen_size.width); + let mode = self.chat_widget.history_render_mode(); + if notices.iter().any(|notice| { + !notice + .display_hyperlink_lines_for_mode(width, mode) + .is_empty() + }) { + scrollback_reflow = ConsolidationScrollbackReflow::Required; + } + } if tui.is_owned_screen() { self.transcript_view.replace_group( &self.transcript_cells, @@ -82,13 +134,16 @@ impl App { &consolidated, ); } - self.transcript_cells - .splice(start..end, std::iter::once(consolidated.clone())); - if let Some(Overlay::Transcript(t)) = &mut self.overlay { - t.regroup_cells(start..end, consolidated.clone()); + t.regroup_answer( + range.start, + &self.transcript_cells[range], + fragments, + consolidated.clone(), + ); tui.frame_requester().schedule_frame(); } + self.transcript_cells.splice(start..end, [consolidated]); self.finish_agent_message_consolidation(tui, scrollback_reflow)?; } else { diff --git a/codex-rs/tui/src/app/event_dispatch.rs b/codex-rs/tui/src/app/event_dispatch.rs index 0aa9cf2ade..6f0406637b 100644 --- a/codex-rs/tui/src/app/event_dispatch.rs +++ b/codex-rs/tui/src/app/event_dispatch.rs @@ -1258,6 +1258,7 @@ impl App { self.finish_initial_history_replay_buffer(tui); } AppEvent::ConsolidateAgentMessage { + emitted_cells, phase, interrupted_item, source, @@ -1273,6 +1274,7 @@ impl App { self.handle_consolidate_agent_message( tui, cell, + emitted_cells, scrollback_reflow, deferred_history_cell, )?; @@ -1299,7 +1301,7 @@ impl App { if hidden { self.finish_required_stream_reflow(tui)?; } else { - self.replace_agent_message(tui, index..index + 1, cell, crate::app_event::ConsolidationScrollbackReflow::Required)?; + self.replace_agent_message(tui, index..index + 1, /*fragments*/ 1, cell, crate::app_event::ConsolidationScrollbackReflow::Required)?; } let previous = self.transcript_cells.iter().rev().find(|cell| { (cell.as_any().is::() && !cell.raw_lines().is_empty()) diff --git a/codex-rs/tui/src/app/native_history_tests.rs b/codex-rs/tui/src/app/native_history_tests.rs index 3521543cd5..8d3f8a934f 100644 --- a/codex-rs/tui/src/app/native_history_tests.rs +++ b/codex-rs/tui/src/app/native_history_tests.rs @@ -73,6 +73,31 @@ async fn settled_tool_precedes_queued_output_and_is_not_emitted_twice() -> Resul app.insert_history_cell(&mut tui, Box::new(cell.clone())); app.flush_native_history(&mut tui); assert!(tui.pending_history_lines_for_test().is_empty()); + // Nothing in the split answer has printed. Replaying here would clear shell + // scrollback and re-emit "past context" while the tool still blocks output. + app.insert_history_cell( + &mut tui, + Box::new(history_cell::AgentMessageCell::new( + vec!["Introduction".into()], + /*is_first_line*/ true, + )), + ); + app.insert_history_cell( + &mut tui, + Box::new(history_cell::new_error_event("Paste failed".into())), + ); + app.handle_consolidate_agent_message( + &mut tui, + history_cell::AgentMarkdownCell::new("Introduction and conclusion".into(), &app.config.cwd), + /*emitted_cells*/ 2, + crate::app_event::ConsolidationScrollbackReflow::IfResizeReflowRan, + Some(Box::new(history_cell::AgentMessageCell::new( + vec!["and conclusion".into()], + /*is_first_line*/ false, + ))), + )?; + assert!(tui.pending_history_lines_for_test().is_empty()); + assert!(!app.transcript_reflow.has_pending_reflow()); // A long-lived tool must not lose output queued behind it. for index in 0..4097 { app.insert_history_cell( @@ -109,7 +134,11 @@ async fn settled_tool_precedes_queued_output_and_is_not_emitted_twice() -> Resul .join("\n"); assert_eq!(text.matches("unique result").count(), 1); assert_eq!(text.matches("later output").count(), 4097); - assert!(text.find("unique result").unwrap() < text.find("later output").unwrap()); + let answer = text.find("Introduction and conclusion").unwrap(); + let error = text.find("Paste failed").unwrap(); + assert_eq!(text.matches("Introduction").count(), 1); + assert!(text.find("unique result").unwrap() < answer); + assert!(answer < error && error < text.find("later output").unwrap()); app.flush_native_history(&mut tui); assert_eq!(tui.pending_history_lines_for_test(), lines); // Rollback replay consumes even a queue larger than one frame's drain budget. diff --git a/codex-rs/tui/src/app/owned_transcript_tests.rs b/codex-rs/tui/src/app/owned_transcript_tests.rs index f2f22ae2d7..f15eff2bb6 100644 --- a/codex-rs/tui/src/app/owned_transcript_tests.rs +++ b/codex-rs/tui/src/app/owned_transcript_tests.rs @@ -186,6 +186,7 @@ async fn list_spacing_completion_preserves_the_scrolled_reader() -> Result<()> { "- First item wraps onto a second row\n- b\n- c".into(), &app.config.cwd, ), + /*emitted_cells*/ 1, ConsolidationScrollbackReflow::Required, /*deferred_history_cell*/ None, )?; @@ -1277,7 +1278,7 @@ async fn inline_select_mode_routes_find_and_returns_to_the_preserved_draft() -> async fn inline_transcript_search_draws_and_escape_precedes_backtrack() -> Result<()> { let mut app = crate::app::test_support::make_test_app().await; attach_thread(&mut app, ThreadId::new()); - app.transcript_cells = vec![user_cell("needle in history")]; + app.transcript_cells = vec![user_cell("older NEEDLE"), user_cell("newer needle")]; let mut app_server = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?; let mut tui = crate::tui::test_support::make_test_tui()?; app.open_transcript_overlay(&mut tui); @@ -1285,6 +1286,8 @@ async fn inline_transcript_search_draws_and_escape_precedes_backtrack() -> Resul TuiEvent::Key(KeyEvent::new(KeyCode::Char('/'), KeyModifiers::NONE)), TuiEvent::Paste("needle".to_string()), TuiEvent::Draw, + TuiEvent::Key(KeyEvent::new(KeyCode::Char('p'), KeyModifiers::CONTROL)), + TuiEvent::Draw, ] { app.handle_backtrack_overlay_event(&mut tui, &mut app_server, event) .await?; @@ -1305,6 +1308,38 @@ async fn inline_transcript_search_draws_and_escape_precedes_backtrack() -> Resul assert!( matches!(&app.overlay, Some(Overlay::Transcript(overlay)) if overlay.has_active_interaction() && !overlay.is_search_editing()) ); + // Completing a later split answer must preserve the older, non-default hit. + app.insert_history_cell( + &mut tui, + Box::new(history_cell::AgentMessageCell::new( + vec!["Introduction".into()], + /*is_first_line*/ true, + )), + ); + app.insert_history_cell( + &mut tui, + Box::new(history_cell::new_warning_event("Diagnostic".into())), + ); + app.handle_consolidate_agent_message( + &mut tui, + history_cell::AgentMarkdownCell::new("Introduction and conclusion".into(), &app.config.cwd), + /*emitted_cells*/ 2, + ConsolidationScrollbackReflow::IfResizeReflowRan, + Some(Box::new(history_cell::AgentMessageCell::new( + vec!["and conclusion".into()], + /*is_first_line*/ false, + ))), + )?; + app.handle_backtrack_overlay_event(&mut tui, &mut app_server, TuiEvent::Draw) + .await?; + let buffer = crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal); + let highlighted = buffer + .content() + .iter() + .filter(|cell| cell.modifier.contains(ratatui::style::Modifier::REVERSED)) + .map(ratatui::buffer::Cell::symbol) + .collect::(); + assert_eq!(highlighted, "NEEDLE"); assert!(!app.backtrack.overlay_preview_active); app.handle_backtrack_overlay_event( &mut tui, diff --git a/codex-rs/tui/src/app/tests.rs b/codex-rs/tui/src/app/tests.rs index 94a52a909e..cd727beefc 100644 --- a/codex-rs/tui/src/app/tests.rs +++ b/codex-rs/tui/src/app/tests.rs @@ -10277,6 +10277,7 @@ async fn directive_only_completion_removes_streamed_directive() -> Result<()> { app.handle_consolidate_agent_message( &mut tui, AgentMarkdownCell::new(String::new(), Path::new("/tmp")), + /*emitted_cells*/ 1, ConsolidationScrollbackReflow::Required, /*deferred_history_cell*/ None, )?; @@ -10324,6 +10325,7 @@ async fn required_stream_reflow_during_capped_initial_replay_survives_transcript .into(), Path::new("/tmp"), ), + /*emitted_cells*/ 1, ConsolidationScrollbackReflow::Required, /*deferred_history_cell*/ None, )?; diff --git a/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__transcript_composer__interleaved_notices_preserve_the_answer_in_transcript_and_reflow.snap b/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__transcript_composer__interleaved_notices_preserve_the_answer_in_transcript_and_reflow.snap new file mode 100644 index 0000000000..c647d72bed --- /dev/null +++ b/codex-rs/tui/src/app/tests/snapshots/codex_tui__app__tests__transcript_composer__interleaved_notices_preserve_the_answer_in_transcript_and_reflow.snap @@ -0,0 +1,19 @@ +--- +source: tui/src/app/tests/transcript_composer.rs +expression: "screens[0]" +--- +/ T R A N S C R I P T / / / / / / / / / / / / / / / / / / / / / / / / / / / / / +• Earlier answer + +• Introduction + + Conclusion + +⚠ Diagnostic + +■ Failed to paste image: no image on clipboard + + +⌃space select + ↑/↓ to scroll · pgup/pgdn to page · home/end to jump + q close · f3 find · esc browse prompts diff --git a/codex-rs/tui/src/app/tests/transcript_composer.rs b/codex-rs/tui/src/app/tests/transcript_composer.rs index 846034a10f..ab236aec0f 100644 --- a/codex-rs/tui/src/app/tests/transcript_composer.rs +++ b/codex-rs/tui/src/app/tests/transcript_composer.rs @@ -41,6 +41,81 @@ async fn press_key( Ok(()) } +#[tokio::test] +async fn interleaved_notices_preserve_the_answer_in_transcript_and_reflow() -> Result<()> { + let mut screens = Vec::new(); + for trailing_error in [false, true] { + let (mut app, _rx, _op_rx) = make_test_app_with_channels().await; + let mut tui = crate::tui::test_support::make_test_tui()?; + app.transcript_cells = vec![ + Arc::new(AgentMarkdownCell::new( + "Earlier answer".into(), + &app.config.cwd, + )), + Arc::new(AgentMessageCell::new( + vec!["Introduction".into()], + /*is_first_line*/ true, + )), + // Visible in Ctrl+T but hidden in native scrollback. + Arc::new(history_cell::new_warning_event("Diagnostic".into())), + ]; + let error = Arc::new(history_cell::new_error_event( + "Failed to paste image: no image on clipboard".into(), + )); + let tail = Arc::new(AgentMessageCell::new( + vec!["Conclusion".into()], + /*is_first_line*/ false, + )); + let last: [Arc; 2] = if trailing_error { + [tail, error] + } else { + [error, tail] + }; + app.transcript_cells.extend(last); + app.open_transcript_overlay(&mut tui); + app.handle_consolidate_agent_message( + &mut tui, + AgentMarkdownCell::new("Introduction\n\nConclusion".into(), &app.config.cwd), + /*emitted_cells*/ 2, + ConsolidationScrollbackReflow::IfResizeReflowRan, + /*deferred_history_cell*/ None, + )?; + + // Only a visible notice between fragments warrants clearing native scrollback. + assert_eq!(app.transcript_reflow.has_pending_reflow(), !trailing_error); + for width in [80, 60, 80] { + let rendered = app.render_transcript_lines_for_reflow(width); + let lines = rendered + .lines + .iter() + .map(rendered_line_text) + .filter(|line| !line.trim().is_empty()) + .collect::>(); + assert_eq!( + lines, + [ + "• Earlier answer", + "• Introduction", + " Conclusion", + "■ Failed to paste image: no image on clipboard", + ] + ); + } + let area = Rect::new( + /*x*/ 0, /*y*/ 0, /*width*/ 80, /*height*/ 16, + ); + let mut buffer = ratatui::buffer::Buffer::empty(area); + let Some(Overlay::Transcript(overlay)) = &mut app.overlay else { + panic!("viewer closed") + }; + overlay.render(area, &mut buffer); + screens.push(buffer_text(&buffer)); + } + assert_eq!(screens[0], screens[1]); + insta::assert_snapshot!(screens[0]); + Ok(()) +} + #[tokio::test] async fn analytics_preserves_the_draft_and_retains_the_view_on_reopen() -> Result<()> { let (mut app, _app_event_rx, _op_rx) = make_test_app_with_channels().await; diff --git a/codex-rs/tui/src/app/tests/user_verification_routes_tests.rs b/codex-rs/tui/src/app/tests/user_verification_routes_tests.rs index ef49e991de..16072a5a08 100644 --- a/codex-rs/tui/src/app/tests/user_verification_routes_tests.rs +++ b/codex-rs/tui/src/app/tests/user_verification_routes_tests.rs @@ -287,6 +287,7 @@ async fn inactive_thread_user_verification_preserves_foreground_stream() -> Resu } => approved.push((thread_id, server_name, request_id)), AppEvent::InsertHistoryCell(cell) => app.insert_history_cell(&mut tui, cell), AppEvent::ConsolidateAgentMessage { + emitted_cells, source, copy_source, cwd, @@ -304,6 +305,7 @@ async fn inactive_thread_user_verification_preserves_foreground_stream() -> Resu inline_visualization_context, ) .with_copy_source(copy_source), + emitted_cells, scrollback_reflow, deferred_history_cell, )?; diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index db735c7101..992a0e7173 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -1439,8 +1439,7 @@ pub(crate) enum AppEvent { /// Finish buffering initial resume replay after all replay events have been queued. EndInitialHistoryReplayBuffer, - /// Replace the contiguous run of streaming `AgentMessageCell`s at the end of - /// the transcript with a single `AgentMarkdownCell` that stores the raw + /// Replace this answer's streaming `AgentMessageCell`s with a single `AgentMarkdownCell` that stores the raw /// markdown source and re-renders from it on resize. /// /// Emitted by `ChatWidget::flush_answer_stream_with_separator` after stream @@ -1452,6 +1451,8 @@ pub(crate) enum AppEvent { /// `deferred_history_cell` lets callers add the final stream tail to the /// transcript without first writing its provisional render to scrollback. ConsolidateAgentMessage { + /// Bounds the search across notices, including when the stream emitted no cells. + emitted_cells: usize, phase: Option, interrupted_item: Option<(String, String)>, source: String, diff --git a/codex-rs/tui/src/chatwidget/streaming.rs b/codex-rs/tui/src/chatwidget/streaming.rs index 88451040f3..f2ffee9d4a 100644 --- a/codex-rs/tui/src/chatwidget/streaming.rs +++ b/codex-rs/tui/src/chatwidget/streaming.rs @@ -158,6 +158,7 @@ impl ChatWidget { }); self.note_stream_consolidation_queued(); self.app_event_tx.send(AppEvent::ConsolidateAgentMessage { + emitted_cells: controller.emitted_cells(), phase, interrupted_item, source, diff --git a/codex-rs/tui/src/pager_overlay/transcript.rs b/codex-rs/tui/src/pager_overlay/transcript.rs index d8643b2859..f01b641839 100644 --- a/codex-rs/tui/src/pager_overlay/transcript.rs +++ b/codex-rs/tui/src/pager_overlay/transcript.rs @@ -379,6 +379,21 @@ impl TranscriptOverlay { self.view.set_highlight(self.highlight_cell); } + pub(crate) fn regroup_answer( + &mut self, + start: usize, + ordered: &[Arc], + fragments: usize, + consolidated: Arc, + ) { + if fragments < ordered.len() { + let range = start..start + ordered.len(); + self.view.retain_before_regroup(&self.cells, range.clone()); + self.cells[range].clone_from_slice(ordered); + } + self.regroup_cells(start..start + fragments, consolidated); + } + /// Grouping may change compact previews; retain the reader's revision before replacing cells. pub(crate) fn regroup_cells( &mut self, diff --git a/codex-rs/tui/src/streaming/controller.rs b/codex-rs/tui/src/streaming/controller.rs index 39f10f7c68..8fdeb15f7d 100644 --- a/codex-rs/tui/src/streaming/controller.rs +++ b/codex-rs/tui/src/streaming/controller.rs @@ -589,7 +589,7 @@ impl StreamCore { /// Wraps [`StreamCore`] and adds `AgentMessageCell` emission styling. pub(crate) struct StreamController { core: StreamCore, - header_emitted: bool, + emitted_cells: usize, } impl StreamController { @@ -622,7 +622,7 @@ impl StreamController { ) -> Self { Self { core: StreamCore::new(width, cwd, render_mode, inline_visualization_context), - header_emitted: false, + emitted_cells: 0, } } @@ -676,7 +676,7 @@ impl StreamController { #[inline] pub(crate) fn tail_starts_stream(&self) -> bool { - !self.header_emitted && self.core.enqueued_stable_len == 0 + self.emitted_cells == 0 && self.core.enqueued_stable_len == 0 } #[inline] @@ -684,6 +684,11 @@ impl StreamController { self.core.has_tail() } + /// Includes the final fragment, if any, after `finalize`. + pub(crate) fn emitted_cells(&self) -> usize { + self.emitted_cells + } + /// Include the unterminated line when handing an in-flight answer to another view. pub(crate) fn source_snapshot(&self) -> String { let collector = &self.core.state.collector; @@ -729,12 +734,9 @@ impl StreamController { if lines.is_empty() { return None; } + self.emitted_cells += 1; Some(Box::new( - history_cell::AgentMessageCell::new_hyperlink_lines(lines, { - let header_emitted = self.header_emitted; - self.header_emitted = true; - !header_emitted - }), + history_cell::AgentMessageCell::new_hyperlink_lines(lines, self.emitted_cells == 1), )) } } diff --git a/codex-rs/tui/src/transcript_view/mutations.rs b/codex-rs/tui/src/transcript_view/mutations.rs index c53fc265d0..a5bf2f1da4 100644 --- a/codex-rs/tui/src/transcript_view/mutations.rs +++ b/codex-rs/tui/src/transcript_view/mutations.rs @@ -135,9 +135,19 @@ impl TranscriptView { snapshot.cells = joined.into(); return; } - if searching - || matches!(self.position, Position::Reading(anchor) - if cells[range].iter().any(|cell| EntryKey::cell(cell) == anchor.key)) + self.retain_before_regroup(cells, range); + } + + /// Preserve the original order before a regroup moves cells across a search cursor. + pub(crate) fn retain_before_regroup( + &mut self, + cells: &[Arc], + range: Range, + ) { + if self.snapshot().is_none() + && (self.search.has_active_query() + || matches!(self.position, Position::Reading(anchor) + if cells[range].iter().any(|cell| EntryKey::cell(cell) == anchor.key))) { self.held_reading = Some(self.capture_snapshot(cells)); }