diff --git a/codex-rs/tui/src/conversation_history_widget.rs b/codex-rs/tui/src/conversation_history_widget.rs index ecaf5a02ab..cd5f125358 100644 --- a/codex-rs/tui/src/conversation_history_widget.rs +++ b/codex-rs/tui/src/conversation_history_widget.rs @@ -12,7 +12,6 @@ use ratatui::style::Style; use ratatui::text::Span; use ratatui::widgets::*; use serde_json::Value as JsonValue; -use std::cell::Cell as StdCell; use std::cell::Cell; use std::collections::HashMap; use std::path::PathBuf; @@ -27,31 +26,24 @@ pub struct ConversationHistoryWidget { entries: Vec, /// The width (in terminal cells/columns) that [`Entry::line_count`] was /// computed for. When the available width changes we recompute counts. - cached_width: StdCell, + cached_width: Cell, scroll_position: usize, /// Number of lines the last time render_ref() was called - num_rendered_lines: StdCell, + num_rendered_lines: Cell, /// The height of the viewport last time render_ref() was called - last_viewport_height: StdCell, + last_viewport_height: Cell, has_input_focus: bool, - /// Scratch buffer used while incrementally streaming an agent message. - /// We accumulate the full text so we can re-render markdown cleanly when the turn finishes. - streaming_agent_message_buf: String, - /// Scratch buffer used while incrementally streaming agent reasoning. - streaming_agent_reasoning_buf: String, } impl ConversationHistoryWidget { pub fn new() -> Self { Self { entries: Vec::new(), - cached_width: StdCell::new(0), + cached_width: Cell::new(0), scroll_position: usize::MAX, - num_rendered_lines: StdCell::new(0), - last_viewport_height: StdCell::new(0), + num_rendered_lines: Cell::new(0), + last_viewport_height: Cell::new(0), has_input_focus: false, - streaming_agent_message_buf: String::new(), - streaming_agent_reasoning_buf: String::new(), } } @@ -203,133 +195,35 @@ impl ConversationHistoryWidget { } pub fn add_agent_message(&mut self, config: &Config, message: String) { - // Reset streaming buffer – we are starting a new message. - self.streaming_agent_message_buf.clear(); - self.streaming_agent_message_buf.push_str(&message); self.add_to_history(HistoryCell::new_agent_message(config, message)); } pub fn add_agent_reasoning(&mut self, config: &Config, text: String) { - self.streaming_agent_reasoning_buf.clear(); - self.streaming_agent_reasoning_buf.push_str(&text); self.add_to_history(HistoryCell::new_agent_reasoning(config, text)); } - /// Append incremental assistant text without *forcing* a newline between chunks. - /// - /// The earlier implementation re-ran the markdown renderer on each delta. - /// Because `tui_markdown` always produces whole `Line` values, every chunk - /// showed up on its own row ("stair‑stepping" output). Instead we take a - /// lightweight approach during streaming: extend the last visible line with - /// plain text and only honour explicit `\n` boundaries from the model. When - /// the turn completes the caller should invoke `replace_last_agent_message()` - /// to re-render the full accumulated markdown so styling (code blocks, bold, - /// links, etc.) is correct. + /// Append incremental assistant text. Streaming mode deliberately avoids expensive + /// markdown re-rendering on every token; we just extend the final (currently-visible) + /// body line(s) and honour explicit newlines from the delta chunk. When the turn + /// completes the caller should invoke `replace_last_agent_message()` with the *full* + /// accumulated markdown so that styling (code fences, emphasis, links, etc.) is correct. pub fn append_agent_message_delta(&mut self, _config: &Config, text: String) { if text.is_empty() { return; } - - // Accumulate in scratch buffer so we can re-render later. - self.streaming_agent_message_buf.push_str(&text); - - // If the newly received chunk contains a newline we re-render the entire - // accumulated buffer using the markdown renderer so formatting (bold, - // code blocks, links) becomes visible incrementally. This is cheaper and - // less visually noisy than re-rendering on every token while still - // giving the user feedback at natural boundaries. - if text.contains('\n') { - // Rebuild the most recent AgentMessage entry from scratch. - let mut found_idx: Option = None; - for i in (0..self.entries.len()).rev() { - if matches!(self.entries[i].cell, HistoryCell::AgentMessage { .. }) { - found_idx = Some(i); - break; - } - } - if let Some(idx) = found_idx { - let width = self.cached_width.get(); - // Rebuild cell then borrow entry once. - let rebuilt = HistoryCell::new_agent_message( - _config, - self.streaming_agent_message_buf.clone(), - ); - let entry = &mut self.entries[idx]; - entry.cell = rebuilt; - // Drop the trailing blank added by new_agent_message so we can continue streaming. - if let HistoryCell::AgentMessage { view } = &mut entry.cell { - if let Some(last) = view.lines.last() { - if last.spans.len() == 1 && last.spans[0].content.is_empty() { - view.lines.pop(); - } - } - if width > 0 { - entry.line_count.set(view.height(width)); - } - } - return; - } - } - - if let Some(entry) = self.entries.last_mut() { + // Fast path: mutate the most recent AgentMessage cell if present; else create one. + if let Some(idx) = last_agent_message_idx(&self.entries) { + let width = self.cached_width.get(); + let entry = &mut self.entries[idx]; if let HistoryCell::AgentMessage { view } = &mut entry.cell { - // Ensure there is *at least* one line available for content after the header. - // new_agent_message() with an empty string produces a header line and one blank line. - // We keep that blank as our first append target. - if view.lines.len() < 2 { - view.lines.push(Line::from("")); - } - - // Trim *at most one* trailing separator line that we added for spacing. - // Preserve user-intended blank lines (paragraph breaks) so we do not collapse newlines. - if view.lines.len() > 1 { - if let Some(last) = view.lines.last() { - if last.spans.len() == 1 && last.spans[0].content.is_empty() { - view.lines.pop(); - } - } - } - - // Append respecting embedded newlines from the chunk. - let mut first_part = true; - for part in text.split_inclusive('\n') { - let has_newline = part.ends_with('\n'); - let content = part.trim_end_matches('\n'); - if first_part { - if let Some(last_line) = view.lines.last_mut() { - last_line.spans.push(Span::raw(content.to_string())); - } else { - view.lines.push(Line::from(content.to_string())); - } - first_part = false; - } else { - // Option 1: If this is a new line, and content starts with a space, trim it. - let trimmed_content = if content.starts_with(' ') - && matches!(view.lines.last(), Some(l) if l.spans.is_empty()) - { - content.trim_start() - } else { - content - }; - view.lines.push(Line::from(trimmed_content.to_string())); - } - if has_newline { - // honour explicit newline: start a fresh empty line (content target) - view.lines.push(Line::from("")); - } - } - - // DO NOT push the cell separator yet; we'll add it on finalisation. - - let width = self.cached_width.get(); + append_streaming_text_chunks(&mut view.lines, &text); if width > 0 { - entry.line_count.set(view.height(width)); + update_entry_height(entry, width); } return; } } - // Fallback: no existing AgentMessage – start a new one. - // Start a streaming cell with an *empty* body so we don't parse partial markdown. + // No existing cell – begin a new (header‑only) streaming cell and retry. self.add_agent_message(_config, String::new()); self.append_agent_message_delta(_config, text); } @@ -339,81 +233,13 @@ impl ConversationHistoryWidget { if text.is_empty() { return; } - self.streaming_agent_reasoning_buf.push_str(&text); - - // Re-render incrementally at newline boundaries. - if text.contains('\n') { - let mut found_idx: Option = None; - for i in (0..self.entries.len()).rev() { - if matches!(self.entries[i].cell, HistoryCell::AgentReasoning { .. }) { - found_idx = Some(i); - break; - } - } - if let Some(idx) = found_idx { - let width = self.cached_width.get(); - let rebuilt = HistoryCell::new_agent_reasoning( - _config, - self.streaming_agent_reasoning_buf.clone(), - ); - let entry = &mut self.entries[idx]; - entry.cell = rebuilt; - if let HistoryCell::AgentReasoning { view } = &mut entry.cell { - if let Some(last) = view.lines.last() { - if last.spans.len() == 1 && last.spans[0].content.is_empty() { - view.lines.pop(); - } - } - if width > 0 { - entry.line_count.set(view.height(width)); - } - } - return; - } - } - - if let Some(entry) = self.entries.last_mut() { + if let Some(idx) = last_agent_reasoning_idx(&self.entries) { + let width = self.cached_width.get(); + let entry = &mut self.entries[idx]; if let HistoryCell::AgentReasoning { view } = &mut entry.cell { - if view.lines.len() < 2 { - view.lines.push(Line::from("")); - } - if view.lines.len() > 1 { - if let Some(last) = view.lines.last() { - if last.spans.len() == 1 && last.spans[0].content.is_empty() { - view.lines.pop(); - } - } - } - let mut first_part = true; - for part in text.split_inclusive('\n') { - let has_newline = part.ends_with('\n'); - let content = part.trim_end_matches('\n'); - if first_part { - if let Some(last_line) = view.lines.last_mut() { - last_line.spans.push(Span::raw(content.to_string())); - } else { - view.lines.push(Line::from(content.to_string())); - } - first_part = false; - } else { - let trimmed_content = if content.starts_with(' ') - && matches!(view.lines.last(), Some(l) if l.spans.is_empty()) - { - content.trim_start() - } else { - content - }; - view.lines.push(Line::from(trimmed_content.to_string())); - } - if has_newline { - view.lines.push(Line::from("")); - } - } - // no separator until finalisation - - let width = self.cached_width.get(); + append_streaming_text_chunks(&mut view.lines, &text); if width > 0 { - entry.line_count.set(view.height(width)); + update_entry_height(entry, width); } return; } @@ -425,18 +251,12 @@ impl ConversationHistoryWidget { /// Replace the most recent AgentMessage cell with the fully accumulated `text`. /// This should be called once the turn is complete so we can render proper markdown. pub fn replace_last_agent_message(&mut self, config: &Config, text: String) { - self.streaming_agent_message_buf.clear(); - // Find the most recent AgentMessage entry (search from end). - if let Some(idx) = self - .entries - .iter() - .rposition(|e| matches!(e.cell, HistoryCell::AgentMessage { .. })) - { + if let Some(idx) = last_agent_message_idx(&self.entries) { let width = self.cached_width.get(); let entry = &mut self.entries[idx]; entry.cell = HistoryCell::new_agent_message(config, text); if width > 0 { - entry.line_count.set(entry.cell.height(width)); + update_entry_height(entry, width); } } else { // No existing AgentMessage (shouldn't happen) – append new. @@ -446,17 +266,12 @@ impl ConversationHistoryWidget { /// Replace the most recent AgentReasoning cell with the fully accumulated `text`. pub fn replace_last_agent_reasoning(&mut self, config: &Config, text: String) { - self.streaming_agent_reasoning_buf.clear(); - if let Some(idx) = self - .entries - .iter() - .rposition(|e| matches!(e.cell, HistoryCell::AgentReasoning { .. })) - { + if let Some(idx) = last_agent_reasoning_idx(&self.entries) { let width = self.cached_width.get(); let entry = &mut self.entries[idx]; entry.cell = HistoryCell::new_agent_reasoning(config, text); if width > 0 { - entry.line_count.set(entry.cell.height(width)); + update_entry_height(entry, width); } } else { self.add_agent_reasoning(config, text); @@ -540,7 +355,7 @@ impl ConversationHistoryWidget { // Update cached line count. if width > 0 { - entry.line_count.set(cell.height(width)); + update_entry_height(entry, width); } break; } @@ -574,7 +389,7 @@ impl ConversationHistoryWidget { entry.cell = completed; if width > 0 { - entry.line_count.set(entry.cell.height(width)); + update_entry_height(entry, width); } break; @@ -758,3 +573,76 @@ impl WidgetRef for ConversationHistoryWidget { pub(crate) const fn wrap_cfg() -> ratatui::widgets::Wrap { ratatui::widgets::Wrap { trim: false } } + +// --------------------------------------------------------------------------- +// Streaming helpers (private) +// --------------------------------------------------------------------------- + +/// Locate the most recent `HistoryCell::AgentMessage` entry. +fn last_agent_message_idx(entries: &[Entry]) -> Option { + entries + .iter() + .rposition(|e| matches!(e.cell, HistoryCell::AgentMessage { .. })) +} + +/// Locate the most recent `HistoryCell::AgentReasoning` entry. +fn last_agent_reasoning_idx(entries: &[Entry]) -> Option { + entries + .iter() + .rposition(|e| matches!(e.cell, HistoryCell::AgentReasoning { .. })) +} + +/// True if the line is an empty spacer (single empty span). +fn is_blank_line(line: &Line<'_>) -> bool { + line.spans.len() == 1 && line.spans[0].content.is_empty() +} + +/// Ensure that the vector has *at least* one body line after the header. +/// A freshly-created AgentMessage/Reasoning cell always has a header + blank line, +/// but streaming cells may be created empty; this makes sure we have a target line. +fn ensure_body_line(lines: &mut Vec>) { + if lines.len() < 2 { + lines.push(Line::from("")); + } +} + +/// Trim a single trailing blank spacer line (but preserve intentional paragraph breaks). +fn drop_trailing_blank_line(lines: &mut Vec>) { + if let Some(last) = lines.last() { + if is_blank_line(last) { + lines.pop(); + } + } +} + +/// Append streaming text, honouring embedded newlines. +fn append_streaming_text_chunks(lines: &mut Vec>, text: &str) { + ensure_body_line(lines); + drop_trailing_blank_line(lines); + + // We use `split_inclusive` so we can detect (and preserve) explicit newlines. + let mut first = true; + for chunk in text.split_inclusive('\n') { + let had_nl = chunk.ends_with('\n'); + let content = chunk.trim_end_matches('\n'); + if first { + if let Some(last_line) = lines.last_mut() { + last_line.spans.push(Span::raw(content.to_string())); + } else { + lines.push(Line::from(content.to_string())); + } + first = false; + } else { + lines.push(Line::from(content.to_string())); + } + if had_nl { + // Start a fresh (potentially target) line for subsequent appends. + lines.push(Line::from("")); + } + } +} + +/// Re-measure a mutated entry at `width` columns and update its cached height. +fn update_entry_height(entry: &Entry, width: u16) { + entry.line_count.set(entry.cell.height(width)); +}