Base: codex-main originale (prima del fork aKode)
This commit is contained in:
457
codex-rs/tui/src/streaming/chunking.rs
Normal file
457
codex-rs/tui/src/streaming/chunking.rs
Normal file
@@ -0,0 +1,457 @@
|
||||
//! Adaptive stream chunking policy for commit animation ticks.
|
||||
//!
|
||||
//! This policy preserves the baseline user experience while adapting to bursty
|
||||
//! stream input. In [`ChunkingMode::Smooth`], one queued line is drained per
|
||||
//! baseline commit tick. When queue pressure rises, it switches to
|
||||
//! [`ChunkingMode::CatchUp`] and drains queued backlog immediately so display
|
||||
//! lag converges as quickly as possible.
|
||||
//!
|
||||
//! The policy is source-agnostic: it depends only on queue depth and queue
|
||||
//! age from [`QueueSnapshot`]. It does not branch on source identity or explicit
|
||||
//! throughput targets.
|
||||
//!
|
||||
//! # Mental model
|
||||
//!
|
||||
//! Think of this as a two-gear system:
|
||||
//!
|
||||
//! - [`ChunkingMode::Smooth`]: steady baseline display pacing.
|
||||
//! - [`ChunkingMode::CatchUp`]: full queue draining while backlog exists.
|
||||
//!
|
||||
//! The transition logic intentionally uses hysteresis:
|
||||
//!
|
||||
//! - enter catch-up on higher-pressure thresholds
|
||||
//! - exit catch-up on lower-pressure thresholds, held for [`EXIT_HOLD`]
|
||||
//! - after exit, suppress immediate re-entry for [`REENTER_CATCH_UP_HOLD`]
|
||||
//! unless backlog is severe
|
||||
//!
|
||||
//! This avoids rapid gear-flapping near threshold boundaries.
|
||||
//!
|
||||
//! # Policy flow
|
||||
//!
|
||||
//! On each decision tick, [`AdaptiveChunkingPolicy::decide`] does:
|
||||
//!
|
||||
//! 1. If queue is empty, reset to [`ChunkingMode::Smooth`].
|
||||
//! 2. If currently smooth, call [`AdaptiveChunkingPolicy::maybe_enter_catch_up`].
|
||||
//! 3. If currently catch-up, call [`AdaptiveChunkingPolicy::maybe_exit_catch_up`].
|
||||
//! 4. Build [`DrainPlan`] (`Single` for smooth, `Batch(queued_lines)` for catch-up).
|
||||
//!
|
||||
//! # Concrete examples
|
||||
//!
|
||||
//! With current defaults:
|
||||
//!
|
||||
//! - `Smooth` drains one line per commit tick.
|
||||
//! - `CatchUp` drains all currently queued lines in a tick.
|
||||
//!
|
||||
//! # Tuning guide (in code terms)
|
||||
//!
|
||||
//! Prefer tuning in this order so causes remain clear:
|
||||
//!
|
||||
//! 1. enter/exit thresholds: [`ENTER_QUEUE_DEPTH_LINES`], [`ENTER_OLDEST_AGE`],
|
||||
//! [`EXIT_QUEUE_DEPTH_LINES`], [`EXIT_OLDEST_AGE`]
|
||||
//! 2. hysteresis windows: [`EXIT_HOLD`], [`REENTER_CATCH_UP_HOLD`]
|
||||
//! 3. severe gates: [`SEVERE_QUEUE_DEPTH_LINES`], [`SEVERE_OLDEST_AGE`]
|
||||
//!
|
||||
//! Symptom-oriented adjustments:
|
||||
//!
|
||||
//! - lag starts too late: lower enter thresholds
|
||||
//! - frequent smooth/catch-up chatter: increase hold windows, or tighten exit
|
||||
//! thresholds
|
||||
//! - catch-up re-enters too eagerly after exit: increase re-entry hold
|
||||
//!
|
||||
//! # Responsibilities
|
||||
//!
|
||||
//! - track mode and hysteresis state
|
||||
//! - produce deterministic [`ChunkingDecision`] values from queue snapshots
|
||||
//! - preserve queue order by draining from queue head only
|
||||
//!
|
||||
//! # Non-responsibilities
|
||||
//!
|
||||
//! - scheduling commit ticks
|
||||
//! - reordering stream lines
|
||||
//! - transport/source-specific semantics
|
||||
//!
|
||||
//! Markdown docs remain supplemental:
|
||||
//!
|
||||
//! - `docs/tui-stream-chunking-review.md`
|
||||
//! - `docs/tui-stream-chunking-tuning.md`
|
||||
//! - `docs/tui-stream-chunking-validation.md`
|
||||
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
/// Queue-depth threshold that allows entering catch-up mode.
|
||||
///
|
||||
/// Crossing this threshold alone is sufficient to leave smooth mode.
|
||||
const ENTER_QUEUE_DEPTH_LINES: usize = 8;
|
||||
|
||||
/// Oldest-line age threshold that allows entering catch-up mode.
|
||||
///
|
||||
/// Crossing this threshold alone is sufficient to leave smooth mode.
|
||||
const ENTER_OLDEST_AGE: Duration = Duration::from_millis(120);
|
||||
|
||||
/// Queue-depth threshold used when evaluating catch-up exit hysteresis.
|
||||
///
|
||||
/// Depth must be at or below this value before exit hold timing can begin.
|
||||
const EXIT_QUEUE_DEPTH_LINES: usize = 2;
|
||||
|
||||
/// Oldest-line age threshold used when evaluating catch-up exit hysteresis.
|
||||
///
|
||||
/// Age must be at or below this value before exit hold timing can begin.
|
||||
const EXIT_OLDEST_AGE: Duration = Duration::from_millis(40);
|
||||
|
||||
/// Minimum duration queue pressure must stay below exit thresholds to leave catch-up mode.
|
||||
const EXIT_HOLD: Duration = Duration::from_millis(250);
|
||||
|
||||
/// Cooldown window after a catch-up exit that suppresses immediate re-entry.
|
||||
///
|
||||
/// Severe backlog still bypasses this hold to avoid unbounded queue-age growth.
|
||||
const REENTER_CATCH_UP_HOLD: Duration = Duration::from_millis(250);
|
||||
|
||||
/// Queue-depth cutoff that marks backlog as severe for faster convergence.
|
||||
///
|
||||
/// This threshold is used to bypass re-entry hold after a recent catch-up exit.
|
||||
const SEVERE_QUEUE_DEPTH_LINES: usize = 64;
|
||||
|
||||
/// Oldest-line age cutoff that marks backlog as severe for faster convergence.
|
||||
const SEVERE_OLDEST_AGE: Duration = Duration::from_millis(300);
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub(crate) enum ChunkingMode {
|
||||
/// Drain one line per baseline commit tick.
|
||||
#[default]
|
||||
Smooth,
|
||||
/// Drain multiple lines per tick according to queue pressure.
|
||||
CatchUp,
|
||||
}
|
||||
|
||||
/// Captures queue pressure inputs used by adaptive chunking decisions.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub(crate) struct QueueSnapshot {
|
||||
/// Number of queued stream lines waiting to be displayed.
|
||||
pub(crate) queued_lines: usize,
|
||||
/// Age of the oldest queued line at decision time.
|
||||
pub(crate) oldest_age: Option<Duration>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum DrainPlan {
|
||||
/// Emit exactly one queued line.
|
||||
Single,
|
||||
/// Emit up to `usize` queued lines.
|
||||
Batch(usize),
|
||||
}
|
||||
|
||||
/// Represents one policy decision for a specific queue snapshot.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct ChunkingDecision {
|
||||
/// Mode after applying hysteresis transitions for this decision.
|
||||
pub(crate) mode: ChunkingMode,
|
||||
/// Whether this decision transitioned from `Smooth` into `CatchUp`.
|
||||
pub(crate) entered_catch_up: bool,
|
||||
/// Drain plan to execute for the current commit tick.
|
||||
pub(crate) drain_plan: DrainPlan,
|
||||
}
|
||||
|
||||
/// Maintains adaptive chunking mode and hysteresis state across ticks.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct AdaptiveChunkingPolicy {
|
||||
mode: ChunkingMode,
|
||||
below_exit_threshold_since: Option<Instant>,
|
||||
last_catch_up_exit_at: Option<Instant>,
|
||||
}
|
||||
|
||||
impl AdaptiveChunkingPolicy {
|
||||
/// Returns the policy mode used by the most recent decision.
|
||||
pub(crate) fn mode(&self) -> ChunkingMode {
|
||||
self.mode
|
||||
}
|
||||
|
||||
/// Resets state to baseline smooth mode.
|
||||
pub(crate) fn reset(&mut self) {
|
||||
self.mode = ChunkingMode::Smooth;
|
||||
self.below_exit_threshold_since = None;
|
||||
self.last_catch_up_exit_at = None;
|
||||
}
|
||||
|
||||
/// Computes a drain decision from the current queue snapshot.
|
||||
///
|
||||
/// The decision is deterministic for a given `(mode, snapshot, now)` triple. Callers should
|
||||
/// avoid inventing synthetic snapshots; stale queue age data can cause premature catch-up exits.
|
||||
pub(crate) fn decide(&mut self, snapshot: QueueSnapshot, now: Instant) -> ChunkingDecision {
|
||||
if snapshot.queued_lines == 0 {
|
||||
self.note_catch_up_exit(now);
|
||||
self.mode = ChunkingMode::Smooth;
|
||||
self.below_exit_threshold_since = None;
|
||||
return ChunkingDecision {
|
||||
mode: self.mode,
|
||||
entered_catch_up: false,
|
||||
drain_plan: DrainPlan::Single,
|
||||
};
|
||||
}
|
||||
|
||||
let entered_catch_up = match self.mode {
|
||||
ChunkingMode::Smooth => self.maybe_enter_catch_up(snapshot, now),
|
||||
ChunkingMode::CatchUp => {
|
||||
self.maybe_exit_catch_up(snapshot, now);
|
||||
false
|
||||
}
|
||||
};
|
||||
|
||||
let drain_plan = match self.mode {
|
||||
ChunkingMode::Smooth => DrainPlan::Single,
|
||||
ChunkingMode::CatchUp => DrainPlan::Batch(snapshot.queued_lines.max(1)),
|
||||
};
|
||||
|
||||
ChunkingDecision {
|
||||
mode: self.mode,
|
||||
entered_catch_up,
|
||||
drain_plan,
|
||||
}
|
||||
}
|
||||
|
||||
/// Switches from `Smooth` to `CatchUp` when enter thresholds are crossed.
|
||||
///
|
||||
/// Returns `true` only on the transition tick so callers can emit one-shot
|
||||
/// transition observability.
|
||||
fn maybe_enter_catch_up(&mut self, snapshot: QueueSnapshot, now: Instant) -> bool {
|
||||
if !should_enter_catch_up(snapshot) {
|
||||
return false;
|
||||
}
|
||||
if self.reentry_hold_active(now) && !is_severe_backlog(snapshot) {
|
||||
return false;
|
||||
}
|
||||
self.mode = ChunkingMode::CatchUp;
|
||||
self.below_exit_threshold_since = None;
|
||||
self.last_catch_up_exit_at = None;
|
||||
true
|
||||
}
|
||||
|
||||
/// Applies exit hysteresis while in `CatchUp` mode.
|
||||
///
|
||||
/// The policy requires queue pressure to stay below exit thresholds for the
|
||||
/// full `EXIT_HOLD` window before returning to `Smooth`.
|
||||
fn maybe_exit_catch_up(&mut self, snapshot: QueueSnapshot, now: Instant) {
|
||||
if !should_exit_catch_up(snapshot) {
|
||||
self.below_exit_threshold_since = None;
|
||||
return;
|
||||
}
|
||||
|
||||
match self.below_exit_threshold_since {
|
||||
Some(since) if now.saturating_duration_since(since) >= EXIT_HOLD => {
|
||||
self.mode = ChunkingMode::Smooth;
|
||||
self.below_exit_threshold_since = None;
|
||||
self.last_catch_up_exit_at = Some(now);
|
||||
}
|
||||
Some(_) => {}
|
||||
None => {
|
||||
self.below_exit_threshold_since = Some(now);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn note_catch_up_exit(&mut self, now: Instant) {
|
||||
if self.mode == ChunkingMode::CatchUp {
|
||||
self.last_catch_up_exit_at = Some(now);
|
||||
}
|
||||
}
|
||||
|
||||
fn reentry_hold_active(&self, now: Instant) -> bool {
|
||||
self.last_catch_up_exit_at
|
||||
.is_some_and(|exit| now.saturating_duration_since(exit) < REENTER_CATCH_UP_HOLD)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns whether current queue pressure warrants entering catch-up mode.
|
||||
///
|
||||
/// Either depth or age pressure is sufficient to trigger catch-up.
|
||||
fn should_enter_catch_up(snapshot: QueueSnapshot) -> bool {
|
||||
snapshot.queued_lines >= ENTER_QUEUE_DEPTH_LINES
|
||||
|| snapshot
|
||||
.oldest_age
|
||||
.is_some_and(|oldest| oldest >= ENTER_OLDEST_AGE)
|
||||
}
|
||||
|
||||
/// Returns whether queue pressure is low enough to begin exit hysteresis.
|
||||
///
|
||||
/// Both depth and age must be below thresholds; this prevents oscillation when
|
||||
/// one signal is still under load.
|
||||
fn should_exit_catch_up(snapshot: QueueSnapshot) -> bool {
|
||||
snapshot.queued_lines <= EXIT_QUEUE_DEPTH_LINES
|
||||
&& snapshot
|
||||
.oldest_age
|
||||
.is_some_and(|oldest| oldest <= EXIT_OLDEST_AGE)
|
||||
}
|
||||
|
||||
/// Returns whether backlog is severe enough to use a faster catch-up target.
|
||||
///
|
||||
/// Severe pressure bypasses re-entry hold to avoid queue-age growth after a
|
||||
/// recent catch-up exit.
|
||||
fn is_severe_backlog(snapshot: QueueSnapshot) -> bool {
|
||||
snapshot.queued_lines >= SEVERE_QUEUE_DEPTH_LINES
|
||||
|| snapshot
|
||||
.oldest_age
|
||||
.is_some_and(|oldest| oldest >= SEVERE_OLDEST_AGE)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn snapshot(queued_lines: usize, oldest_age_ms: u64) -> QueueSnapshot {
|
||||
QueueSnapshot {
|
||||
queued_lines,
|
||||
oldest_age: Some(Duration::from_millis(oldest_age_ms)),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smooth_mode_is_default() {
|
||||
let mut policy = AdaptiveChunkingPolicy::default();
|
||||
let now = Instant::now();
|
||||
|
||||
let decision = policy.decide(snapshot(/*queued_lines*/ 1, /*oldest_age_ms*/ 10), now);
|
||||
assert_eq!(decision.mode, ChunkingMode::Smooth);
|
||||
assert_eq!(decision.entered_catch_up, false);
|
||||
assert_eq!(decision.drain_plan, DrainPlan::Single);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enters_catch_up_on_depth_threshold() {
|
||||
let mut policy = AdaptiveChunkingPolicy::default();
|
||||
let now = Instant::now();
|
||||
|
||||
let decision = policy.decide(snapshot(/*queued_lines*/ 8, /*oldest_age_ms*/ 10), now);
|
||||
assert_eq!(decision.mode, ChunkingMode::CatchUp);
|
||||
assert_eq!(decision.entered_catch_up, true);
|
||||
assert_eq!(decision.drain_plan, DrainPlan::Batch(8));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enters_catch_up_on_age_threshold() {
|
||||
let mut policy = AdaptiveChunkingPolicy::default();
|
||||
let now = Instant::now();
|
||||
|
||||
let decision = policy.decide(snapshot(/*queued_lines*/ 2, /*oldest_age_ms*/ 120), now);
|
||||
assert_eq!(decision.mode, ChunkingMode::CatchUp);
|
||||
assert_eq!(decision.entered_catch_up, true);
|
||||
assert_eq!(decision.drain_plan, DrainPlan::Batch(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn severe_backlog_uses_faster_paced_batches() {
|
||||
let mut policy = AdaptiveChunkingPolicy::default();
|
||||
let now = Instant::now();
|
||||
let _ = policy.decide(snapshot(/*queued_lines*/ 9, /*oldest_age_ms*/ 10), now);
|
||||
|
||||
let decision = policy.decide(
|
||||
snapshot(/*queued_lines*/ 64, /*oldest_age_ms*/ 10),
|
||||
now + Duration::from_millis(5),
|
||||
);
|
||||
assert_eq!(decision.mode, ChunkingMode::CatchUp);
|
||||
assert_eq!(decision.drain_plan, DrainPlan::Batch(64));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catch_up_batch_drains_current_backlog() {
|
||||
let mut policy = AdaptiveChunkingPolicy::default();
|
||||
let now = Instant::now();
|
||||
let decision = policy.decide(snapshot(/*queued_lines*/ 512, /*oldest_age_ms*/ 400), now);
|
||||
assert_eq!(decision.mode, ChunkingMode::CatchUp);
|
||||
assert_eq!(decision.drain_plan, DrainPlan::Batch(512));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exits_catch_up_after_hysteresis_hold() {
|
||||
let mut policy = AdaptiveChunkingPolicy::default();
|
||||
let t0 = Instant::now();
|
||||
|
||||
let _ = policy.decide(snapshot(/*queued_lines*/ 9, /*oldest_age_ms*/ 10), t0);
|
||||
assert_eq!(policy.mode(), ChunkingMode::CatchUp);
|
||||
|
||||
let pre_hold = policy.decide(
|
||||
snapshot(/*queued_lines*/ 2, /*oldest_age_ms*/ 40),
|
||||
t0 + Duration::from_millis(200),
|
||||
);
|
||||
assert_eq!(pre_hold.mode, ChunkingMode::CatchUp);
|
||||
|
||||
let post_hold = policy.decide(
|
||||
snapshot(/*queued_lines*/ 2, /*oldest_age_ms*/ 40),
|
||||
t0 + Duration::from_millis(460),
|
||||
);
|
||||
assert_eq!(post_hold.mode, ChunkingMode::Smooth);
|
||||
assert_eq!(post_hold.drain_plan, DrainPlan::Single);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drops_back_to_smooth_when_idle() {
|
||||
let mut policy = AdaptiveChunkingPolicy::default();
|
||||
let now = Instant::now();
|
||||
let _ = policy.decide(snapshot(/*queued_lines*/ 9, /*oldest_age_ms*/ 10), now);
|
||||
assert_eq!(policy.mode(), ChunkingMode::CatchUp);
|
||||
|
||||
let decision = policy.decide(
|
||||
QueueSnapshot {
|
||||
queued_lines: 0,
|
||||
oldest_age: None,
|
||||
},
|
||||
now + Duration::from_millis(20),
|
||||
);
|
||||
assert_eq!(decision.mode, ChunkingMode::Smooth);
|
||||
assert_eq!(decision.drain_plan, DrainPlan::Single);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn holds_reentry_after_catch_up_exit() {
|
||||
let mut policy = AdaptiveChunkingPolicy::default();
|
||||
let t0 = Instant::now();
|
||||
|
||||
let entered = policy.decide(snapshot(/*queued_lines*/ 8, /*oldest_age_ms*/ 20), t0);
|
||||
assert_eq!(entered.mode, ChunkingMode::CatchUp);
|
||||
|
||||
let drained = policy.decide(
|
||||
QueueSnapshot {
|
||||
queued_lines: 0,
|
||||
oldest_age: None,
|
||||
},
|
||||
t0 + Duration::from_millis(20),
|
||||
);
|
||||
assert_eq!(drained.mode, ChunkingMode::Smooth);
|
||||
|
||||
let held = policy.decide(
|
||||
snapshot(/*queued_lines*/ 8, /*oldest_age_ms*/ 20),
|
||||
t0 + Duration::from_millis(120),
|
||||
);
|
||||
assert_eq!(held.mode, ChunkingMode::Smooth);
|
||||
assert_eq!(held.drain_plan, DrainPlan::Single);
|
||||
|
||||
let reentered = policy.decide(
|
||||
snapshot(/*queued_lines*/ 8, /*oldest_age_ms*/ 20),
|
||||
t0 + Duration::from_millis(320),
|
||||
);
|
||||
assert_eq!(reentered.mode, ChunkingMode::CatchUp);
|
||||
assert_eq!(reentered.drain_plan, DrainPlan::Batch(8));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn severe_backlog_can_reenter_during_hold() {
|
||||
let mut policy = AdaptiveChunkingPolicy::default();
|
||||
let t0 = Instant::now();
|
||||
|
||||
let _ = policy.decide(snapshot(/*queued_lines*/ 8, /*oldest_age_ms*/ 20), t0);
|
||||
let _ = policy.decide(
|
||||
QueueSnapshot {
|
||||
queued_lines: 0,
|
||||
oldest_age: None,
|
||||
},
|
||||
t0 + Duration::from_millis(20),
|
||||
);
|
||||
|
||||
let severe = policy.decide(
|
||||
snapshot(/*queued_lines*/ 64, /*oldest_age_ms*/ 20),
|
||||
t0 + Duration::from_millis(120),
|
||||
);
|
||||
assert_eq!(severe.mode, ChunkingMode::CatchUp);
|
||||
assert_eq!(severe.drain_plan, DrainPlan::Batch(64));
|
||||
}
|
||||
}
|
||||
140
codex-rs/tui/src/streaming/code_fence.rs
Normal file
140
codex-rs/tui/src/streaming/code_fence.rs
Normal file
@@ -0,0 +1,140 @@
|
||||
//! A conservative fast path for one open, top-level, language-tagged code fence.
|
||||
|
||||
use crate::markdown_copy::CopyLine;
|
||||
use crate::render::highlight::MAX_HIGHLIGHT_LINE_BYTES;
|
||||
use crate::render::highlight::StreamingCodeHighlighter;
|
||||
use crate::render::highlight::syntax_theme_revision;
|
||||
use crate::terminal_hyperlinks::HyperlinkLine;
|
||||
use crate::terminal_hyperlinks::LogicalLineSource;
|
||||
use ratatui::text::Span;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// An append-only fence whose original source is identical to pulldown-cmark's code text.
|
||||
pub(super) struct OpenCodeFence {
|
||||
marker: u8,
|
||||
marker_len: usize,
|
||||
language: String,
|
||||
content_start: usize,
|
||||
source_len: usize,
|
||||
theme_revision: u64,
|
||||
/// Initialized only if another chunk arrives, avoiding duplicate work on one-shot fences.
|
||||
highlighter: Option<StreamingCodeHighlighter>,
|
||||
}
|
||||
|
||||
impl OpenCodeFence {
|
||||
/// Recognize the final mutable top-level block after its canonical render.
|
||||
///
|
||||
/// `source` is the final block's suffix, while `source_len` includes the entire committed
|
||||
/// Markdown source and anchors the retained fence within it.
|
||||
///
|
||||
/// Indentation, CR/NUL normalization, and escaped info strings stay on the canonical path.
|
||||
/// Any line that could end the fence also stays there, including deliberately conservative
|
||||
/// false positives, so this fast path need not duplicate CommonMark's closing-fence grammar.
|
||||
pub(super) fn detect(source: &str, source_len: usize, theme_revision: u64) -> Option<Self> {
|
||||
let marker = *source.as_bytes().first()?;
|
||||
if marker != b'`' && marker != b'~' {
|
||||
return None;
|
||||
}
|
||||
let (opening, code) = source.split_once('\n')?;
|
||||
let marker_len = opening.bytes().take_while(|byte| *byte == marker).count();
|
||||
if marker_len < 3
|
||||
|| !source.ends_with('\n')
|
||||
|| theme_revision != syntax_theme_revision()
|
||||
|| source.contains(['\r', '\0'])
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let info = opening[marker_len..].trim_matches([' ', '\t', '\u{b}', '\u{c}']);
|
||||
if info.contains(['&', '\\']) || (marker == b'`' && info.contains('`')) {
|
||||
return None;
|
||||
}
|
||||
let language = info
|
||||
.split([',', ' ', '\t'])
|
||||
.next()
|
||||
.filter(|language| !language.is_empty())?;
|
||||
// Markdown fences may gain visible delimiters when a disabled table is recognized.
|
||||
if !crate::markdown_render::preferences::current().tables
|
||||
&& crate::table_detect::is_markdown_fence_info(info, /*marker_len*/ 0)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
// Retain at most one bounded language token, never the streamed code itself.
|
||||
if language.len() > MAX_HIGHLIGHT_LINE_BYTES
|
||||
|| has_possible_closing_line(code, marker, marker_len)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(Self {
|
||||
marker,
|
||||
marker_len,
|
||||
language: language.to_string(),
|
||||
content_start: source_len.checked_sub(code.len())?,
|
||||
source_len,
|
||||
theme_revision,
|
||||
highlighter: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Append code only while the caller's newline-committed source extends this same fence.
|
||||
///
|
||||
/// Returning `None` consumes the retained state and requires a canonical whole-fence render.
|
||||
/// Successful lines include the empty indent span expected by the canonical Markdown writer.
|
||||
pub(super) fn append(
|
||||
mut self,
|
||||
raw_source: &str,
|
||||
committed_source: &str,
|
||||
) -> Option<(Self, Vec<HyperlinkLine>)> {
|
||||
if self.source_len.checked_add(committed_source.len()) != Some(raw_source.len())
|
||||
|| !raw_source.ends_with(committed_source)
|
||||
|| committed_source.contains(['\r', '\0'])
|
||||
|| has_possible_closing_line(committed_source, self.marker, self.marker_len)
|
||||
|| self.theme_revision != syntax_theme_revision()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let highlighter = match self.highlighter.take() {
|
||||
Some(highlighter) => highlighter,
|
||||
None => StreamingCodeHighlighter::new(
|
||||
&raw_source[self.content_start..self.source_len],
|
||||
&self.language,
|
||||
self.theme_revision,
|
||||
)?,
|
||||
};
|
||||
let (highlighter, lines) = highlighter.append(committed_source)?;
|
||||
self.highlighter = Some(highlighter);
|
||||
self.source_len = raw_source.len();
|
||||
let mut copy = CopyLine::default();
|
||||
copy.code = true;
|
||||
let copy = Arc::new(copy);
|
||||
let lines = lines
|
||||
.into_iter()
|
||||
.map(|mut line| {
|
||||
let mut source = LogicalLineSource::from_line(&line);
|
||||
source.copy = Some(Arc::clone(©));
|
||||
// The canonical writer installs an empty indent span for top-level fences.
|
||||
line.spans.insert(/*index*/ 0, Span::default());
|
||||
let mut line = HyperlinkLine::new(line);
|
||||
line.source = Some(source);
|
||||
line
|
||||
})
|
||||
.collect();
|
||||
Some((self, lines))
|
||||
}
|
||||
}
|
||||
|
||||
/// Conservatively detect any line that might close the fence.
|
||||
///
|
||||
/// False positives intentionally fall back to CommonMark instead of duplicating its closer rules.
|
||||
fn has_possible_closing_line(source: &str, marker: u8, marker_len: usize) -> bool {
|
||||
source.lines().any(|line| {
|
||||
line.trim_start_matches([' ', '\t'])
|
||||
.bytes()
|
||||
.take_while(|byte| *byte == marker)
|
||||
.count()
|
||||
>= marker_len
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "code_fence_tests.rs"]
|
||||
mod tests;
|
||||
147
codex-rs/tui/src/streaming/code_fence_render_tests.rs
Normal file
147
codex-rs/tui/src/streaming/code_fence_render_tests.rs
Normal file
@@ -0,0 +1,147 @@
|
||||
use super::StreamingRender;
|
||||
use super::append;
|
||||
use super::append_rich_and_assert_matches_full;
|
||||
use super::assert_rich_stream_matches_full_render;
|
||||
use super::lines_to_plain_strings;
|
||||
use super::test_cwd;
|
||||
use crate::history_cell::HistoryRenderMode;
|
||||
use crate::render::highlight::MAX_HIGHLIGHT_LINE_BYTES;
|
||||
use insta::assert_debug_snapshot;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn growing_code_fences_preserve_styles_unicode_links_and_blank_lines() {
|
||||
let (_, render) = assert_rich_stream_matches_full_render(
|
||||
&[
|
||||
"Before [link](https://example.com).\n\n```rust,no_run\n",
|
||||
"fn main() {\n",
|
||||
" /* a multiline\n",
|
||||
" comment */\n\n",
|
||||
" println!(\"界 e\u{301} https://example.com\");\n",
|
||||
"}\n",
|
||||
"```\n\n~~~~python\n",
|
||||
"text = \"\"\"a multiline\n",
|
||||
"string\"\"\"\n",
|
||||
"~~~~\n",
|
||||
],
|
||||
Some(18),
|
||||
);
|
||||
assert!(render.open_code_fence.is_none());
|
||||
assert_debug_snapshot!(lines_to_plain_strings(&render.lines), @r#"
|
||||
[
|
||||
"Before link",
|
||||
"(https://example.com).",
|
||||
"",
|
||||
"fn main() {",
|
||||
" /* a multiline",
|
||||
" comment */",
|
||||
"",
|
||||
" println!(\"界 e\u{301} https://example.com\");",
|
||||
"}",
|
||||
"",
|
||||
"text = \"\"\"a multiline",
|
||||
"string\"\"\"",
|
||||
]
|
||||
"#);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_open_fence_retains_its_rendered_prefix() {
|
||||
let cwd = test_cwd();
|
||||
let mut source = String::new();
|
||||
let mut render = StreamingRender::new();
|
||||
append_rich_and_assert_matches_full(
|
||||
&mut render,
|
||||
&mut source,
|
||||
"```rust\nfn main() {\n",
|
||||
Some(80),
|
||||
&cwd,
|
||||
);
|
||||
let first_line = render.lines[0].line.spans[1].content.as_ptr();
|
||||
for index in 0..512 {
|
||||
append(
|
||||
&mut render,
|
||||
&mut source,
|
||||
&format!(" let value_{index} = {index};\n"),
|
||||
Some(80),
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
);
|
||||
assert!(render.open_code_fence.is_some());
|
||||
}
|
||||
assert_eq!(render.lines[0].line.spans[1].content.as_ptr(), first_line);
|
||||
append_rich_and_assert_matches_full(&mut render, &mut source, "}\n```\n", Some(80), &cwd);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ambiguous_and_normalized_fences_use_canonical_semantics() {
|
||||
let streams: &[&[&str]] = &[
|
||||
&["```rust\n", "x\n", "``", "`\n"],
|
||||
&["```rust\n", "x\n", "```\t\n", "after\n"],
|
||||
&["```rust\n", "x\n", " ```` \n", "after\n"],
|
||||
&["~~~rust\n", "x\n", "~~~\u{a0}\n", "after\n"],
|
||||
&["```rust\r\n", "let value = 'é';\r\n", "```\r\n"],
|
||||
&["```rust\n", "let value = '\0';\n", "```\n"],
|
||||
&["```rust,no_run\n", "fn main() {}\n", "```\n"],
|
||||
&[" ```rust\n", " fn main() {}\n", " ```\n"],
|
||||
&["```unknown-language\n", "first\n", "second\n", "```\n"],
|
||||
&[
|
||||
"```markdown\n| A | B |\n",
|
||||
"| --- | --- |\n",
|
||||
"| 1 | 2 |\n```\n\n```rust\nfn first() {}\n",
|
||||
"fn second() {}\n",
|
||||
"```\n",
|
||||
],
|
||||
];
|
||||
for chunks in streams {
|
||||
assert_rich_stream_matches_full_render(chunks, Some(40));
|
||||
}
|
||||
for indent in 0..=3 {
|
||||
let closing = format!("{}~~~~~\t\n", " ".repeat(indent));
|
||||
assert_rich_stream_matches_full_render(
|
||||
&["~~~~rust\n", "x\n", &closing, "after\n"],
|
||||
Some(40),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crossing_a_highlight_limit_removes_previously_highlighted_colors() {
|
||||
let cwd = test_cwd();
|
||||
let mut source = String::new();
|
||||
let mut render = StreamingRender::new();
|
||||
for chunk in [
|
||||
"```rust\nlet first = 1;\n".to_string(),
|
||||
format!("{}\n", "x".repeat(MAX_HIGHLIGHT_LINE_BYTES + 1)),
|
||||
"let second = 2;\n".to_string(),
|
||||
"```\n".to_string(),
|
||||
] {
|
||||
append_rich_and_assert_matches_full(&mut render, &mut source, &chunk, Some(80), &cwd);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recomputing_after_resize_or_mode_change_drops_fence_state() {
|
||||
let (mut source, mut render) =
|
||||
assert_rich_stream_matches_full_render(&["```rust\nfn first() {}\n"], Some(80));
|
||||
assert!(render.open_code_fence.is_some());
|
||||
let cwd = test_cwd();
|
||||
render.recompute(
|
||||
&source,
|
||||
Some(20),
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
/*inline_visualization_context*/ None,
|
||||
);
|
||||
assert!(render.open_code_fence.is_none());
|
||||
append_rich_and_assert_matches_full(
|
||||
&mut render,
|
||||
&mut source,
|
||||
"fn second() {}\n",
|
||||
Some(20),
|
||||
&cwd,
|
||||
);
|
||||
assert!(render.open_code_fence.is_some());
|
||||
render.clear();
|
||||
assert!(render.open_code_fence.is_none());
|
||||
}
|
||||
69
codex-rs/tui/src/streaming/code_fence_tests.rs
Normal file
69
codex-rs/tui/src/streaming/code_fence_tests.rs
Normal file
@@ -0,0 +1,69 @@
|
||||
use super::OpenCodeFence;
|
||||
use super::has_possible_closing_line;
|
||||
use crate::render::highlight::MAX_HIGHLIGHT_LINE_BYTES;
|
||||
use crate::render::highlight::syntax_theme_revision;
|
||||
|
||||
#[test]
|
||||
fn detects_only_source_preserving_open_fences() {
|
||||
for source in [
|
||||
"```rust,no_run\nfn main() {}\n",
|
||||
"~~~~python title=demo\nvalue = 1\n",
|
||||
"```\u{b}rust\u{c}\nfn main() {}\n",
|
||||
"```unknown-language\ntext\n",
|
||||
] {
|
||||
let fence =
|
||||
OpenCodeFence::detect(source, source.len(), syntax_theme_revision()).expect(source);
|
||||
assert!(fence.highlighter.is_none());
|
||||
}
|
||||
for source in [
|
||||
" ```rust\ncode\n",
|
||||
"```\ncode\n",
|
||||
"```rust\r\ncode\r\n",
|
||||
"```rust\n'\0'\n",
|
||||
"```rust\ncode\n",
|
||||
"```rust\\,no_run\ncode\n",
|
||||
"```rust\npartial",
|
||||
] {
|
||||
assert!(
|
||||
OpenCodeFence::detect(source, source.len(), syntax_theme_revision()).is_none(),
|
||||
"{source:?}"
|
||||
);
|
||||
}
|
||||
let source = format!("```{}\n", "x".repeat(MAX_HIGHLIGHT_LINE_BYTES + 1));
|
||||
assert!(OpenCodeFence::detect(&source, source.len(), syntax_theme_revision()).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_possible_closer_returns_to_the_canonical_parser() {
|
||||
let opening = "~~~~rust\n";
|
||||
assert!(!has_possible_closing_line(
|
||||
"~~~\n```\n",
|
||||
/*marker*/ b'~',
|
||||
/*marker_len*/ 4
|
||||
));
|
||||
for line in [
|
||||
"~~~~\n",
|
||||
" ~~~~~~ \n",
|
||||
"~~~~\t\n",
|
||||
"~~~~\u{a0}\n",
|
||||
"\t~~~~\n",
|
||||
" ~~~~\n",
|
||||
"~~~~ trailing text\n",
|
||||
] {
|
||||
let source = format!("{opening}{line}");
|
||||
assert!(OpenCodeFence::detect(&source, source.len(), syntax_theme_revision()).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lazy_initialization_rejects_a_changed_theme() {
|
||||
let source = "```rust\nfn first() {}\n";
|
||||
let mut fence = OpenCodeFence::detect(source, source.len(), syntax_theme_revision()).unwrap();
|
||||
fence.theme_revision = fence.theme_revision.wrapping_sub(1);
|
||||
let appended = "fn second() {}\n";
|
||||
assert!(
|
||||
fence
|
||||
.append(&format!("{source}{appended}"), appended)
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
223
codex-rs/tui/src/streaming/commit_tick.rs
Normal file
223
codex-rs/tui/src/streaming/commit_tick.rs
Normal file
@@ -0,0 +1,223 @@
|
||||
//! Orchestrates commit-tick drains across streaming controllers.
|
||||
//!
|
||||
//! This module bridges queue-based chunking policy (`chunking`) with the concrete stream
|
||||
//! controllers (`controller`). Callers provide the current controllers and tick scope; the module
|
||||
//! computes queue pressure, selects a drain plan, applies it, and returns emitted history cells.
|
||||
//!
|
||||
//! The module preserves ordering by draining only from controller queue heads. It does not schedule
|
||||
//! ticks and it does not mutate UI state directly; callers remain responsible for animation events
|
||||
//! and history insertion side effects.
|
||||
//!
|
||||
//! The main flow is:
|
||||
//! [`run_commit_tick`] -> [`stream_queue_snapshot`] -> [`QueueSnapshot`] ->
|
||||
//! [`resolve_chunking_plan`] -> [`ChunkingDecision`]/[`DrainPlan`] ->
|
||||
//! [`apply_commit_tick_plan`] -> [`CommitTickOutput`].
|
||||
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use crate::history_cell::HistoryCell;
|
||||
|
||||
use super::chunking::AdaptiveChunkingPolicy;
|
||||
use super::chunking::ChunkingDecision;
|
||||
use super::chunking::ChunkingMode;
|
||||
use super::chunking::DrainPlan;
|
||||
use super::chunking::QueueSnapshot;
|
||||
use super::controller::PlanStreamController;
|
||||
use super::controller::StreamController;
|
||||
|
||||
/// Selects how a commit tick drains queued stable lines.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum CommitTickScope {
|
||||
/// Always run the tick, regardless of current chunking mode.
|
||||
AnyMode,
|
||||
/// Run model transitions and policy updates, but commit lines only in `CatchUp`.
|
||||
CatchUpOnly,
|
||||
/// Commit all stable replay lines before restoring the reader, leaving the live tail open.
|
||||
Replay,
|
||||
}
|
||||
|
||||
/// Describes what a single commit tick produced.
|
||||
pub(crate) struct CommitTickOutput {
|
||||
/// Cells produced by drained stream lines during this tick.
|
||||
pub(crate) cells: Vec<Box<dyn HistoryCell>>,
|
||||
/// Whether at least one stream controller was present for this tick.
|
||||
pub(crate) has_controller: bool,
|
||||
/// Whether all present controllers were idle after this tick.
|
||||
pub(crate) all_idle: bool,
|
||||
}
|
||||
|
||||
impl Default for CommitTickOutput {
|
||||
/// Creates an output that represents "no commit performed".
|
||||
///
|
||||
/// This is used when a tick is intentionally suppressed, for example when
|
||||
/// the scope is [`CommitTickScope::CatchUpOnly`] and policy is not in catch-up mode.
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
cells: Vec::new(),
|
||||
has_controller: false,
|
||||
all_idle: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs one commit tick against the provided stream controllers.
|
||||
///
|
||||
/// This function collects a [`QueueSnapshot`], asks [`AdaptiveChunkingPolicy`] for a
|
||||
/// [`ChunkingDecision`], and then applies the resulting [`DrainPlan`] to both controllers.
|
||||
/// If callers pass stale controller references (for example, references not tied to the
|
||||
/// current turn), queue age can be misread and the policy may stay in catch-up longer
|
||||
/// than expected.
|
||||
pub(crate) fn run_commit_tick(
|
||||
policy: &mut AdaptiveChunkingPolicy,
|
||||
stream_controller: Option<&mut StreamController>,
|
||||
plan_stream_controller: Option<&mut PlanStreamController>,
|
||||
scope: CommitTickScope,
|
||||
now: Instant,
|
||||
) -> CommitTickOutput {
|
||||
let snapshot = stream_queue_snapshot(
|
||||
stream_controller.as_deref(),
|
||||
plan_stream_controller.as_deref(),
|
||||
now,
|
||||
);
|
||||
if scope == CommitTickScope::Replay {
|
||||
return apply_commit_tick_plan(
|
||||
DrainPlan::Batch(snapshot.queued_lines),
|
||||
stream_controller,
|
||||
plan_stream_controller,
|
||||
);
|
||||
}
|
||||
let decision = resolve_chunking_plan(policy, snapshot, now);
|
||||
if scope == CommitTickScope::CatchUpOnly && decision.mode != ChunkingMode::CatchUp {
|
||||
return CommitTickOutput::default();
|
||||
}
|
||||
|
||||
apply_commit_tick_plan(
|
||||
decision.drain_plan,
|
||||
stream_controller,
|
||||
plan_stream_controller,
|
||||
)
|
||||
}
|
||||
|
||||
/// Builds the combined queue-pressure snapshot consumed by chunking policy.
|
||||
///
|
||||
/// The snapshot sums queue depth across controllers and keeps the maximum oldest age
|
||||
/// so policy decisions reflect the most delayed queued line currently visible.
|
||||
fn stream_queue_snapshot(
|
||||
stream_controller: Option<&StreamController>,
|
||||
plan_stream_controller: Option<&PlanStreamController>,
|
||||
now: Instant,
|
||||
) -> QueueSnapshot {
|
||||
let mut queued_lines = 0usize;
|
||||
let mut oldest_age: Option<Duration> = None;
|
||||
|
||||
if let Some(controller) = stream_controller {
|
||||
queued_lines += controller.queued_lines();
|
||||
oldest_age = max_duration(oldest_age, controller.oldest_queued_age(now));
|
||||
}
|
||||
if let Some(controller) = plan_stream_controller {
|
||||
queued_lines += controller.queued_lines();
|
||||
oldest_age = max_duration(oldest_age, controller.oldest_queued_age(now));
|
||||
}
|
||||
|
||||
QueueSnapshot {
|
||||
queued_lines,
|
||||
oldest_age,
|
||||
}
|
||||
}
|
||||
|
||||
/// Computes one policy decision and emits a trace log on mode transitions.
|
||||
///
|
||||
/// This keeps policy transition logging in one place so callers can rely on
|
||||
/// [`run_commit_tick`] to provide consistent observability.
|
||||
fn resolve_chunking_plan(
|
||||
policy: &mut AdaptiveChunkingPolicy,
|
||||
snapshot: QueueSnapshot,
|
||||
now: Instant,
|
||||
) -> ChunkingDecision {
|
||||
let prior_mode = policy.mode();
|
||||
let decision = policy.decide(snapshot, now);
|
||||
if decision.mode != prior_mode {
|
||||
tracing::trace!(
|
||||
prior_mode = ?prior_mode,
|
||||
new_mode = ?decision.mode,
|
||||
queued_lines = snapshot.queued_lines,
|
||||
oldest_queued_age_ms = snapshot.oldest_age.map(|age| age.as_millis() as u64),
|
||||
entered_catch_up = decision.entered_catch_up,
|
||||
"stream chunking mode transition"
|
||||
);
|
||||
}
|
||||
decision
|
||||
}
|
||||
|
||||
/// Applies a [`DrainPlan`] to all available stream controllers.
|
||||
///
|
||||
/// The returned [`CommitTickOutput`] reports emitted cells and whether all
|
||||
/// present controllers are idle after draining.
|
||||
fn apply_commit_tick_plan(
|
||||
drain_plan: DrainPlan,
|
||||
stream_controller: Option<&mut StreamController>,
|
||||
plan_stream_controller: Option<&mut PlanStreamController>,
|
||||
) -> CommitTickOutput {
|
||||
let mut output = CommitTickOutput::default();
|
||||
|
||||
if let Some(controller) = stream_controller {
|
||||
output.has_controller = true;
|
||||
let (cell, is_idle) = drain_stream_controller(controller, drain_plan);
|
||||
if let Some(cell) = cell {
|
||||
output.cells.push(cell);
|
||||
}
|
||||
output.all_idle &= is_idle;
|
||||
}
|
||||
if let Some(controller) = plan_stream_controller {
|
||||
output.has_controller = true;
|
||||
let (cell, is_idle) = drain_plan_stream_controller(controller, drain_plan);
|
||||
if let Some(cell) = cell {
|
||||
output.cells.push(cell);
|
||||
}
|
||||
output.all_idle &= is_idle;
|
||||
}
|
||||
|
||||
output
|
||||
}
|
||||
|
||||
/// Applies one drain step to the main stream controller.
|
||||
///
|
||||
/// [`DrainPlan::Single`] maps to one-line drain; [`DrainPlan::Batch`] maps to
|
||||
/// multi-line drain (including instant catch-up when policy requests the full
|
||||
/// queued backlog).
|
||||
fn drain_stream_controller(
|
||||
controller: &mut StreamController,
|
||||
drain_plan: DrainPlan,
|
||||
) -> (Option<Box<dyn HistoryCell>>, bool) {
|
||||
match drain_plan {
|
||||
DrainPlan::Single => controller.on_commit_tick(),
|
||||
DrainPlan::Batch(max_lines) => controller.on_commit_tick_batch(max_lines),
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies one drain step to the plan stream controller.
|
||||
///
|
||||
/// This mirrors [`drain_stream_controller`] so both controller types follow the
|
||||
/// same chunking policy decisions.
|
||||
fn drain_plan_stream_controller(
|
||||
controller: &mut PlanStreamController,
|
||||
drain_plan: DrainPlan,
|
||||
) -> (Option<Box<dyn HistoryCell>>, bool) {
|
||||
match drain_plan {
|
||||
DrainPlan::Single => controller.on_commit_tick(),
|
||||
DrainPlan::Batch(max_lines) => controller.on_commit_tick_batch(max_lines),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the greater of two optional durations.
|
||||
///
|
||||
/// This helper preserves whichever side is present when only one duration exists.
|
||||
fn max_duration(lhs: Option<Duration>, rhs: Option<Duration>) -> Option<Duration> {
|
||||
match (lhs, rhs) {
|
||||
(Some(left), Some(right)) => Some(left.max(right)),
|
||||
(Some(left), None) => Some(left),
|
||||
(None, Some(right)) => Some(right),
|
||||
(None, None) => None,
|
||||
}
|
||||
}
|
||||
2208
codex-rs/tui/src/streaming/controller.rs
Normal file
2208
codex-rs/tui/src/streaming/controller.rs
Normal file
File diff suppressed because it is too large
Load Diff
510
codex-rs/tui/src/streaming/controller_preview_tests.rs
Normal file
510
codex-rs/tui/src/streaming/controller_preview_tests.rs
Normal file
@@ -0,0 +1,510 @@
|
||||
use super::*;
|
||||
use crate::terminal_hyperlinks::visible_lines;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn followup_preview_hides_prompts_until_complete() {
|
||||
let cwd = std::env::temp_dir();
|
||||
let mut controller = StreamController::new(Some(40), &cwd, HistoryRenderMode::Rich);
|
||||
controller.push("Before ");
|
||||
let prefix = controller.current_tail_lines();
|
||||
controller.push(":codex-followup[");
|
||||
for character in r#"Inspect `items[0]`]{prompt="Use \\"}\" and `ticks`""#.chars() {
|
||||
controller.push(&character.to_string());
|
||||
assert_eq!(controller.current_tail_lines(), prefix);
|
||||
}
|
||||
insta::assert_debug_snapshot!(visible_lines(controller.current_tail_lines()), @r#"
|
||||
[
|
||||
Line::from("Before"),
|
||||
]
|
||||
"#);
|
||||
controller.push("} after.");
|
||||
assert_eq!(
|
||||
controller.current_tail_lines(),
|
||||
render_source(
|
||||
"Before Inspect `items[0]` after.",
|
||||
Some(40),
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
/*inline_visualization_context*/ None
|
||||
),
|
||||
);
|
||||
let mut controller = StreamController::new(Some(40), &cwd, HistoryRenderMode::Rich);
|
||||
controller.push("Before ");
|
||||
let prefix = controller.current_tail_lines();
|
||||
controller.push(&format!(
|
||||
":codex-followup[Long]{{prompt=\"{}",
|
||||
"界".repeat(3000)
|
||||
));
|
||||
controller.push("more prompt");
|
||||
assert_eq!(controller.current_tail_lines(), prefix);
|
||||
controller.push("\"}");
|
||||
insta::assert_debug_snapshot!(visible_lines(controller.current_tail_lines()), @r#"
|
||||
[
|
||||
Line::from("…"),
|
||||
]
|
||||
"#);
|
||||
controller.push(" after.");
|
||||
assert_eq!(
|
||||
visible_lines(controller.current_tail_lines()),
|
||||
vec![Line::from("…"), Line::from("after.")]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn followup_preview_resumes_after_the_directive_leaves_the_window() {
|
||||
let cwd = std::env::temp_dir();
|
||||
let mut controller = StreamController::new(Some(40), &cwd, HistoryRenderMode::Rich);
|
||||
controller.push(":codex-followup[First]{prompt=secret}");
|
||||
let prose = "ordinary prose ".repeat(700);
|
||||
controller.push(&prose);
|
||||
controller.push(":codex-followup[Second]{prompt=hidden} after.");
|
||||
let rendered = visible_lines(controller.current_tail_lines());
|
||||
let text = rendered
|
||||
.iter()
|
||||
.map(Line::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
assert!(text.ends_with("Second after."), "{text}");
|
||||
assert!(!text.contains("prompt="), "{text}");
|
||||
assert_eq!(rendered.first(), Some(&Line::from("…")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn followup_preview_only_opens_quotes_at_value_boundaries() {
|
||||
let cwd = std::env::temp_dir();
|
||||
for attributes in [
|
||||
"prompt=don't",
|
||||
"prompt=foo='bar",
|
||||
"prompt=don't other = \"quote } here\"",
|
||||
"prompt = 'quote } here'other=don't",
|
||||
] {
|
||||
let mut controller = StreamController::new(Some(40), &cwd, HistoryRenderMode::Rich);
|
||||
controller.push("Before ");
|
||||
let prefix = controller.current_tail_lines();
|
||||
controller.push(":codex-followup[");
|
||||
for character in format!("Open]{{{attributes}").chars() {
|
||||
controller.push(&character.to_string());
|
||||
assert_eq!(controller.current_tail_lines(), prefix);
|
||||
}
|
||||
controller.push("} after.");
|
||||
assert_eq!(
|
||||
visible_lines(controller.current_tail_lines()),
|
||||
vec![Line::from("Before Open after.")],
|
||||
"{attributes}",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn followup_preview_handles_surrounding_unfinished_markdown() {
|
||||
let cwd = std::env::temp_dir();
|
||||
let mut controller = StreamController::new(Some(40), &cwd, HistoryRenderMode::Rich);
|
||||
controller.push("[unfinished ");
|
||||
let prefix = controller.current_tail_lines();
|
||||
controller.push(":codex-followup[Inspect]{prompt=\"secret\"");
|
||||
assert_eq!(controller.current_tail_lines(), prefix);
|
||||
controller.push("}");
|
||||
assert_eq!(
|
||||
visible_lines(controller.current_tail_lines()),
|
||||
vec![Line::from("[unfinished Inspect")]
|
||||
);
|
||||
|
||||
for source in [
|
||||
":codex-followup[not a directive] continuing text",
|
||||
":codex-followup[not a directive] `code`",
|
||||
] {
|
||||
let mut controller = StreamController::new(Some(80), &cwd, HistoryRenderMode::Rich);
|
||||
for character in source.chars() {
|
||||
controller.push(&character.to_string());
|
||||
}
|
||||
assert_eq!(
|
||||
controller.current_tail_lines(),
|
||||
render_source(
|
||||
source,
|
||||
Some(80),
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
/*inline_visualization_context*/ None
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unmatched_code_openers_do_not_expose_followup_prompts() {
|
||||
let cwd = std::env::temp_dir();
|
||||
let mut controller = StreamController::new(Some(80), &cwd, HistoryRenderMode::Rich);
|
||||
controller.push("Type ` then ");
|
||||
let prefix = controller.current_tail_lines();
|
||||
controller.push(":codex-followup[");
|
||||
for character in "Open]{prompt=secret}".chars() {
|
||||
controller.push(&character.to_string());
|
||||
assert_eq!(controller.current_tail_lines(), prefix);
|
||||
}
|
||||
insta::assert_debug_snapshot!(visible_lines(controller.current_tail_lines()), @r#"
|
||||
[
|
||||
Line::from("Type ` then"),
|
||||
]
|
||||
"#);
|
||||
// A matching closer establishes literal code; its full contents can then be previewed.
|
||||
controller.push("`");
|
||||
assert_eq!(
|
||||
controller.current_tail_lines(),
|
||||
render_source(
|
||||
"Type ` then :codex-followup[Open]{prompt=secret}`",
|
||||
Some(80),
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
/*inline_visualization_context*/ None,
|
||||
),
|
||||
);
|
||||
|
||||
// Extending a tentative closing run must restore the old, safely cropped preview.
|
||||
let mut controller = StreamController::new(Some(80), &cwd, HistoryRenderMode::Rich);
|
||||
controller.push(&format!(
|
||||
":codex-followup[Long]{{prompt={}}} ` then ",
|
||||
"x".repeat(9000)
|
||||
));
|
||||
let prefix = controller.current_tail_lines();
|
||||
controller.push(&format!(
|
||||
":codex-followup[Open]{{prompt={}}}",
|
||||
"y".repeat(9000)
|
||||
));
|
||||
controller.push("`");
|
||||
controller.push("`");
|
||||
assert_eq!(controller.current_tail_lines(), prefix);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unfinished_link_destinations_do_not_expand_the_preview() {
|
||||
let cwd = std::env::temp_dir();
|
||||
for destination in [
|
||||
"https://example.com/a/very/long/path/to/the/guide",
|
||||
"https://example.com/a_(nested_(path))",
|
||||
r"https://example.com/escaped\)parenthesis",
|
||||
"<https://example.com/unbalanced)parenthesis>",
|
||||
" <https://example.com/unbalanced)parenthesis>",
|
||||
"https://example.com/guide \"a title with ) parentheses\"",
|
||||
"https://example.com/guide (x < y)",
|
||||
] {
|
||||
let mut controller = StreamController::new(Some(24), &cwd, HistoryRenderMode::Rich);
|
||||
controller.push("See [documentation]");
|
||||
let label = controller.current_tail_lines();
|
||||
// Split at every character, including the opening delimiter and escapes.
|
||||
for character in format!("({destination}").chars() {
|
||||
controller.push(&character.to_string());
|
||||
assert_eq!(controller.current_tail_lines(), label);
|
||||
}
|
||||
controller.push(") and continue.");
|
||||
assert_eq!(
|
||||
controller.current_tail_lines(),
|
||||
render_source(
|
||||
&format!("See [documentation]({destination}) and continue."),
|
||||
Some(24),
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
/*inline_visualization_context*/ None,
|
||||
),
|
||||
);
|
||||
}
|
||||
// The preview's byte limit must not drop the opener and expose a long URL tail.
|
||||
let mut controller = StreamController::new(Some(24), &cwd, HistoryRenderMode::Rich);
|
||||
controller.push("See [documentation]");
|
||||
let label = controller.current_tail_lines();
|
||||
controller.push(&format!("(https://example.com/{}", "界".repeat(3000)));
|
||||
controller.push("more-path");
|
||||
assert_eq!(controller.current_tail_lines(), label);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unfinished_links_flush_on_newline_or_completion() {
|
||||
let cwd = std::env::temp_dir();
|
||||
for (source, prefix) in [
|
||||
(
|
||||
"See [documentation](https://example.com/a/very/long/path",
|
||||
"See [documentation]",
|
||||
),
|
||||
("See :codex-followup[Inspect]{prompt=\"unfinished", "See"),
|
||||
] {
|
||||
for ending in ["", "\n"] {
|
||||
let mut controller = StreamController::new(Some(24), &cwd, HistoryRenderMode::Rich);
|
||||
controller.push(source);
|
||||
assert_eq!(
|
||||
visible_lines(controller.current_tail_lines()),
|
||||
vec![Line::from(prefix)]
|
||||
);
|
||||
controller.set_width(Some(32));
|
||||
assert_eq!(
|
||||
visible_lines(controller.current_tail_lines()),
|
||||
vec![Line::from(prefix)],
|
||||
);
|
||||
controller.push(ending);
|
||||
let (queued, _) = controller.on_commit_tick_batch(usize::MAX);
|
||||
let (remaining, finalized_source) = controller.finalize();
|
||||
let displayed = queued
|
||||
.into_iter()
|
||||
.chain(remaining)
|
||||
.flat_map(|cell| cell.display_lines(/*width*/ 34))
|
||||
.collect::<Vec<_>>();
|
||||
let expected = history_cell::AgentMessageCell::new_hyperlink_lines(
|
||||
render_source(
|
||||
source,
|
||||
Some(32),
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
/*inline_visualization_context*/ None,
|
||||
),
|
||||
/*is_first_line*/ true,
|
||||
);
|
||||
assert_eq!(displayed, expected.display_lines(/*width*/ 34));
|
||||
assert_eq!(finalized_source, Some(format!("{source}\n")));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn link_preview_respects_code_escapes_and_raw_mode() {
|
||||
let cwd = std::env::temp_dir();
|
||||
for source in [
|
||||
r"See \[label](https://example.com/unfinished",
|
||||
r"See [label\](https://example.com/unfinished",
|
||||
"See `[label](https://example.com/unfinished`",
|
||||
"See ``[la`bel](https://example.com/unfinished``",
|
||||
"See [label](https://example.com/complete) and prose",
|
||||
r"See \:codex-followup[label]{prompt=unfinished",
|
||||
"See `:codex-followup[label]{prompt=unfinished`",
|
||||
] {
|
||||
let mut controller = StreamController::new(Some(24), &cwd, HistoryRenderMode::Rich);
|
||||
for character in source.chars() {
|
||||
controller.push(&character.to_string());
|
||||
}
|
||||
assert_eq!(
|
||||
controller.current_tail_lines(),
|
||||
render_source(
|
||||
source,
|
||||
Some(24),
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
/*inline_visualization_context*/ None,
|
||||
),
|
||||
"{source}",
|
||||
);
|
||||
}
|
||||
let mut controller = StreamController::new(Some(24), &cwd, HistoryRenderMode::Rich);
|
||||
controller.push("See `[code](literal` then [label](https://example.com/unfinished");
|
||||
assert_eq!(
|
||||
controller.current_tail_lines(),
|
||||
render_source(
|
||||
"See `[code](literal` then [label]",
|
||||
Some(24),
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
/*inline_visualization_context*/ None,
|
||||
),
|
||||
);
|
||||
|
||||
let source = "See [label](https://example.com/unfinished";
|
||||
let mut controller = StreamController::new(Some(24), &cwd, HistoryRenderMode::Raw);
|
||||
controller.push(source);
|
||||
assert_eq!(
|
||||
controller.current_tail_lines(),
|
||||
render_source(
|
||||
source,
|
||||
Some(24),
|
||||
&cwd,
|
||||
HistoryRenderMode::Raw,
|
||||
/*inline_visualization_context*/ None,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn link_holdback_stays_rich_only_when_a_pipe_freezes_the_preview() {
|
||||
let cwd = std::env::temp_dir();
|
||||
let source = "See [label](https://example.com";
|
||||
let mut controller = StreamController::new(Some(40), &cwd, HistoryRenderMode::Rich);
|
||||
controller.push(source);
|
||||
let label = controller.current_tail_lines();
|
||||
controller.push("|suffix)");
|
||||
assert_eq!(controller.current_tail_lines(), label);
|
||||
controller.set_render_mode(HistoryRenderMode::Raw);
|
||||
assert_eq!(
|
||||
controller.current_tail_lines(),
|
||||
render_source(
|
||||
source,
|
||||
Some(40),
|
||||
&cwd,
|
||||
HistoryRenderMode::Raw,
|
||||
/*inline_visualization_context*/ None,
|
||||
),
|
||||
);
|
||||
controller.set_render_mode(HistoryRenderMode::Rich);
|
||||
assert_eq!(controller.current_tail_lines(), label);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_only_changes_refresh_the_preview_and_active_tail() {
|
||||
let cwd = std::env::temp_dir();
|
||||
let mut controller = StreamController::new(Some(5), &cwd, HistoryRenderMode::Rich);
|
||||
controller.push("hello");
|
||||
let before = controller.current_tail_lines();
|
||||
|
||||
// An entity preserves trailing whitespace that Markdown otherwise trims at EOF.
|
||||
assert!(controller.push(" "));
|
||||
let after = controller.current_tail_lines();
|
||||
assert_eq!(visible_lines(before.clone()), visible_lines(after.clone()));
|
||||
assert_eq!(
|
||||
after[0].source,
|
||||
render_source(
|
||||
"hello ",
|
||||
Some(5),
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
/*inline_visualization_context*/ None,
|
||||
)[0]
|
||||
.source,
|
||||
);
|
||||
assert_ne!(
|
||||
history_cell::StreamingAgentTailCell::new(before.clone(), /*is_first_line*/ true),
|
||||
history_cell::StreamingAgentTailCell::new(after.clone(), /*is_first_line*/ true),
|
||||
);
|
||||
assert_ne!(
|
||||
history_cell::StreamingPlanTailCell::new(before, /*is_stream_continuation*/ false),
|
||||
history_cell::StreamingPlanTailCell::new(after, /*is_stream_continuation*/ false),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unterminated_prose_reflows_and_finishes_without_duplication() {
|
||||
let cwd = std::env::temp_dir();
|
||||
for ending in ["", "\n"] {
|
||||
let mut controller = StreamController::new(Some(32), &cwd, HistoryRenderMode::Rich);
|
||||
let mut source = String::from("`numbers` ");
|
||||
controller.push(&source);
|
||||
for number in 100..200 {
|
||||
let delta = format!("{number} ");
|
||||
source.push_str(&delta);
|
||||
controller.push(&delta);
|
||||
assert_eq!(controller.queued_lines(), 0);
|
||||
assert_eq!(
|
||||
controller.current_tail_lines(),
|
||||
render_source(
|
||||
&source,
|
||||
Some(32),
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
/*inline_visualization_context*/ None
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
controller.push(" | pending structure");
|
||||
controller.set_width(Some(48));
|
||||
assert_eq!(controller.queued_lines(), 0);
|
||||
assert_eq!(
|
||||
controller.current_tail_lines(),
|
||||
render_source(
|
||||
&source,
|
||||
Some(48),
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
/*inline_visualization_context*/ None
|
||||
),
|
||||
);
|
||||
source.push_str(" | pending structure");
|
||||
controller.push(ending);
|
||||
let (queued, _) = controller.on_commit_tick_batch(usize::MAX);
|
||||
let (remaining, finalized_source) = controller.finalize();
|
||||
let displayed = queued
|
||||
.into_iter()
|
||||
.chain(remaining)
|
||||
.flat_map(|cell| cell.display_lines(/*width*/ 50))
|
||||
.collect::<Vec<_>>();
|
||||
let expected = history_cell::AgentMessageCell::new_hyperlink_lines(
|
||||
render_source(
|
||||
&source,
|
||||
Some(48),
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
/*inline_visualization_context*/ None,
|
||||
),
|
||||
/*is_first_line*/ true,
|
||||
);
|
||||
assert_eq!(displayed, expected.display_lines(/*width*/ 50));
|
||||
assert_eq!(finalized_source, Some(format!("{source}\n")));
|
||||
assert!(!controller.has_live_tail());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_markdown_structures_remain_newline_gated() {
|
||||
let cwd = std::env::temp_dir();
|
||||
for (committed, partial) in [
|
||||
("", "| partial header"),
|
||||
("", "```rust"),
|
||||
("", "> ~~~rust"),
|
||||
("```rust\n", "let partial = 1;"),
|
||||
("- ```rust\n", " let partial = 1;"),
|
||||
("> - ```rust\n", "> let partial = 1;"),
|
||||
(" indented code\n", " partial code"),
|
||||
("```markdown\n", "partial markdown fence"),
|
||||
("| A | B |\n| --- | --- |\n", "partial row"),
|
||||
] {
|
||||
let mut controller = StreamController::new(Some(40), &cwd, HistoryRenderMode::Rich);
|
||||
controller.push(committed);
|
||||
let tail = controller.current_tail_lines();
|
||||
let queued = controller.queued_lines();
|
||||
controller.push(partial);
|
||||
assert_eq!(controller.current_tail_lines(), tail);
|
||||
assert_eq!(controller.queued_lines(), queued);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_unicode_preview_keeps_recent_text_and_finalizes_full_source() {
|
||||
let cwd = std::env::temp_dir();
|
||||
let mut controller = StreamController::new(Some(40), &cwd, HistoryRenderMode::Rich);
|
||||
controller.push(&"🦀 ".repeat(3000));
|
||||
controller.push("latest text");
|
||||
let preview = visible_lines(controller.current_tail_lines());
|
||||
assert_eq!(preview.first(), Some(&Line::from("…")));
|
||||
let text = preview
|
||||
.iter()
|
||||
.map(Line::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
assert!(text.trim_end().ends_with("latest text"), "{text}");
|
||||
assert_eq!(controller.queued_lines(), 0);
|
||||
let (_, source) = controller.finalize();
|
||||
assert_eq!(source, Some(format!("{}latest text\n", "🦀 ".repeat(3000))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
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.on_commit_tick_batch(usize::MAX);
|
||||
controller.push("prose after code");
|
||||
assert_eq!(
|
||||
visible_lines(controller.current_tail_lines()),
|
||||
vec![Line::from("prose after code")],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prose_after_a_table_is_previewed_until_another_table_starts() {
|
||||
let cwd = std::env::temp_dir();
|
||||
let mut controller = StreamController::new(Some(40), &cwd, HistoryRenderMode::Rich);
|
||||
controller.push("| A | B |\n| --- | --- |\n| a | b |\n\n");
|
||||
controller.push("prose after the table");
|
||||
let tail = visible_lines(controller.current_tail_lines());
|
||||
assert_eq!(tail.last(), Some(&Line::from("prose after the table")));
|
||||
assert_eq!(controller.queued_lines(), 0);
|
||||
|
||||
controller.push("\n\n| C | D |\n| --- | --- |\n");
|
||||
let tail = controller.current_tail_lines();
|
||||
controller.push("partial row");
|
||||
assert_eq!(controller.current_tail_lines(), tail);
|
||||
}
|
||||
60
codex-rs/tui/src/streaming/inline_math_tests.rs
Normal file
60
codex-rs/tui/src/streaming/inline_math_tests.rs
Normal file
@@ -0,0 +1,60 @@
|
||||
use super::StreamingRender;
|
||||
use crate::history_cell::HistoryRenderMode;
|
||||
use crate::markdown::render_streaming_markdown_agent_with_links_and_cwd;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn unicode_math_inline_stream_preserves_display_exclusion_boundaries() {
|
||||
let cwd = std::env::temp_dir();
|
||||
for delimiters in [("$$", "$$"), ("\\[", "\\]")] {
|
||||
let mut render = StreamingRender::new();
|
||||
let mut source = String::new();
|
||||
for chunk in [
|
||||
delimiters.0,
|
||||
"\n\nx^2\n\n",
|
||||
delimiters.1,
|
||||
"\n\n",
|
||||
"After $\\alpha$.\n",
|
||||
] {
|
||||
source.push_str(chunk);
|
||||
render.append(
|
||||
&source,
|
||||
chunk,
|
||||
Some(40),
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
/*inline_visualization_context*/ None,
|
||||
);
|
||||
assert_eq!(
|
||||
render.lines,
|
||||
render_streaming_markdown_agent_with_links_and_cwd(
|
||||
&source,
|
||||
Some(40),
|
||||
Some(&cwd),
|
||||
crate::markdown_render::ListSpacing::AfterMultiline
|
||||
)
|
||||
.lines
|
||||
);
|
||||
for width in [16, 40] {
|
||||
let mut resized = StreamingRender::new();
|
||||
resized.recompute(
|
||||
&source,
|
||||
Some(width),
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
/*inline_visualization_context*/ None,
|
||||
);
|
||||
assert_eq!(
|
||||
resized.lines,
|
||||
render_streaming_markdown_agent_with_links_and_cwd(
|
||||
&source,
|
||||
Some(width),
|
||||
Some(&cwd),
|
||||
crate::markdown_render::ListSpacing::AfterMultiline,
|
||||
)
|
||||
.lines
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
230
codex-rs/tui/src/streaming/math_tests.rs
Normal file
230
codex-rs/tui/src/streaming/math_tests.rs
Normal file
@@ -0,0 +1,230 @@
|
||||
use super::StreamCore;
|
||||
use super::render_source;
|
||||
use crate::history_cell::HistoryRenderMode;
|
||||
use crate::markdown::render_streaming_markdown_agent_with_links_and_cwd;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn unicode_math_aligned_stream_matches_complete_render() {
|
||||
let cwd = std::env::temp_dir();
|
||||
let source = "Before.\n\n\\[\n\\begin{aligned}\n\\underset{x}{\\min}&=\\sum_{i=1}^N x_{gpt}\\\\[2mm]\ny&=2\n\\end{aligned}\n\\]\n\nAfter $\\alpha$.\n";
|
||||
for width in [80, 12] {
|
||||
for mode in [HistoryRenderMode::Rich, HistoryRenderMode::Raw] {
|
||||
let mut stream = StreamCore::new(
|
||||
Some(width),
|
||||
&cwd,
|
||||
mode,
|
||||
/*inline_visualization_context*/ None,
|
||||
);
|
||||
let mut emitted = Vec::new();
|
||||
for ch in source.chars() {
|
||||
stream.push_delta(&ch.to_string());
|
||||
emitted.extend(stream.tick_batch(usize::MAX));
|
||||
}
|
||||
let (remaining, raw) = stream.finalize_remaining();
|
||||
emitted.extend(remaining);
|
||||
assert_eq!(raw, source);
|
||||
assert_eq!(
|
||||
emitted,
|
||||
render_source(
|
||||
source,
|
||||
Some(width),
|
||||
&cwd,
|
||||
mode,
|
||||
/*inline_visualization_context*/ None
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unicode_math_stream_holds_display_until_closed_and_preserves_source() {
|
||||
let cwd = std::env::temp_dir();
|
||||
for mode in [HistoryRenderMode::Rich, HistoryRenderMode::Raw] {
|
||||
for (delimiters, prefix) in [(("$$", "$$"), "Before.\n\n"), (("\\[", "\\]"), "Before.\n")] {
|
||||
let mut stream = StreamCore::new(
|
||||
Some(60),
|
||||
&cwd,
|
||||
mode,
|
||||
/*inline_visualization_context*/ None,
|
||||
);
|
||||
let mut emitted = Vec::new();
|
||||
let mut source = String::new();
|
||||
for chunk in [
|
||||
prefix,
|
||||
delimiters.0,
|
||||
"\n",
|
||||
"\\frac{a+b}{c}\n",
|
||||
"\n",
|
||||
delimiters.1,
|
||||
"\n\n",
|
||||
"After $\\alpha^2$.\n",
|
||||
] {
|
||||
source.push_str(chunk);
|
||||
stream.push_delta(chunk);
|
||||
emitted.extend(stream.tick_batch(usize::MAX));
|
||||
if mode == HistoryRenderMode::Rich && source.ends_with("\\frac{a+b}{c}\n") {
|
||||
assert_eq!(
|
||||
emitted,
|
||||
render_source(
|
||||
prefix,
|
||||
Some(60),
|
||||
&cwd,
|
||||
mode,
|
||||
/*inline_visualization_context*/ None
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
let (remaining, raw) = stream.finalize_remaining();
|
||||
emitted.extend(remaining);
|
||||
assert_eq!(raw, source);
|
||||
assert_eq!(
|
||||
emitted,
|
||||
render_source(
|
||||
&source,
|
||||
Some(60),
|
||||
&cwd,
|
||||
mode,
|
||||
/*inline_visualization_context*/ None
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unicode_math_raw_preview_preserves_line_on_newline() {
|
||||
let cwd = std::env::temp_dir();
|
||||
for open in ["$$", "\\["] {
|
||||
let mut stream = StreamCore::new(
|
||||
Some(12),
|
||||
&cwd,
|
||||
HistoryRenderMode::Raw,
|
||||
/*inline_visualization_context*/ None,
|
||||
);
|
||||
let source = format!("{open}\\frac{{abcdefghijk}}{{lmnop}}");
|
||||
stream.push_delta(&source);
|
||||
let preview = stream.current_tail_lines();
|
||||
assert_eq!(preview.len(), 1);
|
||||
assert_eq!(preview[0].line.to_string(), source);
|
||||
if open == "$$" {
|
||||
insta::assert_snapshot!("unicode_math_raw_preview", preview[0].line.to_string());
|
||||
}
|
||||
stream.push_delta("\n");
|
||||
let (lines, raw) = stream.finalize_remaining();
|
||||
assert_eq!(lines, preview);
|
||||
assert_eq!(raw, format!("{source}\n"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unicode_math_unfinished_display_is_visible_and_reflows() {
|
||||
let cwd = std::env::temp_dir();
|
||||
for (open, close) in [("$$", "$$"), (r"\[", r"\]")] {
|
||||
let mut stream = StreamCore::new(
|
||||
Some(80),
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
/*inline_visualization_context*/ None,
|
||||
);
|
||||
for (chunk, expected) in [(&open[..1], &open[..1]), (&open[1..], open)] {
|
||||
stream.push_delta(chunk);
|
||||
assert_eq!(stream.current_tail_lines()[0].line.to_string(), expected);
|
||||
}
|
||||
stream.push_delta("\n \\frac{|a+b+c+d+e+f|}{g+h}");
|
||||
for width in [80, 20, 80] {
|
||||
stream.set_width(Some(width));
|
||||
let lines = stream.current_tail_lines();
|
||||
assert!(
|
||||
lines
|
||||
.iter()
|
||||
.any(|line| line.line.to_string().contains("frac"))
|
||||
);
|
||||
assert!(lines.iter().all(|line| line.line.width() <= width));
|
||||
if open == "$$" && width == 20 {
|
||||
insta::assert_snapshot!(
|
||||
"unicode_math_live_source_narrow",
|
||||
lines
|
||||
.iter()
|
||||
.map(|line| line.line.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
);
|
||||
}
|
||||
}
|
||||
stream.push_delta(&format!("\n{close}\n"));
|
||||
let (lines, source) = stream.finalize_remaining();
|
||||
assert_eq!(
|
||||
lines,
|
||||
render_source(
|
||||
&source,
|
||||
Some(80),
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
/*inline_visualization_context*/ None
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unicode_math_rejected_display_keeps_its_closer_and_following_text() {
|
||||
let cwd = std::env::temp_dir();
|
||||
for (open, close) in [("$$", "$$"), ("\\[", "\\]")] {
|
||||
for (prefix, body) in [
|
||||
("", "x".repeat(/*n*/ 5000)),
|
||||
("", "`x`".to_owned()),
|
||||
("", format!("`{close}\nx`")),
|
||||
("", "[x](https://example.com)".to_owned()),
|
||||
("Equation: ", "x^2".to_owned()),
|
||||
] {
|
||||
let mut render = super::super::render::StreamingRender::new();
|
||||
let mut source = String::new();
|
||||
for chunk in [
|
||||
format!("{prefix}{open}\n\n"),
|
||||
format!("{body}\n\n"),
|
||||
format!("{close}\n\n"),
|
||||
"After $\\alpha$.\n\n".to_owned(),
|
||||
"$$\\beta$$\n".to_owned(),
|
||||
] {
|
||||
source.push_str(&chunk);
|
||||
render.append(
|
||||
&source,
|
||||
&chunk,
|
||||
Some(40),
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
/*inline_visualization_context*/ None,
|
||||
);
|
||||
let expected = render_streaming_markdown_agent_with_links_and_cwd(
|
||||
&source,
|
||||
Some(40),
|
||||
Some(&cwd),
|
||||
crate::markdown_render::ListSpacing::AfterMultiline,
|
||||
);
|
||||
assert_eq!(
|
||||
(&render.lines, render.pending_math_start),
|
||||
(&expected.lines, expected.pending_math_start)
|
||||
);
|
||||
if source.len() > 4096 || !prefix.is_empty() {
|
||||
assert_eq!(render.pending_math_start, None);
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
render
|
||||
.lines
|
||||
.iter()
|
||||
.any(|line| line.line.to_string().contains("After α."))
|
||||
);
|
||||
assert!(
|
||||
render
|
||||
.lines
|
||||
.iter()
|
||||
.any(|line| line.line.to_string().contains('β'))
|
||||
);
|
||||
assert_eq!(render.pending_math_start, None);
|
||||
}
|
||||
}
|
||||
}
|
||||
218
codex-rs/tui/src/streaming/mermaid_tests.rs
Normal file
218
codex-rs/tui/src/streaming/mermaid_tests.rs
Normal file
@@ -0,0 +1,218 @@
|
||||
use super::controller::StreamController;
|
||||
use super::render::StreamingRender;
|
||||
use crate::history_cell::HistoryRenderMode;
|
||||
use insta::assert_snapshot;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn mermaid_stream_closes_resizes_and_preserves_raw_source() {
|
||||
let cwd = std::env::temp_dir();
|
||||
let mut render = StreamingRender::new();
|
||||
let mut source = String::new();
|
||||
let mut stages = Vec::new();
|
||||
for chunk in [
|
||||
"Before.\n\n```mermaid\n",
|
||||
"flowchart LR\nA[\"Codex reply<br/>completed\"] --> B[\"Rendered in Ghostty\"]\n",
|
||||
"```\n",
|
||||
"\nAfter.\n",
|
||||
] {
|
||||
source.push_str(chunk);
|
||||
render.append(
|
||||
&source,
|
||||
chunk,
|
||||
Some(80),
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
/*inline_visualization_context*/ None,
|
||||
);
|
||||
assert_eq!(
|
||||
render.lines,
|
||||
super::render::render_source(
|
||||
&source,
|
||||
Some(80),
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
/*inline_visualization_context*/ None
|
||||
)
|
||||
);
|
||||
stages.push(
|
||||
render
|
||||
.lines
|
||||
.iter()
|
||||
.map(|line| line.line.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n"),
|
||||
);
|
||||
}
|
||||
for (width, mode) in [
|
||||
(8, HistoryRenderMode::Rich),
|
||||
(80, HistoryRenderMode::Raw),
|
||||
(80, HistoryRenderMode::Rich),
|
||||
] {
|
||||
render.recompute(
|
||||
&source,
|
||||
Some(width),
|
||||
&cwd,
|
||||
mode,
|
||||
/*inline_visualization_context*/ None,
|
||||
);
|
||||
assert_eq!(
|
||||
render.lines,
|
||||
super::render::render_source(
|
||||
&source,
|
||||
Some(width),
|
||||
&cwd,
|
||||
mode,
|
||||
/*inline_visualization_context*/ None
|
||||
)
|
||||
);
|
||||
stages.push(
|
||||
render
|
||||
.lines
|
||||
.iter()
|
||||
.map(|line| line.line.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n"),
|
||||
);
|
||||
}
|
||||
assert_snapshot!(stages.join("\n\n---\n\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mermaid_holdback_tracks_nested_blocks_after_normalized_markdown() {
|
||||
let cwd = std::env::temp_dir();
|
||||
let prefix = "```md\n| Name | Value |\n| --- | --- |\n| A | B |\n```\n\n";
|
||||
for block in [
|
||||
"> ```mermaid\n> flowchart LR\n> A --> B\n> ```\n",
|
||||
"- Diagram:\n\n ```mermaid\n flowchart LR\n A --> B\n ```\n",
|
||||
] {
|
||||
let mut render = StreamingRender::new();
|
||||
let mut source = prefix.to_owned();
|
||||
render.append(
|
||||
&source,
|
||||
prefix,
|
||||
Some(80),
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
/*inline_visualization_context*/ None,
|
||||
);
|
||||
for chunk in block.split_inclusive('\n') {
|
||||
source.push_str(chunk);
|
||||
render.append(
|
||||
&source,
|
||||
chunk,
|
||||
Some(80),
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
/*inline_visualization_context*/ None,
|
||||
);
|
||||
}
|
||||
assert_eq!(render.mutable_fence_start, Some(prefix.len()));
|
||||
render.recompute(
|
||||
&source,
|
||||
Some(80),
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
/*inline_visualization_context*/ None,
|
||||
);
|
||||
assert_eq!(render.mutable_fence_start, Some(prefix.len()));
|
||||
let continuation = "\nAfter.\n\n";
|
||||
source.push_str(continuation);
|
||||
render.append(
|
||||
&source,
|
||||
continuation,
|
||||
Some(80),
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
/*inline_visualization_context*/ None,
|
||||
);
|
||||
assert_eq!(render.mutable_fence_start, None);
|
||||
render.recompute(
|
||||
&source,
|
||||
Some(80),
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
/*inline_visualization_context*/ None,
|
||||
);
|
||||
assert_eq!(render.mutable_fence_start, None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mermaid_controller_keeps_diagram_mutable_and_returns_original_source() {
|
||||
let mut controller =
|
||||
StreamController::new(Some(80), &std::env::temp_dir(), HistoryRenderMode::Rich);
|
||||
let source = "```mermaid\nflowchart LR\nA[Request<br />completed] --> B[Reply]\n```\n";
|
||||
for chunk in source.split_inclusive('\n') {
|
||||
controller.push(chunk);
|
||||
assert!(
|
||||
controller.on_commit_tick().0.is_none(),
|
||||
"Mermaid escaped into scrollback"
|
||||
);
|
||||
}
|
||||
let diagram = controller.current_tail_lines();
|
||||
assert!(
|
||||
diagram
|
||||
.iter()
|
||||
.any(|line| line.line.to_string().contains('┌'))
|
||||
);
|
||||
controller.set_width(Some(8));
|
||||
assert!(
|
||||
controller
|
||||
.current_tail_lines()
|
||||
.iter()
|
||||
.any(|line| line.line.to_string().contains("A[Request<br />completed]"))
|
||||
);
|
||||
controller.set_width(Some(80));
|
||||
assert_eq!(controller.current_tail_lines(), diagram);
|
||||
assert_eq!(
|
||||
crate::markdown::extract_copy_targets(source),
|
||||
vec![crate::markdown::CopyTarget::Code {
|
||||
language: Some("mermaid".to_owned()),
|
||||
content: std::sync::Arc::from("flowchart LR\nA[Request<br />completed] --> B[Reply]\n"),
|
||||
}],
|
||||
);
|
||||
let mut full_source = source.to_owned();
|
||||
for i in 0..256 {
|
||||
let continuation = format!("\nStep {i}\n");
|
||||
full_source.push_str(&continuation);
|
||||
controller.push(&continuation);
|
||||
assert!(!controller.has_live_tail());
|
||||
assert!(controller.current_tail_lines().is_empty());
|
||||
assert!(controller.on_commit_tick_batch(usize::MAX).0.is_some());
|
||||
}
|
||||
controller.set_width(Some(8));
|
||||
controller.set_width(Some(80));
|
||||
full_source.push('\n');
|
||||
controller.push("\n");
|
||||
controller.on_commit_tick_batch(usize::MAX);
|
||||
for chunk in source.split_inclusive('\n') {
|
||||
full_source.push_str(chunk);
|
||||
controller.push(chunk);
|
||||
assert!(controller.on_commit_tick().0.is_none());
|
||||
}
|
||||
assert!(controller.has_live_tail());
|
||||
let second_diagram = controller.current_tail_lines();
|
||||
assert!(second_diagram.len() <= diagram.len() + 1);
|
||||
controller.set_width(Some(8));
|
||||
assert!(
|
||||
controller
|
||||
.current_tail_lines()
|
||||
.iter()
|
||||
.any(|line| line.line.to_string().contains("A[Request<br />completed]"))
|
||||
);
|
||||
controller.set_width(Some(80));
|
||||
assert_eq!(controller.current_tail_lines(), second_diagram);
|
||||
controller.set_render_mode(HistoryRenderMode::Raw);
|
||||
assert_eq!(controller.queued_lines(), source.lines().count());
|
||||
controller.set_render_mode(HistoryRenderMode::Rich);
|
||||
assert_eq!(controller.current_tail_lines(), second_diagram);
|
||||
controller.set_render_mode(HistoryRenderMode::Raw);
|
||||
assert!(controller.on_commit_tick_batch(/*max_lines*/ 1).0.is_some());
|
||||
controller.set_render_mode(HistoryRenderMode::Rich);
|
||||
assert_eq!(controller.current_tail_lines(), second_diagram[1..]);
|
||||
assert_eq!(
|
||||
controller.finalize().1.as_deref(),
|
||||
Some(full_source.as_str())
|
||||
);
|
||||
}
|
||||
131
codex-rs/tui/src/streaming/mod.rs
Normal file
131
codex-rs/tui/src/streaming/mod.rs
Normal file
@@ -0,0 +1,131 @@
|
||||
//! Streaming primitives used by the TUI transcript pipeline.
|
||||
//!
|
||||
//! `StreamState` owns newline-gated markdown collection and a FIFO queue of committed render lines.
|
||||
//! Higher-level modules build on top of this state:
|
||||
//! - `controller` adapts queued lines into `HistoryCell` emission rules for message and plan streams.
|
||||
//! - `chunking` computes adaptive drain plans from queue pressure.
|
||||
//! - `commit_tick` binds policy decisions to concrete controller drains.
|
||||
//!
|
||||
//! The key invariant is queue ordering. All drains pop from the front, and enqueue records an
|
||||
//! arrival timestamp so policy code can reason about oldest queued age without peeking into text.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use crate::markdown_stream::MarkdownStreamCollector;
|
||||
use crate::terminal_hyperlinks::HyperlinkLine;
|
||||
pub(crate) mod chunking;
|
||||
mod code_fence;
|
||||
pub(crate) mod commit_tick;
|
||||
pub(crate) mod controller;
|
||||
mod prose_preview;
|
||||
mod render;
|
||||
mod table_holdback;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "mermaid_tests.rs"]
|
||||
mod mermaid_tests;
|
||||
|
||||
struct QueuedLine {
|
||||
line: HyperlinkLine,
|
||||
enqueued_at: Instant,
|
||||
}
|
||||
|
||||
/// Holds in-flight markdown stream state and queued committed lines.
|
||||
pub(crate) struct StreamState {
|
||||
pub(crate) collector: MarkdownStreamCollector,
|
||||
queued_lines: VecDeque<QueuedLine>,
|
||||
pub(crate) has_seen_delta: bool,
|
||||
}
|
||||
|
||||
impl StreamState {
|
||||
/// Create stream state whose markdown collector renders local file links relative to `cwd`.
|
||||
///
|
||||
/// Controllers are expected to pass the session cwd here once and keep it stable for the
|
||||
/// lifetime of the active stream.
|
||||
pub(crate) fn new(width: Option<usize>, cwd: &Path) -> Self {
|
||||
Self {
|
||||
collector: MarkdownStreamCollector::new(width, cwd),
|
||||
queued_lines: VecDeque::new(),
|
||||
has_seen_delta: false,
|
||||
}
|
||||
}
|
||||
/// Resets collector and queue state for the next stream lifecycle.
|
||||
pub(crate) fn clear(&mut self) {
|
||||
self.collector.clear();
|
||||
self.queued_lines.clear();
|
||||
self.has_seen_delta = false;
|
||||
}
|
||||
/// Drains one queued line from the front of the queue.
|
||||
pub(crate) fn step(&mut self) -> Vec<HyperlinkLine> {
|
||||
self.queued_lines
|
||||
.pop_front()
|
||||
.map(|queued| queued.line)
|
||||
.into_iter()
|
||||
.collect()
|
||||
}
|
||||
/// Drains up to `max_lines` queued lines from the front of the queue.
|
||||
///
|
||||
/// Callers that pass very large values still get bounded behavior because this method clamps to
|
||||
/// the currently available queue length.
|
||||
pub(crate) fn drain_n(&mut self, max_lines: usize) -> Vec<HyperlinkLine> {
|
||||
let end = max_lines.min(self.queued_lines.len());
|
||||
self.queued_lines
|
||||
.drain(..end)
|
||||
.map(|queued| queued.line)
|
||||
.collect()
|
||||
}
|
||||
/// Clears queued lines while keeping collector/turn lifecycle state intact.
|
||||
pub(crate) fn clear_queue(&mut self) {
|
||||
self.queued_lines.clear();
|
||||
}
|
||||
/// Returns whether no lines are queued for commit.
|
||||
pub(crate) fn is_idle(&self) -> bool {
|
||||
self.queued_lines.is_empty()
|
||||
}
|
||||
/// Returns the current queue depth.
|
||||
pub(crate) fn queued_len(&self) -> usize {
|
||||
self.queued_lines.len()
|
||||
}
|
||||
/// Returns the age of the oldest queued line.
|
||||
pub(crate) fn oldest_queued_age(&self, now: Instant) -> Option<Duration> {
|
||||
self.queued_lines
|
||||
.front()
|
||||
.map(|queued| now.saturating_duration_since(queued.enqueued_at))
|
||||
}
|
||||
/// Appends committed lines to the queue with a shared enqueue timestamp.
|
||||
pub(crate) fn enqueue(&mut self, lines: Vec<HyperlinkLine>) {
|
||||
let now = Instant::now();
|
||||
self.queued_lines
|
||||
.extend(lines.into_iter().map(|line| QueuedLine {
|
||||
line,
|
||||
enqueued_at: now,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use ratatui::text::Line;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn test_cwd() -> PathBuf {
|
||||
// These tests only need a stable absolute cwd; using temp_dir() avoids baking Unix- or
|
||||
// Windows-specific root semantics into the fixtures.
|
||||
std::env::temp_dir()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drain_n_clamps_to_available_lines() {
|
||||
let mut state = StreamState::new(/*width*/ None, &test_cwd());
|
||||
state.enqueue(vec![HyperlinkLine::new(Line::from("one"))]);
|
||||
|
||||
let drained = state.drain_n(/*max_lines*/ 8);
|
||||
assert_eq!(drained, vec![HyperlinkLine::new(Line::from("one"))]);
|
||||
assert!(state.is_idle());
|
||||
}
|
||||
}
|
||||
290
codex-rs/tui/src/streaming/prose_preview.rs
Normal file
290
codex-rs/tui/src/streaming/prose_preview.rs
Normal file
@@ -0,0 +1,290 @@
|
||||
//! Bounded, disposable previews of unterminated prose. Preview lines never enter scrollback;
|
||||
//! newline commitment and finalization render the original source independently. Math previews
|
||||
//! show wrapped source until closure, without interpreting TeX punctuation as Markdown.
|
||||
//! Rich prose withholds unfinished link destinations and follow-up directives until closure.
|
||||
//! Cropped previews skip completed directives atomically so their prompt text stays hidden.
|
||||
|
||||
use super::render::render_source;
|
||||
use crate::history_cell::HistoryRenderMode;
|
||||
use crate::inline_visualization::InlineVisualizationContext;
|
||||
use crate::terminal_hyperlinks::HyperlinkLine;
|
||||
use crate::terminal_hyperlinks::lines_with_sources_eq;
|
||||
use ratatui::text::Line;
|
||||
use std::collections::VecDeque;
|
||||
use std::ops::Range;
|
||||
use std::path::Path;
|
||||
|
||||
const MAX_PREVIEW_BYTES: usize = 8192;
|
||||
|
||||
pub(super) enum PreviewMode {
|
||||
Prose(HistoryRenderMode),
|
||||
Math,
|
||||
}
|
||||
|
||||
/// Tracks one append-only incomplete line; reset when a newline is committed.
|
||||
#[derive(Default)]
|
||||
pub(super) struct ProsePreview {
|
||||
pub(super) lines: Vec<HyperlinkLine>,
|
||||
scanned_len: usize,
|
||||
safe_len: usize,
|
||||
rich_safe_len: usize,
|
||||
has_pipe: bool,
|
||||
link: LinkPreview,
|
||||
}
|
||||
|
||||
impl ProsePreview {
|
||||
pub(super) fn update(
|
||||
&mut self,
|
||||
source: &str,
|
||||
width: Option<usize>,
|
||||
cwd: &Path,
|
||||
mode: PreviewMode,
|
||||
inline_visualization_context: Option<&InlineVisualizationContext>,
|
||||
) -> bool {
|
||||
// Only scan newly arrived bytes, including on very long single-line responses.
|
||||
self.has_pipe |= source[self.scanned_len..].contains('|');
|
||||
// Indented and quoted lines may belong to nested code blocks. Keep their
|
||||
// existing newline holdback instead of guessing at the missing block context.
|
||||
let advances = matches!(mode, PreviewMode::Math)
|
||||
|| !(self.has_pipe
|
||||
|| source.starts_with([' ', '\t', '>'])
|
||||
|| source.starts_with("```")
|
||||
|| source.starts_with("~~~")
|
||||
|| matches!(source, "`" | "``" | "~" | "~~"));
|
||||
// Keep tentative fence delimiters in the scanner, but stop collecting ranges once
|
||||
// block structure freezes this tail until newline commitment.
|
||||
if advances || source.len() <= 2 {
|
||||
self.link.scan(source, self.scanned_len);
|
||||
}
|
||||
if advances {
|
||||
self.safe_len = source.len();
|
||||
self.rich_safe_len = source.len();
|
||||
}
|
||||
self.scanned_len = source.len();
|
||||
// Keep Raw/Math's structural bound independent of Rich-only link holdback.
|
||||
if let Some((start, _)) = self.link.destination {
|
||||
self.rich_safe_len = self.rich_safe_len.min(start);
|
||||
}
|
||||
if let Some(start) = self.link.followup_start {
|
||||
self.rich_safe_len = self.rich_safe_len.min(start);
|
||||
}
|
||||
if let Some(start) = self.link.code_followup_start
|
||||
&& self.link.pending_ticks != self.link.code_ticks
|
||||
{
|
||||
self.rich_safe_len = self.rich_safe_len.min(start);
|
||||
}
|
||||
// Retain the last safe text when tokens reveal structure, but still reflow it.
|
||||
let source = &source[..if matches!(mode, PreviewMode::Prose(HistoryRenderMode::Rich)) {
|
||||
self.rich_safe_len
|
||||
} else {
|
||||
self.safe_len
|
||||
}];
|
||||
let mut start = source.ceil_char_boundary(source.len().saturating_sub(MAX_PREVIEW_BYTES));
|
||||
// A tentative closing backtick run can grow on the next update. Retain the old
|
||||
// window's directive boundaries until a non-backtick confirms that the span closed.
|
||||
let retained_len = self
|
||||
.link
|
||||
.code_followup_start
|
||||
.map_or(self.rich_safe_len, |start| start.min(self.rich_safe_len));
|
||||
while self
|
||||
.link
|
||||
.followups
|
||||
.front()
|
||||
.is_some_and(|range| range.end <= retained_len.saturating_sub(MAX_PREVIEW_BYTES))
|
||||
{
|
||||
self.link.followups.pop_front();
|
||||
}
|
||||
// A rolling preview may skip a completed directive, but must never start in its prompt.
|
||||
if matches!(mode, PreviewMode::Prose(HistoryRenderMode::Rich))
|
||||
&& let Some(range) = self.link.followups.iter().find(|range| range.end > start)
|
||||
&& range.start < start
|
||||
{
|
||||
start = range.end;
|
||||
}
|
||||
let mut lines = match mode {
|
||||
PreviewMode::Prose(render_mode) => render_source(
|
||||
&source[start..],
|
||||
width,
|
||||
cwd,
|
||||
render_mode,
|
||||
inline_visualization_context,
|
||||
),
|
||||
PreviewMode::Math => textwrap::wrap(&source[start..], width.unwrap_or(usize::MAX))
|
||||
.into_iter()
|
||||
.map(|line| HyperlinkLine::new(Line::from(line.into_owned())))
|
||||
.collect(),
|
||||
};
|
||||
if start > 0 {
|
||||
lines.insert(0, HyperlinkLine::new(Line::from("…")));
|
||||
}
|
||||
if lines_with_sources_eq(&self.lines, &lines) {
|
||||
return false;
|
||||
}
|
||||
self.lines = lines;
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// Scans append-only source without buffering or rescanning a growing destination.
|
||||
/// Keep the label visible; the opening `(` and everything after it wait for closure.
|
||||
#[derive(Default)]
|
||||
struct LinkPreview {
|
||||
brackets: usize,
|
||||
closed_label: bool,
|
||||
destination: Option<(usize, usize)>,
|
||||
delimiter: Option<u8>,
|
||||
whitespace: bool,
|
||||
escaped: bool,
|
||||
code_ticks: usize,
|
||||
pending_ticks: usize,
|
||||
code_followup_start: Option<usize>,
|
||||
followup_start: Option<usize>,
|
||||
followup_brackets: usize,
|
||||
followups: VecDeque<Range<usize>>,
|
||||
followup_attributes: Option<AttributeState>,
|
||||
}
|
||||
|
||||
enum AttributeState {
|
||||
Key,
|
||||
ValueStart,
|
||||
Unquoted,
|
||||
Quoted(u8),
|
||||
}
|
||||
|
||||
impl LinkPreview {
|
||||
fn scan(&mut self, source: &str, start: usize) {
|
||||
for (index, byte) in source.bytes().enumerate().skip(start) {
|
||||
if self.followup_start.is_some()
|
||||
&& self.closed_label
|
||||
&& self.brackets == self.followup_brackets
|
||||
&& byte != b'{'
|
||||
{
|
||||
self.followup_start = None;
|
||||
}
|
||||
if let Some(state) = self.followup_attributes.as_mut() {
|
||||
if let AttributeState::Quoted(quote) = state {
|
||||
if byte == *quote && !self.escaped {
|
||||
*state = AttributeState::Key;
|
||||
}
|
||||
// Match the directive parser: only a backslash before the quote escapes it.
|
||||
self.escaped = byte == b'\\';
|
||||
} else if byte == b'}' {
|
||||
if let Some(start) = self.followup_start.take() {
|
||||
self.followups.push_back(start..index + 1);
|
||||
}
|
||||
self.followup_attributes = None;
|
||||
} else {
|
||||
*state = match (&*state, byte) {
|
||||
(AttributeState::Key, b'=') => AttributeState::ValueStart,
|
||||
(AttributeState::ValueStart, b'\'' | b'"') => AttributeState::Quoted(byte),
|
||||
(AttributeState::ValueStart, b' ' | b'\t') => AttributeState::ValueStart,
|
||||
(AttributeState::ValueStart, _) => AttributeState::Unquoted,
|
||||
(AttributeState::Unquoted, b' ' | b'\t') => AttributeState::Key,
|
||||
(AttributeState::Unquoted, _) => AttributeState::Unquoted,
|
||||
(AttributeState::Key, _) | (AttributeState::Quoted(_), _) => {
|
||||
AttributeState::Key
|
||||
}
|
||||
};
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if self.destination.is_none() {
|
||||
if byte == b'`' && (self.code_ticks > 0 || !self.escaped) {
|
||||
self.pending_ticks += 1;
|
||||
self.closed_label = false;
|
||||
continue;
|
||||
}
|
||||
if self.pending_ticks > 0 {
|
||||
if self.code_ticks == 0 {
|
||||
self.code_ticks = self.pending_ticks;
|
||||
} else if self.code_ticks == self.pending_ticks {
|
||||
self.code_ticks = 0;
|
||||
self.code_followup_start = None;
|
||||
}
|
||||
self.pending_ticks = 0;
|
||||
}
|
||||
if self.code_ticks > 0 {
|
||||
// Until the code span closes, its opener may still be a literal unmatched
|
||||
// backtick. Withhold directive-like text rather than reveal a live prompt.
|
||||
if byte == b'['
|
||||
&& self.code_followup_start.is_none()
|
||||
&& let Some(prefix) = source[..index].strip_suffix(":codex-followup")
|
||||
{
|
||||
self.code_followup_start = Some(prefix.len());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if self.escaped {
|
||||
self.escaped = false;
|
||||
self.closed_label = false;
|
||||
self.whitespace = false;
|
||||
continue;
|
||||
}
|
||||
if byte == b'\\' {
|
||||
self.escaped = true;
|
||||
self.closed_label = false;
|
||||
continue;
|
||||
}
|
||||
if let Some((destination_start, depth)) = self.destination.as_mut() {
|
||||
if let Some(delimiter) = self.delimiter {
|
||||
if byte == delimiter {
|
||||
self.delimiter = None;
|
||||
}
|
||||
} else if byte == b'<'
|
||||
&& *depth == 1
|
||||
&& (index == *destination_start + 1 || self.whitespace)
|
||||
{
|
||||
self.delimiter = Some(b'>');
|
||||
} else if matches!(byte, b'\'' | b'"') && self.whitespace && *depth == 1 {
|
||||
self.delimiter = Some(byte);
|
||||
} else if byte == b'(' {
|
||||
*depth += 1;
|
||||
} else if byte == b')' {
|
||||
*depth -= 1;
|
||||
if *depth == 0 {
|
||||
self.destination = None;
|
||||
}
|
||||
}
|
||||
self.whitespace = byte.is_ascii_whitespace();
|
||||
} else {
|
||||
match byte {
|
||||
b'[' => {
|
||||
if self.followup_start.is_none()
|
||||
&& let Some(prefix) = source[..index].strip_suffix(":codex-followup")
|
||||
&& !prefix.ends_with(':')
|
||||
&& prefix
|
||||
.bytes()
|
||||
.rev()
|
||||
.take_while(|byte| *byte == b'\\')
|
||||
.count()
|
||||
% 2
|
||||
== 0
|
||||
{
|
||||
self.followup_start = Some(prefix.len());
|
||||
self.followup_brackets = self.brackets;
|
||||
}
|
||||
self.brackets += 1;
|
||||
}
|
||||
b']' if self.brackets > 0 => {
|
||||
self.brackets -= 1;
|
||||
self.closed_label = true;
|
||||
continue;
|
||||
}
|
||||
b'(' if self.closed_label => {
|
||||
self.destination = Some((index, 1));
|
||||
self.whitespace = false;
|
||||
}
|
||||
b'{' if self.closed_label
|
||||
&& self.followup_start.is_some()
|
||||
&& self.brackets == self.followup_brackets =>
|
||||
{
|
||||
self.followup_attributes = Some(AttributeState::Key);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
self.closed_label = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
291
codex-rs/tui/src/streaming/render.rs
Normal file
291
codex-rs/tui/src/streaming/render.rs
Normal file
@@ -0,0 +1,291 @@
|
||||
//! Incremental markdown rendering for in-flight transcript streams.
|
||||
//!
|
||||
//! Completed top-level blocks are retained while the final block stays mutable, avoiding repeated
|
||||
//! rendering of the stable prefix as newline-bearing deltas arrive.
|
||||
|
||||
use super::code_fence::OpenCodeFence;
|
||||
use crate::history_cell::HistoryRenderMode;
|
||||
use crate::history_cell::raw_lines_from_source;
|
||||
use crate::inline_visualization::InlineVisualizationContext;
|
||||
use crate::inline_visualization::contains_inline_visualization;
|
||||
use crate::markdown::render_markdown_agent_with_list_spacing;
|
||||
use crate::markdown::render_streaming_markdown_agent_with_links_and_cwd;
|
||||
use crate::markdown_render::ListSpacing;
|
||||
use crate::render::highlight::syntax_theme_revision;
|
||||
use crate::terminal_hyperlinks::HyperlinkLine;
|
||||
use crate::terminal_hyperlinks::plain_hyperlink_lines;
|
||||
use ratatui::text::Line;
|
||||
use std::path::Path;
|
||||
|
||||
/// Incremental render state split at source and rendered-line boundaries.
|
||||
///
|
||||
/// The prefix before both boundaries is immutable; only the final top-level Markdown block is
|
||||
/// re-rendered as committed source arrives.
|
||||
pub(super) struct StreamingRender {
|
||||
pub(super) list_spacing: ListSpacing,
|
||||
pub(super) lines: Vec<HyperlinkLine>,
|
||||
pub(super) pending_math_start: Option<usize>,
|
||||
pub(super) mutable_fence_start: Option<usize>,
|
||||
/// Source boundary before the final top-level block, including after full re-renders.
|
||||
pub(super) completed_source_len: usize,
|
||||
/// Source prefix containing only completed top-level markdown blocks.
|
||||
stable_source_len: usize,
|
||||
/// Rendered-line boundary corresponding to `stable_source_len`.
|
||||
stable_rendered_len: usize,
|
||||
/// Reference-style link definitions can affect any earlier or later markdown block.
|
||||
pub(super) has_reference_link_definition: bool,
|
||||
/// Inline visualization directives require source-wide rewriting once one is committed.
|
||||
has_inline_visualization_directive: bool,
|
||||
/// Parser state for a directly appendable, open top-level code fence.
|
||||
open_code_fence: Option<OpenCodeFence>,
|
||||
}
|
||||
|
||||
impl StreamingRender {
|
||||
pub(super) fn new() -> Self {
|
||||
Self {
|
||||
list_spacing: ListSpacing::AfterMultiline,
|
||||
lines: Vec::with_capacity(64),
|
||||
pending_math_start: None,
|
||||
mutable_fence_start: None,
|
||||
completed_source_len: 0,
|
||||
stable_source_len: 0,
|
||||
stable_rendered_len: 0,
|
||||
has_reference_link_definition: false,
|
||||
has_inline_visualization_directive: false,
|
||||
open_code_fence: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn clear(&mut self) {
|
||||
self.lines.clear();
|
||||
self.pending_math_start = None;
|
||||
self.mutable_fence_start = None;
|
||||
self.completed_source_len = 0;
|
||||
self.stable_source_len = 0;
|
||||
self.stable_rendered_len = 0;
|
||||
self.has_reference_link_definition = false;
|
||||
self.has_inline_visualization_directive = false;
|
||||
self.open_code_fence = None;
|
||||
}
|
||||
|
||||
/// Re-render the full source and reset both stable-prefix boundaries.
|
||||
///
|
||||
/// This is used when width or render mode changes, and whenever source-wide rendering state
|
||||
/// makes retaining previously rendered blocks unsafe.
|
||||
pub(super) fn recompute(
|
||||
&mut self,
|
||||
source: &str,
|
||||
width: Option<usize>,
|
||||
cwd: &Path,
|
||||
render_mode: HistoryRenderMode,
|
||||
inline_visualization_context: Option<&InlineVisualizationContext>,
|
||||
) {
|
||||
self.open_code_fence = None;
|
||||
self.pending_math_start = None;
|
||||
self.mutable_fence_start = None;
|
||||
self.completed_source_len = 0;
|
||||
self.has_inline_visualization_directive = contains_inline_visualization(source);
|
||||
self.lines = match (render_mode, inline_visualization_context) {
|
||||
(HistoryRenderMode::Rich, None) if !self.has_inline_visualization_directive => {
|
||||
let rendered = render_streaming_markdown_agent_with_links_and_cwd(
|
||||
source,
|
||||
width,
|
||||
Some(cwd),
|
||||
self.list_spacing,
|
||||
);
|
||||
self.has_reference_link_definition = rendered.has_reference_link_definition;
|
||||
self.completed_source_len = rendered.last_top_level_block_start.unwrap_or(0);
|
||||
self.pending_math_start = rendered.pending_math_start;
|
||||
self.mutable_fence_start = rendered.mutable_fence_start;
|
||||
rendered.lines
|
||||
}
|
||||
_ => {
|
||||
self.has_reference_link_definition = false;
|
||||
if render_mode == HistoryRenderMode::Rich {
|
||||
let rendered = render_streaming_markdown_agent_with_links_and_cwd(
|
||||
source,
|
||||
width,
|
||||
Some(cwd),
|
||||
self.list_spacing,
|
||||
);
|
||||
self.has_reference_link_definition = rendered.has_reference_link_definition;
|
||||
self.completed_source_len = rendered.last_top_level_block_start.unwrap_or(0);
|
||||
self.pending_math_start = rendered.pending_math_start;
|
||||
self.mutable_fence_start = rendered.mutable_fence_start;
|
||||
}
|
||||
render_source_with_list_spacing(
|
||||
source,
|
||||
width,
|
||||
cwd,
|
||||
render_mode,
|
||||
inline_visualization_context,
|
||||
self.list_spacing,
|
||||
)
|
||||
}
|
||||
};
|
||||
self.stable_source_len = 0;
|
||||
self.stable_rendered_len = 0;
|
||||
}
|
||||
|
||||
/// Append newly committed source while retaining only the final markdown block as mutable.
|
||||
///
|
||||
/// The final top-level block can still change meaning when another line arrives (for example,
|
||||
/// list tightness, a setext heading, a fenced block, or a table). Earlier top-level blocks are
|
||||
/// rendered once and retained. Reference-style link definitions and inline visualization
|
||||
/// rewriting fall back to a full render because they can affect source-wide rendering state.
|
||||
pub(super) fn append(
|
||||
&mut self,
|
||||
raw_source: &str,
|
||||
committed_source: &str,
|
||||
width: Option<usize>,
|
||||
cwd: &Path,
|
||||
render_mode: HistoryRenderMode,
|
||||
inline_visualization_context: Option<&InlineVisualizationContext>,
|
||||
) {
|
||||
if render_mode == HistoryRenderMode::Raw {
|
||||
self.lines
|
||||
.extend(plain_hyperlink_lines(raw_lines_from_source(
|
||||
committed_source,
|
||||
)));
|
||||
return;
|
||||
}
|
||||
|
||||
self.has_inline_visualization_directive |= contains_inline_visualization(committed_source);
|
||||
if self.has_inline_visualization_directive {
|
||||
self.recompute(
|
||||
raw_source,
|
||||
width,
|
||||
cwd,
|
||||
render_mode,
|
||||
inline_visualization_context,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if self.has_reference_link_definition {
|
||||
self.recompute(
|
||||
raw_source,
|
||||
width,
|
||||
cwd,
|
||||
render_mode,
|
||||
inline_visualization_context,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(fence) = self.open_code_fence.take()
|
||||
&& let Some((fence, lines)) = fence.append(raw_source, committed_source)
|
||||
{
|
||||
self.lines.extend(lines);
|
||||
self.open_code_fence = Some(fence);
|
||||
return;
|
||||
}
|
||||
|
||||
let pending_source = &raw_source[self.stable_source_len..];
|
||||
let theme_revision = syntax_theme_revision();
|
||||
let pending = render_streaming_markdown_agent_with_links_and_cwd(
|
||||
pending_source,
|
||||
width,
|
||||
Some(cwd),
|
||||
self.list_spacing,
|
||||
);
|
||||
self.pending_math_start = pending
|
||||
.pending_math_start
|
||||
.map(|start| self.stable_source_len + start);
|
||||
self.mutable_fence_start = pending
|
||||
.mutable_fence_start
|
||||
.map(|start| self.stable_source_len + start);
|
||||
if pending.has_reference_link_definition {
|
||||
self.has_reference_link_definition = true;
|
||||
self.recompute(
|
||||
raw_source,
|
||||
width,
|
||||
cwd,
|
||||
render_mode,
|
||||
inline_visualization_context,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let final_block_start = pending.last_top_level_block_start.unwrap_or(/*default*/ 0);
|
||||
self.completed_source_len = self.stable_source_len + final_block_start;
|
||||
self.open_code_fence = OpenCodeFence::detect(
|
||||
&pending_source[final_block_start..],
|
||||
raw_source.len(),
|
||||
theme_revision,
|
||||
);
|
||||
|
||||
let mut newly_stable_rendered_len = None;
|
||||
if let Some(boundary) = pending.last_top_level_block_start {
|
||||
let newly_stable_source = &pending_source[..boundary];
|
||||
let newly_stable = render_source_with_list_spacing(
|
||||
newly_stable_source,
|
||||
width,
|
||||
cwd,
|
||||
render_mode,
|
||||
inline_visualization_context,
|
||||
self.list_spacing,
|
||||
);
|
||||
self.stable_source_len += boundary;
|
||||
newly_stable_rendered_len = Some(newly_stable.len());
|
||||
}
|
||||
|
||||
self.lines.truncate(self.stable_rendered_len);
|
||||
if !self.lines.is_empty()
|
||||
&& (!pending.lines.is_empty() || !pending_source.trim().is_empty())
|
||||
&& !pending.first_top_level_block_is_html
|
||||
{
|
||||
self.lines.push(HyperlinkLine::new(Line::default()));
|
||||
}
|
||||
let pending_render_start = self.lines.len();
|
||||
self.lines.extend(pending.lines);
|
||||
if let Some(newly_stable_rendered_len) = newly_stable_rendered_len {
|
||||
self.stable_rendered_len = pending_render_start + newly_stable_rendered_len;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn render_source(
|
||||
source: &str,
|
||||
width: Option<usize>,
|
||||
cwd: &Path,
|
||||
render_mode: HistoryRenderMode,
|
||||
inline_visualization_context: Option<&InlineVisualizationContext>,
|
||||
) -> Vec<HyperlinkLine> {
|
||||
render_source_with_list_spacing(
|
||||
source,
|
||||
width,
|
||||
cwd,
|
||||
render_mode,
|
||||
inline_visualization_context,
|
||||
ListSpacing::AfterMultiline,
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn render_source_with_list_spacing(
|
||||
source: &str,
|
||||
width: Option<usize>,
|
||||
cwd: &Path,
|
||||
render_mode: HistoryRenderMode,
|
||||
inline_visualization_context: Option<&InlineVisualizationContext>,
|
||||
list_spacing: ListSpacing,
|
||||
) -> Vec<HyperlinkLine> {
|
||||
match render_mode {
|
||||
HistoryRenderMode::Rich => render_markdown_agent_with_list_spacing(
|
||||
source,
|
||||
width,
|
||||
Some(cwd),
|
||||
inline_visualization_context,
|
||||
list_spacing,
|
||||
),
|
||||
HistoryRenderMode::Raw => plain_hyperlink_lines(raw_lines_from_source(source)),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "render_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "inline_math_tests.rs"]
|
||||
mod inline_math_tests;
|
||||
565
codex-rs/tui/src/streaming/render_tests.rs
Normal file
565
codex-rs/tui/src/streaming/render_tests.rs
Normal file
@@ -0,0 +1,565 @@
|
||||
use super::StreamingRender;
|
||||
use super::render_source;
|
||||
use crate::history_cell::HistoryRenderMode;
|
||||
use crate::inline_visualization::InlineVisualizationContext;
|
||||
use crate::markdown::render_streaming_markdown_agent_with_links_and_cwd;
|
||||
use crate::terminal_hyperlinks::HyperlinkLine;
|
||||
use crate::terminal_hyperlinks::visible_lines;
|
||||
use codex_protocol::ThreadId;
|
||||
use insta::assert_debug_snapshot;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[path = "code_fence_render_tests.rs"]
|
||||
mod code_fence_tests;
|
||||
|
||||
fn test_cwd() -> PathBuf {
|
||||
std::env::temp_dir()
|
||||
}
|
||||
|
||||
fn append(
|
||||
render: &mut StreamingRender,
|
||||
source: &mut String,
|
||||
chunk: &str,
|
||||
width: Option<usize>,
|
||||
cwd: &Path,
|
||||
render_mode: HistoryRenderMode,
|
||||
) {
|
||||
source.push_str(chunk);
|
||||
render.append(
|
||||
source,
|
||||
chunk,
|
||||
width,
|
||||
cwd,
|
||||
render_mode,
|
||||
/*inline_visualization_context*/ None,
|
||||
);
|
||||
}
|
||||
|
||||
fn append_rich_and_assert_matches_full(
|
||||
render: &mut StreamingRender,
|
||||
source: &mut String,
|
||||
chunk: &str,
|
||||
width: Option<usize>,
|
||||
cwd: &Path,
|
||||
) {
|
||||
append(render, source, chunk, width, cwd, HistoryRenderMode::Rich);
|
||||
assert_eq!(
|
||||
render.lines,
|
||||
render_source(
|
||||
source,
|
||||
width,
|
||||
cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
/*inline_visualization_context*/ None,
|
||||
),
|
||||
"incremental render diverged after chunk {chunk:?}",
|
||||
);
|
||||
}
|
||||
|
||||
fn lines_to_plain_strings(lines: &[HyperlinkLine]) -> Vec<String> {
|
||||
visible_lines(lines.to_vec())
|
||||
.iter()
|
||||
.map(|line| {
|
||||
line.spans
|
||||
.iter()
|
||||
.map(|span| span.content.as_ref())
|
||||
.collect::<String>()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn assert_rich_stream_matches_full_render(
|
||||
chunks: &[&str],
|
||||
width: Option<usize>,
|
||||
) -> (String, StreamingRender) {
|
||||
let cwd = test_cwd();
|
||||
let mut source = String::new();
|
||||
let mut render = StreamingRender::new();
|
||||
|
||||
for chunk in chunks {
|
||||
append_rich_and_assert_matches_full(&mut render, &mut source, chunk, width, &cwd);
|
||||
}
|
||||
|
||||
(source, render)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incremental_render_keeps_final_block_mutable_and_matches_full_render() {
|
||||
let chunks = [
|
||||
"# Heading\n",
|
||||
"\n",
|
||||
"First paragraph with a [link](https://example.com).\n",
|
||||
"continued on the next line.\n\n",
|
||||
"1. First item\n",
|
||||
"2. Second item\n\n",
|
||||
"> Quoted paragraph\n\n",
|
||||
"```rust\n",
|
||||
"fn main() {}\n",
|
||||
"```\n\n",
|
||||
"| Key | Value |\n",
|
||||
"| --- | --- |\n",
|
||||
"| alpha | beta |\n",
|
||||
];
|
||||
let (source, render) = crate::terminal_palette::with_test_default_colors(
|
||||
crate::terminal_probe::DefaultColors {
|
||||
fg: (220, 220, 220),
|
||||
bg: (20, 20, 20),
|
||||
},
|
||||
|| assert_rich_stream_matches_full_render(&chunks, /*width*/ Some(48)),
|
||||
);
|
||||
|
||||
assert!(render.stable_source_len > 0);
|
||||
assert!(render.stable_source_len < source.len());
|
||||
assert_debug_snapshot!("incremental_render_representative_stream", render.lines);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incremental_file_citations_preserve_metadata_unicode_and_markdown() {
|
||||
let cwd = test_cwd();
|
||||
let rendered_cases = [
|
||||
(
|
||||
"Quarterly Report.xlsx",
|
||||
"- :codex-file-citation{artifact_kind=\"workbook\" ",
|
||||
),
|
||||
("Résumé *final* ✨.xlsx", "- :codex-file-citation{"),
|
||||
]
|
||||
.map(|(filename, prefix)| {
|
||||
let tail = format!("path=\"{}\"}}\n", cwd.join(filename).display());
|
||||
let chunks = ["# Output\n\n", prefix, &tail, "\n", "Continue.\n"];
|
||||
let (_, render) = crate::terminal_palette::with_test_default_colors(
|
||||
crate::terminal_probe::DefaultColors {
|
||||
fg: (220, 220, 220),
|
||||
bg: (20, 20, 20),
|
||||
},
|
||||
|| assert_rich_stream_matches_full_render(&chunks, /*width*/ Some(80)),
|
||||
);
|
||||
|
||||
render.lines
|
||||
});
|
||||
assert_debug_snapshot!("incremental_file_citations", rendered_cases);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn growing_single_top_level_blocks_render_and_scan_in_one_pass() {
|
||||
let streams: &[&[&str]] = &[
|
||||
&[
|
||||
"A paragraph that keeps growing\n",
|
||||
"without a blank line between chunks.\n",
|
||||
"It stays one top-level block.\n",
|
||||
],
|
||||
&[
|
||||
"| Key | Value |\n",
|
||||
"| --- | --- |\n",
|
||||
"| alpha | beta |\n",
|
||||
"| gamma | delta |\n",
|
||||
],
|
||||
];
|
||||
let cwd = test_cwd();
|
||||
let width = Some(80);
|
||||
|
||||
for chunks in streams {
|
||||
let mut source = String::new();
|
||||
let mut render = StreamingRender::new();
|
||||
for chunk in *chunks {
|
||||
append_rich_and_assert_matches_full(&mut render, &mut source, chunk, width, &cwd);
|
||||
let pending = render_streaming_markdown_agent_with_links_and_cwd(
|
||||
&source,
|
||||
width,
|
||||
Some(cwd.as_path()),
|
||||
crate::markdown_render::ListSpacing::AfterMultiline,
|
||||
);
|
||||
assert_eq!(pending.last_top_level_block_start, None);
|
||||
assert_eq!(render.lines, pending.lines);
|
||||
assert_eq!(render.stable_source_len, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incremental_raw_render_preserves_blank_lines() {
|
||||
let cwd = test_cwd();
|
||||
let width = Some(80);
|
||||
let mut source = String::new();
|
||||
let mut render = StreamingRender::new();
|
||||
|
||||
for chunk in ["alpha\n", "\n", "beta\n", "\n"] {
|
||||
append(
|
||||
&mut render,
|
||||
&mut source,
|
||||
chunk,
|
||||
width,
|
||||
&cwd,
|
||||
HistoryRenderMode::Raw,
|
||||
);
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
lines_to_plain_strings(&render.lines),
|
||||
vec!["alpha", "", "beta", ""],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compact_list_spacing_keeps_incremental_and_full_renders_aligned() {
|
||||
use crate::markdown_render::ListSpacing;
|
||||
|
||||
let cwd = test_cwd();
|
||||
for mode in [HistoryRenderMode::Rich, HistoryRenderMode::Raw] {
|
||||
let mut render = StreamingRender::new();
|
||||
render.list_spacing = ListSpacing::Compact;
|
||||
let mut source = String::new();
|
||||
for chunk in [
|
||||
"- Short\n",
|
||||
"- A sibling with enough words to wrap across rows\n",
|
||||
"- Last\n",
|
||||
"\nAfter the list.\n\n",
|
||||
"| Name | Value |\n| --- | --- |\n| A | B |\n",
|
||||
"\n- Nested\n - One\n - Two\n- End\n",
|
||||
] {
|
||||
append(&mut render, &mut source, chunk, Some(24), &cwd, mode);
|
||||
assert_eq!(
|
||||
render.lines,
|
||||
super::render_source_with_list_spacing(
|
||||
&source,
|
||||
Some(24),
|
||||
&cwd,
|
||||
mode,
|
||||
/*inline_visualization_context*/ None,
|
||||
ListSpacing::Compact,
|
||||
)
|
||||
);
|
||||
}
|
||||
for width in [80, 24] {
|
||||
render.recompute(
|
||||
&source,
|
||||
Some(width),
|
||||
&cwd,
|
||||
mode,
|
||||
/*inline_visualization_context*/ None,
|
||||
);
|
||||
assert_eq!(
|
||||
render.lines,
|
||||
super::render_source_with_list_spacing(
|
||||
&source,
|
||||
Some(width),
|
||||
&cwd,
|
||||
mode,
|
||||
/*inline_visualization_context*/ None,
|
||||
ListSpacing::Compact,
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_visualization_context_without_directives_keeps_stable_prefix() {
|
||||
let cwd = test_cwd();
|
||||
let context = InlineVisualizationContext::new(&cwd, ThreadId::new())
|
||||
.expect("UUIDv7 thread id should provide a timestamp");
|
||||
let width = Some(80);
|
||||
let mut source = String::new();
|
||||
let mut render = StreamingRender::new();
|
||||
|
||||
for chunk in ["First paragraph.\n\n", "Second paragraph.\n\n"] {
|
||||
source.push_str(chunk);
|
||||
render.append(
|
||||
&source,
|
||||
chunk,
|
||||
width,
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
Some(&context),
|
||||
);
|
||||
assert_eq!(
|
||||
render.lines,
|
||||
render_source(
|
||||
&source,
|
||||
width,
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
Some(&context),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
assert!(render.stable_source_len > 0);
|
||||
assert!(!render.has_inline_visualization_directive);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_visualizations_use_canonical_full_render() {
|
||||
let cwd = test_cwd();
|
||||
let context = InlineVisualizationContext::new(&cwd, ThreadId::new())
|
||||
.expect("UUIDv7 thread id should provide a timestamp");
|
||||
let width = Some(80);
|
||||
let mut source = String::new();
|
||||
let mut render = StreamingRender::new();
|
||||
|
||||
for chunk in ["Before.\n\n", "::codex-inline-vis{file=\"missing.html\"}\n"] {
|
||||
source.push_str(chunk);
|
||||
render.append(
|
||||
&source,
|
||||
chunk,
|
||||
width,
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
Some(&context),
|
||||
);
|
||||
assert_eq!(
|
||||
render.lines,
|
||||
render_source(
|
||||
&source,
|
||||
width,
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
Some(&context),
|
||||
),
|
||||
);
|
||||
assert_eq!(render.stable_source_len, 0);
|
||||
}
|
||||
|
||||
assert!(render.has_inline_visualization_directive);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_visualizations_without_context_use_canonical_full_render() {
|
||||
let (_, render) = assert_rich_stream_matches_full_render(
|
||||
&["Before.\n\n", "::codex-inline-vis{file=\"missing.html\"}\n"],
|
||||
Some(80),
|
||||
);
|
||||
|
||||
assert_eq!(render.stable_source_len, 0);
|
||||
assert!(render.has_inline_visualization_directive);
|
||||
assert_debug_snapshot!(
|
||||
"inline_visualizations_without_context_use_canonical_full_render",
|
||||
render.lines
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_visualization_content_references_use_canonical_full_render() {
|
||||
let (_, render) = assert_rich_stream_matches_full_render(
|
||||
&[
|
||||
"Before.\n\n",
|
||||
"\u{e200}visualize\u{e202}{\"path\":\"/tmp/missing.html\"}\u{e201}\n",
|
||||
],
|
||||
Some(80),
|
||||
);
|
||||
|
||||
assert_eq!(render.stable_source_len, 0);
|
||||
assert!(render.has_inline_visualization_directive);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_visualization_directive_survives_raw_to_rich_render_mode_switch() {
|
||||
let cwd = test_cwd();
|
||||
let width = Some(80);
|
||||
let mut source = String::new();
|
||||
let mut render = StreamingRender::new();
|
||||
|
||||
append(
|
||||
&mut render,
|
||||
&mut source,
|
||||
"::codex-inline-vis{file=\"missing.html\"}\n",
|
||||
width,
|
||||
&cwd,
|
||||
HistoryRenderMode::Raw,
|
||||
);
|
||||
assert!(!render.has_inline_visualization_directive);
|
||||
|
||||
render.recompute(
|
||||
&source,
|
||||
width,
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
/*inline_visualization_context*/ None,
|
||||
);
|
||||
|
||||
assert!(render.has_inline_visualization_directive);
|
||||
assert_eq!(
|
||||
render.lines,
|
||||
render_source(
|
||||
&source,
|
||||
width,
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
/*inline_visualization_context*/ None,
|
||||
),
|
||||
);
|
||||
|
||||
render.clear();
|
||||
assert!(!render.has_inline_visualization_directive);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_link_definition_recomputes_earlier_and_later_blocks() {
|
||||
let streams: &[&[&str]] = &[
|
||||
&[
|
||||
"Earlier [reference][id].\n\n",
|
||||
"An unrelated paragraph.\n\n",
|
||||
"[id]: https://example.com/reference\n",
|
||||
"\n",
|
||||
"Later [reference][id].\n",
|
||||
],
|
||||
&[
|
||||
"Earlier [reference][id].\n\n",
|
||||
"Another paragraph.\n\n",
|
||||
"```markdown\n",
|
||||
"| Key | Value |\n",
|
||||
"| --- | --- |\n",
|
||||
"| alpha | beta |\n",
|
||||
"\n",
|
||||
"[id]: https://example.com/reference\n",
|
||||
"```\n",
|
||||
],
|
||||
];
|
||||
for chunks in streams {
|
||||
let (_, render) = assert_rich_stream_matches_full_render(chunks, Some(80));
|
||||
assert!(render.has_reference_link_definition);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_link_definition_survives_raw_to_rich_render_mode_switch() {
|
||||
let cwd = test_cwd();
|
||||
let width = Some(80);
|
||||
let mut source = String::new();
|
||||
let mut render = StreamingRender::new();
|
||||
|
||||
append(
|
||||
&mut render,
|
||||
&mut source,
|
||||
"[id]: https://example.com/reference\n\n",
|
||||
width,
|
||||
&cwd,
|
||||
HistoryRenderMode::Raw,
|
||||
);
|
||||
render.recompute(
|
||||
&source,
|
||||
width,
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
/*inline_visualization_context*/ None,
|
||||
);
|
||||
for chunk in ["First [reference][id].\n\n", "Later [reference][id].\n"] {
|
||||
append_rich_and_assert_matches_full(&mut render, &mut source, chunk, width, &cwd);
|
||||
}
|
||||
|
||||
assert!(render.has_reference_link_definition);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incremental_render_does_not_add_blank_line_before_html_block() {
|
||||
let streams: &[&[&str]] = &[
|
||||
&[
|
||||
"Paragraph.\n\n",
|
||||
"<div>x</div>\n\n",
|
||||
"Following paragraph.\n",
|
||||
],
|
||||
&["Paragraph.\n\n<div>x</div>\n\n", "Following paragraph.\n"],
|
||||
];
|
||||
for chunks in streams {
|
||||
let (_, render) = assert_rich_stream_matches_full_render(chunks, Some(80));
|
||||
assert_eq!(
|
||||
lines_to_plain_strings(&render.lines),
|
||||
vec!["Paragraph.", "<div>x</div>", "", "Following paragraph.",],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incremental_render_preserves_heading_and_normalized_html_seams() {
|
||||
let streams: &[&[&str]] = &[
|
||||
&["Paragraph.\n\n# Heading\n\n", "Next paragraph.\n"],
|
||||
&[
|
||||
"Paragraph.\n\n",
|
||||
"<div>x</div>\n\n",
|
||||
"```markdown\n",
|
||||
"| Key | Value |\n",
|
||||
"| --- | --- |\n",
|
||||
"| alpha | beta |\n",
|
||||
"\n",
|
||||
"Following paragraph.\n",
|
||||
"```\n",
|
||||
],
|
||||
];
|
||||
for chunks in streams {
|
||||
assert_rich_stream_matches_full_render(chunks, Some(80));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paragraphs_after_unwrapped_table_fence_advance_stable_source() {
|
||||
let cwd = test_cwd();
|
||||
let width = Some(80);
|
||||
let (mut source, mut render) = assert_rich_stream_matches_full_render(
|
||||
&[
|
||||
"```markdown\n",
|
||||
"| Key | Value |\n",
|
||||
"| --- | --- |\n",
|
||||
"| alpha | beta |\n",
|
||||
"```\n\n",
|
||||
],
|
||||
width,
|
||||
);
|
||||
|
||||
let mut previous_stable_source_len = render.stable_source_len;
|
||||
for block in ["<div>Post-fence HTML.</div>\n\n", "First paragraph.\n\n"] {
|
||||
append_rich_and_assert_matches_full(&mut render, &mut source, block, width, &cwd);
|
||||
assert!(render.stable_source_len > previous_stable_source_len);
|
||||
previous_stable_source_len = render.stable_source_len;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shell_pid_preserves_following_equations() {
|
||||
for shell in [
|
||||
"Shell examples: $HOME and echo $$.",
|
||||
"Shell examples: $HOME.",
|
||||
] {
|
||||
let source = format!("{shell}\n\nAfter rejected equations: $\\alpha$.\n\n$$\\beta$$");
|
||||
for width in [80, 24] {
|
||||
let (_, render) = assert_rich_stream_matches_full_render(
|
||||
&source.split_inclusive('$').collect::<Vec<_>>(),
|
||||
Some(width),
|
||||
);
|
||||
let expected = format!("{shell}\n\nAfter rejected equations: α.\n\nβ");
|
||||
assert_eq!(
|
||||
render.lines,
|
||||
render_source(
|
||||
&expected,
|
||||
Some(width),
|
||||
&test_cwd(),
|
||||
HistoryRenderMode::Rich,
|
||||
/*inline_visualization_context*/ None,
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejected_math_openers_allow_bounded_incremental_rendering() {
|
||||
let cwd = test_cwd();
|
||||
for (open, close) in [
|
||||
("echo $$", "$$"),
|
||||
("Equation: \\[", "\\]"),
|
||||
(r"\[label\]\*", "\\]"),
|
||||
] {
|
||||
let (mut source, mut render) =
|
||||
assert_rich_stream_matches_full_render(&[&format!("{open}\n\n")], Some(80));
|
||||
let distant_closer = format!("{close}\n\nAfter $\\alpha$.\n\n");
|
||||
for chunk in std::iter::repeat_n(
|
||||
"An ordinary paragraph that must not retain the entire response.\n\n",
|
||||
/*count*/ 160,
|
||||
)
|
||||
.chain(std::iter::once(distant_closer.as_str()))
|
||||
{
|
||||
append_rich_and_assert_matches_full(&mut render, &mut source, chunk, Some(80), &cwd);
|
||||
assert!(source.len() - render.stable_source_len < 4200);
|
||||
}
|
||||
}
|
||||
}
|
||||
186
codex-rs/tui/src/streaming/rendering_preferences_tests.rs
Normal file
186
codex-rs/tui/src/streaming/rendering_preferences_tests.rs
Normal file
@@ -0,0 +1,186 @@
|
||||
use super::StreamCore;
|
||||
use super::render_source;
|
||||
use crate::history_cell::HistoryRenderMode;
|
||||
use crate::markdown_render::preferences;
|
||||
use codex_config::types::TuiRendering;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn empty_list_item_stays_mutable_until_finalization() {
|
||||
let cwd = std::env::temp_dir();
|
||||
for (marker, continuation) in [
|
||||
("8.", ""),
|
||||
("8.\n", " answer\n"),
|
||||
("> 8.\n", "> answer\n"),
|
||||
] {
|
||||
let mut stream = StreamCore::new(
|
||||
Some(24),
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
/*inline_visualization_context*/ None,
|
||||
);
|
||||
stream.push_delta(marker);
|
||||
let mut emitted = stream.tick_batch(usize::MAX);
|
||||
stream.push_delta(continuation);
|
||||
let (remaining, source) = stream.finalize_remaining();
|
||||
emitted.extend(remaining);
|
||||
assert_eq!(
|
||||
emitted,
|
||||
render_source(
|
||||
&source,
|
||||
Some(24),
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
/*inline_visualization_context*/ None,
|
||||
),
|
||||
"marker={marker:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resizing_does_not_drop_held_list_marker() {
|
||||
let cwd = std::env::temp_dir();
|
||||
let mut stream = StreamCore::new(
|
||||
Some(10),
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
/*inline_visualization_context*/ None,
|
||||
);
|
||||
stream.push_delta("Long prose with enough words to wrap.\n\n");
|
||||
assert!(stream.tick_batch(usize::MAX).len() > 1);
|
||||
stream.push_delta("8.\n");
|
||||
stream.set_width(Some(40));
|
||||
let (remaining, _) = stream.finalize_remaining();
|
||||
assert_eq!(
|
||||
remaining.last().map(|line| line.line.to_string()),
|
||||
Some("8. ".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lists_match_incremental_and_emitted_responses() {
|
||||
let cwd = std::env::temp_dir();
|
||||
let source = concat!(
|
||||
"- [ ] First task with enough words to wrap\n",
|
||||
" - [x] Nested task\n- [X] Done\n\n",
|
||||
"> 9. [ ] [link](https://example.com)\n> 10. [x] Done\n\n",
|
||||
"After.\n\nOne.\n\nTwo.\n\nThree.\n"
|
||||
);
|
||||
for lists in [true, false] {
|
||||
preferences::init(TuiRendering {
|
||||
lists,
|
||||
..Default::default()
|
||||
});
|
||||
let mut stream = StreamCore::new(
|
||||
Some(24),
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
/*inline_visualization_context*/ None,
|
||||
);
|
||||
let render = |source: &str| {
|
||||
render_source(
|
||||
source,
|
||||
Some(24),
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
/*inline_visualization_context*/ None,
|
||||
)
|
||||
};
|
||||
let mut emitted = Vec::new();
|
||||
let mut committed = String::new();
|
||||
// Split inside markers as well as words to exercise partial task-list input.
|
||||
for character in source.chars() {
|
||||
committed.push(character);
|
||||
stream.push_delta(&character.to_string());
|
||||
emitted.extend(stream.tick_batch(usize::MAX));
|
||||
if character == '\n' {
|
||||
assert_eq!(stream.render.lines, render(&committed));
|
||||
}
|
||||
}
|
||||
let (remaining, _) = stream.finalize_remaining();
|
||||
emitted.extend(remaining);
|
||||
assert_eq!(emitted, render(source), "lists={lists}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rendering_preferences_match_incremental_final_and_emitted_responses() {
|
||||
let cwd = std::env::temp_dir();
|
||||
let source = concat!(
|
||||
"Before.\n\n",
|
||||
"```markdown\n| A | B |\n|---|---|\n| `a` | \\(x_1\\) |\n```\n\n",
|
||||
"```mermaid\nflowchart LR\nA --> B\n```\n\n",
|
||||
"Inline \\(\\alpha_1\\) and $x^2$.\n\n\\[\n\\frac{a}{b}\n\\]\n\n",
|
||||
"| Name | Value |\n|---|---|\n| **a** | $x^2$ |\n\n",
|
||||
"Prose after the table.\n\nOne.\n\nTwo.\n\nThree.\n\nFour.\n\n",
|
||||
"| **Name** | Value |\n|---|---|\n| `a` | b |\n\nAfter.\n"
|
||||
);
|
||||
for mermaid in [true, false] {
|
||||
for math in [true, false] {
|
||||
for tables in [true, false] {
|
||||
preferences::init(TuiRendering {
|
||||
mermaid,
|
||||
math,
|
||||
tables,
|
||||
..Default::default()
|
||||
});
|
||||
// A disabled table must retain even the prose preceding it inside its fence.
|
||||
let mut source = if tables {
|
||||
source.to_owned()
|
||||
} else {
|
||||
source.replacen(
|
||||
"```markdown\n",
|
||||
"```markdown\nIntro inside fence.\n\n",
|
||||
/*count*/ 1,
|
||||
)
|
||||
};
|
||||
if !math {
|
||||
// A later protected code block can reject provisional math masking even
|
||||
// without Unicode conversion, so the pending expression must stay mutable.
|
||||
source.insert_str(
|
||||
/*idx*/ 0,
|
||||
"$$\n# heading\none\ntwo\nthree\nfour\nfive\n```rust\nx\n```\n$$\n\n",
|
||||
);
|
||||
}
|
||||
let mut stream = StreamCore::new(
|
||||
Some(80),
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
/*inline_visualization_context*/ None,
|
||||
);
|
||||
let render = |source: &str| {
|
||||
render_source(
|
||||
source,
|
||||
Some(80),
|
||||
&cwd,
|
||||
HistoryRenderMode::Rich,
|
||||
/*inline_visualization_context*/ None,
|
||||
)
|
||||
};
|
||||
let mut emitted = Vec::new();
|
||||
let mut committed = String::new();
|
||||
for chunk in source.split_inclusive('\n') {
|
||||
committed.push_str(chunk);
|
||||
stream.push_delta(chunk);
|
||||
emitted.extend(stream.tick_batch(usize::MAX));
|
||||
assert_eq!(
|
||||
stream.render.lines,
|
||||
render(&committed),
|
||||
"{mermaid}/{math}/{tables}: {committed}"
|
||||
);
|
||||
}
|
||||
if !tables {
|
||||
assert!(
|
||||
emitted
|
||||
.iter()
|
||||
.any(|line| line.line.to_string() == "Prose after the table.")
|
||||
);
|
||||
}
|
||||
let (remaining, _) = stream.finalize_remaining();
|
||||
emitted.extend(remaining);
|
||||
assert_eq!(emitted, render(&source), "{mermaid}/{math}/{tables}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
---
|
||||
source: tui/src/streaming/math_tests.rs
|
||||
assertion_line: 134
|
||||
expression: "stream.current_tail_lines().iter().map(|line|\nline.line.to_string()).collect::<Vec<_>>().join(\"\\n\")"
|
||||
---
|
||||
$$
|
||||
\frac{|
|
||||
a+b+c+d+e+f|}{g+h}
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
source: tui/src/streaming/math_tests.rs
|
||||
expression: "preview[0].line.to_string()"
|
||||
---
|
||||
$$\frac{abcdefghijk}{lmnop}
|
||||
@@ -0,0 +1,11 @@
|
||||
---
|
||||
source: tui/src/streaming/controller.rs
|
||||
expression: lines_to_plain_strings(&visible_lines(rendered))
|
||||
---
|
||||
[
|
||||
" Key Value",
|
||||
"━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━━━━",
|
||||
" A (https://example.com) row",
|
||||
"",
|
||||
"After table.",
|
||||
]
|
||||
@@ -0,0 +1,13 @@
|
||||
---
|
||||
source: tui/src/streaming/controller.rs
|
||||
assertion_line: 1456
|
||||
expression: "lines_to_plain_strings(&committed.transcript_lines(u16::MAX))"
|
||||
---
|
||||
[
|
||||
" ",
|
||||
" Key Value",
|
||||
" ━━━━━━━ ━━━━━━━",
|
||||
" first row",
|
||||
" ",
|
||||
" After table.",
|
||||
]
|
||||
@@ -0,0 +1,129 @@
|
||||
---
|
||||
source: tui/src/streaming/controller.rs
|
||||
expression: lines
|
||||
---
|
||||
[
|
||||
HyperlinkLine {
|
||||
line: Line::from_iter([
|
||||
Span::from("• ").dim(),
|
||||
Span::from("Proposed Plan").bold(),
|
||||
]),
|
||||
hyperlinks: [],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::from(" "),
|
||||
hyperlinks: [],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::from_iter([
|
||||
Span::from(" "),
|
||||
Span::from(" "),
|
||||
]).bg(Color::Rgb(244, 244, 244)),
|
||||
hyperlinks: [],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::from_iter([
|
||||
Span::from(" "),
|
||||
Span::from("# ").fg(Color::Rgb(210, 15, 57)).bold().underlined(),
|
||||
Span::from("Plan").fg(Color::Rgb(210, 15, 57)).bold().underlined(),
|
||||
]).bg(Color::Rgb(244, 244, 244)),
|
||||
hyperlinks: [],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::from(" ").bg(Color::Rgb(244, 244, 244)),
|
||||
hyperlinks: [],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::from_iter([
|
||||
Span::from(" "),
|
||||
Span::from("> "),
|
||||
Span::from("Quote"),
|
||||
]).fg(Color::Rgb(165, 82, 143)).bg(Color::Rgb(244, 244, 244)),
|
||||
hyperlinks: [],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::from(" ").bg(Color::Rgb(244, 244, 244)),
|
||||
hyperlinks: [],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::from_iter([
|
||||
Span::from(" "),
|
||||
Span::from(" "),
|
||||
Span::from("Step"),
|
||||
Span::from(" "),
|
||||
Span::from(" "),
|
||||
Span::from(" "),
|
||||
Span::from(" "),
|
||||
Span::from("URL"),
|
||||
]).fg(Color::Rgb(156, 99, 20)).bg(Color::Rgb(244, 244, 244)).bold(),
|
||||
hyperlinks: [],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::from_iter([
|
||||
Span::from(" "),
|
||||
Span::from("━━━━━━━━ ━━━━━━━━━━━━━━━━━━━━━━").dim(),
|
||||
]).bg(Color::Rgb(244, 244, 244)),
|
||||
hyperlinks: [],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::from_iter([
|
||||
Span::from(" "),
|
||||
Span::from(" "),
|
||||
Span::from("Verify"),
|
||||
Span::from(" "),
|
||||
Span::from(" "),
|
||||
Span::from(" "),
|
||||
Span::from("https://example.com/").fg(Color::Rgb(29, 101, 244)).underlined(),
|
||||
]).bg(Color::Rgb(244, 244, 244)),
|
||||
hyperlinks: [
|
||||
TerminalHyperlink {
|
||||
columns: 13..33,
|
||||
destination: "https://example.com/a/very/long/path/to/a/table/artifact",
|
||||
destination_kind: Web,
|
||||
},
|
||||
],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::from_iter([
|
||||
Span::from(" "),
|
||||
Span::from(" "),
|
||||
Span::from(" "),
|
||||
Span::from(" "),
|
||||
Span::from(" "),
|
||||
Span::from(" "),
|
||||
Span::from("a/very/long/path/to/").fg(Color::Rgb(29, 101, 244)).underlined(),
|
||||
]).bg(Color::Rgb(244, 244, 244)),
|
||||
hyperlinks: [
|
||||
TerminalHyperlink {
|
||||
columns: 13..33,
|
||||
destination: "https://example.com/a/very/long/path/to/a/table/artifact",
|
||||
destination_kind: Web,
|
||||
},
|
||||
],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::from_iter([
|
||||
Span::from(" "),
|
||||
Span::from(" "),
|
||||
Span::from(" "),
|
||||
Span::from(" "),
|
||||
Span::from(" "),
|
||||
Span::from(" "),
|
||||
Span::from("a/table/artifact").fg(Color::Rgb(29, 101, 244)).underlined(),
|
||||
]).bg(Color::Rgb(244, 244, 244)),
|
||||
hyperlinks: [
|
||||
TerminalHyperlink {
|
||||
columns: 13..29,
|
||||
destination: "https://example.com/a/very/long/path/to/a/table/artifact",
|
||||
destination_kind: Web,
|
||||
},
|
||||
],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::from_iter([
|
||||
Span::from(" "),
|
||||
Span::from(" "),
|
||||
]).bg(Color::Rgb(244, 244, 244)),
|
||||
hyperlinks: [],
|
||||
},
|
||||
]
|
||||
@@ -0,0 +1,88 @@
|
||||
---
|
||||
source: tui/src/streaming/mermaid_tests.rs
|
||||
assertion_line: 78
|
||||
expression: "stages.join(\"\\n\\n---\\n\\n\")"
|
||||
---
|
||||
Before.
|
||||
|
||||
|
||||
---
|
||||
|
||||
Before.
|
||||
|
||||
flowchart LR
|
||||
A["Codex reply<br/>completed"] --> B["Rendered in Ghostty"]
|
||||
|
||||
---
|
||||
|
||||
Before.
|
||||
|
||||
┌─────────────┐ ┌─────────────────────┐
|
||||
│ Codex reply │ │ Rendered in Ghostty │
|
||||
│ completed │ │ │
|
||||
└┬────────────┘ └┬────────────────────┘
|
||||
│ ▲
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
└────────────────┘
|
||||
|
||||
---
|
||||
|
||||
Before.
|
||||
|
||||
┌─────────────┐ ┌─────────────────────┐
|
||||
│ Codex reply │ │ Rendered in Ghostty │
|
||||
│ completed │ │ │
|
||||
└┬────────────┘ └┬────────────────────┘
|
||||
│ ▲
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
└────────────────┘
|
||||
|
||||
After.
|
||||
|
||||
---
|
||||
|
||||
Before.
|
||||
|
||||
This
|
||||
Mermaid
|
||||
diagram
|
||||
doesn't
|
||||
fit the
|
||||
current
|
||||
terminal
|
||||
width.
|
||||
flowchart LR
|
||||
A["Codex reply<br/>completed"] --> B["Rendered in Ghostty"]
|
||||
|
||||
After.
|
||||
|
||||
---
|
||||
|
||||
Before.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A["Codex reply<br/>completed"] --> B["Rendered in Ghostty"]
|
||||
```
|
||||
|
||||
After.
|
||||
|
||||
---
|
||||
|
||||
Before.
|
||||
|
||||
┌─────────────┐ ┌─────────────────────┐
|
||||
│ Codex reply │ │ Rendered in Ghostty │
|
||||
│ completed │ │ │
|
||||
└┬────────────┘ └┬────────────────────┘
|
||||
│ ▲
|
||||
│ │
|
||||
│ │
|
||||
│ │
|
||||
└────────────────┘
|
||||
|
||||
After.
|
||||
@@ -0,0 +1,62 @@
|
||||
---
|
||||
source: tui/src/streaming/render_tests.rs
|
||||
expression: rendered_cases
|
||||
---
|
||||
[
|
||||
[
|
||||
HyperlinkLine {
|
||||
line: Line::from_iter([
|
||||
Span::from("# ").fg(Color::Rgb(243, 139, 168)).bold().underlined(),
|
||||
Span::from("Output").fg(Color::Rgb(243, 139, 168)).bold().underlined(),
|
||||
]),
|
||||
hyperlinks: [],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::default(),
|
||||
hyperlinks: [],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::from_iter([
|
||||
Span::from("• ").fg(Color::Rgb(148, 226, 213)),
|
||||
Span::from("Quarterly Report.xlsx").fg(Color::Rgb(166, 227, 161)),
|
||||
]),
|
||||
hyperlinks: [],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::default(),
|
||||
hyperlinks: [],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::from("Continue."),
|
||||
hyperlinks: [],
|
||||
},
|
||||
],
|
||||
[
|
||||
HyperlinkLine {
|
||||
line: Line::from_iter([
|
||||
Span::from("# ").fg(Color::Rgb(243, 139, 168)).bold().underlined(),
|
||||
Span::from("Output").fg(Color::Rgb(243, 139, 168)).bold().underlined(),
|
||||
]),
|
||||
hyperlinks: [],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::default(),
|
||||
hyperlinks: [],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::from_iter([
|
||||
Span::from("• ").fg(Color::Rgb(148, 226, 213)),
|
||||
Span::from("Résumé *final* ✨.xlsx").fg(Color::Rgb(166, 227, 161)),
|
||||
]),
|
||||
hyperlinks: [],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::default(),
|
||||
hyperlinks: [],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::from("Continue."),
|
||||
hyperlinks: [],
|
||||
},
|
||||
],
|
||||
]
|
||||
@@ -0,0 +1,128 @@
|
||||
---
|
||||
source: tui/src/streaming/render_tests.rs
|
||||
assertion_line: 115
|
||||
expression: render.lines
|
||||
---
|
||||
[
|
||||
HyperlinkLine {
|
||||
line: Line::from_iter([
|
||||
Span::from("# ").fg(Color::Rgb(243, 139, 168)).bold().underlined(),
|
||||
Span::from("Heading").fg(Color::Rgb(243, 139, 168)).bold().underlined(),
|
||||
]),
|
||||
hyperlinks: [],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::default(),
|
||||
hyperlinks: [],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::from_iter([
|
||||
Span::from("First paragraph with a "),
|
||||
Span::from("link").fg(Color::Rgb(137, 180, 250)).underlined(),
|
||||
]),
|
||||
hyperlinks: [
|
||||
TerminalHyperlink {
|
||||
columns: 23..27,
|
||||
destination: "https://example.com",
|
||||
destination_kind: Web,
|
||||
},
|
||||
],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::from_iter([
|
||||
Span::from("("),
|
||||
Span::from("https://example.com").fg(Color::Rgb(137, 180, 250)).underlined(),
|
||||
Span::from(")"),
|
||||
Span::from("."),
|
||||
]),
|
||||
hyperlinks: [
|
||||
TerminalHyperlink {
|
||||
columns: 1..20,
|
||||
destination: "https://example.com",
|
||||
destination_kind: Web,
|
||||
},
|
||||
],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::from("continued on the next line."),
|
||||
hyperlinks: [],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::default(),
|
||||
hyperlinks: [],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::from_iter([
|
||||
Span::from("1. ").light_blue(),
|
||||
Span::from("First item"),
|
||||
]),
|
||||
hyperlinks: [],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::from_iter([
|
||||
Span::from("2. ").light_blue(),
|
||||
Span::from("Second item"),
|
||||
]),
|
||||
hyperlinks: [],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::default(),
|
||||
hyperlinks: [],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::from_iter([
|
||||
Span::from("> "),
|
||||
Span::from("Quoted paragraph"),
|
||||
]).fg(Color::Rgb(245, 194, 231)),
|
||||
hyperlinks: [],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::default(),
|
||||
hyperlinks: [],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::from_iter([
|
||||
Span::default(),
|
||||
Span::from("fn").fg(Color::Rgb(203, 166, 247)),
|
||||
Span::from(" ").fg(Color::Rgb(205, 214, 244)),
|
||||
Span::from("main").fg(Color::Rgb(137, 180, 250)),
|
||||
Span::from("(").fg(Color::Rgb(147, 153, 178)),
|
||||
Span::from(")").fg(Color::Rgb(147, 153, 178)),
|
||||
Span::from(" ").fg(Color::Rgb(205, 214, 244)),
|
||||
Span::from("{").fg(Color::Rgb(147, 153, 178)),
|
||||
Span::from("}").fg(Color::Rgb(147, 153, 178)),
|
||||
]),
|
||||
hyperlinks: [],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::default(),
|
||||
hyperlinks: [],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::from_iter([
|
||||
Span::from(" "),
|
||||
Span::from("Key"),
|
||||
Span::from(" "),
|
||||
Span::from(" "),
|
||||
Span::from(" "),
|
||||
Span::from(" "),
|
||||
Span::from("Value"),
|
||||
]).fg(Color::Rgb(249, 226, 175)).bold(),
|
||||
hyperlinks: [],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::from(Span::from("━━━━━━━ ━━━━━━━").dim()),
|
||||
hyperlinks: [],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::from_iter([
|
||||
Span::from(" "),
|
||||
Span::from("alpha"),
|
||||
Span::from(" "),
|
||||
Span::from(" "),
|
||||
Span::from(" "),
|
||||
Span::from("beta"),
|
||||
]),
|
||||
hyperlinks: [],
|
||||
},
|
||||
]
|
||||
@@ -0,0 +1,18 @@
|
||||
---
|
||||
source: tui/src/streaming/render_tests.rs
|
||||
expression: render.lines
|
||||
---
|
||||
[
|
||||
HyperlinkLine {
|
||||
line: Line::from("Before."),
|
||||
hyperlinks: [],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::default(),
|
||||
hyperlinks: [],
|
||||
},
|
||||
HyperlinkLine {
|
||||
line: Line::from(Span::from("Visualization unavailable on this device.").fg(Color::Reset).italic()),
|
||||
hyperlinks: [],
|
||||
},
|
||||
]
|
||||
271
codex-rs/tui/src/streaming/table_holdback.rs
Normal file
271
codex-rs/tui/src/streaming/table_holdback.rs
Normal file
@@ -0,0 +1,271 @@
|
||||
//! Pipe-table holdback scanner for source-backed agent streams.
|
||||
//!
|
||||
//! Agent streams with markdown tables keep the active table as mutable tail so
|
||||
//! adding a row can reflow earlier table rows instead of committing a stale
|
||||
//! render to scrollback.
|
||||
//! Literal tables only retain candidate headers until their delimiter arrives.
|
||||
//!
|
||||
//! The scanner is intentionally conservative: it only looks for enough
|
||||
//! structure to decide where the mutable tail should start. It does not try to
|
||||
//! validate an entire table or predict final layout. Rendering remains the job
|
||||
//! of the markdown renderer.
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
use crate::table_detect::FenceKind;
|
||||
use crate::table_detect::FenceTracker;
|
||||
use crate::table_detect::is_table_delimiter_line;
|
||||
use crate::table_detect::is_table_header_line;
|
||||
use crate::table_detect::parse_table_segments;
|
||||
use crate::table_detect::strip_blockquote_prefix;
|
||||
|
||||
/// Result of scanning accumulated raw source for pipe-table patterns.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum TableHoldbackState {
|
||||
/// No table detected -- all rendered lines can flow into the stable queue.
|
||||
None,
|
||||
/// The last non-blank line looks like a table header row but no delimiter
|
||||
/// row has followed yet. Hold back in case the next delta is a delimiter.
|
||||
PendingHeader { header_start: usize },
|
||||
/// A header + delimiter pair was found -- the source contains a confirmed
|
||||
/// table. Content from the table header onward stays mutable.
|
||||
Confirmed { table_start: usize },
|
||||
}
|
||||
|
||||
/// Facts remembered about the previous committed source line.
|
||||
///
|
||||
/// The scanner only needs one-line lookbehind because a table is confirmed by
|
||||
/// a header row immediately followed by a delimiter row.
|
||||
#[derive(Clone, Copy)]
|
||||
struct PreviousLineState {
|
||||
source_start: usize,
|
||||
fence_kind: FenceKind,
|
||||
is_header: bool,
|
||||
}
|
||||
|
||||
/// Incremental scanner for table holdback state on append-only source streams.
|
||||
///
|
||||
/// `scan` receives the append-only source and the renderer's completed-block
|
||||
/// boundary. Completed tables are released only when their containing top-level
|
||||
/// block is stable; the remaining tail is rescanned to find later tables.
|
||||
pub(super) struct TableHoldbackScanner {
|
||||
source_offset: usize,
|
||||
fence_tracker: FenceTracker,
|
||||
previous_line: Option<PreviousLineState>,
|
||||
pending_header_start: Option<usize>,
|
||||
confirmed_table_start: Option<usize>,
|
||||
/// Unlike scrollback holdback, partial-row holdback ends at a blank line.
|
||||
in_table: bool,
|
||||
}
|
||||
|
||||
impl TableHoldbackScanner {
|
||||
pub(super) fn new() -> Self {
|
||||
Self {
|
||||
source_offset: 0,
|
||||
fence_tracker: FenceTracker::new(),
|
||||
previous_line: None,
|
||||
pending_header_start: None,
|
||||
confirmed_table_start: None,
|
||||
in_table: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn reset(&mut self) {
|
||||
*self = Self::new();
|
||||
}
|
||||
|
||||
/// Return the current holdback decision for the committed source prefix.
|
||||
///
|
||||
/// `PendingHeader` means the newest non-blank line looks like a table
|
||||
/// header but the delimiter row has not arrived yet, so callers should
|
||||
/// optimistically keep that region mutable. `Confirmed` means the header
|
||||
/// and delimiter pair has been seen and all subsequent body rows remain in
|
||||
/// the live tail until their containing top-level block is stable.
|
||||
pub(super) fn state(&self) -> TableHoldbackState {
|
||||
if let Some(table_start) = self.confirmed_table_start {
|
||||
TableHoldbackState::Confirmed { table_start }
|
||||
} else if let Some(header_start) = self.pending_header_start {
|
||||
TableHoldbackState::PendingHeader { header_start }
|
||||
} else {
|
||||
TableHoldbackState::None
|
||||
}
|
||||
}
|
||||
|
||||
/// Partial prose can be previewed only outside tables and fenced blocks.
|
||||
pub(super) fn allows_prose_preview(&self) -> bool {
|
||||
!self.in_table
|
||||
&& !self.previous_line.is_some_and(|line| line.is_header)
|
||||
&& self.fence_tracker.kind() == FenceKind::Outside
|
||||
}
|
||||
|
||||
/// Scan newly committed source, releasing holdback for completed blocks.
|
||||
///
|
||||
/// Source must contain only complete lines. Releasing a table rescans from
|
||||
/// the final top-level block, where fence state can safely start outside.
|
||||
/// This also detects later tables that arrived in the same delta.
|
||||
pub(super) fn scan(&mut self, source: &str, completed_source_len: usize) {
|
||||
let holdback_start = match self.state() {
|
||||
TableHoldbackState::Confirmed { table_start } => Some(table_start),
|
||||
TableHoldbackState::PendingHeader { header_start } => Some(header_start),
|
||||
TableHoldbackState::None => None,
|
||||
};
|
||||
if self.source_offset < completed_source_len
|
||||
|| holdback_start.is_some_and(|start| start < completed_source_len)
|
||||
{
|
||||
self.reset();
|
||||
self.source_offset = completed_source_len;
|
||||
}
|
||||
let source_chunk = &source[self.source_offset..];
|
||||
if source_chunk.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let scan_start = Instant::now();
|
||||
let mut lines = 0usize;
|
||||
for source_line in source_chunk.split_inclusive('\n') {
|
||||
lines += 1;
|
||||
self.push_line(source_line);
|
||||
}
|
||||
tracing::trace!(
|
||||
bytes = source_chunk.len(),
|
||||
lines,
|
||||
state = ?self.state(),
|
||||
elapsed_us = scan_start.elapsed().as_micros(),
|
||||
"table holdback incremental scan",
|
||||
);
|
||||
}
|
||||
|
||||
/// Fold one committed source line into the scanner state machine.
|
||||
fn push_line(&mut self, source_line: &str) {
|
||||
let line = source_line.strip_suffix('\n').unwrap_or(source_line);
|
||||
let source_start = self.source_offset;
|
||||
let fence_kind = self.fence_tracker.kind();
|
||||
|
||||
let candidate_text = if fence_kind == FenceKind::Other {
|
||||
None
|
||||
} else {
|
||||
table_candidate_text(line)
|
||||
};
|
||||
let is_header = candidate_text.is_some_and(is_table_header_line);
|
||||
let is_delimiter = candidate_text.is_some_and(is_table_delimiter_line);
|
||||
|
||||
if strip_blockquote_prefix(line).is_empty() {
|
||||
self.in_table = false;
|
||||
}
|
||||
if let Some(previous_line) = self.previous_line
|
||||
&& previous_line.fence_kind != FenceKind::Other
|
||||
&& fence_kind != FenceKind::Other
|
||||
&& previous_line.is_header
|
||||
&& is_delimiter
|
||||
{
|
||||
if crate::markdown_render::preferences::current().tables {
|
||||
self.confirmed_table_start
|
||||
.get_or_insert(previous_line.source_start);
|
||||
}
|
||||
self.pending_header_start = None;
|
||||
self.in_table = true;
|
||||
}
|
||||
|
||||
if self.confirmed_table_start.is_none() && !line.trim().is_empty() {
|
||||
if fence_kind != FenceKind::Other && is_header {
|
||||
self.pending_header_start = Some(source_start);
|
||||
} else {
|
||||
self.pending_header_start = None;
|
||||
}
|
||||
}
|
||||
|
||||
self.previous_line = Some(PreviousLineState {
|
||||
source_start,
|
||||
fence_kind,
|
||||
is_header,
|
||||
});
|
||||
|
||||
self.fence_tracker.advance(line);
|
||||
if fence_kind != FenceKind::Outside && self.fence_tracker.kind() == FenceKind::Outside {
|
||||
self.in_table = false;
|
||||
}
|
||||
self.source_offset = self.source_offset.saturating_add(source_line.len());
|
||||
}
|
||||
}
|
||||
|
||||
/// Strip blockquote prefixes and return the trimmed text if it contains
|
||||
/// pipe-table segments, or `None` otherwise.
|
||||
///
|
||||
/// Table holdback treats quoted tables as real tables, but it still requires a
|
||||
/// pipe-table shape after the quote markers are removed.
|
||||
fn table_candidate_text(line: &str) -> Option<&str> {
|
||||
let stripped = strip_blockquote_prefix(line).trim();
|
||||
parse_table_segments(stripped).map(|_| stripped)
|
||||
}
|
||||
|
||||
/// A source line annotated with whether it falls inside a fenced code block.
|
||||
#[cfg(test)]
|
||||
struct ParsedLine<'a> {
|
||||
text: &'a str,
|
||||
fence_context: FenceKind,
|
||||
source_start: usize,
|
||||
}
|
||||
|
||||
/// Parse source into lines tagged with fenced-code context for table scanning.
|
||||
#[cfg(test)]
|
||||
fn parse_lines_with_fence_state(source: &str) -> Vec<ParsedLine<'_>> {
|
||||
let mut tracker = FenceTracker::new();
|
||||
let mut lines = Vec::new();
|
||||
let mut source_start = 0usize;
|
||||
|
||||
for raw_line in source.split('\n') {
|
||||
lines.push(ParsedLine {
|
||||
text: raw_line,
|
||||
fence_context: tracker.kind(),
|
||||
source_start,
|
||||
});
|
||||
|
||||
tracker.advance(raw_line);
|
||||
source_start = source_start
|
||||
.saturating_add(raw_line.len())
|
||||
.saturating_add(1);
|
||||
}
|
||||
|
||||
lines
|
||||
}
|
||||
|
||||
/// Scan `source` for pipe-table patterns outside of non-markdown fenced code
|
||||
/// blocks.
|
||||
#[cfg(test)]
|
||||
pub(super) fn table_holdback_state(source: &str) -> TableHoldbackState {
|
||||
let lines = parse_lines_with_fence_state(source);
|
||||
for pair in lines.windows(2) {
|
||||
let [header_line, delimiter_line] = pair else {
|
||||
continue;
|
||||
};
|
||||
if header_line.fence_context == FenceKind::Other
|
||||
|| delimiter_line.fence_context == FenceKind::Other
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
let Some(header_text) = table_candidate_text(header_line.text) else {
|
||||
continue;
|
||||
};
|
||||
let Some(delimiter_text) = table_candidate_text(delimiter_line.text) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
if is_table_header_line(header_text) && is_table_delimiter_line(delimiter_text) {
|
||||
return TableHoldbackState::Confirmed {
|
||||
table_start: header_line.source_start,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
let pending_header = lines.iter().rev().find(|line| !line.text.trim().is_empty());
|
||||
if let Some(line) = pending_header
|
||||
&& line.fence_context != FenceKind::Other
|
||||
&& table_candidate_text(line.text).is_some_and(is_table_header_line)
|
||||
{
|
||||
return TableHoldbackState::PendingHeader {
|
||||
header_start: line.source_start,
|
||||
};
|
||||
}
|
||||
TableHoldbackState::None
|
||||
}
|
||||
Reference in New Issue
Block a user