From cc6d3e58679dcaa4dd69be5f6d61107814545040 Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Thu, 26 Nov 2026 02:24:54 +0000 Subject: [PATCH] Fix code fence tracking in the TUI streaming preview (#64067) ## Why A fence marker inside a blockquote can prematurely end an unquoted code block in the streaming scanner, exposing code to prose preview and table detection. Fence state can also linger when a blockquote ends exactly where the next streamed chunk begins. ## What changed Share fence parsing between Markdown rendering and the streaming scanner so both use the same indentation and blockquote rules. Reset the table scanner when it reaches the renderer's completed-block boundary, including when both offsets are equal. ## Testing Regression tests cover table-like text inside fenced code, prose and table handling after adjacent quoted and unquoted fences, and table detection after indented fence-like text. GitOrigin-RevId: 071c7745a2e925ed44ab6d6f47bf53c3d4be6143 --- codex-rs/tui/src/markdown.rs | 82 +------------- codex-rs/tui/src/streaming/controller.rs | 17 +-- .../src/streaming/controller_preview_tests.rs | 35 +++++- codex-rs/tui/src/streaming/table_holdback.rs | 3 +- codex-rs/tui/src/table_detect.rs | 107 ++++++++++-------- 5 files changed, 111 insertions(+), 133 deletions(-) diff --git a/codex-rs/tui/src/markdown.rs b/codex-rs/tui/src/markdown.rs index 9673c72605..41d0aefd18 100644 --- a/codex-rs/tui/src/markdown.rs +++ b/codex-rs/tui/src/markdown.rs @@ -34,6 +34,8 @@ use crate::inline_visualization::InlineVisualizationContext; use crate::inline_visualization::rewrite_inline_visualizations; use crate::markdown_render::ListSpacing; use crate::table_detect; +use crate::table_detect::Fence; +use crate::table_detect::FenceKind; use crate::terminal_hyperlinks::HyperlinkLine; /// Render Markdown for a widget that measures its height in terminal rows. @@ -320,78 +322,6 @@ fn unwrap_markdown_fences_with_sources<'a>( return Cow::Borrowed(markdown_source); } - #[derive(Clone, Copy)] - struct Fence { - marker: u8, - len: usize, - is_blockquoted: bool, - } - - // Strip a trailing newline and up to 3 leading spaces, returning the - // trimmed slice. Returns `None` when the line has 4+ leading spaces - // (which makes it an indented code line per CommonMark). - fn strip_line_indent(line: &str) -> Option<&str> { - let without_newline = line.strip_suffix('\n').unwrap_or(line); - let mut byte_idx = 0usize; - let mut column = 0usize; - for b in without_newline.as_bytes() { - match b { - b' ' => { - byte_idx += 1; - column += 1; - } - b'\t' => { - byte_idx += 1; - column += 4; - } - _ => break, - } - if column >= 4 { - return None; - } - } - Some(&without_newline[byte_idx..]) - } - - // Parse an opening fence line, returning the fence metadata and whether - // the fence info string indicates markdown content. - fn parse_open_fence(line: &str) -> Option<(Fence, bool)> { - let trimmed = strip_line_indent(line)?; - let is_blockquoted = trimmed.trim_start().starts_with('>'); - let fence_scan_text = table_detect::strip_blockquote_prefix(trimmed); - let (marker, len) = table_detect::parse_fence_marker(fence_scan_text)?; - let is_markdown = table_detect::is_markdown_fence_info(fence_scan_text, len); - Some(( - Fence { - marker: marker as u8, - len, - is_blockquoted, - }, - is_markdown, - )) - } - - fn is_close_fence(line: &str, fence: Fence) -> bool { - let Some(trimmed) = strip_line_indent(line) else { - return false; - }; - let fence_scan_text = if fence.is_blockquoted { - if !trimmed.trim_start().starts_with('>') { - return false; - } - table_detect::strip_blockquote_prefix(trimmed) - } else { - trimmed - }; - if let Some((marker, len)) = table_detect::parse_fence_marker(fence_scan_text) { - marker as u8 == fence.marker - && len >= fence.len - && fence_scan_text[len..].trim().is_empty() - } else { - false - } - } - fn markdown_fence_contains_table(content: &str, is_blockquoted_fence: bool) -> bool { let mut previous_line: Option<&str> = None; for line in content.lines() { @@ -459,12 +389,12 @@ fn unwrap_markdown_fences_with_sources<'a>( match active { ActiveFence::Passthrough(fence) => { push_source_range(&mut out, line_range); - if !is_close_fence(line, fence) { + if !fence.closes(line) { active_fence = Some(ActiveFence::Passthrough(fence)); } } ActiveFence::MarkdownCandidate(mut data) => { - if is_close_fence(line, data.fence) { + if data.fence.closes(line) { if markdown_fence_contains_table( &content_from_ranges(markdown_source, &data.content_ranges), data.fence.is_blockquoted, @@ -500,8 +430,8 @@ fn unwrap_markdown_fences_with_sources<'a>( continue; } - if let Some((fence, is_markdown)) = parse_open_fence(line) { - if is_markdown { + if let Some(fence) = Fence::open(line) { + if fence.kind == FenceKind::Markdown { active_fence = Some(ActiveFence::MarkdownCandidate(Box::new( MarkdownCandidateData { fence, diff --git a/codex-rs/tui/src/streaming/controller.rs b/codex-rs/tui/src/streaming/controller.rs index 5f7a1200f6..071763ff33 100644 --- a/codex-rs/tui/src/streaming/controller.rs +++ b/codex-rs/tui/src/streaming/controller.rs @@ -2066,14 +2066,15 @@ mod tests { #[test] fn table_holdback_state_treats_indented_fence_text_as_plain_content() { - let source = " ```sh\n| Key | Description |\n| --- | --- |\n"; - assert!( - matches!( - table_holdback_state(source), - TableHoldbackState::Confirmed { .. } - ), - "indented fence-like text should not open a fence and should not block table detection", - ); + for prefix in [" ```sh\n", "\t```sh\n"] { + let source = format!("{prefix}| Key | Description |\n| --- | --- |\n"); + assert_eq!( + table_holdback_state(&source), + TableHoldbackState::Confirmed { + table_start: prefix.len() + } + ); + } } #[test] diff --git a/codex-rs/tui/src/streaming/controller_preview_tests.rs b/codex-rs/tui/src/streaming/controller_preview_tests.rs index 45268f6fe5..81a2f98cd0 100644 --- a/codex-rs/tui/src/streaming/controller_preview_tests.rs +++ b/codex-rs/tui/src/streaming/controller_preview_tests.rs @@ -484,7 +484,22 @@ fn long_unicode_preview_keeps_recent_text_and_finalizes_full_source() { fn prose_preview_resumes_after_fenced_code() { let cwd = std::env::temp_dir(); let mut controller = StreamController::new(Some(40), &cwd, HistoryRenderMode::Rich); - controller.push("```rust\nlet x = 1;\n```\n"); + controller.push("```rust\n> ```\n"); + let tail = controller.current_tail_lines(); + controller.push("let x = 1;"); + assert_eq!(controller.current_tail_lines(), tail); + controller.push("\n| A | B |\n| --- | --- |\n"); + let (code, _) = controller.on_commit_tick_batch(usize::MAX); + let lines = code.unwrap().display_lines(/*width*/ 40); + insta::assert_debug_snapshot!(lines.iter().map(Line::to_string).collect::>(), @r#" + [ + "• > ```", + " let x = 1;", + " | A | B |", + " | --- | --- |", + ] + "#); + controller.push("```\n"); controller.on_commit_tick_batch(usize::MAX); controller.push("prose after code"); assert_eq!( @@ -493,6 +508,24 @@ fn prose_preview_resumes_after_fenced_code() { ); } +#[test] +fn adjacent_fences_resume_preview_when_the_blockquote_ends() { + let cwd = std::env::temp_dir(); + let mut controller = StreamController::new(Some(40), &cwd, HistoryRenderMode::Rich); + controller.push("> ```text\n> quoted code\n"); + controller.push("```rust\nlet x = 1;\n```\n"); + controller.on_commit_tick_batch(usize::MAX); + + controller.push("City"); + insta::assert_debug_snapshot!(visible_lines(controller.current_tail_lines()), @r#" + [ + Line::from("City"), + ] + "#); + controller.push(" | Count\n--- | ---\nOslo | 2\n"); + assert_eq!(controller.queued_lines(), 0); +} + #[test] fn prose_after_a_table_is_previewed_until_another_table_starts() { let cwd = std::env::temp_dir(); diff --git a/codex-rs/tui/src/streaming/table_holdback.rs b/codex-rs/tui/src/streaming/table_holdback.rs index 482e7fa28d..145b829308 100644 --- a/codex-rs/tui/src/streaming/table_holdback.rs +++ b/codex-rs/tui/src/streaming/table_holdback.rs @@ -109,7 +109,8 @@ impl TableHoldbackScanner { TableHoldbackState::PendingHeader { header_start } => Some(header_start), TableHoldbackState::None => None, }; - if self.source_offset < completed_source_len + // A new block can start exactly at the next delta, implicitly ending a quoted fence. + if self.source_offset <= completed_source_len || holdback_start.is_some_and(|start| start < completed_source_len) { self.reset(); diff --git a/codex-rs/tui/src/table_detect.rs b/codex-rs/tui/src/table_detect.rs index 39ca35a8d0..0fdfb926c7 100644 --- a/codex-rs/tui/src/table_detect.rs +++ b/codex-rs/tui/src/table_detect.rs @@ -130,18 +130,59 @@ pub(crate) enum FenceKind { Other, } -/// Incremental tracker for fenced-code-block open/close transitions. -/// -/// Feed lines one at a time via [`advance`](Self::advance); query the current -/// context with [`kind`](Self::kind). The tracker handles leading-whitespace -/// limits (>3 spaces → not a fence), blockquote prefix stripping, and -/// backtick/tilde marker matching. -/// -/// The tracker reports the fence context that applies to the current line -/// before that line mutates the state. Callers rely on that when deciding -/// whether the current raw line can open or continue a table. +/// An opening fence shared by the Markdown unwrapper and the streaming scanner. +#[derive(Clone, Copy)] +pub(crate) struct Fence { + marker: char, + len: usize, + pub(crate) is_blockquoted: bool, + pub(crate) kind: FenceKind, +} + +impl Fence { + pub(crate) fn open(line: &str) -> Option { + let line = strip_line_indent(line)?; + let text = strip_blockquote_prefix(line); + let (marker, len) = parse_fence_marker(text)?; + Some(Self { + marker, + len, + is_blockquoted: line.trim_start().starts_with('>'), + kind: if is_markdown_fence_info(text, len) { + FenceKind::Markdown + } else { + FenceKind::Other + }, + }) + } + + pub(crate) fn closes(self, line: &str) -> bool { + let Some(line) = strip_line_indent(line) else { + return false; + }; + let text = if self.is_blockquoted { + if !line.trim_start().starts_with('>') { + return false; + } + strip_blockquote_prefix(line) + } else { + line + }; + parse_fence_marker(text).is_some_and(|(marker, len)| { + marker == self.marker && len >= self.len && text[len..].trim().is_empty() + }) + } +} + +/// Fences allow up to three leading spaces. A leading tab reaches at least column four. +fn strip_line_indent(line: &str) -> Option<&str> { + let trimmed = line.trim_start_matches(' '); + (line.len() - trimmed.len() < 4 && !trimmed.starts_with('\t')).then_some(trimmed) +} + +/// Query the fence context before advancing past each raw source line. pub(crate) struct FenceTracker { - state: Option<(char, usize, FenceKind)>, + state: Option, } impl FenceTracker { @@ -150,47 +191,17 @@ impl FenceTracker { Self { state: None } } - /// Process one raw source line and update fence state. - /// - /// Lines with >3 leading spaces are ignored (indented code blocks, not - /// fences). Blockquote prefixes (`>`) are stripped before scanning. pub(crate) fn advance(&mut self, raw_line: &str) { - let leading_spaces = raw_line - .as_bytes() - .iter() - .take_while(|byte| **byte == b' ') - .count(); - if leading_spaces > 3 { - return; - } - - let trimmed = &raw_line[leading_spaces..]; - let fence_scan_text = strip_blockquote_prefix(trimmed); - if let Some((marker, len)) = parse_fence_marker(fence_scan_text) { - if let Some((open_char, open_len, _)) = self.state { - // Close the current fence if the marker matches. - if marker == open_char - && len >= open_len - && fence_scan_text[len..].trim().is_empty() - { - self.state = None; - } - } else { - // Opening a new fence. - let kind = if is_markdown_fence_info(fence_scan_text, len) { - FenceKind::Markdown - } else { - FenceKind::Other - }; - self.state = Some((marker, len, kind)); - } + match self.state { + None => self.state = Fence::open(raw_line), + Some(fence) if fence.closes(raw_line) => self.state = None, + Some(_) => {} } } - /// Current fence context for the most-recently-advanced line. #[inline] pub(crate) fn kind(&self) -> FenceKind { - self.state.map_or(FenceKind::Outside, |(_, _, k)| k) + self.state.map_or(FenceKind::Outside, |fence| fence.kind) } } @@ -200,7 +211,7 @@ impl FenceTracker { /// The input should already have leading whitespace and blockquote prefixes /// stripped. #[inline] -pub(crate) fn parse_fence_marker(line: &str) -> Option<(char, usize)> { +fn parse_fence_marker(line: &str) -> Option<(char, usize)> { let first = line.as_bytes().first().copied()?; if first != b'`' && first != b'~' { return None; @@ -427,6 +438,8 @@ mod tests { let mut tracker = FenceTracker::new(); tracker.advance("> ```sh"); assert_eq!(tracker.kind(), FenceKind::Other); + tracker.advance("```"); + assert_eq!(tracker.kind(), FenceKind::Other); tracker.advance("> ```"); assert_eq!(tracker.kind(), FenceKind::Outside); }