From 69a470755d1f59aa651a1aa2f31ac70f99031d58 Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Mon, 23 Nov 2026 07:17:08 +0000 Subject: [PATCH] Render terminal progress redraws in TUI command output (#63278) ## Why Commands often update progress in place using carriage returns and ANSI erase-line sequences. Treating those writes as ordinary text can leave stale progress visible, and treating each streamed chunk as a line can split a single update in `/ps`. ## What changed Resolve redraws into the visible row before laying out live and completed command output or rendering transcript entries. Preserve the unwritten suffix on a shorter overwrite, honor line erases, and retain ANSI styling for the text that survives. Buffer partial rows across output chunks so `/ps` shows the latest visible lines as plain text. ## Testing Cover split escape sequences and CRLF, styled and wide-character overwrites, and redraws after the live output byte limit. Check that live and completed previews agree and that replayed background terminals and historical command fallbacks show the resolved text. GitOrigin-RevId: cabb3d33442fbf119e23a12b2c66cb62d88bd06c --- codex-rs/tui/src/chatwidget.rs | 2 +- .../tui/src/chatwidget/command_lifecycle.rs | 30 +-- codex-rs/tui/src/chatwidget/exec_state.rs | 19 ++ .../tui/src/chatwidget/tests/exec_flow.rs | 12 ++ codex-rs/tui/src/exec_cell/live_output.rs | 149 +++++++++----- .../tui/src/exec_cell/live_output_tests.rs | 71 ++++++- codex-rs/tui/src/exec_cell/mod.rs | 4 + codex-rs/tui/src/exec_cell/model.rs | 5 +- codex-rs/tui/src/exec_cell/output_line.rs | 182 ++++++++++++++++++ codex-rs/tui/src/thread_transcript/tools.rs | 11 +- .../tui/src/thread_transcript/tools_tests.rs | 4 +- codex-rs/tui/src/tool_output_tests.rs | 2 +- 12 files changed, 419 insertions(+), 72 deletions(-) create mode 100644 codex-rs/tui/src/exec_cell/output_line.rs diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 2e43388cd5..07c3f65b8e 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -1555,7 +1555,7 @@ impl ChatWidget { .iter() .map(|process| history_cell::UnifiedExecProcessDetails { command_display: process.command_display.clone(), - recent_chunks: process.recent_chunks.clone(), + recent_chunks: process.recent_lines(), }) .collect(); self.add_to_history(history_cell::new_unified_exec_processes_output(processes)); diff --git a/codex-rs/tui/src/chatwidget/command_lifecycle.rs b/codex-rs/tui/src/chatwidget/command_lifecycle.rs index 68455112a8..8a1d16f37a 100644 --- a/codex-rs/tui/src/chatwidget/command_lifecycle.rs +++ b/codex-rs/tui/src/chatwidget/command_lifecycle.rs @@ -5,6 +5,7 @@ use super::*; use crate::exec_cell::CommandOutput; +use crate::exec_cell::plain_output_text; impl ChatWidget { pub(super) fn flush_unified_exec_wait_streak(&mut self) { @@ -57,7 +58,7 @@ impl ChatWidget { } pub(super) fn on_exec_command_output_delta(&mut self, call_id: &str, delta: &str) { - self.track_unified_exec_output_chunk(call_id, delta.as_bytes()); + self.track_unified_exec_output_chunk(call_id, delta); if !self.bottom_pane.is_task_running() { return; } @@ -184,12 +185,14 @@ impl ChatWidget { existing.call_id = call_id.to_string(); existing.command_display = command_display; existing.recent_chunks.clear(); + existing.pending = Default::default(); } else { self.unified_exec_processes.push(UnifiedExecProcessSummary { key, call_id: call_id.to_string(), command_display, recent_chunks: Vec::new(), + pending: Default::default(), }); } self.sync_unified_exec_footer(); @@ -230,6 +233,7 @@ impl ChatWidget { call_id: terminal.item_id, command_display: terminal.command, recent_chunks: Vec::new(), + pending: Default::default(), }); } } @@ -263,7 +267,7 @@ impl ChatWidget { } /// Record recent stdout/stderr lines for the unified exec footer. - pub(super) fn track_unified_exec_output_chunk(&mut self, call_id: &str, chunk: &[u8]) { + fn track_unified_exec_output_chunk(&mut self, call_id: &str, chunk: &str) { let Some(process) = self .unified_exec_processes .iter_mut() @@ -272,20 +276,20 @@ impl ChatWidget { return; }; - let text = String::from_utf8_lossy(chunk); - for line in text - .lines() - .map(str::trim_end) + let limit = UnifiedExecProcessSummary::MAX_RECENT_CHUNKS; + let insert_at = process.recent_chunks.len(); + for line in process + .pending + .push_lines(chunk) + .rev() + .map(plain_output_text) .filter(|line| !line.is_empty()) + .take(limit) { - process.recent_chunks.push(line.to_string()); - } - - const MAX_RECENT_CHUNKS: usize = 3; - if process.recent_chunks.len() > MAX_RECENT_CHUNKS { - let drop_count = process.recent_chunks.len() - MAX_RECENT_CHUNKS; - process.recent_chunks.drain(0..drop_count); + process.recent_chunks.insert(insert_at, line); } + let excess = process.recent_chunks.len().saturating_sub(limit); + process.recent_chunks.drain(..excess); } pub(crate) fn handle_command_execution_started_now(&mut self, item: ThreadItemPayload) { diff --git a/codex-rs/tui/src/chatwidget/exec_state.rs b/codex-rs/tui/src/chatwidget/exec_state.rs index c8bb698cef..7c5e609bb6 100644 --- a/codex-rs/tui/src/chatwidget/exec_state.rs +++ b/codex-rs/tui/src/chatwidget/exec_state.rs @@ -3,6 +3,8 @@ use codex_app_server_protocol::CommandExecutionSource as ExecCommandSource; use codex_protocol::parse_command::ParsedCommand; +use crate::exec_cell::PendingLine; +use crate::exec_cell::plain_output_text; use crate::exec_command::split_command_string; pub(super) struct RunningCommand { @@ -16,6 +18,23 @@ pub(super) struct UnifiedExecProcessSummary { pub(super) call_id: String, pub(super) command_display: String, pub(super) recent_chunks: Vec, + pub(super) pending: PendingLine, +} + +impl UnifiedExecProcessSummary { + pub(super) const MAX_RECENT_CHUNKS: usize = 3; + + pub(super) fn recent_lines(&self) -> Vec { + let mut lines = self.recent_chunks.clone(); + let pending = plain_output_text(self.pending.clone().render()); + if !pending.is_empty() { + if lines.len() == Self::MAX_RECENT_CHUNKS { + lines.remove(0); + } + lines.push(pending); + } + lines + } } pub(super) struct UnifiedExecWaitState { diff --git a/codex-rs/tui/src/chatwidget/tests/exec_flow.rs b/codex-rs/tui/src/chatwidget/tests/exec_flow.rs index f2cabb6d07..e0a71e9f34 100644 --- a/codex-rs/tui/src/chatwidget/tests/exec_flow.rs +++ b/codex-rs/tui/src/chatwidget/tests/exec_flow.rs @@ -78,6 +78,14 @@ async fn replayed_background_terminals_belong_to_the_displayed_thread() { }; fork.track_unified_exec_process_end(&exited.item_id, Some(&exited.process_id)); fork.restore_background_terminals(request_id, vec![live, exited]); + for chunk in [ + "starting\n\x1b]0;Building\x07Warning\n10%\r50%\r\x1b[", + "K\x1b]0;Done\x1b", + "\\100%\r", + "\nDone\ncleared\r\x1b[K", + ] { + fork.on_exec_command_output_delta("child-call", chunk); + } fork.add_ps_output(); let history = drain_insert_history(&mut events) .iter() @@ -89,6 +97,9 @@ async fn replayed_background_terminals_belong_to_the_displayed_thread() { Background terminals • sleep 200 + ↳ Warning + 100% + Done "); } @@ -948,6 +959,7 @@ async fn unified_exec_wait_status_header_updates_on_late_command_display() { call_id: "call-1".to_string(), command_display: "sleep 5".to_string(), recent_chunks: Vec::new(), + pending: Default::default(), }); terminal_interaction(&mut chat, "call-1", "proc-1", ""); diff --git a/codex-rs/tui/src/exec_cell/live_output.rs b/codex-rs/tui/src/exec_cell/live_output.rs index 46f9ab2a9f..fe71e69115 100644 --- a/codex-rs/tui/src/exec_cell/live_output.rs +++ b/codex-rs/tui/src/exec_cell/live_output.rs @@ -1,3 +1,4 @@ +use super::command_output_line; use itertools::Either; use std::borrow::Cow; use std::collections::VecDeque; @@ -21,10 +22,9 @@ pub(super) struct LiveCommandOutput { truncated: bool, head: Vec, tail: VecDeque, - current: LiveCommandOutputLine, + current: PendingLine, completed_lines: usize, has_partial_line: bool, - pending_carriage_return: bool, } impl LiveCommandOutput { @@ -52,39 +52,12 @@ impl LiveCommandOutput { self.push_truncated_str(chunk); } - /// Appends bounded output while treating a split CRLF as one terminator and retaining lone CRs. fn push_truncated_str(&mut self, chunk: &str) { - for part in chunk.split_inclusive('\n') { - let Some(part) = part.strip_suffix('\n') else { - if part.is_empty() { - continue; - } - if self.pending_carriage_return { - self.current.push_str("\r"); - self.pending_carriage_return = false; - } - let part = if let Some(part) = part.strip_suffix('\r') { - self.pending_carriage_return = true; - part - } else { - part - }; - self.current.push_str(part); - self.has_partial_line |= !part.is_empty() || self.pending_carriage_return; - continue; - }; - - let has_carriage_return = part.ends_with('\r'); - let part = part.strip_suffix('\r').unwrap_or(part); - if self.pending_carriage_return && (has_carriage_return || !part.is_empty()) { - self.current.push_str("\r"); - } - self.pending_carriage_return = false; - self.current.push_str(part); + if !chunk.is_empty() { + self.has_partial_line = !chunk.ends_with('\n'); + } + for line in self.current.push_lines(chunk) { self.completed_lines = self.completed_lines.saturating_add(1); - self.has_partial_line = false; - - let line = std::mem::take(&mut self.current).render(); if self.head.len() < LIVE_COMMAND_OUTPUT_MAX_LINES { self.head.push(line); } else { @@ -122,23 +95,24 @@ impl LiveCommandOutput { .map(|line| Cow::Borrowed(line.as_str())) .chain( self.has_partial_line - .then(|| Cow::Owned(self.render_partial_line())), + .then(|| Cow::Owned(self.current.clone().render())), ), ) } else { Either::Right(self.full_output.lines().map(|line| { + let line = command_output_line(line); if line.len() <= LIVE_COMMAND_OUTPUT_MAX_LINE_BYTES { - Cow::Borrowed(line) + line } else { let mut truncated = LiveCommandOutputLine::default(); - truncated.push_str(line); + truncated.push_str(&line); Cow::Owned(truncated.render()) } })) } } - /// Returns lossless transcript lines until truncated, then inserts the omitted-line marker. + /// Returns full visible transcript lines until truncated, then inserts the omitted-line marker. pub(super) fn transcript_lines(&self) -> impl Iterator> { let omitted = self.total_lines().saturating_sub(self.retained_lines()); if self.truncated { @@ -153,32 +127,111 @@ impl LiveCommandOutput { .chain(self.tail.iter().map(|line| Cow::Borrowed(line.as_str()))) .chain( self.has_partial_line - .then(|| Cow::Owned(self.render_partial_line())), + .then(|| Cow::Owned(self.current.clone().render())), ), ) } else { - Either::Right(self.full_output.lines().map(Cow::Borrowed)) + Either::Right(self.full_output.lines().map(command_output_line)) } } - - fn render_partial_line(&self) -> String { - let mut line = self.current.render(); - if self.pending_carriage_return { - line.push('\r'); - } - line - } } -#[derive(Debug, Default)] +/// Bounded state for an unfinished row. Keep the write after the last CR +/// together across deltas, including any partial escape or grapheme. +#[derive(Clone, Debug, Default)] +pub(crate) struct PendingLine { + previous: LiveCommandOutputLine, + write: LiveCommandOutputLine, +} + +impl PendingLine { + /// Yield completed rows lazily and keep the unfinished row for the next delta. + pub(crate) fn push_lines(&mut self, chunk: &str) -> impl DoubleEndedIterator { + let mut parts = chunk.split('\n'); + let partial = parts.next_back().unwrap_or_default(); + let first = parts.next().map(|part| (std::mem::take(self), part)); + self.push_str(partial); + first + .into_iter() + .chain(parts.map(|part| (Self::default(), part))) + .map(|(mut row, part)| { + row.push_str(part); + row.render() + }) + } + + fn push_str(&mut self, mut text: &str) { + while !text.is_empty() { + // Fold a batch of redraws together before abbreviating. A long + // single write still uses the ordinary bounded head/tail buffer. + let room = if self.previous.omitted_bytes > 0 && !self.previous.variable_width { + // Overlay individual writes directly at their original byte offsets. + 0 + } else { + LIVE_COMMAND_OUTPUT_MAX_LINE_BYTES + .saturating_sub(self.write.head.len() + self.write.tail.len()) + }; + let end = text.floor_char_boundary(room.min(text.len())); + let Some(cr) = text[..end].rfind('\r').or_else(|| text.find('\r')) else { + self.write.push_str(text); + break; + }; + self.write.push_str(text[..cr].trim_end_matches('\r')); + self.previous.overwrite(std::mem::take(&mut self.write)); + text = &text[cr + 1..]; + } + } + + pub(crate) fn render(mut self) -> String { + self.previous.overwrite(self.write); + self.previous.render() + } +} + +#[derive(Clone, Debug, Default)] struct LiveCommandOutputLine { head: String, tail: String, omitted_bytes: usize, + variable_width: bool, } impl LiveCommandOutputLine { + fn overwrite(&mut self, write: Self) { + if write.head.is_empty() { + return; + } + if !self.variable_width && !write.variable_width { + // Byte offsets equal columns, even across an omitted middle. + let end = write.head.len() + write.omitted_bytes + write.tail.len(); + let tail_start = self.head.len() + self.omitted_bytes; + if end >= tail_start + self.tail.len() { + *self = write; + } else { + self.head.replace_range(..write.head.len(), &write.head); + let overlap = end.saturating_sub(tail_start); + self.tail + .replace_range(..overlap, &write.tail[write.tail.len() - overlap..]); + } + return; + } + + let mut raw = self.render(); + if !raw.is_empty() { + raw.push('\r'); + } + raw.push_str(&write.render()); + match command_output_line(&raw) { + Cow::Borrowed(_) => *self = write, + Cow::Owned(line) => { + *self = Self::default(); + self.push_str(&line); + } + } + } + fn push_str(&mut self, chunk: &str) { + self.variable_width |= !chunk.is_ascii() || chunk.contains(['\x1b', '\t', '\r']); let head_remaining = if self.tail.is_empty() && self.omitted_bytes == 0 { LIVE_COMMAND_OUTPUT_LINE_HEAD_BYTES.saturating_sub(self.head.len()) } else { diff --git a/codex-rs/tui/src/exec_cell/live_output_tests.rs b/codex-rs/tui/src/exec_cell/live_output_tests.rs index 246c82022f..a5d2696ab3 100644 --- a/codex-rs/tui/src/exec_cell/live_output_tests.rs +++ b/codex-rs/tui/src/exec_cell/live_output_tests.rs @@ -53,7 +53,7 @@ fn switches_to_bounded_storage_after_the_byte_budget_and_preserves_split_crlf() .transcript_lines() .next() .expect("partial line") - .ends_with('\r') + .ends_with('x') ); split.push_str("\n"); @@ -133,3 +133,72 @@ fn retained_output_stays_within_the_live_byte_budget() { ); assert!(lines.iter().map(|line| line.len()).sum::() <= LIVE_COMMAND_OUTPUT_MAX_BYTES); } + +#[test] +fn progress_redraws_agree_across_chunks_and_the_live_byte_limit() { + for prefix in [String::new(), "x".repeat(LIVE_COMMAND_OUTPUT_MAX_BYTES)] { + let mut output = LiveCommandOutput::default(); + output.push_str(&prefix); + output.push_str("\n"); + for (chunk, expected) in [ + ("abcdef\r", "abcdef"), + ("XY", "XYcdef"), + ("\x1b[", "XYcdef"), + ("K", "XY"), + ("\r界\u{301}ok\r!", "! ok"), + ("\r\x1b[0K100%", "100%"), + ("\rDownloading 100%\r\x1b[2KDone", "Done"), + ("\rXY\x1b[2K!", " !"), + ("\r\x1b[K\r\x1b[K\r\x1b[K", ""), + ("\x1b[31m10%\r", "\x1b[31m10%"), + ("100%\x1b[0m", "\x1b[31m100%\x1b[0m"), + ("\r\x1b[31mabcdef\rXY\rZ", "\x1b[31mZYcdef"), + ("\r\x1b[32m!", "\x1b[32m!\x1b[31mYcdef"), + ("\r\x1b[1;44;31m.\x1b[39m\rFinished", "\x1b[1;44mFinished"), + ] { + output.push_str(chunk); + let row = output.lines().next_back().expect("progress row"); + let actual = ansi_escape_line(&row); + let expected = ansi_escape_line(expected); + let base = ratatui::style::Style::reset(); + assert_eq!( + actual.styled_graphemes(base).collect::>(), + expected.styled_graphemes(base).collect::>() + ); + } + } +} + +#[test] +fn overwritten_colors_do_not_consume_the_preview_budget() { + let raw = "\x1b[31m.\x1b[39m\r".repeat(1100) + "Done!"; + let mut live = LiveCommandOutput::default(); + live.push_str(&raw); + let mut pending = super::PendingLine::default(); + pending.push_str(&raw); + let ps = crate::exec_cell::plain_output_text(pending.render()); + let completed = crate::exec_cell::CommandOutput::new(/*exit_code*/ 0, raw); + + assert_eq!(ps, "Done!"); + for row in [live.lines().next(), completed.lines().next()] { + let line = ansi_escape_line(&row.expect("progress row")); + let base = ratatui::style::Style::reset(); + assert_eq!(line.to_string(), "Done!"); + assert!(line.styled_graphemes(base).all(|g| g.style == base)); + } +} + +#[test] +fn long_redraw_overwrites_columns_before_abbreviating_the_row() { + let mut output = LiveCommandOutput::default(); + output.push_str(&"x".repeat(LIVE_COMMAND_OUTPUT_MAX_BYTES)); + output.push_str("\n"); + output.push_str(&"x".repeat(15_000)); + output.push_str(&format!("\r{}\rabc\rXY\r\n", "y".repeat(12_000))); + + let mut expected = LiveCommandOutput::default(); + expected.push_str("XYc"); + expected.push_str(&"y".repeat(11_997)); + expected.push_str(&"x".repeat(3_000)); + assert_eq!(output.lines().next_back(), expected.lines().next_back()); +} diff --git a/codex-rs/tui/src/exec_cell/mod.rs b/codex-rs/tui/src/exec_cell/mod.rs index aaa32e1951..aa4fc0c3fa 100644 --- a/codex-rs/tui/src/exec_cell/mod.rs +++ b/codex-rs/tui/src/exec_cell/mod.rs @@ -1,13 +1,17 @@ mod compact; mod live_output; mod model; +mod output_line; mod render; mod transcript; +pub(crate) use live_output::PendingLine; pub(crate) use model::CommandOutput; #[cfg(test)] pub(crate) use model::ExecCall; pub(crate) use model::ExecCell; +pub(crate) use output_line::command_output_line; +pub(crate) use output_line::plain_output_text; pub(crate) use render::OutputLinesParams; pub(crate) use render::TOOL_CALL_MAX_LINES; pub(crate) use render::new_active_exec_command; diff --git a/codex-rs/tui/src/exec_cell/model.rs b/codex-rs/tui/src/exec_cell/model.rs index 241e682a49..4b1e2c7f93 100644 --- a/codex-rs/tui/src/exec_cell/model.rs +++ b/codex-rs/tui/src/exec_cell/model.rs @@ -11,6 +11,7 @@ use std::borrow::Cow; use std::time::Duration; use std::time::Instant; +use super::command_output_line; use super::live_output::LiveCommandOutput; use crate::history_cell::ActivityGroup; use codex_app_server_protocol::CommandExecutionSource as ExecCommandSource; @@ -69,7 +70,7 @@ impl CommandOutput { pub(super) fn lines(&self) -> impl DoubleEndedIterator> { match self.live_output.as_ref() { Some(output) => Either::Left(output.lines()), - None => Either::Right(self.aggregated_output.lines().map(Cow::Borrowed)), + None => Either::Right(self.aggregated_output.lines().map(command_output_line)), } } @@ -77,7 +78,7 @@ impl CommandOutput { pub(super) fn transcript_lines(&self) -> impl Iterator> { match self.live_output.as_ref() { Some(output) => Either::Left(output.transcript_lines()), - None => Either::Right(self.aggregated_output.lines().map(Cow::Borrowed)), + None => Either::Right(self.aggregated_output.lines().map(command_output_line)), } } } diff --git a/codex-rs/tui/src/exec_cell/output_line.rs b/codex-rs/tui/src/exec_cell/output_line.rs new file mode 100644 index 0000000000..bd6dd88a9d --- /dev/null +++ b/codex-rs/tui/src/exec_cell/output_line.rs @@ -0,0 +1,182 @@ +//! Resolve progress writes within one LF-delimited command output row before layout. +//! CR returns to column zero. Erasing the line discards the unwritten suffix. + +use crate::width::display_width; +use ratatui::style::Style; +use regex_lite::Regex; +use std::borrow::Cow; +use std::sync::LazyLock; +use unicode_segmentation::UnicodeSegmentation; + +// ansi-to-tui only recognizes BEL as an OSC terminator. +static OSC: LazyLock = LazyLock::new(|| { + Regex::new(r"\x1b\][^\x07\x1b]*(?:\x07|\x1b\\|\x1b?$)") + .unwrap_or_else(|err| panic!("invalid OSC regex: {err}")) +}); +static CSI: LazyLock = LazyLock::new(|| { + Regex::new(r"\x1b\[[0-?]*[ -/]*(?:[@-~]|$)") + .unwrap_or_else(|err| panic!("invalid CSI regex: {err}")) +}); + +/// Plain text for /ps and historical command fallbacks. +pub(crate) fn plain_output_text(mut line: String) -> String { + if line.contains('\x1b') { + line = codex_ansi_escape::ansi_escape_line(&line).to_string(); + } + line.truncate(line.trim_end().len()); + line +} + +/// Keep an SGR only while it supplies an attribute that later SGRs leave alone. +/// Use the renderer's parser so compound codes and partial resets agree with layout. +fn style_prefixes(raw: &str, offsets: impl Iterator) -> Vec> { + let mut active: Vec<(&str, Style)> = Vec::new(); + let mut sample = String::new(); + let mut controls = CSI.find_iter(raw).peekable(); + offsets + .map(|offset| { + while let Some(control) = controls.next_if(|c| c.start() < offset) { + let sgr = control.as_str(); + if !sgr.ends_with('m') || active.first().is_some_and(|(last, _)| *last == sgr) { + continue; + } + if matches!(sgr, "\x1b[m" | "\x1b[0m") { + active.clear(); + continue; + } + // The parser attaches the style to the next printable character. + sample.clear(); + sample.push_str(sgr); + sample.push(' '); + let text = codex_ansi_escape::ansi_escape(&sample); + let Some(span) = text.lines.first().and_then(|line| line.spans.first()) else { + continue; + }; + let mut newer = span.style; + // Newest first. Each retained code contributes at least one attribute. + active.retain(|(_, style)| { + let combined = style.patch(newer); + let needed = combined != newer; + newer = combined; + needed + }); + active.insert(0, (sgr, span.style)); + } + active.iter().rev().map(|(sgr, _)| *sgr).collect() + }) + .collect() +} + +pub(crate) fn command_output_line(raw: &str) -> Cow<'_, str> { + let raw = raw.trim_end_matches('\r'); + let raw = if raw.contains("\x1b]") && (raw.contains('\r') || raw.contains("\x1b\\")) { + OSC.replace_all(raw, "") + } else { + Cow::Borrowed(raw) + }; + if !raw.contains('\r') && !raw.contains("\x1b[2K") { + return raw; + } + + // Later writes cover a prefix of every earlier write. Walk backwards so a + // short repeated progress update never copies a long surviving tail twice. + let mut covered = 0; + let styled = raw.contains('\x1b'); + let mut result = String::new(); + let mut fragments = Vec::new(); + let mut end = raw.len(); + for write in raw.rsplit('\r') { + let start_of_write = end - write.len(); + end = start_of_write.saturating_sub(1); + let mut offset = start_of_write; + let mut erased = false; + let (column, suffix) = if write.is_ascii() && !write.contains(['\x1b', '\t']) { + ( + write.len(), + Cow::Borrowed(write.get(covered..).unwrap_or_default()), + ) + } else { + let mut column = 0; + let mut start = 0; + let mut suffix = String::new(); + let mut visible_end = 0; + // A whole-line erase blanks earlier columns without moving the cursor. + let clear = write.rfind("\x1b[2K"); + for control in CSI.find_iter(write).map(Some).chain([None]) { + let end = control + .as_ref() + .map_or(write.len(), regex_lite::Match::start); + for g in write[start..end].graphemes(true) { + if g == "\x1b" { + continue; + } + let width = if g == "\t" { 4 } else { display_width(g) }; + if clear.is_some_and(|clear| start < clear) { + column += width; + continue; + } + if suffix.is_empty() { + offset = start_of_write + start; + } + if column >= covered { + suffix.push_str(g); + } else if column + width > covered { + // Overwriting half a wide glyph clears its remaining cells. + suffix.extend(std::iter::repeat_n(' ', column + width - covered)); + } + column += width; + visible_end = suffix.len(); + } + if let Some(control) = control { + match control.as_str() { + "\x1b[K" | "\x1b[0K" => erased = true, + "\x1b[2K" if Some(control.start()) == clear => { + erased = true; + offset = start_of_write + control.start(); + suffix.extend(std::iter::repeat_n(' ', column.saturating_sub(covered))); + visible_end = suffix.len(); + } + sgr if !suffix.is_empty() && sgr.ends_with('m') => suffix.push_str(sgr), + _ => {} + } + start = control.end(); + } + } + suffix.truncate(visible_end); + (column, Cow::Owned(suffix)) + }; + if column > covered { + if styled { + fragments.push((offset, suffix)); + } else { + result.push_str(&suffix); + } + covered = column; + } + if erased { + break; + } + } + + if !styled { + return Cow::Owned(result); + } + // Resolve styles in write order, then apply them in display order. Restore + // the final cursor style because bounded previews reuse this row for later CRs. + let offsets = fragments.iter().rev().map(|(offset, _)| *offset); + let mut styles = style_prefixes(&raw, offsets.chain([raw.len()])); + let cursor = styles.pop().unwrap_or_default(); + let texts = fragments.iter().map(|(_, text)| text.as_ref()).chain([""]); + let mut current: Option<&[&str]> = Some(&[]); + for (style, text) in styles.iter().rev().chain([&cursor]).zip(texts) { + if current != Some(style.as_slice()) { + if !matches!(current, Some([])) { + result.push_str("\x1b[0m"); + } + result.extend(style.iter().copied()); + } + result.push_str(text); + current = (!text.contains('\x1b')).then_some(style.as_slice()); + } + Cow::Owned(result) +} diff --git a/codex-rs/tui/src/thread_transcript/tools.rs b/codex-rs/tui/src/thread_transcript/tools.rs index 74e6eec9bf..48078eea30 100644 --- a/codex-rs/tui/src/thread_transcript/tools.rs +++ b/codex-rs/tui/src/thread_transcript/tools.rs @@ -8,7 +8,9 @@ use std::time::Duration; use crate::exec_cell::CommandOutput; use crate::exec_cell::ExecCell; +use crate::exec_cell::command_output_line; use crate::exec_cell::new_active_exec_command; +use crate::exec_cell::plain_output_text; use crate::history_cell::McpInvocation; use crate::history_cell::McpToolCallCell; use crate::history_cell::PlainHistoryCell; @@ -67,11 +69,10 @@ pub(crate) fn historical_tool_fallback( status_line.dim().into(), ]; if let Some(output) = aggregated_output { - lines.extend( - output - .lines() - .map(|line| vec![" ".dim(), line.trim_end().to_string().dim()].into()), - ); + lines.extend(output.lines().map(|raw| { + let text = plain_output_text(command_output_line(raw).into_owned()); + vec![" ".dim(), text.dim()].into() + })); } lines } diff --git a/codex-rs/tui/src/thread_transcript/tools_tests.rs b/codex-rs/tui/src/thread_transcript/tools_tests.rs index d6b924b164..bc207b48ae 100644 --- a/codex-rs/tui/src/thread_transcript/tools_tests.rs +++ b/codex-rs/tui/src/thread_transcript/tools_tests.rs @@ -219,7 +219,9 @@ fn historical_command_fallbacks_preserve_status_output_and_group_boundaries() { } else if label == "UNC command" { *command = r"\\server\share\tool.exe -arg".to_owned(); } - *aggregated_output = Some("first line\n indented output\nlast line".to_owned()); + *aggregated_output = Some( + "first line\n indented output\r\nlong stale message\r\x1b[Klast line".to_owned(), + ); *exit_code = recorded_exit; } let cells = thread_items_to_transcript_cells( diff --git a/codex-rs/tui/src/tool_output_tests.rs b/codex-rs/tui/src/tool_output_tests.rs index 47ffd76ad5..0e48bb3e9c 100644 --- a/codex-rs/tui/src/tool_output_tests.rs +++ b/codex-rs/tui/src/tool_output_tests.rs @@ -148,7 +148,7 @@ fn command_preview_matches_streamed_and_completed_output() { /*interaction_input*/ None, /*animations_enabled*/ false, ); - let output = "first\nsecond\nthird\nfourth\nfifth\n"; + let output = "first\nsecond\nthird\nupdating\r\x1b[Kfourth\r\nfifth\n"; cell.append_output("call-preview", output); let live = cell.display_lines(/*width*/ 80); cell.complete_call(