Skip to main content

ftui_runtime/
terminal_writer.rs

1#![forbid(unsafe_code)]
2
3//! Terminal output coordinator with inline mode support.
4//!
5//! The `TerminalWriter` is the component that makes inline mode work. It:
6//! - Serializes log writes and UI presents (one-writer rule)
7//! - Implements the cursor save/restore contract
8//! - Manages scroll regions (when optimization enabled)
9//! - Ensures single buffered write per operation
10//!
11//! # Screen Modes
12//!
13//! - **Inline Mode**: Preserves terminal scrollback. UI is rendered at the
14//!   bottom, logs scroll normally above. Uses cursor save/restore.
15//!
16//! - **AltScreen Mode**: Uses alternate screen buffer. Full-screen UI,
17//!   no scrollback preservation.
18//!
19//! # Inline Mode Contract
20//!
21//! 1. Cursor is saved before any UI operation
22//! 2. UI region is cleared and redrawn
23//! 3. Cursor is restored after UI operation
24//! 4. Log writes go above the UI region: with an active scroll region they
25//!    accumulate into scrollback; in the overlay fallback exactly one
26//!    width-clamped line is rewritten per call (an unqualified LF would
27//!    scroll the whole screen and displace the UI)
28//! 5. Terminal state is restored on drop
29//!
30//! # Usage
31//!
32//! ```ignore
33//! use ftui_runtime::{TerminalWriter, ScreenMode, UiAnchor};
34//! use ftui_render::buffer::Buffer;
35//! use ftui_core::terminal_capabilities::TerminalCapabilities;
36//!
37//! // Create writer for inline mode with 10-row UI
38//! let mut writer = TerminalWriter::new(
39//!     std::io::stdout(),
40//!     ScreenMode::Inline { ui_height: 10 },
41//!     UiAnchor::Bottom,
42//!     TerminalCapabilities::detect(),
43//! );
44//!
45//! // Write logs (goes to scrollback above UI)
46//! writer.write_log("Starting...\n")?;
47//!
48//! // Present UI
49//! let buffer = Buffer::new(80, 10);
50//! writer.present_ui(&buffer, None, true)?;
51//! ```
52
53use std::io::{self, BufWriter, Write};
54use std::sync::Arc;
55use std::sync::atomic::{AtomicU32, Ordering};
56use web_time::Instant;
57
58/// Global gauge: number of active inline-mode `TerminalWriter` instances.
59///
60/// Incremented when a writer is created in `Inline` or `InlineAuto` mode,
61/// decremented on drop. Read with [`inline_active_widgets`].
62static INLINE_ACTIVE_WIDGETS: AtomicU32 = AtomicU32::new(0);
63
64/// Read the current number of active inline-mode terminal writers.
65pub fn inline_active_widgets() -> u32 {
66    INLINE_ACTIVE_WIDGETS.load(Ordering::Relaxed)
67}
68
69use crate::evidence_sink::EvidenceSink;
70
71struct CallbackEvidenceWriter(Arc<dyn Fn(&str) + Send + Sync>);
72
73impl Write for CallbackEvidenceWriter {
74    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
75        let text = String::from_utf8_lossy(buf);
76        let trimmed = text.trim_end_matches(['\r', '\n']);
77        if !trimmed.is_empty() {
78            (self.0)(trimmed);
79        }
80        Ok(buf.len())
81    }
82
83    fn flush(&mut self) -> io::Result<()> {
84        Ok(())
85    }
86}
87
88/// A strategy downgrade forced by the DECSTBM self-test
89/// (`TerminalWriter::set_scroll_region_verified`).
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct InlineStrategyFallback {
92    /// Strategy selected from capabilities before the test.
93    pub from: InlineStrategy,
94    /// `cpr_mismatch` (the cursor left the region) or `cpr_timeout` (no
95    /// cursor-position report arrived).
96    pub reason: &'static str,
97    /// Row the terminal reported, if it answered.
98    pub observed_row: Option<u16>,
99    /// Row a terminal that honours the region reports.
100    pub expected_row: u16,
101    /// Terminal height at the time of the test.
102    pub rows: u16,
103    /// Last row of the tested scroll region.
104    pub region_bottom: u16,
105}
106
107impl InlineStrategyFallback {
108    /// The `inline_strategy_fallback` evidence row.
109    #[must_use]
110    pub fn to_jsonl(&self) -> String {
111        let observed = self
112            .observed_row
113            .map_or_else(|| "null".to_string(), |row| row.to_string());
114        format!(
115            r#"{{"event":"inline_strategy_fallback","from":"{}","to":"overlay_redraw","reason":"{}","observed_row":{},"expected_row":{},"rows":{},"region_bottom":{}}}"#,
116            inline_strategy_str(self.from),
117            self.reason,
118            observed,
119            self.expected_row,
120            self.rows,
121            self.region_bottom
122        )
123    }
124}
125use crate::evidence_telemetry::{DiffDecisionSnapshot, set_diff_snapshot};
126use crate::render_trace::{
127    RenderTraceFrame, RenderTraceRecorder, build_diff_runs_payload, build_full_buffer_payload,
128};
129use ftui_core::caps_probe::CapabilityDecision;
130use ftui_core::inline_mode::{InlineStrategy, sanitize_overlay_log_line};
131use ftui_core::session_teardown::terminal_output_lock;
132#[cfg(test)]
133use ftui_core::terminal_capabilities::ColorDepth;
134use ftui_core::terminal_capabilities::TerminalCapabilities;
135use ftui_render::ansi;
136use ftui_render::buffer::{Buffer, DirtySpanConfig, DirtySpanStats};
137use ftui_render::counting_writer::CountingWriter;
138use ftui_render::diff::{BufferDiff, TileDiffConfig, TileDiffFallback, TileDiffStats};
139use ftui_render::diff_strategy::{
140    DiffRegime, DiffStrategy, DiffStrategyConfig, DiffStrategySelector,
141};
142use ftui_render::grapheme_pool::GraphemePool;
143use ftui_render::link_registry::LinkRegistry;
144use ftui_render::presenter::Presenter;
145use ftui_render::render_certificate::{
146    RenderCertificate, RenderCertificateLevel, evaluate_render_certificate_for_buffers,
147};
148use ftui_render::sanitize::{SanitizeMode, Text, sanitize, sanitize_with};
149use tracing::{debug_span, info, info_span, trace, warn};
150
151/// Size of the internal write buffer (64KB).
152#[allow(dead_code)] // Used by Presenter::new; kept here for reference.
153const BUFFER_CAPACITY: usize = 64 * 1024;
154
155/// DEC cursor save (ESC 7) - more portable than CSI s.
156const CURSOR_SAVE: &[u8] = b"\x1b7";
157
158/// DEC cursor restore (ESC 8) - more portable than CSI u.
159const CURSOR_RESTORE: &[u8] = b"\x1b8";
160
161/// Reset SGR before returning control to the UI renderer.
162const SGR_RESET: &[u8] = b"\x1b[0m";
163
164/// Move to `row`, `col` (0-indexed): `CUP`, or with `bottom: Some(height)`
165/// the same row of a `height`-row terminal counted from its last row (see
166/// `TerminalWriter::move_to_row`).
167fn write_row_address(
168    w: &mut impl Write,
169    bottom: Option<u16>,
170    row: u16,
171    col: u16,
172) -> io::Result<()> {
173    match bottom {
174        Some(height) => ansi::cup_from_bottom(w, height.saturating_sub(1).saturating_sub(row), col),
175        None => ansi::cup(w, row, col),
176    }
177}
178
179/// Clamp the plain projection using the same policy as unstyled overlay logs,
180/// then retain the SGR sequences interspersed through that visible prefix.
181/// `text` must already have passed SGR-only sanitization.
182fn sgr_overlay_log_line(text: &str, max_cols: usize) -> String {
183    let plain = sanitize(text);
184    let line = sanitize_overlay_log_line(&plain, max_cols);
185    let mut visible = line.chars();
186    let mut next_visible = visible.next();
187    let mut out = String::new();
188    let mut chars = text.chars();
189    while next_visible.is_some() {
190        let Some(ch) = chars.next() else {
191            break;
192        };
193        if ch == '\x1b' {
194            out.push(ch);
195            for sgr_char in chars.by_ref() {
196                out.push(sgr_char);
197                if sgr_char == 'm' {
198                    break;
199                }
200            }
201        } else if Some(ch) == next_visible {
202            out.push(ch);
203            next_visible = visible.next();
204        }
205    }
206    out
207}
208
209/// Synchronized output begin (DEC 2026).
210const SYNC_BEGIN: &[u8] = b"\x1b[?2026h";
211
212/// Synchronized output end (DEC 2026).
213const SYNC_END: &[u8] = b"\x1b[?2026l";
214
215/// Erase entire line (CSI 2 K).
216const ERASE_LINE: &[u8] = b"\x1b[2K";
217/// Reset background to terminal default (CSI 49 m).
218const SGR_BG_DEFAULT: &[u8] = b"\x1b[49m";
219
220/// How often to probe with a real diff when FullRedraw is selected.
221#[allow(dead_code)] // API for future diff strategy integration
222const FULL_REDRAW_PROBE_INTERVAL: u64 = 60;
223
224// CountingWriter is re-used from ftui_render::counting_writer::CountingWriter.
225// The Presenter wraps the writer in CountingWriter<BufWriter<W>>.
226// For byte counting, use reset_counter() and bytes_written() on the counting writer.
227
228fn default_diff_run_id() -> String {
229    format!("diff-{}", std::process::id())
230}
231
232fn diff_strategy_str(strategy: DiffStrategy) -> &'static str {
233    match strategy {
234        DiffStrategy::Full => "full",
235        DiffStrategy::DirtyRows => "dirty",
236        DiffStrategy::FullRedraw => "redraw",
237    }
238}
239
240fn inline_strategy_str(strategy: InlineStrategy) -> &'static str {
241    match strategy {
242        InlineStrategy::ScrollRegion => "scroll_region",
243        InlineStrategy::OverlayRedraw => "overlay_redraw",
244        InlineStrategy::Hybrid => "hybrid",
245    }
246}
247
248fn ui_anchor_str(anchor: UiAnchor) -> &'static str {
249    match anchor {
250        UiAnchor::Bottom => "bottom",
251        UiAnchor::Top => "top",
252    }
253}
254
255#[allow(dead_code)]
256#[inline]
257fn json_escape(value: &str) -> String {
258    let mut out = String::with_capacity(value.len());
259    for ch in value.chars() {
260        match ch {
261            '"' => out.push_str("\\\""),
262            '\\' => out.push_str("\\\\"),
263            '\n' => out.push_str("\\n"),
264            '\r' => out.push_str("\\r"),
265            '\t' => out.push_str("\\t"),
266            c if c.is_control() => {
267                use std::fmt::Write as _;
268                let _ = write!(out, "\\u{:04X}", c as u32);
269            }
270            _ => out.push(ch),
271        }
272    }
273    out
274}
275
276#[allow(dead_code)]
277fn estimate_diff_scan_cost(
278    strategy: DiffStrategy,
279    dirty_rows: usize,
280    width: usize,
281    height: usize,
282    span_stats: &DirtySpanStats,
283    tile_stats: Option<TileDiffStats>,
284) -> (usize, &'static str) {
285    match strategy {
286        DiffStrategy::Full => (width.saturating_mul(height), "full_strategy"),
287        DiffStrategy::FullRedraw => (0, "full_redraw"),
288        DiffStrategy::DirtyRows => {
289            if dirty_rows == 0 {
290                return (0, "no_dirty_rows");
291            }
292            if let Some(tile_stats) = tile_stats
293                && tile_stats.fallback.is_none()
294            {
295                return (tile_stats.scan_cells_estimate, "tile_skip");
296            }
297            let span_cells = span_stats.span_coverage_cells;
298            if span_stats.overflows > 0 {
299                let estimate = if span_cells > 0 {
300                    span_cells
301                } else {
302                    dirty_rows.saturating_mul(width)
303                };
304                return (estimate, "span_overflow");
305            }
306            if span_cells > 0 {
307                (span_cells, "none")
308            } else {
309                (dirty_rows.saturating_mul(width), "no_spans")
310            }
311        }
312    }
313}
314
315fn sanitize_auto_bounds(min_height: u16, max_height: u16) -> (u16, u16) {
316    let min = min_height.max(1);
317    let max = max_height.max(min);
318    (min, max)
319}
320
321pub use ftui_backend::{PresentTimings, ScreenMode, UiAnchor};
322
323#[derive(Debug, Clone, Copy, PartialEq, Eq)]
324struct InlineRegion {
325    start: u16,
326    height: u16,
327}
328
329/// One already-sanitized piece of log text waiting for the overlay
330/// transport: a complete line (`terminated`: its newline was received), or
331/// text without a newline yet, which the next piece continues on the same
332/// row.
333#[derive(Debug, Clone)]
334struct PendingLogLine {
335    text: String,
336    mode: SanitizeMode,
337    terminated: bool,
338}
339
340/// Where the overlay transport left an open log line (text streamed without
341/// a terminator): on the row directly above a `ui_height`-row UI (the
342/// bottom row when there is no UI) of a `term`-sized terminal, ending at
343/// 0-indexed column `col`. The next stream continues it only in that same
344/// geometry; otherwise the next text starts on a fresh row.
345#[derive(Debug, Clone, Copy, PartialEq, Eq)]
346struct OverlayOpenLine {
347    col: u16,
348    term: (u16, u16),
349    ui_height: u16,
350}
351
352/// Overlay log batches are streamed early once they reach this many lines
353/// or bytes, bounding memory and latency when no frame is presented.
354const OVERLAY_LOG_BATCH_LINES: usize = 256;
355const OVERLAY_LOG_BATCH_BYTES: usize = 64 * 1024;
356
357/// Bound on overlay log lines held while no row is free to stream them
358/// (the UI fills the terminal until a resize or present frees one): four
359/// batches. Beyond it the oldest lines are dropped and counted, see
360/// [`TerminalWriter::dropped_log_lines`].
361const OVERLAY_LOG_QUEUE_MAX_LINES: usize = 4 * OVERLAY_LOG_BATCH_LINES;
362const OVERLAY_LOG_QUEUE_MAX_BYTES: usize = 4 * OVERLAY_LOG_BATCH_BYTES;
363
364/// Rows an open overlay log line advances and the 0-indexed column it ends
365/// at (`0..=width`; `width` means the next character wraps first), for
366/// text written from `start_col`: display width after sanitizing, autowrap
367/// at `width`, a CR returning to column 0. Like the DECSTBM column tracking
368/// this is an estimate for trusted raw text that moves the cursor itself.
369fn open_line_extent<'a>(
370    start_col: u16,
371    texts: impl IntoIterator<Item = &'a str>,
372    width: u16,
373) -> (u16, u16) {
374    let width = usize::from(width.max(1));
375    let mut col = usize::from(start_col).min(width);
376    let mut rows = 0usize;
377    for text in texts {
378        for (i, piece) in text.split('\r').enumerate() {
379            if i > 0 {
380                col = 0;
381            }
382            let piece_width = ftui_core::text_width::display_width(&sanitize(piece));
383            if piece_width == 0 {
384                continue;
385            }
386            if col >= width {
387                rows += 1;
388                col = 0;
389            }
390            let last = col + piece_width - 1;
391            rows += last / width;
392            col = last % width + 1;
393        }
394    }
395    (
396        u16::try_from(rows).unwrap_or(u16::MAX),
397        u16::try_from(col).unwrap_or(u16::MAX),
398    )
399}
400
401struct DiffDecision {
402    #[allow(dead_code)] // reserved for future diff strategy introspection
403    strategy: DiffStrategy,
404    has_diff: bool,
405}
406
407#[derive(Debug, Clone, Copy)]
408#[allow(dead_code)]
409struct EmitStats {
410    diff_cells: usize,
411    diff_runs: usize,
412}
413
414#[derive(Debug, Clone, Copy)]
415#[allow(dead_code)]
416struct FrameEmitStats {
417    diff_strategy: DiffStrategy,
418    diff_cells: usize,
419    diff_runs: usize,
420    ui_height: u16,
421}
422
423// =============================================================================
424// Runtime Diff Configuration
425// =============================================================================
426
427/// Runtime-level configuration for diff strategy selection.
428///
429/// This wraps [`DiffStrategyConfig`] and adds runtime-specific toggles
430/// for enabling/disabling features and controlling reset policies.
431///
432/// # Example
433///
434/// ```
435/// use ftui_runtime::{RuntimeDiffConfig, DiffStrategyConfig};
436///
437/// // Use defaults (Bayesian selection enabled, dirty-rows enabled)
438/// let config = RuntimeDiffConfig::default();
439///
440/// // Disable Bayesian selection (always use dirty-rows if available)
441/// let config = RuntimeDiffConfig::default()
442///     .with_bayesian_enabled(false);
443///
444/// // Custom cost model
445/// let config = RuntimeDiffConfig::default()
446///     .with_strategy_config(DiffStrategyConfig {
447///         c_emit: 10.0,  // Higher I/O cost
448///         ..Default::default()
449///     });
450/// ```
451#[derive(Debug, Clone)]
452pub struct RuntimeDiffConfig {
453    /// Enable Bayesian strategy selection.
454    ///
455    /// When enabled, the selector uses a Beta posterior over the change rate
456    /// to choose between Full, DirtyRows, and FullRedraw strategies.
457    ///
458    /// When disabled, always uses DirtyRows if dirty tracking is available,
459    /// otherwise Full.
460    ///
461    /// Default: true
462    pub bayesian_enabled: bool,
463
464    /// Enable dirty-row optimization.
465    ///
466    /// When enabled, the DirtyRows strategy is available for selection.
467    /// When disabled, the selector chooses between Full and FullRedraw only.
468    ///
469    /// Default: true
470    pub dirty_rows_enabled: bool,
471
472    /// Emit explicit render certificates and route the DirtyRows strategy
473    /// through the certified diff path (skip-all on zero dirty rows,
474    /// narrow-to-dirty otherwise). Behavior-identical to the uncertified
475    /// dirty path; disabling only removes the certificate evidence and the
476    /// zero-dirty fast path.
477    ///
478    /// Default: true
479    pub certified_skips: bool,
480
481    /// Dirty-span tracking configuration (thresholds + feature flags).
482    ///
483    /// Controls span merging, guard bands, and enable/disable behavior.
484    pub dirty_span_config: DirtySpanConfig,
485
486    /// Tile-based diff skipping configuration (thresholds + feature flags).
487    ///
488    /// Controls SAT tile size, thresholds, and enable/disable behavior.
489    pub tile_diff_config: TileDiffConfig,
490
491    /// Reset posterior on dimension change.
492    ///
493    /// When true, the Bayesian posterior resets to priors when the buffer
494    /// dimensions change (e.g., terminal resize).
495    ///
496    /// Default: true
497    pub reset_on_resize: bool,
498
499    /// Reset posterior on buffer invalidation.
500    ///
501    /// When true, resets to priors when the previous buffer becomes invalid
502    /// (e.g., mode switch, scroll region change).
503    ///
504    /// Default: true
505    pub reset_on_invalidation: bool,
506
507    /// Underlying strategy configuration.
508    ///
509    /// Contains cost model constants, prior parameters, and decay settings.
510    pub strategy_config: DiffStrategyConfig,
511
512    /// Maximum successful incremental frames to allow between physical full redraws.
513    ///
514    /// Terminals and mux panes can lose their visible buffer without notifying the
515    /// process. A bounded full redraw interval repairs that state divergence even
516    /// when the application model has not changed. Set to `0` to disable.
517    ///
518    /// Default: 240
519    pub full_redraw_interval_frames: u64,
520
521    /// Maximum *wall-clock* time to allow between physical full redraws.
522    ///
523    /// The frame-count interval ([`Self::full_redraw_interval_frames`]) only
524    /// advances on rendered frames, so a TUI that renders sparsely (dirty-driven,
525    /// idle, or rendering slowly) can leave a desynchronized physical terminal —
526    /// e.g. corruption from an aggressive incremental diff, or a mux pane swap /
527    /// reattach — visible for a long time. A wall-clock bound guarantees the
528    /// physical terminal is fully repainted at least this often regardless of
529    /// render cadence, so any such corruption self-heals within the interval.
530    ///
531    /// `None` (the default) disables the time-based resync, preserving the
532    /// purely frame-count behavior (and deterministic-test reproducibility).
533    pub full_redraw_max_interval: Option<std::time::Duration>,
534}
535
536impl Default for RuntimeDiffConfig {
537    fn default() -> Self {
538        Self {
539            bayesian_enabled: true,
540            dirty_rows_enabled: true,
541            certified_skips: true,
542            dirty_span_config: DirtySpanConfig::default(),
543            tile_diff_config: TileDiffConfig::default(),
544            reset_on_resize: true,
545            reset_on_invalidation: true,
546            strategy_config: DiffStrategyConfig::default(),
547            full_redraw_interval_frames: 240,
548            full_redraw_max_interval: None,
549        }
550    }
551}
552
553impl RuntimeDiffConfig {
554    /// Create a new config with all defaults.
555    pub fn new() -> Self {
556        Self::default()
557    }
558
559    /// Set whether Bayesian strategy selection is enabled.
560    #[must_use]
561    pub fn with_bayesian_enabled(mut self, enabled: bool) -> Self {
562        self.bayesian_enabled = enabled;
563        self
564    }
565
566    /// Set whether dirty-row optimization is enabled.
567    #[must_use]
568    pub fn with_dirty_rows_enabled(mut self, enabled: bool) -> Self {
569        self.dirty_rows_enabled = enabled;
570        self
571    }
572
573    /// Set whether dirty-span tracking is enabled.
574    #[must_use]
575    pub fn with_dirty_spans_enabled(mut self, enabled: bool) -> Self {
576        self.dirty_span_config = self.dirty_span_config.with_enabled(enabled);
577        self
578    }
579
580    /// Set the dirty-span tracking configuration.
581    #[must_use]
582    pub fn with_dirty_span_config(mut self, config: DirtySpanConfig) -> Self {
583        self.dirty_span_config = config;
584        self
585    }
586
587    /// Toggle tile-based skipping.
588    #[must_use]
589    pub fn with_tile_skip_enabled(mut self, enabled: bool) -> Self {
590        self.tile_diff_config = self.tile_diff_config.with_enabled(enabled);
591        self
592    }
593
594    /// Set the tile-based diff configuration.
595    #[must_use]
596    pub fn with_tile_diff_config(mut self, config: TileDiffConfig) -> Self {
597        self.tile_diff_config = config;
598        self
599    }
600
601    /// Set whether to reset posterior on resize.
602    #[must_use]
603    pub fn with_reset_on_resize(mut self, enabled: bool) -> Self {
604        self.reset_on_resize = enabled;
605        self
606    }
607
608    /// Set whether to reset posterior on invalidation.
609    #[must_use]
610    pub fn with_reset_on_invalidation(mut self, enabled: bool) -> Self {
611        self.reset_on_invalidation = enabled;
612        self
613    }
614
615    /// Set the underlying strategy configuration.
616    #[must_use]
617    pub fn with_strategy_config(mut self, config: DiffStrategyConfig) -> Self {
618        self.strategy_config = config;
619        self
620    }
621
622    /// Set the maximum successful incremental frames between physical full redraws.
623    ///
624    /// A value of `0` disables periodic terminal resynchronization.
625    #[must_use]
626    pub fn with_full_redraw_interval_frames(mut self, frames: u64) -> Self {
627        self.full_redraw_interval_frames = frames;
628        self
629    }
630
631    /// Set the maximum wall-clock time between physical full redraws.
632    ///
633    /// Unlike [`Self::with_full_redraw_interval_frames`] (which only advances on
634    /// rendered frames), this bounds resynchronization by elapsed time, so an
635    /// idle or sparsely-rendering TUI still repaints the physical terminal at
636    /// least this often — bounding how long any terminal-state desync (diff
637    /// corruption, mux pane swap, reattach) can stay on screen. `None` disables
638    /// it.
639    #[must_use]
640    pub fn with_full_redraw_max_interval(mut self, interval: Option<std::time::Duration>) -> Self {
641        self.full_redraw_max_interval = interval;
642        self
643    }
644}
645
646#[inline]
647fn is_uncolored_blank(cell: &ftui_render::cell::Cell) -> bool {
648    use ftui_render::cell::{CellAttrs, CellContent};
649    (cell.content.is_empty() || cell.content == CellContent::from_char(' '))
650        && cell.bg.a() == 0
651        && cell.attrs.link_id() == CellAttrs::LINK_ID_NONE
652        && cell.attrs.flags().is_empty()
653}
654
655fn row_occupied_width(buffer: &Buffer, y: u16) -> u16 {
656    let row = buffer.row_cells(y);
657    row.iter()
658        .rposition(|cell| !is_uncolored_blank(cell))
659        .map_or(0, |idx| (idx as u16).saturating_add(1))
660}
661
662/// Unified terminal output coordinator.
663///
664/// Enforces the one-writer rule and implements inline mode correctly.
665/// All terminal output should go through this struct.
666pub struct TerminalWriter<W: Write> {
667    /// Presenter handles efficient ANSI emission and cursor tracking.
668    /// Wrapped in `Option` so `into_inner` can take ownership; `Drop` skips
669    /// cleanup when `None` (already consumed).
670    presenter: Option<Presenter<W>>,
671    /// Current screen mode.
672    screen_mode: ScreenMode,
673    /// Last computed auto UI height (inline auto mode only).
674    auto_ui_height: Option<u16>,
675    /// Where UI is anchored in inline mode.
676    ui_anchor: UiAnchor,
677    /// Previous buffer for diffing.
678    prev_buffer: Option<Buffer>,
679    /// Spare buffer for reuse as the next render target.
680    spare_buffer: Option<Buffer>,
681    /// Pre-allocated buffer for zero-alloc clone in present_ui.
682    /// Part of a 3-buffer rotation: spare ← prev ← clone_buf ← spare.
683    clone_buf: Option<Buffer>,
684    /// Grapheme pool for complex characters.
685    pool: GraphemePool,
686    /// Link registry for hyperlinks.
687    links: LinkRegistry,
688    /// Terminal capabilities.
689    capabilities: TerminalCapabilities,
690    /// Terminal width in columns.
691    term_width: u16,
692    /// Terminal height in rows.
693    term_height: u16,
694    /// Whether we're in the middle of a sync block.
695    in_sync_block: bool,
696    /// Whether cursor has been saved.
697    cursor_saved: bool,
698    /// Current cursor visibility state (best-effort).
699    cursor_visible: bool,
700    /// Inline mode rendering strategy (selected from capabilities).
701    inline_strategy: InlineStrategy,
702    /// Whether a scroll region is currently active.
703    scroll_region_active: bool,
704    /// Whether the bottom margin row of a bottom-anchored DECSTBM region
705    /// still holds a completed pre-region line (from `reserve_inline_rows`
706    /// or `flush_pending_logs`) that must scroll up before the next
707    /// DECSTBM log write starts at column 1.
708    decstbm_row_occupied: bool,
709    /// 0-indexed cursor column on the DECSTBM log row after a partial log
710    /// write (one that did not end with `\n`).
711    decstbm_col: u16,
712    /// DECSTBM self-test verdict (`None`: not run).
713    scroll_region_verified: Option<bool>,
714    /// Strategy fallback taken because of the self-test, exported with the
715    /// capability ledger.
716    strategy_fallback: Option<InlineStrategyFallback>,
717    /// Last inline UI region for clearing on shrink.
718    last_inline_region: Option<InlineRegion>,
719    /// Log text batched for the overlay transport (bottom-anchored UI
720    /// without an active scroll region); see [`Self::flush_pending_logs`].
721    pending_logs: Vec<PendingLogLine>,
722    /// Text bytes held in `pending_logs`.
723    pending_log_bytes: usize,
724    /// `pending_logs` held lines when the terminal was last resized, and no
725    /// log text was queued since. Until a frame is drawn at the new geometry
726    /// the bare [`Self::flush`] leaves them for the next present: the rows a
727    /// stream would erase hold the terminal's reflowed content, not UI rows.
728    /// Teardown streams them without erasing.
729    logs_held_across_resize: bool,
730    /// The open line the last overlay stream left (see [`OverlayOpenLine`]).
731    overlay_open: Option<OverlayOpenLine>,
732    /// Overlay log lines dropped at the queue bound (see
733    /// [`Self::dropped_log_lines`]).
734    dropped_log_lines: u64,
735    /// Whether the rows under the bottom-anchored inline UI have been made
736    /// room for below the shell's cursor (done once, before the first
737    /// inline output).
738    inline_rows_reserved: bool,
739    /// Absolute position of the visible UI cursor after the last inline
740    /// present (`None`: hidden), restored after a standalone log flush.
741    last_ui_cursor: Option<(u16, u16)>,
742    /// The cursor's row within the displayed bottom-anchored overlay UI, and
743    /// that UI's height, after this writer's last output (`None`: unknown).
744    /// A multiplexer that shrinks a pane deletes the rows below the cursor
745    /// before it moves anything else (tmux 3.6), so the UI may have lost
746    /// that many bottom rows; see `reanchor_inline_cursor`. Unlike absolute
747    /// coordinates this survives a resize: the multiplexer keeps the cursor
748    /// on its content.
749    cursor_ui_row: Option<(u16, u16)>,
750    /// First row below the last streamed log line (bottom-anchored overlay
751    /// transport). Before a frame is displayed, a later stream and the first
752    /// frame must not start above it: an inline-auto UI may have grown
753    /// since, and the rows it now claims hold lines not yet in scrollback.
754    log_floor: Option<u16>,
755    /// The displayed frame after an inline-auto height change dropped it as
756    /// the diff baseline: still what the screen shows at
757    /// `last_inline_region`, so a log flush before the next present can
758    /// repaint it. Cleared by the next present.
759    stale_frame: Option<Buffer>,
760    /// Bayesian diff strategy selector.
761    diff_strategy: DiffStrategySelector,
762    /// Reusable diff buffer to avoid per-frame allocations.
763    diff_scratch: BufferDiff,
764    /// Frames since last diff probe while in FullRedraw.
765    full_redraw_probe: u64,
766    /// Successful incremental frames since the terminal was physically redrawn.
767    frames_since_full_redraw: u64,
768    /// Wall-clock instant of the last physical full redraw, used to bound
769    /// terminal-state desync by elapsed time (see
770    /// [`RuntimeDiffConfig::full_redraw_max_interval`]). `None` until the first
771    /// full redraw is presented.
772    last_full_redraw_at: Option<Instant>,
773    /// Runtime diff configuration.
774    #[allow(dead_code)] // runtime toggles wired up in follow-up work
775    diff_config: RuntimeDiffConfig,
776    /// Evidence JSONL sink for diff decisions.
777    evidence_sink: Option<EvidenceSink>,
778    /// Capability decision ledger from the live probe, held until an evidence
779    /// sink is attached and then written out once (drained).
780    capability_decisions: Vec<CapabilityDecision>,
781    /// Run identifier for diff decision evidence.
782    #[allow(dead_code)]
783    /// The explicit skip certificate for the most recent diff decision.
784    last_certificate: Option<RenderCertificate>,
785    diff_evidence_run_id: String,
786    /// Monotonic event index for diff decision evidence.
787    #[allow(dead_code)]
788    diff_evidence_idx: u64,
789    /// Last diff strategy selected during present.
790    last_diff_strategy: Option<DiffStrategy>,
791    /// Render-trace recorder (optional).
792    render_trace: Option<RenderTraceRecorder>,
793    /// Whether per-frame timing capture is enabled.
794    timing_enabled: bool,
795    /// Last present timings (diff compute duration).
796    last_present_timings: Option<PresentTimings>,
797    /// Current diff regime classification.
798    diff_regime: DiffRegime,
799    /// Number of consecutive frames spent in the current diff regime.
800    diff_regime_frames: u64,
801}
802
803impl<W: Write> TerminalWriter<W> {
804    /// Create a new terminal writer.
805    ///
806    /// # Arguments
807    ///
808    /// * `writer` - Output destination (takes ownership for one-writer rule)
809    /// * `screen_mode` - Inline or alternate screen mode
810    /// * `ui_anchor` - Where to anchor UI in inline mode
811    /// * `capabilities` - Terminal capabilities
812    pub fn new(
813        writer: W,
814        screen_mode: ScreenMode,
815        ui_anchor: UiAnchor,
816        capabilities: TerminalCapabilities,
817    ) -> Self {
818        Self::with_diff_config(
819            writer,
820            screen_mode,
821            ui_anchor,
822            capabilities,
823            RuntimeDiffConfig::default(),
824        )
825    }
826
827    /// Create a new terminal writer with custom diff strategy configuration.
828    ///
829    /// # Arguments
830    ///
831    /// * `writer` - Output destination (takes ownership for one-writer rule)
832    /// * `screen_mode` - Inline or alternate screen mode
833    /// * `ui_anchor` - Where to anchor UI in inline mode
834    /// * `capabilities` - Terminal capabilities
835    /// * `diff_config` - Configuration for diff strategy selection
836    ///
837    /// # Example
838    ///
839    /// ```ignore
840    /// use ftui_runtime::{TerminalWriter, ScreenMode, UiAnchor, RuntimeDiffConfig};
841    /// use ftui_core::terminal_capabilities::TerminalCapabilities;
842    ///
843    /// // Disable Bayesian selection for deterministic diffing
844    /// let config = RuntimeDiffConfig::default()
845    ///     .with_bayesian_enabled(false);
846    ///
847    /// let writer = TerminalWriter::with_diff_config(
848    ///     std::io::stdout(),
849    ///     ScreenMode::AltScreen,
850    ///     UiAnchor::Bottom,
851    ///     TerminalCapabilities::detect(),
852    ///     config,
853    /// );
854    /// ```
855    pub fn with_diff_config(
856        writer: W,
857        screen_mode: ScreenMode,
858        ui_anchor: UiAnchor,
859        capabilities: TerminalCapabilities,
860        diff_config: RuntimeDiffConfig,
861    ) -> Self {
862        let inline_strategy = InlineStrategy::select(&capabilities);
863        let auto_ui_height = None;
864        let diff_strategy = DiffStrategySelector::new(diff_config.strategy_config.clone());
865
866        // Increment the inline-active gauge.
867        // We do this BEFORE potentially returning/panicking to maintain invariant
868        // that a TerminalWriter in inline mode ALWAYS has a corresponding increment,
869        // which will be decremented on Drop.
870        let is_inline = matches!(
871            screen_mode,
872            ScreenMode::Inline { .. } | ScreenMode::InlineAuto { .. }
873        );
874        if is_inline {
875            INLINE_ACTIVE_WIDGETS.fetch_add(1, Ordering::SeqCst);
876        }
877
878        // Log inline mode activation.
879        match screen_mode {
880            ScreenMode::Inline { ui_height } => {
881                info!(
882                    inline_height = ui_height,
883                    render_mode = %inline_strategy_str(inline_strategy),
884                    "inline mode activated"
885                );
886            }
887            ScreenMode::InlineAuto {
888                min_height,
889                max_height,
890            } => {
891                info!(
892                    min_height,
893                    max_height,
894                    render_mode = %inline_strategy_str(inline_strategy),
895                    "inline auto mode activated"
896                );
897            }
898            ScreenMode::AltScreen => {}
899        }
900
901        let mut diff_scratch = BufferDiff::new();
902        diff_scratch
903            .tile_config_mut()
904            .clone_from(&diff_config.tile_diff_config);
905
906        let presenter = Presenter::new(writer, capabilities);
907
908        Self {
909            presenter: Some(presenter),
910            screen_mode,
911            auto_ui_height,
912            ui_anchor,
913            prev_buffer: None,
914            spare_buffer: None,
915            clone_buf: None,
916            pool: GraphemePool::new(),
917            links: LinkRegistry::new(),
918            capabilities,
919            term_width: 80,
920            term_height: 24,
921            in_sync_block: false,
922            cursor_saved: false,
923            cursor_visible: true,
924            inline_strategy,
925            scroll_region_active: false,
926            decstbm_row_occupied: false,
927            decstbm_col: 0,
928            scroll_region_verified: None,
929            strategy_fallback: None,
930            last_inline_region: None,
931            pending_logs: Vec::new(),
932            pending_log_bytes: 0,
933            logs_held_across_resize: false,
934            overlay_open: None,
935            dropped_log_lines: 0,
936            inline_rows_reserved: false,
937            last_ui_cursor: None,
938            cursor_ui_row: None,
939            log_floor: None,
940            stale_frame: None,
941            diff_strategy,
942            diff_scratch,
943            full_redraw_probe: 0,
944            frames_since_full_redraw: 0,
945            last_full_redraw_at: None,
946            diff_config,
947            evidence_sink: None,
948            capability_decisions: Vec::new(),
949            diff_evidence_run_id: default_diff_run_id(),
950            diff_evidence_idx: 0,
951            last_diff_strategy: None,
952            last_certificate: None,
953            render_trace: None,
954            timing_enabled: false,
955            last_present_timings: None,
956            diff_regime: DiffRegime::Sparse,
957            diff_regime_frames: 0,
958        }
959    }
960
961    /// Get a mutable reference to the internal counting writer.
962    ///
963    /// # Panics
964    ///
965    /// Panics if the presenter has been taken (via `into_inner`).
966    #[inline]
967    fn writer(&mut self) -> &mut CountingWriter<BufWriter<W>> {
968        self.presenter_mut().counting_writer_mut()
969    }
970
971    /// Get a mutable reference to the presenter.
972    ///
973    /// # Panics
974    ///
975    /// Panics if the presenter has been taken (via `into_inner`).
976    #[inline]
977    fn presenter_mut(&mut self) -> &mut Presenter<W> {
978        self.presenter
979            .as_mut()
980            .expect("presenter has been consumed")
981    }
982
983    /// Reset diff strategy state when the previous buffer is invalidated.
984    fn reset_diff_strategy(&mut self) {
985        if self.diff_config.reset_on_invalidation {
986            self.diff_strategy.reset();
987        }
988        self.full_redraw_probe = 0;
989        self.frames_since_full_redraw = 0;
990        self.last_diff_strategy = None;
991    }
992
993    /// Reset diff strategy state on terminal resize.
994    #[allow(dead_code)] // used by upcoming resize-aware diff strategy work
995    fn reset_diff_on_resize(&mut self) {
996        if self.diff_config.reset_on_resize {
997            self.diff_strategy.reset();
998        }
999        self.full_redraw_probe = 0;
1000        self.frames_since_full_redraw = 0;
1001        self.last_diff_strategy = None;
1002    }
1003
1004    /// Get the current diff configuration.
1005    pub fn diff_config(&self) -> &RuntimeDiffConfig {
1006        &self.diff_config
1007    }
1008
1009    /// Enable or disable per-frame timing capture.
1010    pub(crate) fn set_timing_enabled(&mut self, enabled: bool) {
1011        self.timing_enabled = enabled;
1012        if !enabled {
1013            self.last_present_timings = None;
1014        }
1015    }
1016
1017    /// Take the last present timings (if available).
1018    pub fn take_last_present_timings(&mut self) -> Option<PresentTimings> {
1019        self.last_present_timings.take()
1020    }
1021
1022    /// Access the last present timings (if available).
1023    #[must_use]
1024    pub fn last_present_timings(&self) -> Option<&PresentTimings> {
1025        self.last_present_timings.as_ref()
1026    }
1027
1028    /// Attach an evidence sink for diff decision logging.
1029    #[must_use]
1030    pub fn with_evidence_sink(mut self, sink: EvidenceSink) -> Self {
1031        self.evidence_sink = Some(sink);
1032        self.export_capability_decisions();
1033        self
1034    }
1035
1036    /// Set the evidence JSONL sink for diff decision logging.
1037    pub fn set_evidence_sink(&mut self, sink: Option<EvidenceSink>) {
1038        self.evidence_sink = sink;
1039        self.export_capability_decisions();
1040    }
1041
1042    /// Set a callback that receives every formatted JSONL evidence line.
1043    pub fn set_evidence_callback(&mut self, callback: Option<Arc<dyn Fn(&str) + Send + Sync>>) {
1044        if let Some(cb) = callback {
1045            self.set_evidence_sink(Some(EvidenceSink::from_writer(CallbackEvidenceWriter(cb))));
1046        } else {
1047            self.set_evidence_sink(None);
1048        }
1049    }
1050
1051    /// Attach the capability decision ledger produced by the live terminal
1052    /// probe. The rows are written to the evidence sink as
1053    /// `capability_decision` events, followed by one `inline_strategy` event
1054    /// naming the strategy selected from those capabilities, as soon as both
1055    /// the ledger and a sink are present (in either order).
1056    #[must_use]
1057    pub fn with_capability_decisions(mut self, decisions: Vec<CapabilityDecision>) -> Self {
1058        self.capability_decisions = decisions;
1059        self.export_capability_decisions();
1060        self
1061    }
1062
1063    fn export_capability_decisions(&mut self) {
1064        let Some(sink) = self.evidence_sink.as_ref() else {
1065            return;
1066        };
1067        if self.capability_decisions.is_empty() && self.strategy_fallback.is_none() {
1068            return;
1069        }
1070        for decision in self.capability_decisions.drain(..) {
1071            let _ = sink.write_jsonl(&decision.to_jsonl());
1072        }
1073        if let Some(fallback) = self.strategy_fallback.take() {
1074            let _ = sink.write_jsonl(&fallback.to_jsonl());
1075        }
1076        let verified = self
1077            .scroll_region_verified
1078            .map_or_else(|| "null".to_string(), |v| v.to_string());
1079        // Where inline log lines go (G48): through the DECSTBM region, by the
1080        // overlay whole-screen scroll stream, or (top-anchored overlay) one
1081        // overwritten row that never reaches scrollback.
1082        let log_transport = match (self.inline_strategy, self.ui_anchor) {
1083            (InlineStrategy::ScrollRegion | InlineStrategy::Hybrid, _) => "decstbm",
1084            (InlineStrategy::OverlayRedraw, UiAnchor::Bottom) => "scroll_repaint",
1085            (InlineStrategy::OverlayRedraw, UiAnchor::Top) => "single_row",
1086        };
1087        let _ = sink.write_jsonl(&format!(
1088            r#"{{"event":"inline_strategy","strategy":"{}","use_scroll_region":{},"use_sync_output":{},"in_mux":{},"scroll_region_verified":{},"log_transport":"{}"}}"#,
1089            inline_strategy_str(self.inline_strategy),
1090            self.capabilities.use_scroll_region(),
1091            self.capabilities.use_sync_output(),
1092            self.capabilities.in_any_mux(),
1093            verified,
1094            log_transport
1095        ));
1096    }
1097
1098    /// Attach a render-trace recorder.
1099    #[must_use]
1100    pub fn with_render_trace(mut self, recorder: RenderTraceRecorder) -> Self {
1101        self.render_trace = Some(recorder);
1102        self
1103    }
1104
1105    /// Set the render-trace recorder.
1106    pub fn set_render_trace(&mut self, recorder: Option<RenderTraceRecorder>) {
1107        self.render_trace = recorder;
1108    }
1109
1110    /// Get mutable access to the diff strategy selector.
1111    ///
1112    /// Useful for advanced scenarios like manual posterior updates.
1113    pub fn diff_strategy_mut(&mut self) -> &mut DiffStrategySelector {
1114        &mut self.diff_strategy
1115    }
1116
1117    /// Get the diff strategy selector (read-only).
1118    pub fn diff_strategy(&self) -> &DiffStrategySelector {
1119        &self.diff_strategy
1120    }
1121
1122    /// Get the last diff strategy selected during present, if any.
1123    pub fn last_diff_strategy(&self) -> Option<DiffStrategy> {
1124        self.last_diff_strategy
1125    }
1126
1127    /// Current diff regime classification.
1128    #[must_use]
1129    pub fn diff_regime(&self) -> DiffRegime {
1130        self.diff_regime
1131    }
1132
1133    /// Number of consecutive frames spent in the current diff regime.
1134    #[must_use]
1135    pub fn diff_regime_frames(&self) -> u64 {
1136        self.diff_regime_frames
1137    }
1138
1139    /// The explicit render certificate behind the most recent diff decision
1140    /// (`None` before the first present or when certified skips are
1141    /// disabled).
1142    #[must_use]
1143    pub fn last_render_certificate(&self) -> Option<&RenderCertificate> {
1144        self.last_certificate.as_ref()
1145    }
1146
1147    /// Notify the writer immediately when a terminal resize arrives, even
1148    /// while [`ResizeCoalescer`](crate::resize_coalescer::ResizeCoalescer)
1149    /// defers the next frame render.
1150    ///
1151    /// A live bottom-anchored inline session that started on a DECSTBM scroll
1152    /// region transitions to [`InlineStrategy::OverlayRedraw`] so in-flight
1153    /// log lines and frames during a resize storm use bottom-relative row
1154    /// addressing instead of stale top-down DECSTBM row coordinates.
1155    pub fn notify_resize(&mut self, width: u16, height: u16) {
1156        let _output_guard = terminal_output_lock();
1157        if (width, height) == (self.term_width, self.term_height) {
1158            return;
1159        }
1160        if self.inline_rows_reserved
1161            && matches!(self.ui_anchor, UiAnchor::Bottom)
1162            && matches!(
1163                self.inline_strategy,
1164                InlineStrategy::ScrollRegion | InlineStrategy::Hybrid
1165            )
1166        {
1167            self.inline_strategy = InlineStrategy::OverlayRedraw;
1168        }
1169        if self.scroll_region_active {
1170            let _ = self.deactivate_scroll_region();
1171            let _ = self.writer().flush();
1172            self.decstbm_row_occupied =
1173                self.inline_rows_reserved && matches!(self.ui_anchor, UiAnchor::Bottom);
1174            self.decstbm_col = 0;
1175        }
1176    }
1177
1178    /// Set the terminal size.
1179    ///
1180    /// Call this when the terminal is resized.
1181    pub fn set_size(&mut self, width: u16, height: u16) {
1182        // May emit a DECSTBM reset when a scroll region is active; keep it
1183        // inside the one-writer discipline (bd-kdn7n item 2).
1184        let _output_guard = terminal_output_lock();
1185        if !self.inline_rows_reserved || (width, height) != (self.term_width, self.term_height) {
1186            self.log_floor = None;
1187        }
1188        self.term_width = width;
1189        self.term_height = height;
1190        if matches!(self.screen_mode, ScreenMode::InlineAuto { .. }) {
1191            self.auto_ui_height = None;
1192        }
1193        // Clear prev_buffer to force full redraw after resize
1194        self.prev_buffer = None;
1195        self.stale_frame = None;
1196        // Old-geometry coordinates are meaningless after a resize: drop the
1197        // displayed-region cache so neither log positioning nor
1198        // clear_inline_region_diff acts on rows that no longer exist. The
1199        // cursor's row within the UI stays: it is relative to the UI, which
1200        // the multiplexer moved together with the cursor.
1201        self.last_inline_region = None;
1202        self.logs_held_across_resize = !self.pending_logs.is_empty();
1203        self.spare_buffer = None;
1204        self.clone_buf = None;
1205        self.reset_diff_on_resize();
1206        // Reset scroll region on resize; it will be re-established on next present
1207        if self.scroll_region_active {
1208            let _ = self.deactivate_scroll_region();
1209        }
1210        self.decstbm_row_occupied =
1211            self.inline_rows_reserved && matches!(self.ui_anchor, UiAnchor::Bottom);
1212        self.decstbm_col = 0;
1213    }
1214
1215    /// Take a reusable render buffer sized for the current frame.
1216    ///
1217    /// Uses a spare buffer when available to avoid per-frame allocation.
1218    pub fn take_render_buffer(&mut self, width: u16, height: u16) -> Buffer {
1219        if let Some(mut buffer) = self.spare_buffer.take()
1220            && buffer.width() == width
1221            && buffer.height() == height
1222        {
1223            buffer.set_dirty_span_config(self.diff_config.dirty_span_config);
1224            buffer.reset_for_frame();
1225            return buffer;
1226        }
1227
1228        let mut buffer = Buffer::new(width, height);
1229        buffer.set_dirty_span_config(self.diff_config.dirty_span_config);
1230        buffer
1231    }
1232
1233    /// Get the current terminal width.
1234    #[inline]
1235    pub fn width(&self) -> u16 {
1236        self.term_width
1237    }
1238
1239    /// Get the current terminal height.
1240    #[inline]
1241    pub fn height(&self) -> u16 {
1242        self.term_height
1243    }
1244
1245    /// Get the current screen mode.
1246    #[inline]
1247    pub fn screen_mode(&self) -> ScreenMode {
1248        self.screen_mode
1249    }
1250
1251    /// Set the screen mode.
1252    ///
1253    /// Leaving inline mode streams any batched overlay log lines first
1254    /// (best effort), so they reach scrollback instead of being dropped,
1255    /// deactivates any active DECSTBM scroll region, and invalidates cached
1256    /// geometry and diff baselines.
1257    pub fn set_screen_mode(&mut self, mode: ScreenMode) {
1258        if self.screen_mode == mode {
1259            return;
1260        }
1261        let _output_guard = terminal_output_lock();
1262        if matches!(mode, ScreenMode::AltScreen) && !self.pending_logs.is_empty() {
1263            let _ = self.flush_pending_logs(false);
1264        }
1265        if self.scroll_region_active {
1266            let _ = self.deactivate_scroll_region();
1267        }
1268        self.screen_mode = mode;
1269        self.auto_ui_height = None;
1270        self.prev_buffer = None;
1271        self.stale_frame = None;
1272        self.log_floor = None;
1273        self.overlay_open = None;
1274        self.last_inline_region = None;
1275        self.reset_diff_strategy();
1276    }
1277
1278    /// Height to use for rendering a frame.
1279    ///
1280    /// Fixed inline heights are clamped to the current terminal height so
1281    /// models lay out their controls within the rows that can be presented.
1282    /// In inline auto mode, this returns the configured maximum (clamped to
1283    /// terminal height) so measurement can determine actual UI height.
1284    pub fn render_height_hint(&self) -> u16 {
1285        match self.screen_mode {
1286            ScreenMode::Inline { ui_height } => ui_height.min(self.term_height),
1287            ScreenMode::InlineAuto {
1288                min_height,
1289                max_height,
1290            } => {
1291                let (min, max) = sanitize_auto_bounds(min_height, max_height);
1292                let max = max.min(self.term_height);
1293                let min = min.min(max);
1294                if let Some(current) = self.auto_ui_height {
1295                    current.clamp(min, max).min(self.term_height).max(min)
1296                } else {
1297                    max.max(min)
1298                }
1299            }
1300            ScreenMode::AltScreen => self.term_height,
1301        }
1302    }
1303
1304    /// Get sanitized min/max bounds for inline auto mode (clamped to terminal height).
1305    pub fn inline_auto_bounds(&self) -> Option<(u16, u16)> {
1306        match self.screen_mode {
1307            ScreenMode::InlineAuto {
1308                min_height,
1309                max_height,
1310            } => {
1311                let (min, max) = sanitize_auto_bounds(min_height, max_height);
1312                Some((min.min(self.term_height), max.min(self.term_height)))
1313            }
1314            _ => None,
1315        }
1316    }
1317
1318    /// Get the cached auto UI height (inline auto mode only).
1319    pub fn auto_ui_height(&self) -> Option<u16> {
1320        match self.screen_mode {
1321            ScreenMode::InlineAuto { .. } => self.auto_ui_height,
1322            _ => None,
1323        }
1324    }
1325
1326    /// Update the computed height for inline auto mode.
1327    pub fn set_auto_ui_height(&mut self, height: u16) {
1328        if let ScreenMode::InlineAuto {
1329            min_height,
1330            max_height,
1331        } = self.screen_mode
1332        {
1333            let (min, max) = sanitize_auto_bounds(min_height, max_height);
1334            let max = max.min(self.term_height);
1335            let min = min.min(max);
1336            let clamped = height.clamp(min, max);
1337            let previous_effective = self.auto_ui_height.unwrap_or(min);
1338            if self.auto_ui_height != Some(clamped) {
1339                self.auto_ui_height = Some(clamped);
1340                if clamped != previous_effective {
1341                    self.stash_displayed_frame();
1342                    self.reset_diff_strategy();
1343                    if self.scroll_region_active {
1344                        let _ = self.deactivate_scroll_region();
1345                    }
1346                }
1347            }
1348        }
1349    }
1350
1351    /// Drop the diff baseline after an inline-auto height change, keeping
1352    /// the displayed frame for repaint until the next present.
1353    fn stash_displayed_frame(&mut self) {
1354        if let Some(prev) = self.prev_buffer.take() {
1355            self.stale_frame = Some(prev);
1356        }
1357    }
1358
1359    /// Clear the cached auto UI height (inline auto mode only).
1360    pub fn clear_auto_ui_height(&mut self) {
1361        if matches!(self.screen_mode, ScreenMode::InlineAuto { .. })
1362            && self.auto_ui_height.is_some()
1363        {
1364            self.auto_ui_height = None;
1365            self.stash_displayed_frame();
1366            self.reset_diff_strategy();
1367            if self.scroll_region_active {
1368                let _ = self.deactivate_scroll_region();
1369            }
1370        }
1371    }
1372
1373    fn effective_ui_height(&self) -> u16 {
1374        match self.screen_mode {
1375            ScreenMode::Inline { ui_height } => ui_height,
1376            ScreenMode::InlineAuto {
1377                min_height,
1378                max_height,
1379            } => {
1380                let (min, max) = sanitize_auto_bounds(min_height, max_height);
1381                let current = self.auto_ui_height.unwrap_or(min);
1382                current.clamp(min, max).min(self.term_height)
1383            }
1384            ScreenMode::AltScreen => self.term_height,
1385        }
1386    }
1387
1388    /// Get the UI height for the current mode.
1389    pub fn ui_height(&self) -> u16 {
1390        self.effective_ui_height()
1391    }
1392
1393    /// Calculate the row where the UI starts (0-indexed).
1394    fn ui_start_row(&self) -> u16 {
1395        let ui_height = self.effective_ui_height().min(self.term_height);
1396        match (self.screen_mode, self.ui_anchor) {
1397            (ScreenMode::Inline { .. }, UiAnchor::Bottom)
1398            | (ScreenMode::InlineAuto { .. }, UiAnchor::Bottom) => {
1399                self.term_height.saturating_sub(ui_height)
1400            }
1401            (ScreenMode::Inline { .. }, UiAnchor::Top)
1402            | (ScreenMode::InlineAuto { .. }, UiAnchor::Top) => 0,
1403            (ScreenMode::AltScreen, _) => 0,
1404        }
1405    }
1406
1407    /// Whether rows are counted from the terminal's last row (see
1408    /// [`Self::move_to_row`]): a bottom-anchored inline UI on the overlay
1409    /// strategy. A DECSTBM region keeps absolute rows; cursor-up there is
1410    /// bounded by the region's margins.
1411    fn bottom_addressed(&self) -> bool {
1412        matches!(self.inline_strategy, InlineStrategy::OverlayRedraw)
1413            && matches!(self.ui_anchor, UiAnchor::Bottom)
1414            && matches!(
1415                self.screen_mode,
1416                ScreenMode::Inline { .. } | ScreenMode::InlineAuto { .. }
1417            )
1418    }
1419
1420    /// Move to `row`, `col` (0-indexed).
1421    ///
1422    /// A bottom-anchored overlay UI always ends at the terminal's last row,
1423    /// so its rows are addressed from that row ([`ansi::cup_from_bottom`]).
1424    /// A multiplexer keeps a pane's bottom rows at the bottom when it is
1425    /// resized (shrinking pushes top rows into history, growing pulls them
1426    /// back), so bytes the terminal reads after a resize this writer has not
1427    /// seen yet still reach the UI's rows. Absolute rows land on log lines
1428    /// instead and erase them for good: in the G42 journey one resize under
1429    /// tmux lost 105 of 100,000 lines and a 50-resize storm about 1,900.
1430    fn move_to_row(&mut self, row: u16, col: u16) -> io::Result<()> {
1431        let bottom = self.bottom_addressed().then_some(self.term_height);
1432        write_row_address(self.writer(), bottom, row, col)
1433    }
1434
1435    /// Bring the displayed bottom-anchored overlay UI back to the last row.
1436    ///
1437    /// From the cursor's known row in the UI, one `CR LF` per UI row below
1438    /// it: where those rows exist this only moves down; where a shrinking
1439    /// multiplexer deleted them (tmux removes the rows below the cursor
1440    /// first, so a visible input cursor above a hint row loses that row),
1441    /// the LFs scroll the screen to make them again. Either way the UI's
1442    /// last row is the screen's last row afterwards, which `move_to_row`
1443    /// relies on; without this the next erase took the newest log line.
1444    fn reanchor_inline_cursor(&mut self) -> io::Result<()> {
1445        if !self.bottom_addressed() {
1446            return Ok(());
1447        }
1448        let Some((row, height)) = self.cursor_ui_row else {
1449            return Ok(());
1450        };
1451        let last = height.saturating_sub(1);
1452        for _ in row..last {
1453            self.writer().write_all(b"\r\n")?;
1454        }
1455        self.cursor_ui_row = Some((last, height));
1456        Ok(())
1457    }
1458
1459    /// Get the inline mode rendering strategy.
1460    pub fn inline_strategy(&self) -> InlineStrategy {
1461        self.inline_strategy
1462    }
1463
1464    /// Check if a scroll region is currently active.
1465    pub fn scroll_region_active(&self) -> bool {
1466        self.scroll_region_active
1467    }
1468
1469    /// Overlay log lines dropped because the queue reached its bound (1,024
1470    /// lines or 256 KiB) while no row above the UI was free to stream them;
1471    /// the oldest lines go first.
1472    pub fn dropped_log_lines(&self) -> u64 {
1473        self.dropped_log_lines
1474    }
1475
1476    /// Whether overlay log text is waiting for the next stream.
1477    #[cfg(feature = "render-thread")]
1478    pub(crate) fn has_pending_logs(&self) -> bool {
1479        !self.pending_logs.is_empty()
1480    }
1481
1482    /// The DECSTBM self-test verdict recorded by
1483    /// [`Self::set_scroll_region_verified`] (`None`: not run).
1484    pub fn scroll_region_verified(&self) -> Option<bool> {
1485        self.scroll_region_verified
1486    }
1487
1488    /// The strategy fallback the self-test forced, if any.
1489    pub fn strategy_fallback(&self) -> Option<&InlineStrategyFallback> {
1490        self.strategy_fallback.as_ref()
1491    }
1492
1493    /// Record the DECSTBM self-test verdict
1494    /// (`ftui_core::caps_probe::probe_scroll_region`), taken by the runtime
1495    /// at construction time before the input reader starts. A negative
1496    /// verdict while the strategy is `ScrollRegion` or `Hybrid` switches the
1497    /// writer to `OverlayRedraw` before its first frame, so a terminal that
1498    /// ignores DECSTBM never scrolls the whole screen into the UI; the
1499    /// fallback is exported as an `inline_strategy_fallback` evidence row
1500    /// when a sink attaches. `None` leaves the strategy as selected.
1501    pub fn set_scroll_region_verified(
1502        &mut self,
1503        verdict: Option<ftui_core::caps_probe::ScrollRegionVerdict>,
1504        rows: u16,
1505        region_bottom: u16,
1506    ) {
1507        let Some(verdict) = verdict else {
1508            self.scroll_region_verified = None;
1509            return;
1510        };
1511        self.scroll_region_verified = Some(verdict.honoured());
1512        if verdict.honoured() {
1513            return;
1514        }
1515        let from = self.inline_strategy;
1516        if !matches!(from, InlineStrategy::ScrollRegion | InlineStrategy::Hybrid) {
1517            return;
1518        }
1519        self.inline_strategy = InlineStrategy::OverlayRedraw;
1520        if self.scroll_region_active {
1521            let _ = self.deactivate_scroll_region();
1522        }
1523        let fallback = InlineStrategyFallback {
1524            from,
1525            reason: verdict.fallback_reason().unwrap_or("cpr_mismatch"),
1526            observed_row: verdict.observed_row(),
1527            expected_row: region_bottom,
1528            rows,
1529            region_bottom,
1530        };
1531        tracing::warn!(
1532            target: crate::telemetry_schema::span::RENDER_SCROLL_REGION,
1533            from = inline_strategy_str(from),
1534            to = "overlay_redraw",
1535            reason = fallback.reason,
1536            observed_row = ?fallback.observed_row,
1537            expected_row = fallback.expected_row,
1538            rows,
1539            "DECSTBM self-test failed: inline strategy falls back to overlay redraw"
1540        );
1541        if let Some(sink) = self.evidence_sink.as_ref() {
1542            let _ = sink.write_jsonl(&fallback.to_jsonl());
1543            self.strategy_fallback = None;
1544        } else {
1545            self.strategy_fallback = Some(fallback);
1546        }
1547    }
1548
1549    /// Activate the scroll region for inline mode.
1550    ///
1551    /// Sets DECSTBM to constrain scrolling to the log region:
1552    /// - Bottom-anchored UI: log region is above the UI.
1553    /// - Top-anchored UI: log region is below the UI.
1554    ///
1555    /// Only called when the strategy permits scroll-region usage.
1556    fn activate_scroll_region(&mut self, ui_height: u16) -> io::Result<()> {
1557        if self.scroll_region_active {
1558            return Ok(());
1559        }
1560
1561        let ui_height = ui_height.min(self.term_height);
1562        if self.term_height.saturating_sub(ui_height) < 2 {
1563            // DECSTBM requires top < bottom. A one-row log area must use
1564            // overlay writes; treating a rejected region as active would
1565            // allow an ordinary LF to scroll the entire screen.
1566            return Ok(());
1567        }
1568
1569        match self.ui_anchor {
1570            UiAnchor::Bottom => {
1571                let term_height = self.term_height;
1572                let log_bottom = term_height.saturating_sub(ui_height);
1573                if log_bottom > 0 {
1574                    // DECSTBM: set scroll region to rows 1..log_bottom (1-indexed)
1575                    write!(self.writer(), "\x1b[1;{}r", log_bottom)?;
1576                    self.scroll_region_active = true;
1577                }
1578            }
1579            UiAnchor::Top => {
1580                let term_height = self.term_height;
1581                let log_top = ui_height.saturating_add(1);
1582                if log_top <= term_height {
1583                    // DECSTBM: set scroll region to rows log_top..term_height (1-indexed)
1584                    write!(self.writer(), "\x1b[{};{}r", log_top, term_height)?;
1585                    self.scroll_region_active = true;
1586                    // DECSTBM moves cursor to home; for top-anchored UI we move it
1587                    // into the log region so any subsequent output stays below UI.
1588                    write!(self.writer(), "\x1b[{};1H", log_top)?;
1589                }
1590            }
1591        }
1592        Ok(())
1593    }
1594
1595    /// Deactivate the scroll region, resetting to full screen.
1596    ///
1597    /// `CSI r` homes the hardware cursor to `(0, 0)`; when called outside a
1598    /// `present_inline` save/restore bracket (e.g. on resize), preserve the
1599    /// cursor so a subsequent terminal shrink does not truncate rows below
1600    /// `(0, 0)`.
1601    fn deactivate_scroll_region(&mut self) -> io::Result<()> {
1602        if self.scroll_region_active {
1603            if self.cursor_saved {
1604                self.writer().write_all(b"\x1b[r")?;
1605            } else {
1606                self.writer().write_all(CURSOR_SAVE)?;
1607                let reset_res = self.writer().write_all(b"\x1b[r");
1608                let restore_res = self.writer().write_all(CURSOR_RESTORE);
1609                reset_res?;
1610                restore_res?;
1611            }
1612            self.scroll_region_active = false;
1613        }
1614        Ok(())
1615    }
1616
1617    fn clear_rows(&mut self, start_row: u16, height: u16) -> io::Result<()> {
1618        let start_row = start_row.min(self.term_height);
1619        let end_row = start_row.saturating_add(height).min(self.term_height);
1620        if start_row >= end_row {
1621            return Ok(());
1622        }
1623
1624        // Ensure erase operations clear to the terminal default background.
1625        // Without this, stale background fills can persist when inline regions shrink.
1626        self.writer().write_all(SGR_BG_DEFAULT)?;
1627        for row in start_row..end_row {
1628            self.move_to_row(row, 0)?;
1629            self.writer().write_all(ERASE_LINE)?;
1630        }
1631        Ok(())
1632    }
1633
1634    fn clear_inline_region_diff(&mut self, current: InlineRegion) -> io::Result<()> {
1635        let Some(previous) = self.last_inline_region else {
1636            return Ok(());
1637        };
1638
1639        let prev_start = previous.start.min(self.term_height);
1640        let prev_end = previous
1641            .start
1642            .saturating_add(previous.height)
1643            .min(self.term_height);
1644        if prev_start >= prev_end {
1645            return Ok(());
1646        }
1647
1648        let curr_start = current.start.min(self.term_height);
1649        let curr_end = current
1650            .start
1651            .saturating_add(current.height)
1652            .min(self.term_height);
1653
1654        if curr_start > prev_start {
1655            let clear_end = curr_start.min(prev_end);
1656            if clear_end > prev_start {
1657                self.clear_rows(prev_start, clear_end - prev_start)?;
1658                if matches!(self.ui_anchor, UiAnchor::Bottom) {
1659                    self.decstbm_row_occupied = false;
1660                    self.decstbm_col = 0;
1661                }
1662            }
1663        }
1664
1665        if curr_end < prev_end {
1666            let clear_start = curr_end.max(prev_start);
1667            if prev_end > clear_start {
1668                self.clear_rows(clear_start, prev_end - clear_start)?;
1669            }
1670        }
1671
1672        Ok(())
1673    }
1674
1675    /// Present a UI frame.
1676    ///
1677    /// In inline mode, this:
1678    /// 1. Begins synchronized output (if supported)
1679    /// 2. Saves cursor position
1680    /// 3. Moves to UI region and clears it
1681    /// 4. Renders the buffer using the presenter
1682    /// 5. Restores cursor position
1683    /// 6. Moves cursor to requested UI position (if any)
1684    /// 7. Applies cursor visibility
1685    /// 8. Ends synchronized output
1686    ///
1687    /// In AltScreen mode, this just renders the buffer and positions cursor.
1688    pub fn present_ui(
1689        &mut self,
1690        buffer: &Buffer,
1691        cursor: Option<(u16, u16)>,
1692        cursor_visible: bool,
1693    ) -> io::Result<()> {
1694        // One-writer discipline vs the signal/panic teardown paths
1695        // (bd-kdn7n item 2): the whole frame is one emission batch.
1696        let _output_guard = terminal_output_lock();
1697        let mode_str = match self.screen_mode {
1698            ScreenMode::Inline { .. } => "inline",
1699            ScreenMode::InlineAuto { .. } => "inline_auto",
1700            ScreenMode::AltScreen => "altscreen",
1701        };
1702        let trace_enabled = self.render_trace.is_some();
1703        if trace_enabled {
1704            self.writer().reset_counter();
1705        }
1706        let present_start = if trace_enabled {
1707            Some(Instant::now())
1708        } else {
1709            None
1710        };
1711        let _span = info_span!(
1712            crate::telemetry_schema::span::RENDER_PRESENT,
1713            mode = mode_str,
1714            width = buffer.width(),
1715            height = buffer.height(),
1716        )
1717        .entered();
1718
1719        let result = match self.screen_mode {
1720            ScreenMode::Inline { ui_height } => {
1721                self.present_inline(buffer, ui_height, cursor, cursor_visible)
1722            }
1723            ScreenMode::InlineAuto { .. } => {
1724                let ui_height = self.effective_ui_height();
1725                self.present_inline(buffer, ui_height, cursor, cursor_visible)
1726            }
1727            ScreenMode::AltScreen => self.present_altscreen(buffer, cursor, cursor_visible),
1728        };
1729
1730        let present_us = present_start.map(|start| start.elapsed().as_micros() as u64);
1731        let present_bytes = if trace_enabled {
1732            {
1733                let w = self.writer();
1734                let count = w.bytes_written();
1735                w.reset_counter();
1736                Some(count)
1737            }
1738        } else {
1739            None
1740        };
1741        if trace_enabled {
1742            // No-op: ftui_render::CountingWriter always counts; reset happens in take above.
1743        }
1744
1745        if let Ok(stats) = result {
1746            self.record_successful_present(stats.diff_strategy);
1747            // 3-buffer rotation: reuse clone_buf's allocation to avoid per-frame alloc.
1748            // Only advance the diff baseline after a successful present. If a write
1749            // failed partway through, the terminal state is unknown; the error path
1750            // below invalidates the baseline so the next frame physically repaints.
1751            let new_prev = match self.clone_buf.take() {
1752                Some(mut buf)
1753                    if buf.width() == buffer.width() && buf.height() == buffer.height() =>
1754                {
1755                    buf.clone_from(buffer);
1756                    buf
1757                }
1758                _ => buffer.clone(),
1759            };
1760            self.clone_buf = self.spare_buffer.take();
1761            self.spare_buffer = self.prev_buffer.take();
1762            self.prev_buffer = Some(new_prev);
1763
1764            if let Some(ref mut trace) = self.render_trace {
1765                let payload_info = match stats.diff_strategy {
1766                    DiffStrategy::FullRedraw => {
1767                        let payload = build_full_buffer_payload(buffer, &self.pool);
1768                        trace.write_payload(&payload).ok()
1769                    }
1770                    _ => {
1771                        let payload =
1772                            build_diff_runs_payload(buffer, &self.diff_scratch, &self.pool);
1773                        trace.write_payload(&payload).ok()
1774                    }
1775                };
1776                let (payload_kind, payload_path) = match payload_info {
1777                    Some(info) => (info.kind, Some(info.path)),
1778                    None => ("none", None),
1779                };
1780                let payload_path_ref = payload_path.as_deref();
1781                let diff_strategy = diff_strategy_str(stats.diff_strategy);
1782                let ui_anchor = ui_anchor_str(self.ui_anchor);
1783                let frame = RenderTraceFrame {
1784                    cols: buffer.width(),
1785                    rows: buffer.height(),
1786                    mode: mode_str,
1787                    ui_height: stats.ui_height,
1788                    ui_anchor,
1789                    diff_strategy,
1790                    diff_cells: stats.diff_cells,
1791                    diff_runs: stats.diff_runs,
1792                    present_bytes: present_bytes.unwrap_or(0),
1793                    render_us: None,
1794                    present_us,
1795                    payload_kind,
1796                    payload_path: payload_path_ref,
1797                    trace_us: None,
1798                };
1799                let _ = trace.record_frame(frame, buffer, &self.pool);
1800            }
1801            return Ok(());
1802        }
1803
1804        self.invalidate_after_present_error();
1805        result.map(|_| ())
1806    }
1807
1808    /// Present a UI frame, taking ownership of the buffer (O(1) — no clone).
1809    ///
1810    /// Prefer this over `present_ui` when the caller has an owned buffer
1811    /// that won't be reused, as it avoids an O(width × height) clone.
1812    pub fn present_ui_owned(
1813        &mut self,
1814        buffer: Buffer,
1815        cursor: Option<(u16, u16)>,
1816        cursor_visible: bool,
1817    ) -> io::Result<()> {
1818        // One-writer discipline vs teardown paths (bd-kdn7n item 2).
1819        let _output_guard = terminal_output_lock();
1820        let mode_str = match self.screen_mode {
1821            ScreenMode::Inline { .. } => "inline",
1822            ScreenMode::InlineAuto { .. } => "inline_auto",
1823            ScreenMode::AltScreen => "altscreen",
1824        };
1825        let trace_enabled = self.render_trace.is_some();
1826        if trace_enabled {
1827            self.writer().reset_counter();
1828        }
1829        let present_start = if trace_enabled {
1830            Some(Instant::now())
1831        } else {
1832            None
1833        };
1834        let _span = info_span!(
1835            crate::telemetry_schema::span::RENDER_PRESENT,
1836            mode = mode_str,
1837            width = buffer.width(),
1838            height = buffer.height(),
1839        )
1840        .entered();
1841
1842        let result = match self.screen_mode {
1843            ScreenMode::Inline { ui_height } => {
1844                self.present_inline(&buffer, ui_height, cursor, cursor_visible)
1845            }
1846            ScreenMode::InlineAuto { .. } => {
1847                let ui_height = self.effective_ui_height();
1848                self.present_inline(&buffer, ui_height, cursor, cursor_visible)
1849            }
1850            ScreenMode::AltScreen => self.present_altscreen(&buffer, cursor, cursor_visible),
1851        };
1852
1853        let present_us = present_start.map(|start| start.elapsed().as_micros() as u64);
1854        let present_bytes = if trace_enabled {
1855            {
1856                let w = self.writer();
1857                let count = w.bytes_written();
1858                w.reset_counter();
1859                Some(count)
1860            }
1861        } else {
1862            None
1863        };
1864        if trace_enabled {
1865            // No-op: ftui_render::CountingWriter always counts; reset happens in take above.
1866        }
1867
1868        if let Ok(stats) = result {
1869            self.record_successful_present(stats.diff_strategy);
1870            if let Some(ref mut trace) = self.render_trace {
1871                let payload_info = match stats.diff_strategy {
1872                    DiffStrategy::FullRedraw => {
1873                        let payload = build_full_buffer_payload(&buffer, &self.pool);
1874                        trace.write_payload(&payload).ok()
1875                    }
1876                    _ => {
1877                        let payload =
1878                            build_diff_runs_payload(&buffer, &self.diff_scratch, &self.pool);
1879                        trace.write_payload(&payload).ok()
1880                    }
1881                };
1882                let (payload_kind, payload_path) = match payload_info {
1883                    Some(info) => (info.kind, Some(info.path)),
1884                    None => ("none", None),
1885                };
1886                let payload_path_ref = payload_path.as_deref();
1887                let diff_strategy = diff_strategy_str(stats.diff_strategy);
1888                let ui_anchor = ui_anchor_str(self.ui_anchor);
1889                let frame = RenderTraceFrame {
1890                    cols: buffer.width(),
1891                    rows: buffer.height(),
1892                    mode: mode_str,
1893                    ui_height: stats.ui_height,
1894                    ui_anchor,
1895                    diff_strategy,
1896                    diff_cells: stats.diff_cells,
1897                    diff_runs: stats.diff_runs,
1898                    present_bytes: present_bytes.unwrap_or(0),
1899                    render_us: None,
1900                    present_us,
1901                    payload_kind,
1902                    payload_path: payload_path_ref,
1903                    trace_us: None,
1904                };
1905                let _ = trace.record_frame(frame, &buffer, &self.pool);
1906            }
1907
1908            // 3-buffer rotation: keep clone_buf populated for present_ui path.
1909            self.clone_buf = self.spare_buffer.take();
1910            self.spare_buffer = self.prev_buffer.take();
1911            self.prev_buffer = Some(buffer);
1912            return Ok(());
1913        }
1914
1915        self.invalidate_after_present_error();
1916        result.map(|_| ())
1917    }
1918
1919    fn decide_diff(&mut self, buffer: &Buffer) -> DiffDecision {
1920        let prev_dims = self
1921            .prev_buffer
1922            .as_ref()
1923            .map(|prev| (prev.width(), prev.height()));
1924        if prev_dims.is_none() || prev_dims != Some((buffer.width(), buffer.height())) {
1925            self.full_redraw_probe = 0;
1926            self.last_diff_strategy = Some(DiffStrategy::FullRedraw);
1927            self.last_certificate = Some(evaluate_render_certificate_for_buffers(
1928                self.prev_buffer.as_ref(),
1929                buffer,
1930                false,
1931            ));
1932            return DiffDecision {
1933                strategy: DiffStrategy::FullRedraw,
1934                has_diff: false,
1935            };
1936        }
1937
1938        if self.full_redraw_interval_due() {
1939            self.full_redraw_probe = 0;
1940            self.last_diff_strategy = Some(DiffStrategy::FullRedraw);
1941            self.last_certificate = Some(evaluate_render_certificate_for_buffers(
1942                self.prev_buffer.as_ref(),
1943                buffer,
1944                true,
1945            ));
1946            return DiffDecision {
1947                strategy: DiffStrategy::FullRedraw,
1948                has_diff: false,
1949            };
1950        }
1951
1952        let dirty_rows = buffer.dirty_row_count();
1953        let width = buffer.width() as usize;
1954        let height = buffer.height() as usize;
1955        let mut span_stats_snapshot: Option<DirtySpanStats> = None;
1956        let mut dirty_scan_cells_estimate = dirty_rows.saturating_mul(width);
1957
1958        if self.diff_config.bayesian_enabled {
1959            let span_stats = buffer.dirty_span_stats();
1960            if span_stats.span_coverage_cells > 0 {
1961                dirty_scan_cells_estimate = span_stats.span_coverage_cells;
1962            }
1963            span_stats_snapshot = Some(span_stats);
1964        }
1965
1966        // Select strategy based on config
1967        let mut strategy = if self.diff_config.bayesian_enabled {
1968            // Use Bayesian selector
1969            self.diff_strategy.select_with_scan_estimate(
1970                buffer.width(),
1971                buffer.height(),
1972                dirty_rows,
1973                dirty_scan_cells_estimate,
1974            )
1975        } else {
1976            // Simple heuristic: use DirtyRows if few rows dirty, else Full
1977            if self.diff_config.dirty_rows_enabled && dirty_rows < buffer.height() as usize {
1978                DiffStrategy::DirtyRows
1979            } else {
1980                DiffStrategy::Full
1981            }
1982        };
1983
1984        // Enforce dirty_rows_enabled toggle
1985        if !self.diff_config.dirty_rows_enabled && strategy == DiffStrategy::DirtyRows {
1986            strategy = DiffStrategy::Full;
1987            if self.diff_config.bayesian_enabled {
1988                self.diff_strategy
1989                    .override_last_strategy(strategy, "dirty_rows_disabled");
1990            }
1991        }
1992
1993        // Periodic probe when FullRedraw is selected (to update posterior)
1994        if strategy == DiffStrategy::FullRedraw {
1995            if self.full_redraw_probe >= FULL_REDRAW_PROBE_INTERVAL {
1996                self.full_redraw_probe = 0;
1997                let probed = if self.diff_config.dirty_rows_enabled
1998                    && dirty_rows < buffer.height() as usize
1999                {
2000                    DiffStrategy::DirtyRows
2001                } else {
2002                    DiffStrategy::Full
2003                };
2004                if probed != strategy {
2005                    strategy = probed;
2006                    if self.diff_config.bayesian_enabled {
2007                        self.diff_strategy
2008                            .override_last_strategy(strategy, "full_redraw_probe");
2009                    }
2010                }
2011            } else {
2012                self.full_redraw_probe = self.full_redraw_probe.saturating_add(1);
2013            }
2014        } else {
2015            self.full_redraw_probe = 0;
2016        }
2017
2018        let mut has_diff = false;
2019        match strategy {
2020            DiffStrategy::Full => {
2021                let prev = self.prev_buffer.as_ref().expect("prev buffer must exist");
2022                self.diff_scratch.compute_into(prev, buffer);
2023                self.last_certificate = Some(RenderCertificate {
2024                    level: RenderCertificateLevel::FullRequired,
2025                    causes: vec!["strategy-selected-full"],
2026                    dirty_rows: Vec::new(),
2027                    fell_back: false,
2028                });
2029                has_diff = true;
2030            }
2031            DiffStrategy::DirtyRows => {
2032                let prev = self.prev_buffer.as_ref().expect("prev buffer must exist");
2033                if self.diff_config.certified_skips {
2034                    let certificate =
2035                        evaluate_render_certificate_for_buffers(Some(prev), buffer, false);
2036                    self.diff_scratch
2037                        .compute_certified_into(prev, buffer, certificate.to_hint());
2038                    self.last_certificate = Some(certificate);
2039                } else {
2040                    self.diff_scratch.compute_dirty_into(prev, buffer);
2041                    self.last_certificate = None;
2042                }
2043                has_diff = true;
2044            }
2045            DiffStrategy::FullRedraw => {}
2046        }
2047
2048        let mut scan_cost_estimate = 0usize;
2049        let mut fallback_reason: &'static str = "none";
2050        let tile_stats = if strategy == DiffStrategy::DirtyRows {
2051            self.diff_scratch.last_tile_stats()
2052        } else {
2053            None
2054        };
2055
2056        // Update posterior if Bayesian mode is enabled
2057        if self.diff_config.bayesian_enabled && has_diff {
2058            let span_stats = span_stats_snapshot.unwrap_or_else(|| buffer.dirty_span_stats());
2059            let (scan_cost, reason) = if self
2060                .last_certificate
2061                .as_ref()
2062                .is_some_and(|cert| cert.fell_back)
2063            {
2064                (
2065                    self.diff_scratch.last_scanned_cells(),
2066                    "certificate_fallback",
2067                )
2068            } else {
2069                estimate_diff_scan_cost(
2070                    strategy,
2071                    dirty_rows,
2072                    width,
2073                    height,
2074                    &span_stats,
2075                    tile_stats,
2076                )
2077            };
2078            let scanned_cells = scan_cost.max(self.diff_scratch.len());
2079            self.diff_strategy
2080                .observe(scanned_cells, self.diff_scratch.len());
2081            span_stats_snapshot = Some(span_stats);
2082            scan_cost_estimate = scan_cost;
2083            fallback_reason = reason;
2084        }
2085
2086        if let Some(evidence) = self.diff_strategy.last_evidence() {
2087            let span_stats = span_stats_snapshot.unwrap_or_else(|| buffer.dirty_span_stats());
2088            let (scan_cost, reason) = if span_stats_snapshot.is_some() {
2089                (scan_cost_estimate, fallback_reason)
2090            } else {
2091                estimate_diff_scan_cost(
2092                    strategy,
2093                    dirty_rows,
2094                    width,
2095                    height,
2096                    &span_stats,
2097                    tile_stats,
2098                )
2099            };
2100            let span_coverage_pct = if evidence.total_cells == 0 {
2101                0.0
2102            } else {
2103                (span_stats.span_coverage_cells as f64 / evidence.total_cells as f64) * 100.0
2104            };
2105            let span_count = span_stats.total_spans;
2106            let max_span_len = span_stats.max_span_len;
2107            let event_idx = self.diff_evidence_idx;
2108            self.diff_evidence_idx = self.diff_evidence_idx.saturating_add(1);
2109            let tile_used = tile_stats.is_some_and(|stats| stats.fallback.is_none());
2110            let tile_fallback = tile_stats
2111                .and_then(|stats| stats.fallback)
2112                .map(TileDiffFallback::as_str)
2113                .unwrap_or("none");
2114            let run_id = json_escape(&self.diff_evidence_run_id);
2115            let strategy_json = json_escape(&strategy.to_string());
2116            let guard_reason_json = json_escape(evidence.guard_reason);
2117            let fallback_reason_json = json_escape(reason);
2118            let tile_fallback_json = json_escape(tile_fallback);
2119            let schema_version = crate::evidence_sink::EVIDENCE_SCHEMA_VERSION;
2120            let screen_mode = match self.screen_mode {
2121                ScreenMode::Inline { .. } => "inline",
2122                ScreenMode::InlineAuto { .. } => "inline_auto",
2123                ScreenMode::AltScreen => "altscreen",
2124            };
2125            let (
2126                tile_w,
2127                tile_h,
2128                tiles_x,
2129                tiles_y,
2130                dirty_tiles,
2131                dirty_cells,
2132                dirty_tile_ratio,
2133                dirty_cell_ratio,
2134                scanned_tiles,
2135                skipped_tiles,
2136                scan_cells_estimate,
2137                sat_build_cells,
2138                skipped_tile_rows,
2139                sat_queries,
2140            ) = if let Some(stats) = tile_stats {
2141                (
2142                    stats.tile_w,
2143                    stats.tile_h,
2144                    stats.tiles_x,
2145                    stats.tiles_y,
2146                    stats.dirty_tiles,
2147                    stats.dirty_cells,
2148                    stats.dirty_tile_ratio,
2149                    stats.dirty_cell_ratio,
2150                    stats.scanned_tiles,
2151                    stats.skipped_tiles,
2152                    stats.scan_cells_estimate,
2153                    stats.sat_build_cells,
2154                    stats.skipped_tile_rows,
2155                    stats.sat_queries,
2156                )
2157            } else {
2158                let cell_ratio = if evidence.total_cells > 0 {
2159                    self.diff_scratch.len() as f64 / evidence.total_cells as f64
2160                } else {
2161                    0.0
2162                };
2163                (0, 0, 0, 0, 0, 0, 0.0, cell_ratio, 0, 0, 0, 0, 0, 0)
2164            };
2165            let tile_size = tile_w as usize * tile_h as usize;
2166            let dirty_tile_count = dirty_tiles;
2167            let skipped_tile_count = skipped_tiles;
2168            let sat_build_cost_est = sat_build_cells;
2169
2170            set_diff_snapshot(Some(DiffDecisionSnapshot {
2171                event_idx,
2172                screen_mode: screen_mode.to_string(),
2173                cols: u16::try_from(width).unwrap_or(u16::MAX),
2174                rows: u16::try_from(height).unwrap_or(u16::MAX),
2175                evidence: evidence.clone(),
2176                span_count,
2177                span_coverage_pct,
2178                max_span_len,
2179                scan_cost_estimate: scan_cost,
2180                fallback_reason: reason.to_string(),
2181                tile_used,
2182                tile_fallback: tile_fallback.to_string(),
2183                strategy_used: strategy,
2184            }));
2185
2186            let current_regime = DiffRegime::classify(strategy, dirty_cell_ratio);
2187
2188            trace!(
2189                strategy = %strategy,
2190                selected = %evidence.strategy,
2191                cost_full = evidence.cost_full,
2192                cost_dirty = evidence.cost_dirty,
2193                cost_redraw = evidence.cost_redraw,
2194                dirty_rows = evidence.dirty_rows,
2195                total_rows = evidence.total_rows,
2196                total_cells = evidence.total_cells,
2197                bayesian_enabled = self.diff_config.bayesian_enabled,
2198                dirty_rows_enabled = self.diff_config.dirty_rows_enabled,
2199                regime = %current_regime.as_str(),
2200                "diff strategy selected"
2201            );
2202            if let Some(ref sink) = self.evidence_sink {
2203                let line = format!(
2204                    r#"{{"schema_version":"{}","event":"diff_decision","run_id":"{}","event_idx":{},"screen_mode":"{}","cols":{},"rows":{},"strategy":"{}","cost_full":{:.6},"cost_dirty":{:.6},"cost_redraw":{:.6},"posterior_mean":{:.6},"posterior_variance":{:.6},"alpha":{:.6},"beta":{:.6},"guard_reason":"{}","hysteresis_applied":{},"hysteresis_ratio":{:.6},"dirty_rows":{},"total_rows":{},"total_cells":{},"span_count":{},"span_coverage_pct":{:.6},"max_span_len":{},"fallback_reason":"{}","scan_cost_estimate":{},"tile_used":{},"tile_fallback":"{}","tile_w":{},"tile_h":{},"tile_size":{},"tiles_x":{},"tiles_y":{},"dirty_tiles":{},"dirty_tile_count":{},"dirty_cells":{},"dirty_tile_ratio":{:.6},"dirty_cell_ratio":{:.6},"scanned_tiles":{},"skipped_tiles":{},"skipped_tile_count":{},"tile_scan_cells_estimate":{},"sat_build_cost_est":{},"skipped_tile_rows":{},"sat_queries":{},"bayesian_enabled":{},"dirty_rows_enabled":{},"regime":"{}"}}"#,
2205                    schema_version,
2206                    run_id,
2207                    event_idx,
2208                    screen_mode,
2209                    width,
2210                    height,
2211                    strategy_json,
2212                    evidence.cost_full,
2213                    evidence.cost_dirty,
2214                    evidence.cost_redraw,
2215                    evidence.posterior_mean,
2216                    evidence.posterior_variance,
2217                    evidence.alpha,
2218                    evidence.beta,
2219                    guard_reason_json,
2220                    evidence.hysteresis_applied,
2221                    evidence.hysteresis_ratio,
2222                    evidence.dirty_rows,
2223                    evidence.total_rows,
2224                    evidence.total_cells,
2225                    span_count,
2226                    span_coverage_pct,
2227                    max_span_len,
2228                    fallback_reason_json,
2229                    scan_cost,
2230                    tile_used,
2231                    tile_fallback_json,
2232                    tile_w,
2233                    tile_h,
2234                    tile_size,
2235                    tiles_x,
2236                    tiles_y,
2237                    dirty_tiles,
2238                    dirty_tile_count,
2239                    dirty_cells,
2240                    dirty_tile_ratio,
2241                    dirty_cell_ratio,
2242                    scanned_tiles,
2243                    skipped_tiles,
2244                    skipped_tile_count,
2245                    scan_cells_estimate,
2246                    sat_build_cost_est,
2247                    skipped_tile_rows,
2248                    sat_queries,
2249                    self.diff_config.bayesian_enabled,
2250                    self.diff_config.dirty_rows_enabled,
2251                    current_regime.as_str(),
2252                );
2253                let _ = sink.write_jsonl(&line);
2254            }
2255
2256            if current_regime != self.diff_regime {
2257                let transition_event_idx = self.diff_evidence_idx;
2258                self.diff_evidence_idx = self.diff_evidence_idx.saturating_add(1);
2259                if let Some(ref sink) = self.evidence_sink {
2260                    let transition_line = format!(
2261                        r#"{{"schema_version":"{}","event":"diff_regime_transition","run_id":"{}","event_idx":{},"from":"{}","to":"{}","frames_in_previous":{},"strategy":"{}","dirty_cell_ratio":{:.6}}}"#,
2262                        schema_version,
2263                        run_id,
2264                        transition_event_idx,
2265                        self.diff_regime.as_str(),
2266                        current_regime.as_str(),
2267                        self.diff_regime_frames,
2268                        strategy_json,
2269                        dirty_cell_ratio,
2270                    );
2271                    let _ = sink.write_jsonl(&transition_line);
2272                }
2273                self.diff_regime = current_regime;
2274                self.diff_regime_frames = 1;
2275            } else {
2276                self.diff_regime_frames = self.diff_regime_frames.saturating_add(1);
2277            }
2278        }
2279
2280        // Emit the explicit skip certificate alongside the diff decision so
2281        // operators can see WHY work was skipped or performed (bd-6b9nr).
2282        if let Some(ref certificate) = self.last_certificate
2283            && let Some(ref sink) = self.evidence_sink
2284        {
2285            let line = format!(
2286                r#"{{"event":"certificate_decision","run_id":"{}","event_idx":{},"strategy":"{:?}","certificate":{}}}"#,
2287                self.diff_evidence_run_id,
2288                self.diff_evidence_idx,
2289                strategy,
2290                certificate.to_evidence_json()
2291            );
2292            let _ = sink.write_jsonl(&line);
2293        }
2294
2295        self.last_diff_strategy = Some(strategy);
2296        DiffDecision { strategy, has_diff }
2297    }
2298
2299    fn full_redraw_interval_due(&self) -> bool {
2300        // Frame-count bound: resync after N rendered incremental frames.
2301        let frame_due = self.diff_config.full_redraw_interval_frames > 0
2302            && self.frames_since_full_redraw >= self.diff_config.full_redraw_interval_frames;
2303        // Wall-clock bound: resync after the configured elapsed time regardless
2304        // of how many frames have rendered. This is what bounds terminal-state
2305        // desync (diff corruption, mux pane swap, reattach) on a sparsely- or
2306        // idly-rendering TUI, where the frame counter advances too slowly. A
2307        // missing `last_full_redraw_at` (no full redraw presented yet) is
2308        // treated as due so the first eligible frame resynchronizes.
2309        let time_due = self
2310            .diff_config
2311            .full_redraw_max_interval
2312            .is_some_and(|interval| {
2313                self.last_full_redraw_at
2314                    .is_none_or(|at| at.elapsed() >= interval)
2315            });
2316        frame_due || time_due
2317    }
2318
2319    fn record_successful_present(&mut self, strategy: DiffStrategy) {
2320        if strategy == DiffStrategy::FullRedraw {
2321            self.frames_since_full_redraw = 0;
2322            // Anchor the wall-clock resync window to this physical full redraw.
2323            if self.diff_config.full_redraw_max_interval.is_some() {
2324                self.last_full_redraw_at = Some(Instant::now());
2325            }
2326        } else {
2327            self.frames_since_full_redraw = self.frames_since_full_redraw.saturating_add(1);
2328        }
2329    }
2330
2331    fn invalidate_after_present_error(&mut self) {
2332        self.prev_buffer = None;
2333        self.stale_frame = None;
2334        self.log_floor = None;
2335        self.last_inline_region = None;
2336        self.cursor_ui_row = None;
2337        self.reset_diff_strategy();
2338    }
2339
2340    /// Drop the diff baseline so the next present rewrites every cell, for a
2341    /// caller that knows the screen no longer matches what was presented.
2342    pub(crate) fn invalidate_diff_baseline(&mut self) {
2343        self.prev_buffer = None;
2344        self.reset_diff_strategy();
2345    }
2346
2347    /// Whether the cursor was last left visible (best-effort).
2348    pub(crate) const fn cursor_visible(&self) -> bool {
2349        self.cursor_visible
2350    }
2351
2352    /// Present UI in inline mode with cursor save/restore.
2353    ///
2354    /// When the scroll-region strategy is active, DECSTBM is set to constrain
2355    /// log scrolling to the region above the UI. This prevents log output from
2356    /// overwriting the UI, reducing redraw work.
2357    fn present_inline(
2358        &mut self,
2359        buffer: &Buffer,
2360        ui_height: u16,
2361        cursor: Option<(u16, u16)>,
2362        cursor_visible: bool,
2363    ) -> io::Result<FrameEmitStats> {
2364        let sync_output_enabled = self.capabilities.use_sync_output();
2365        let render_mode = inline_strategy_str(self.inline_strategy);
2366        let _inline_span = info_span!(
2367            "inline.render",
2368            inline_height = ui_height,
2369            scrollback_preserved = tracing::field::Empty,
2370            render_mode,
2371        )
2372        .entered();
2373
2374        let result = (|| -> io::Result<FrameEmitStats> {
2375            let visible_height = ui_height.min(self.term_height);
2376            let ui_y_start = self.ui_start_row();
2377            let current_region = InlineRegion {
2378                start: ui_y_start,
2379                height: visible_height,
2380            };
2381
2382            // Begin sync output if available
2383            if sync_output_enabled && !self.in_sync_block {
2384                // Mark active before write so cleanup paths conservatively emit
2385                // SYNC_END even if the begin write fails after partial bytes.
2386                self.in_sync_block = true;
2387                if let Err(err) = self.writer().write_all(SYNC_BEGIN) {
2388                    // Attempt immediate close to avoid leaving the terminal in a
2389                    // potentially open synchronized-output state.
2390                    let _ = self.writer().write_all(SYNC_END);
2391                    self.in_sync_block = false;
2392                    let _ = self.writer().flush();
2393                    return Err(err);
2394                }
2395            }
2396
2397            // G48, before anything else moves the cursor: put the displayed
2398            // UI back on the last row if a resize took rows below the cursor,
2399            // make room for the UI below the shell's last line (first inline
2400            // output only), stream batched overlay logs into scrollback, and
2401            // scroll for a grown UI so the rows it now needs are vacated, not
2402            // drawn over.
2403            self.reanchor_inline_cursor()?;
2404            if visible_height > 0 {
2405                self.reserve_inline_rows(visible_height)?;
2406            }
2407            if self.flush_pending_logs(false)? {
2408                // The UI rows were vacated: no on-screen baseline remains.
2409                self.prev_buffer = None;
2410            }
2411            if visible_height > 0 {
2412                self.scroll_for_inline_growth(current_region)?;
2413            }
2414
2415            // Save cursor (DEC save)
2416            self.writer().write_all(CURSOR_SAVE)?;
2417            self.cursor_saved = true;
2418
2419            // Keep the hardware cursor hidden while we issue many cursor moves.
2420            // This prevents visible cursor "speckling" artifacts during redraws.
2421            self.set_cursor_visibility(false)?;
2422
2423            // Activate scroll region if strategy calls for it
2424            {
2425                let _span =
2426                    debug_span!(crate::telemetry_schema::span::RENDER_SCROLL_REGION).entered();
2427                if visible_height > 0 {
2428                    match self.inline_strategy {
2429                        InlineStrategy::ScrollRegion | InlineStrategy::Hybrid => {
2430                            self.activate_scroll_region(visible_height)?;
2431                        }
2432                        InlineStrategy::OverlayRedraw => {}
2433                    }
2434                } else if self.scroll_region_active {
2435                    self.deactivate_scroll_region()?;
2436                }
2437            }
2438
2439            self.clear_inline_region_diff(current_region)?;
2440
2441            let mut diff_strategy = DiffStrategy::FullRedraw;
2442            let mut diff_us = 0u64;
2443            let mut emit_stats = EmitStats {
2444                diff_cells: 0,
2445                diff_runs: 0,
2446            };
2447
2448            if visible_height > 0 {
2449                // If this is a full redraw (no previous buffer) OR dimensions changed,
2450                // we must clear the entire UI region to prevent ghosting (e.g. if width shrank).
2451                let dims_changed = self.prev_buffer.as_ref().map(|b| (b.width(), b.height()))
2452                    != Some((buffer.width(), buffer.height()));
2453                let already_cleared = self.prev_buffer.is_none() || dims_changed;
2454
2455                if already_cleared {
2456                    self.clear_rows(ui_y_start, visible_height)?;
2457                } else {
2458                    // If dimensions match but the buffer is shorter than the visible height,
2459                    // clear the remaining rows to prevent garbage from logs or previous frames.
2460                    let buf_height = buffer.height().min(visible_height);
2461                    if buf_height < visible_height {
2462                        let clear_start = ui_y_start.saturating_add(buf_height);
2463                        let clear_height = visible_height.saturating_sub(buf_height);
2464                        self.clear_rows(clear_start, clear_height)?;
2465                    }
2466                }
2467
2468                // Compute diff
2469                let diff_start = if self.timing_enabled {
2470                    Some(Instant::now())
2471                } else {
2472                    None
2473                };
2474                let decision = {
2475                    let _span =
2476                        debug_span!(crate::telemetry_schema::span::RENDER_DIFF_COMPUTE).entered();
2477                    self.decide_diff(buffer)
2478                };
2479                if let Some(start) = diff_start {
2480                    diff_us = start.elapsed().as_micros() as u64;
2481                }
2482                diff_strategy = decision.strategy;
2483
2484                let render_height = buffer.height().min(visible_height);
2485                let row_widths = self.bottom_addressed().then(|| {
2486                    (0..render_height)
2487                        .map(|y| row_occupied_width(buffer, y))
2488                        .collect::<Vec<u16>>()
2489                });
2490                let mut el_rows: Vec<(u16, u16)> = Vec::new();
2491
2492                // Emit diff using Presenter
2493                {
2494                    let _span = debug_span!(crate::telemetry_schema::span::RENDER_EMIT).entered();
2495
2496                    // Reset presenter state (cursor unknown) because we manually moved cursor/saved
2497                    // and apply viewport offset for inline positioning.
2498                    let bottom_rows = self
2499                        .bottom_addressed()
2500                        .then(|| self.term_height.saturating_sub(ui_y_start));
2501                    let presenter = self.presenter.as_mut().expect("presenter consumed");
2502                    presenter.reset();
2503                    presenter.set_viewport_offset_y(ui_y_start);
2504                    presenter.set_viewport_bottom(bottom_rows);
2505
2506                    if decision.has_diff {
2507                        presenter.prepare_runs(&self.diff_scratch);
2508                        // Clip to the visible terminal region, mirroring the
2509                        // full-redraw branch: when the terminal is shorter
2510                        // than ui_height, a below-the-fold run would emit a
2511                        // CUP past the physical bottom row, which real
2512                        // terminals clamp — corrupting the last visible row.
2513                        presenter.clip_runs_below(visible_height);
2514                        if let Some(ref widths) = row_widths {
2515                            presenter.trim_runs_to_row_widths(widths, Some(&mut el_rows));
2516                        }
2517                        // Emit
2518                        presenter.emit_diff_runs(buffer, Some(&self.pool), Some(&self.links))?;
2519
2520                        emit_stats.diff_cells = self.diff_scratch.len();
2521                        emit_stats.diff_runs = self.diff_scratch.runs().len();
2522                    } else {
2523                        // Full redraw — clip to the visible terminal region and
2524                        // to the buffer's actual height. This avoids generating
2525                        // diff runs for rows that are outside `buffer`.
2526                        let full = BufferDiff::full(buffer.width(), render_height);
2527                        presenter.prepare_runs(&full);
2528                        if let Some(ref widths) = row_widths {
2529                            presenter.trim_runs_to_row_widths(
2530                                widths,
2531                                (!already_cleared).then_some(&mut el_rows),
2532                            );
2533                        }
2534                        presenter.emit_diff_runs(buffer, Some(&self.pool), Some(&self.links))?;
2535
2536                        emit_stats.diff_cells = full.len();
2537                        emit_stats.diff_runs = full.runs().len();
2538                    }
2539
2540                    presenter.finish_frame()?;
2541                }
2542
2543                if !el_rows.is_empty() {
2544                    self.writer().write_all(SGR_BG_DEFAULT)?;
2545                    for (y, occ) in el_rows {
2546                        self.move_to_row(ui_y_start.saturating_add(y), occ)?;
2547                        self.writer().write_all(b"\x1b[K")?;
2548                    }
2549                }
2550            }
2551
2552            // Restore cursor
2553            self.writer().write_all(CURSOR_RESTORE)?;
2554            self.cursor_saved = false;
2555
2556            let mut show_cursor = false;
2557            self.last_ui_cursor = None;
2558            self.cursor_ui_row = None;
2559            if cursor_visible
2560                && let Some((cx, cy)) = cursor
2561                && cx < buffer.width()
2562                && cy < buffer.height()
2563                && cy < visible_height
2564            {
2565                // Move to UI start + cursor y
2566                let abs_y = ui_y_start.saturating_add(cy);
2567                self.move_to_row(abs_y, cx)?;
2568                show_cursor = true;
2569                self.last_ui_cursor = Some((cx, abs_y));
2570                self.cursor_ui_row = Some((cy, visible_height));
2571            } else if visible_height > 0 && matches!(self.ui_anchor, UiAnchor::Bottom) {
2572                // Park the hidden cursor on the UI's last row: the restore
2573                // above returns to wherever it was before the frame, and the
2574                // next re-anchor or terminal shrink needs its row in the UI.
2575                self.move_to_row(self.term_height - 1, 0)?;
2576                self.cursor_ui_row = Some((visible_height - 1, visible_height));
2577            }
2578            self.set_cursor_visibility(show_cursor)?;
2579
2580            // End sync output (mux-aware policy).
2581            if sync_output_enabled && self.in_sync_block {
2582                self.writer().write_all(SYNC_END)?;
2583                self.in_sync_block = false;
2584            } else if !sync_output_enabled {
2585                // Defensive stale-state cleanup: clear internal state without
2586                // emitting DEC 2026 in mux/unsupported environments.
2587                self.in_sync_block = false;
2588            }
2589
2590            self.writer().flush()?;
2591            self.last_inline_region = if visible_height > 0 {
2592                Some(current_region)
2593            } else {
2594                None
2595            };
2596            self.stale_frame = None;
2597            if visible_height > 0 {
2598                // The displayed frame now marks where the log rows end.
2599                self.log_floor = None;
2600            }
2601
2602            if self.timing_enabled {
2603                self.last_present_timings = Some(PresentTimings { diff_us });
2604            }
2605
2606            Ok(FrameEmitStats {
2607                diff_strategy,
2608                diff_cells: emit_stats.diff_cells,
2609                diff_runs: emit_stats.diff_runs,
2610                ui_height: visible_height,
2611            })
2612        })();
2613
2614        if result.is_err() {
2615            _inline_span.record("scrollback_preserved", false);
2616            warn!(
2617                inline_height = ui_height,
2618                render_mode, "scrollback preservation failed during inline render"
2619            );
2620            self.best_effort_inline_cleanup();
2621        } else {
2622            _inline_span.record("scrollback_preserved", true);
2623        }
2624
2625        result
2626    }
2627
2628    /// Present UI in alternate screen mode (simpler, no cursor gymnastics).
2629    fn present_altscreen(
2630        &mut self,
2631        buffer: &Buffer,
2632        cursor: Option<(u16, u16)>,
2633        cursor_visible: bool,
2634    ) -> io::Result<FrameEmitStats> {
2635        let sync_output_enabled = self.capabilities.use_sync_output();
2636        let diff_start = if self.timing_enabled {
2637            Some(Instant::now())
2638        } else {
2639            None
2640        };
2641        let decision = {
2642            let _span = debug_span!(crate::telemetry_schema::span::RENDER_DIFF_COMPUTE).entered();
2643            self.decide_diff(buffer)
2644        };
2645        let diff_us = diff_start
2646            .map(|start| start.elapsed().as_micros() as u64)
2647            .unwrap_or(0);
2648
2649        // Begin sync if available. Track state so we can reliably close the
2650        // block even on early-return error paths.
2651        if sync_output_enabled && !self.in_sync_block {
2652            // Mark active before write so partial begin writes are treated as
2653            // an open block for best-effort close.
2654            self.in_sync_block = true;
2655            if let Err(err) = self.writer().write_all(SYNC_BEGIN) {
2656                // Attempt immediate close to avoid leaving the terminal in a
2657                // potentially open synchronized-output state.
2658                let _ = self.writer().write_all(SYNC_END);
2659                self.in_sync_block = false;
2660                let _ = self.writer().flush();
2661                return Err(err);
2662            }
2663        }
2664
2665        let operation_result = (|| -> io::Result<FrameEmitStats> {
2666            // Keep the hardware cursor hidden while we issue many cursor moves.
2667            // This prevents visible cursor "speckling" artifacts during redraws.
2668            self.set_cursor_visibility(false)?;
2669
2670            let emit_stats = {
2671                let _span = debug_span!(crate::telemetry_schema::span::RENDER_EMIT).entered();
2672                let presenter = self.presenter.as_mut().expect("presenter consumed");
2673
2674                // Reset presenter state (cursor and style) because we manually moved
2675                // the cursor and reset the style at the end of the previous frame.
2676                presenter.reset();
2677                // AltScreen always starts at (0,0) relative to terminal.
2678                presenter.set_viewport_offset_y(0);
2679                presenter.set_viewport_bottom(None);
2680
2681                let stats = if decision.has_diff {
2682                    presenter.prepare_runs(&self.diff_scratch);
2683                    presenter.emit_diff_runs(buffer, Some(&self.pool), Some(&self.links))?;
2684
2685                    EmitStats {
2686                        diff_cells: self.diff_scratch.len(),
2687                        diff_runs: self.diff_scratch.runs().len(),
2688                    }
2689                } else {
2690                    // Full redraw: populate diff with all cells and emit.
2691                    self.diff_scratch.fill_full(buffer.width(), buffer.height());
2692                    presenter.prepare_runs(&self.diff_scratch);
2693                    presenter.emit_diff_runs(buffer, Some(&self.pool), Some(&self.links))?;
2694
2695                    EmitStats {
2696                        diff_cells: (buffer.width() as usize) * (buffer.height() as usize),
2697                        diff_runs: buffer.height() as usize,
2698                    }
2699                };
2700
2701                presenter.finish_frame()?;
2702                stats
2703            };
2704
2705            let mut show_cursor = false;
2706            if cursor_visible
2707                && let Some((cx, cy)) = cursor
2708                && cx < buffer.width()
2709                && cy < buffer.height()
2710            {
2711                // Apply requested cursor position
2712                write!(
2713                    self.writer(),
2714                    "\x1b[{};{}H",
2715                    cy.saturating_add(1),
2716                    cx.saturating_add(1)
2717                )?;
2718                show_cursor = true;
2719            }
2720            self.set_cursor_visibility(show_cursor)?;
2721
2722            if self.timing_enabled {
2723                self.last_present_timings = Some(PresentTimings { diff_us });
2724            }
2725
2726            Ok(FrameEmitStats {
2727                diff_strategy: decision.strategy,
2728                diff_cells: emit_stats.diff_cells,
2729                diff_runs: emit_stats.diff_runs,
2730                ui_height: 0,
2731            })
2732        })();
2733
2734        if operation_result.is_err()
2735            && let Some(ref mut presenter) = self.presenter
2736        {
2737            presenter.finish_frame_best_effort();
2738        }
2739
2740        // Always attempt to close sync and flush, regardless of operation_result.
2741        let sync_end_result = if sync_output_enabled && self.in_sync_block {
2742            let res = self.writer().write_all(SYNC_END);
2743            if res.is_ok() {
2744                self.in_sync_block = false;
2745            }
2746            Some(res)
2747        } else {
2748            if !sync_output_enabled {
2749                // Defensive stale-state cleanup: do not emit DEC 2026 when
2750                // policy disallows synchronized output.
2751                self.in_sync_block = false;
2752            }
2753            None
2754        };
2755        let flush_result = self.writer().flush();
2756
2757        // Cleanup failures (sync-end/flush) take precedence so terminal-state
2758        // restoration errors are never hidden by a concurrent render failure.
2759        let cleanup_error = sync_end_result
2760            .and_then(Result::err)
2761            .or_else(|| flush_result.err());
2762        if let Some(err) = cleanup_error {
2763            return Err(err);
2764        }
2765        operation_result
2766    }
2767
2768    // emit_diff, emit_full_redraw, and emit_style_flags have been removed
2769    // in favor of delegating to the Presenter for all emission paths.
2770
2771    /// Create a full-screen diff (marks all cells as changed).
2772    #[allow(dead_code)] // API for future diff strategy integration
2773    fn create_full_diff(&self, buffer: &Buffer) -> BufferDiff {
2774        BufferDiff::full(buffer.width(), buffer.height())
2775    }
2776
2777    /// Write log output (goes to the log region in inline mode).
2778    ///
2779    /// Behavior depends on how the UI is anchored on screen:
2780    ///
2781    /// - **Scroll region active** (ScrollRegion/Hybrid strategies): the cursor
2782    ///   is parked at the bottom margin of the DECSTBM log region and the text
2783    ///   is written verbatim (after escape-stripping). Each LF scrolls only
2784    ///   the log region, so lines accumulate upward into scrollback while the
2785    ///   UI stays put.
2786    ///
2787    /// - **Overlay transport** (OverlayRedraw strategy — multiplexers and
2788    ///   terminals that fail the DECSTBM self-test — or any transient state
2789    ///   without an active region), bottom-anchored UI: complete lines are
2790    ///   batched and streamed at the next [`present_ui`](Self::present_ui),
2791    ///   [`flush`](Self::flush) or teardown (or early, once a batch reaches
2792    ///   256 lines / 64 KiB). The stream erases the UI rows, writes the lines
2793    ///   from the UI's first row with ordinary CR LF, and lets the terminal
2794    ///   scroll the whole screen, so every line reaches scrollback exactly
2795    ///   once and in order; the UI is then repainted below them. Text without
2796    ///   a trailing newline stays open: it is streamed without a line break
2797    ///   on the row directly above the UI, and the next log text continues
2798    ///   it there (as under DECSTBM), unless the terminal size or UI height
2799    ///   changed in between or the open line no longer fits above the UI.
2800    ///   Lines accepted while a row was free stay queued, not dropped, while
2801    ///   the UI briefly fills the terminal (up to 1,024 lines or 256 KiB; see
2802    ///   [`dropped_log_lines`](Self::dropped_log_lines)).
2803    ///
2804    /// - **Top-anchored UI without a region**: a whole-screen scroll would
2805    ///   push UI rows into history, so the newest line overwrites the bottom
2806    ///   row instead and log lines do not reach scrollback. (A region that
2807    ///   does not start at row 1 never feeds history either.)
2808    ///
2809    /// If the UI consumes the entire terminal height, there is no log region
2810    /// available and the write becomes a no-op.
2811    ///
2812    /// In AltScreen mode, logs are typically not shown (returns Ok silently).
2813    pub fn write_log(&mut self, text: &str) -> io::Result<()> {
2814        self.write_log_with_mode(text, SanitizeMode::Strip)
2815    }
2816
2817    /// Write colored log text, allowing only bounded SGR sequences.
2818    ///
2819    /// Cursor commands, terminal modes and other controls are filtered at the
2820    /// emission boundary. Inline overlay logs retain the first-line and visible
2821    /// width limits of [`Self::write_log`]. Styling resets at every line/write;
2822    /// callers must repeat styling on subsequent lines. Alt-screen logs are
2823    /// suppressed, as with the default mode.
2824    pub fn write_log_sgr_only(&mut self, text: &str) -> io::Result<()> {
2825        self.write_log_with_mode(text, SanitizeMode::SgrOnly)
2826    }
2827
2828    /// Write trusted log text without sanitization or overlay clamping.
2829    ///
2830    /// **Trusted input only:** cursor movement, mode changes, clearing and
2831    /// wrapping/newlines can corrupt inline UI or terminal state. Prefer
2832    /// [`Self::write_log_sgr_only`] for colored compiler/test output. This still
2833    /// uses the terminal output lock and log region, and suppresses alt-screen
2834    /// logs, but arbitrary commands can defeat cursor restoration.
2835    pub fn write_log_raw(&mut self, text: &str) -> io::Result<()> {
2836        self.write_log_with_mode(text, SanitizeMode::Raw)
2837    }
2838
2839    /// Write annotated text, reapplying its policy at the emission boundary.
2840    pub fn write_log_text(&mut self, text: &Text<'_>) -> io::Result<()> {
2841        self.write_log_with_mode(text.as_str(), text.mode())
2842    }
2843
2844    pub(crate) fn write_log_with_mode(&mut self, text: &str, mode: SanitizeMode) -> io::Result<()> {
2845        self.write_log_impl(text, mode, false)
2846    }
2847
2848    /// Emit a model log command as a logical line. Filter before normalizing
2849    /// line endings so control parsing sees the original input boundaries.
2850    pub(crate) fn write_log_line_with_mode(
2851        &mut self,
2852        text: &str,
2853        mode: SanitizeMode,
2854    ) -> io::Result<()> {
2855        self.write_log_impl(text, mode, true)
2856    }
2857
2858    fn write_log_impl(
2859        &mut self,
2860        text: &str,
2861        mode: SanitizeMode,
2862        logical_line: bool,
2863    ) -> io::Result<()> {
2864        // One-writer discipline vs teardown paths (bd-kdn7n item 2).
2865        let _output_guard = terminal_output_lock();
2866        if mode == SanitizeMode::Raw {
2867            tracing::debug!(target: crate::telemetry_schema::TARGET_RUNTIME_LOG, mode = "raw", bytes = text.len());
2868        }
2869        if logical_line && self.scroll_region_active && self.decstbm_col > 0 {
2870            self.decstbm_row_occupied = true;
2871            self.decstbm_col = 0;
2872        }
2873        if logical_line {
2874            // A logical line starts on its own row in the overlay transport
2875            // too: end open text instead of continuing it.
2876            if let Some(last) = self.pending_logs.last_mut() {
2877                last.terminated = true;
2878            }
2879            self.overlay_open = None;
2880        }
2881        // Even publicly constructed Text variants must cross this boundary.
2882        let sanitized = sanitize_with(text, mode);
2883        let sanitized = if logical_line {
2884            let mut line = if sanitized.contains('\n') {
2885                sanitized.replace("\r\n", "\n").replace('\n', "\r\n")
2886            } else {
2887                sanitized.into_owned()
2888            };
2889            if !line.ends_with("\r\n") {
2890                line.push_str("\r\n");
2891            }
2892            std::borrow::Cow::Owned(line)
2893        } else {
2894            sanitized
2895        };
2896        let text = sanitized.as_ref();
2897        match self.screen_mode {
2898            ScreenMode::Inline { ui_height } => self.write_log_inline(ui_height, text, mode),
2899            ScreenMode::InlineAuto { .. } => {
2900                let ui_height = self.effective_ui_height();
2901                self.write_log_inline(ui_height, text, mode)
2902            }
2903            ScreenMode::AltScreen => {
2904                // AltScreen: no scrollback, logs are typically handled differently
2905                // (e.g., written to a log pane or file)
2906                Ok(())
2907            }
2908        }
2909    }
2910
2911    /// Shared inline log-write path for [`ScreenMode::Inline`] and
2912    /// [`ScreenMode::InlineAuto`].
2913    ///
2914    /// `ui_height` is the *effective* (pending) UI height; the physically
2915    /// displayed region may differ until the next `present_ui`, which is why
2916    /// the overlay arm anchors against `last_inline_region`.
2917    fn write_log_inline(
2918        &mut self,
2919        ui_height: u16,
2920        text: &str,
2921        mode: SanitizeMode,
2922    ) -> io::Result<()> {
2923        let visible_height = ui_height.min(self.term_height);
2924        if visible_height >= self.term_height {
2925            // No log region available when UI fills the terminal
2926            return Ok(());
2927        }
2928
2929        if self.scroll_region_active {
2930            // A DECSTBM region matching the current effective height is
2931            // active: parking at its bottom margin lets every LF scroll the
2932            // log region alone, accumulating lines into scrollback. Bound the
2933            // cursor excursion with DECSC/DECRC so the hardware cursor stays
2934            // parked inside the UI rows between writes (otherwise a shrinking
2935            // terminal deletes the UI rows below `log_row`).
2936            if text.is_empty() {
2937                return Ok(());
2938            }
2939            // DECSTBM tracks its own open column; an open overlay line is
2940            // not continued once logs went through the region.
2941            self.overlay_open = None;
2942            let save_cursor = !self.cursor_saved;
2943            if save_cursor {
2944                self.writer().write_all(CURSOR_SAVE)?;
2945            }
2946            let write_result = (|| -> io::Result<()> {
2947                if !self.position_cursor_for_log(visible_height)? {
2948                    return Ok(());
2949                }
2950                let normalized;
2951                let payload = if text.contains('\n') {
2952                    normalized = text.replace("\r\n", "\n").replace('\n', "\r\n");
2953                    normalized.as_str()
2954                } else {
2955                    text
2956                };
2957                self.write_log_payload(payload, mode)?;
2958                self.advance_decstbm_col(payload);
2959                Ok(())
2960            })();
2961            let restore_result = if save_cursor {
2962                self.writer().write_all(CURSOR_RESTORE).and_then(|()| {
2963                    if mode == SanitizeMode::SgrOnly {
2964                        self.writer().write_all(SGR_RESET)
2965                    } else {
2966                        Ok(())
2967                    }
2968                })
2969            } else {
2970                Ok(())
2971            };
2972            write_result?;
2973            restore_result?;
2974            return self.writer().flush();
2975        }
2976
2977        if matches!(self.ui_anchor, UiAnchor::Bottom) {
2978            // Overlay transport (G48): batch the text; it is streamed into
2979            // scrollback by `flush_pending_logs`.
2980            self.queue_overlay_log_lines(text, mode);
2981            if self.pending_logs.len() >= OVERLAY_LOG_BATCH_LINES
2982                || self.pending_log_bytes >= OVERLAY_LOG_BATCH_BYTES
2983            {
2984                self.flush_pending_logs(true)?;
2985                return self.writer().flush();
2986            }
2987            return Ok(());
2988        }
2989
2990        // Top-anchored UI: a whole-screen scroll would push UI rows into
2991        // history, so never emit an unscoped LF here. Erase-and-rewrite the
2992        // bottom row with one width-clamped line instead.
2993        //
2994        // A pending shrink does not free a row until it is presented. The
2995        // old UI may still occupy even the screen's bottom row.
2996        if self.last_inline_region.is_some_and(|displayed| {
2997            displayed.start.saturating_add(displayed.height) >= self.term_height
2998        }) {
2999            return Ok(());
3000        }
3001        // Both displayed and pending UI leave this row free.
3002        let log_row = self.term_height;
3003
3004        let line = match mode {
3005            SanitizeMode::Strip => std::borrow::Cow::Owned(sanitize_overlay_log_line(
3006                text,
3007                usize::from(self.term_width),
3008            )),
3009            SanitizeMode::SgrOnly => {
3010                std::borrow::Cow::Owned(sgr_overlay_log_line(text, usize::from(self.term_width)))
3011            }
3012            SanitizeMode::Raw => {
3013                std::borrow::Cow::Borrowed(text.split(['\n', '\r']).next().unwrap_or(""))
3014            }
3015        };
3016        if line.is_empty() {
3017            return Ok(());
3018        }
3019
3020        // Bound the cursor disturbance to this write so an interleaved
3021        // present (or none) always finds the cursor where it left it.
3022        self.writer().write_all(CURSOR_SAVE)?;
3023        let write_result = write!(self.writer(), "\x1b[{log_row};1H")
3024            .and_then(|()| self.writer().write_all(ERASE_LINE))
3025            .and_then(|()| self.write_log_payload(&line, mode));
3026        let restore_result = self.writer().write_all(CURSOR_RESTORE);
3027
3028        // Restoration failures must not be swallowed by a successful body
3029        // write: the cursor contract outranks the log payload.
3030        write_result?;
3031        restore_result?;
3032        self.writer().flush()
3033    }
3034
3035    /// Isolate SGR styling, including best-effort reset after a write failure.
3036    fn write_log_payload(&mut self, text: &str, mode: SanitizeMode) -> io::Result<()> {
3037        if mode != SanitizeMode::SgrOnly {
3038            return self.writer().write_all(text.as_bytes());
3039        }
3040        let write_result: io::Result<()> = (|| {
3041            self.writer().write_all(SGR_RESET)?;
3042            let bytes = text.as_bytes();
3043            let mut start = 0;
3044            let mut i = 0;
3045            while i < bytes.len() {
3046                if bytes[i] == b'\r' && bytes.get(i + 1) == Some(&b'\n') {
3047                    self.writer().write_all(&bytes[start..i])?;
3048                    self.writer().write_all(SGR_RESET)?;
3049                    self.writer().write_all(b"\r\n")?;
3050                    i += 2;
3051                    start = i;
3052                } else if bytes[i] == b'\n' || bytes[i] == b'\r' {
3053                    self.writer().write_all(&bytes[start..i])?;
3054                    self.writer().write_all(SGR_RESET)?;
3055                    self.writer().write_all(&bytes[i..=i])?;
3056                    i += 1;
3057                    start = i;
3058                } else {
3059                    i += 1;
3060                }
3061            }
3062            if start < bytes.len() {
3063                self.writer().write_all(&bytes[start..])?;
3064            }
3065            Ok(())
3066        })();
3067        let reset_result = self.writer().write_all(SGR_RESET);
3068        write_result?;
3069        reset_result
3070    }
3071
3072    fn advance_decstbm_col(&mut self, payload: &str) {
3073        if payload.ends_with('\n') {
3074            self.decstbm_col = 0;
3075            return;
3076        }
3077        let (tail, reset_col) = match payload.rsplit_once(['\n', '\r']) {
3078            Some((_, after)) => (after, true),
3079            None => (payload, false),
3080        };
3081        let sanitized_tail = sanitize(tail);
3082        let width = u16::try_from(ftui_core::text_width::display_width(&sanitized_tail))
3083            .unwrap_or(u16::MAX);
3084        let base = if reset_col { 0 } else { self.decstbm_col };
3085        let new_col = base.saturating_add(width);
3086        let term_width = self.term_width.max(1);
3087        self.decstbm_col = if new_col >= term_width {
3088            new_col % term_width
3089        } else {
3090            new_col
3091        };
3092    }
3093
3094    /// Split sanitized log text into lines and batch them for the overlay
3095    /// transport. A trailing fragment without a newline stays open: the
3096    /// next text continues it (in the same piece when the mode matches).
3097    fn queue_overlay_log_lines(&mut self, text: &str, mode: SanitizeMode) {
3098        let normalized;
3099        let mut rest = if text.contains("\r\n") {
3100            normalized = text.replace("\r\n", "\n");
3101            normalized.as_str()
3102        } else {
3103            text
3104        };
3105        if !rest.is_empty() {
3106            // New text streams at the next flush, with what is held.
3107            self.logs_held_across_resize = false;
3108        }
3109        while !rest.is_empty() {
3110            let (line, tail, terminated) = match rest.split_once('\n') {
3111                Some((line, tail)) => (line, tail, true),
3112                None => (rest, "", false),
3113            };
3114            self.pending_log_bytes = self.pending_log_bytes.saturating_add(line.len());
3115            match self.pending_logs.last_mut() {
3116                Some(last) if !last.terminated && last.mode == mode => {
3117                    last.text.push_str(line);
3118                    last.terminated = terminated;
3119                }
3120                _ => self.pending_logs.push(PendingLogLine {
3121                    text: line.to_owned(),
3122                    mode,
3123                    terminated,
3124                }),
3125            }
3126            rest = tail;
3127        }
3128        self.bound_pending_logs();
3129    }
3130
3131    /// Keep the overlay queue within its bound (it only grows past one batch
3132    /// while no row is free to stream it): drop the oldest lines and count
3133    /// them.
3134    fn bound_pending_logs(&mut self) {
3135        let mut excess = 0;
3136        let mut bytes = self.pending_log_bytes;
3137        while excess < self.pending_logs.len()
3138            && (self.pending_logs.len() - excess > OVERLAY_LOG_QUEUE_MAX_LINES
3139                || bytes > OVERLAY_LOG_QUEUE_MAX_BYTES)
3140        {
3141            bytes = bytes.saturating_sub(self.pending_logs[excess].text.len());
3142            excess += 1;
3143        }
3144        if excess == 0 {
3145            return;
3146        }
3147        self.pending_logs.drain(..excess);
3148        self.pending_log_bytes = bytes;
3149        self.dropped_log_lines = self.dropped_log_lines.saturating_add(excess as u64);
3150        // The kept text no longer continues what the terminal shows.
3151        self.overlay_open = None;
3152        tracing::debug!(
3153            target: crate::telemetry_schema::TARGET_RUNTIME_LOG,
3154            dropped = excess,
3155            total = self.dropped_log_lines,
3156            "overlay log queue full: dropped the oldest lines"
3157        );
3158    }
3159
3160    /// Make room for a bottom-anchored inline UI before the first inline
3161    /// output: the UI rows sit at the bottom of the screen, and on a full
3162    /// terminal those rows still hold the shell's last lines, which have not
3163    /// reached scrollback. `ui_height - 1` CR LFs from the shell's cursor
3164    /// (the start of a fresh line) scroll exactly enough of the screen into
3165    /// history that every UI row is blank.
3166    fn reserve_inline_rows(&mut self, ui_height: u16) -> io::Result<()> {
3167        if self.inline_rows_reserved || !matches!(self.ui_anchor, UiAnchor::Bottom) {
3168            return Ok(());
3169        }
3170        self.inline_rows_reserved = true;
3171        for _ in 1..ui_height.min(self.term_height) {
3172            self.writer().write_all(b"\r\n")?;
3173        }
3174        self.decstbm_row_occupied = true;
3175        self.decstbm_col = 0;
3176        Ok(())
3177    }
3178
3179    /// Overlay transport (G48): stream batched log lines into scrollback.
3180    ///
3181    /// Let `T` be the first UI row and `u` the UI height. The UI rows are
3182    /// erased (`CUP T;1`, `ED 0`) so no UI text can ever scroll into
3183    /// history; the lines are written from `T` as a plain stream (`line CR
3184    /// LF`), the terminal's own autowrap breaking long lines and its LF at
3185    /// the bottom row scrolling the whole screen; then `u - 1` more `CR LF`
3186    /// leave the cursor exactly as many rows past the bottom as the log text
3187    /// occupied, so the screen has scrolled by that amount and the bottom
3188    /// `u` rows are blank with the newest line directly above them. Every
3189    /// line therefore reaches scrollback exactly once and in order, in any
3190    /// terminal, with no width arithmetic. With `repaint` the last presented
3191    /// frame is redrawn into the vacated rows (standalone flush); otherwise
3192    /// the caller is about to present a frame and must treat the diff
3193    /// baseline as gone.
3194    ///
3195    /// Text without a terminator at the end of the batch is left open on
3196    /// the row directly above the UI ([`Self::write_open_log_line`]), and a
3197    /// stream in the same geometry continues it there.
3198    ///
3199    /// When no row is free (not inline, no height, or the UI fills the
3200    /// screen) the lines stay queued for a later stream.
3201    ///
3202    /// Returns whether anything was streamed.
3203    fn flush_pending_logs(&mut self, repaint: bool) -> io::Result<bool> {
3204        self.stream_pending_logs(repaint, false)
3205    }
3206
3207    /// [`Self::flush_pending_logs`]; with `without_ui` and no displayed
3208    /// region, the lines are streamed as if no UI rows were reserved: from
3209    /// the bottom row, nothing erased (teardown with lines held across a
3210    /// resize).
3211    fn stream_pending_logs(&mut self, repaint: bool, without_ui: bool) -> io::Result<bool> {
3212        if self.pending_logs.is_empty() {
3213            return Ok(false);
3214        }
3215        if !matches!(
3216            self.screen_mode,
3217            ScreenMode::Inline { .. } | ScreenMode::InlineAuto { .. }
3218        ) || self.term_height == 0
3219        {
3220            return Ok(false);
3221        }
3222
3223        // `start`: where the stream begins (and the screen is erased from);
3224        // `height`: the blank rows the UI needs at the bottom afterwards.
3225        let displayed = self.last_inline_region;
3226        let (mut start, height) = match displayed {
3227            Some(region) => {
3228                let start = region.start.min(self.term_height);
3229                (start, region.height.min(self.term_height - start))
3230            }
3231            None if without_ui => (self.term_height, 0),
3232            None => {
3233                let height = self.effective_ui_height().min(self.term_height);
3234                // An earlier stream may have left lines below the pending UI
3235                // start (an inline-auto UI grew since); never erase them.
3236                let floor = self.log_floor.unwrap_or(0);
3237                ((self.term_height - height).max(floor), height)
3238            }
3239        };
3240        if height >= self.term_height {
3241            // The UI fills the screen: there is no row a log line could
3242            // occupy without scrolling UI rows into history. Keep the lines
3243            // for a stream after the next resize or present.
3244            return Ok(false);
3245        }
3246        let lines = std::mem::take(&mut self.pending_logs);
3247        self.pending_log_bytes = 0;
3248        self.logs_held_across_resize = false;
3249        // Column of the line the previous stream left open, when this stream
3250        // can continue it (same geometry, so it is still directly above the
3251        // UI, or on the bottom row without one).
3252        let resume = self
3253            .overlay_open
3254            .take()
3255            .filter(|open| {
3256                open.term == (self.term_width, self.term_height) && open.ui_height == height
3257            })
3258            .map(|open| open.col);
3259        // The trailing run of unterminated text: one line, left open.
3260        let open_from = lines
3261            .iter()
3262            .rposition(|line| line.terminated)
3263            .map_or(0, |last| last + 1);
3264        self.reserve_inline_rows(height)?;
3265
3266        let open_sync = repaint && self.capabilities.use_sync_output() && !self.in_sync_block;
3267        if open_sync {
3268            self.in_sync_block = true;
3269            self.writer().write_all(SYNC_BEGIN)?;
3270        }
3271        let was_visible = self.cursor_visible;
3272        self.set_cursor_visibility(false)?;
3273        // Leftover presenter style must not colour the logs or the rows the
3274        // scroll brings in.
3275        self.writer().write_all(SGR_RESET)?;
3276        self.reanchor_inline_cursor()?;
3277        let bottom = self.term_height - 1;
3278        if height > 0 {
3279            if let Some(col) = resume {
3280                // Continue the open line directly above the UI.
3281                self.move_to_row(bottom - height, col)?;
3282            } else {
3283                if start >= self.term_height {
3284                    // The newest line sits on the bottom row (a UI-less
3285                    // stream came first): open a fresh row below it.
3286                    self.move_to_row(bottom, 0)?;
3287                    self.writer().write_all(b"\r\n")?;
3288                    start = bottom;
3289                }
3290                self.move_to_row(start, 0)?;
3291            }
3292            self.writer().write_all(b"\x1b[J")?;
3293            for line in &lines[..open_from] {
3294                self.write_log_payload(&line.text, line.mode)?;
3295                self.writer().write_all(b"\r\n")?;
3296            }
3297            if open_from < lines.len() {
3298                let resumed = if open_from == 0 { resume } else { None };
3299                self.write_open_log_line(&lines[open_from..], resumed, height)?;
3300            } else {
3301                // `start >= term_height - height`, so these always scroll
3302                // the screen far enough that the last line ends just above
3303                // the UI.
3304                for _ in 0..height - 1 {
3305                    self.writer().write_all(b"\r\n")?;
3306                }
3307            }
3308        } else {
3309            // No UI rows: the newest line lives on the bottom row, so each
3310            // line starts with the scroll instead of ending with it, and an
3311            // open line is continued in place.
3312            self.move_to_row(bottom, resume.unwrap_or(0))?;
3313            let mut open = resume.is_some();
3314            for line in &lines {
3315                if !open {
3316                    self.writer().write_all(b"\r\n")?;
3317                }
3318                self.write_log_payload(&line.text, line.mode)?;
3319                open = !line.terminated;
3320            }
3321            if open {
3322                let start_col = if open_from == 0 {
3323                    resume.unwrap_or(0)
3324                } else {
3325                    0
3326                };
3327                let (_, end_col) = open_line_extent(
3328                    start_col,
3329                    lines[open_from..].iter().map(|line| line.text.as_str()),
3330                    self.term_width,
3331                );
3332                self.record_open_log_line(end_col, 0);
3333            }
3334        }
3335        // The last line now ends just above the bottom `height` rows (or on
3336        // the bottom row when there is no UI), and the cursor is on the last
3337        // of those rows.
3338        self.log_floor = Some(self.term_height - height);
3339        self.decstbm_row_occupied = true;
3340        self.decstbm_col = 0;
3341        self.cursor_ui_row = height.checked_sub(1).map(|last| (last, height));
3342
3343        if repaint {
3344            if displayed.is_some() && height > 0 {
3345                self.repaint_prev_frame(start, height)?;
3346                if let Some((x, y)) = self.last_ui_cursor {
3347                    self.move_to_row(y, x)?;
3348                    self.set_cursor_visibility(true)?;
3349                    self.cursor_ui_row =
3350                        Some((y.saturating_sub(self.term_height - height), height));
3351                } else if self.bottom_addressed() {
3352                    self.move_to_row(self.term_height - 1, 0)?;
3353                    self.cursor_ui_row = Some((height - 1, height));
3354                }
3355            } else if was_visible {
3356                self.set_cursor_visibility(true)?;
3357            }
3358            if open_sync {
3359                self.writer().write_all(SYNC_END)?;
3360                self.in_sync_block = false;
3361            }
3362        }
3363        Ok(true)
3364    }
3365
3366    /// Stream the trailing unterminated run of a batch as one open line on
3367    /// the row directly above a `height`-row UI, with no terminator after
3368    /// it, and record where it ends so the next stream continues it.
3369    ///
3370    /// `resumed`: the cursor is on that row at this column, continuing the
3371    /// previous open line. Otherwise the cursor is at the start of a fresh
3372    /// row no higher than the UI's first row. Room for the UI is made
3373    /// before the text is written: CR LFs over the blank rows below scroll
3374    /// the screen until the line's first row is `height` rows, plus the rows
3375    /// the line will wrap onto, above the last row; then the cursor returns
3376    /// there. A line taller than the rows above the UI cannot stay open on
3377    /// screen and is ended like a complete line.
3378    fn write_open_log_line(
3379        &mut self,
3380        run: &[PendingLogLine],
3381        resumed: Option<u16>,
3382        height: u16,
3383    ) -> io::Result<()> {
3384        let bottom = self.term_height - 1;
3385        let start_col = resumed.unwrap_or(0);
3386        let (wraps, end_col) = open_line_extent(
3387            start_col,
3388            run.iter().map(|line| line.text.as_str()),
3389            self.term_width,
3390        );
3391        let rows_up = height.saturating_add(wraps);
3392        if rows_up > bottom {
3393            for line in run {
3394                self.write_log_payload(&line.text, line.mode)?;
3395            }
3396            for _ in 0..height {
3397                self.writer().write_all(b"\r\n")?;
3398            }
3399            return Ok(());
3400        }
3401        match resumed {
3402            Some(col) => {
3403                // The line's row is `height` rows above the last row; scroll
3404                // by the rows it will wrap onto.
3405                if wraps > 0 {
3406                    self.move_to_row(bottom, 0)?;
3407                    for _ in 0..wraps {
3408                        self.writer().write_all(b"\r\n")?;
3409                    }
3410                }
3411                self.move_to_row(bottom - rows_up, col)?;
3412            }
3413            None => {
3414                // From a row at or below `term_height - height`, `rows_up`
3415                // CR LFs always reach the last row, leaving the fresh row
3416                // exactly `rows_up` rows above it.
3417                for _ in 0..rows_up {
3418                    self.writer().write_all(b"\r\n")?;
3419                }
3420                self.move_to_row(bottom - rows_up, 0)?;
3421            }
3422        }
3423        for line in run {
3424            self.write_log_payload(&line.text, line.mode)?;
3425        }
3426        self.record_open_log_line(end_col, height);
3427        // Leave the cursor on the UI's last row, as a complete stream does.
3428        self.move_to_row(bottom, 0)
3429    }
3430
3431    /// Remember an open overlay line ending at `end_col` for the next
3432    /// stream. One that filled its last row exactly is complete: the next
3433    /// character would wrap onto a fresh row anyway.
3434    fn record_open_log_line(&mut self, end_col: u16, ui_height: u16) {
3435        if end_col < self.term_width.max(1) {
3436            self.overlay_open = Some(OverlayOpenLine {
3437                col: end_col,
3438                term: (self.term_width, self.term_height),
3439                ui_height,
3440            });
3441        }
3442    }
3443
3444    /// Redraw the last presented frame at `start` (after the overlay
3445    /// transport vacated the UI rows). The terminal matches `prev_buffer`
3446    /// again afterwards, so the diff baseline stays valid. After an
3447    /// inline-auto height change the displayed frame is `stale_frame`.
3448    fn repaint_prev_frame(&mut self, start: u16, height: u16) -> io::Result<()> {
3449        let Some(prev) = self.prev_buffer.as_ref().or(self.stale_frame.as_ref()) else {
3450            return Ok(());
3451        };
3452        let render_height = prev.height().min(height);
3453        let row_widths = self.bottom_addressed().then(|| {
3454            (0..render_height)
3455                .map(|y| row_occupied_width(prev, y))
3456                .collect::<Vec<u16>>()
3457        });
3458        let full = BufferDiff::full(prev.width(), render_height);
3459        let bottom_rows = self
3460            .bottom_addressed()
3461            .then(|| self.term_height.saturating_sub(start));
3462        let presenter = self.presenter.as_mut().expect("presenter consumed");
3463        presenter.reset();
3464        presenter.set_viewport_offset_y(start);
3465        presenter.set_viewport_bottom(bottom_rows);
3466        presenter.prepare_runs(&full);
3467        if let Some(ref widths) = row_widths {
3468            presenter.trim_runs_to_row_widths(widths, None);
3469        }
3470        presenter.emit_diff_runs(prev, Some(&self.pool), Some(&self.links))?;
3471        presenter.finish_frame()
3472    }
3473
3474    /// When a bottom-anchored UI grows, the rows it now needs hold the
3475    /// newest log lines, which have not reached scrollback. Scroll the whole
3476    /// screen by the growth first, so they move up instead of being drawn
3477    /// over. The rows in use end at the displayed frame's first row, or —
3478    /// before any frame — at the row after the last streamed log line. The
3479    /// old frame moves up with everything else; the caller then redraws the
3480    /// grown region in full.
3481    fn scroll_for_inline_growth(&mut self, current: InlineRegion) -> io::Result<()> {
3482        if !matches!(self.ui_anchor, UiAnchor::Bottom) || self.term_height == 0 {
3483            return Ok(());
3484        }
3485        let occupied_from = match (self.last_inline_region, self.log_floor) {
3486            (Some(previous), _) => previous.start,
3487            (None, Some(floor)) => floor,
3488            (None, None) => return Ok(()),
3489        };
3490        if current.start >= occupied_from {
3491            return Ok(());
3492        }
3493        let grow = occupied_from - current.start;
3494        if self.scroll_region_active {
3495            self.deactivate_scroll_region()?;
3496        }
3497        self.writer().write_all(SGR_RESET)?;
3498        self.move_to_row(self.term_height - 1, 0)?;
3499        for _ in 0..grow {
3500            self.writer().write_all(b"\r\n")?;
3501        }
3502        if let Some(previous) = self.last_inline_region {
3503            self.last_inline_region = Some(InlineRegion {
3504                start: current.start,
3505                height: previous.height,
3506            });
3507        }
3508        self.log_floor = Some(current.start);
3509        self.decstbm_row_occupied = self.decstbm_row_occupied || self.decstbm_col > 0;
3510        self.decstbm_col = 0;
3511        self.prev_buffer = None;
3512        Ok(())
3513    }
3514
3515    /// Position cursor at the bottom margin of the active DECSTBM log region.
3516    ///
3517    /// Only meaningful while a scroll region is active (see
3518    /// [`TerminalWriter::write_log`]): for bottom-anchored UI the region spans
3519    /// rows 1..=term_height - ui_height, for top-anchored UI rows
3520    /// ui_height + 1..=term_height. Parking at the region's bottom margin
3521    /// makes each subsequent LF scroll only that region, leaving the UI
3522    /// untouched while log lines accumulate into scrollback.
3523    fn position_cursor_for_log(&mut self, ui_height: u16) -> io::Result<bool> {
3524        let visible_height = ui_height.min(self.term_height);
3525        if visible_height >= self.term_height {
3526            // No log region available when UI fills the terminal
3527            return Ok(false);
3528        }
3529
3530        let log_row = match self.ui_anchor {
3531            UiAnchor::Bottom => {
3532                // Log region is above UI: rows 1 to (term_height - ui_height)
3533                // Position at the bottom of the log region
3534                self.term_height.saturating_sub(visible_height)
3535            }
3536            UiAnchor::Top => {
3537                // Log region is below UI: rows (ui_height + 1) to term_height
3538                // Position at the bottom of the log region (last row)
3539                self.term_height
3540            }
3541        };
3542
3543        if matches!(self.ui_anchor, UiAnchor::Bottom) && self.decstbm_row_occupied {
3544            // `reserve_inline_rows` or `flush_pending_logs` left a completed
3545            // line on `log_row`; scroll the DECSTBM region up one row before
3546            // writing at column 1 so that line is never overwritten.
3547            write!(self.writer(), "\x1b[{};1H\r\n", log_row)?;
3548            self.decstbm_row_occupied = false;
3549            self.decstbm_col = 0;
3550        } else {
3551            let col = self
3552                .decstbm_col
3553                .saturating_add(1)
3554                .min(self.term_width.max(1));
3555            write!(self.writer(), "\x1b[{};{}H", log_row, col)?;
3556        }
3557        Ok(true)
3558    }
3559
3560    /// Clear the screen.
3561    pub fn clear_screen(&mut self) -> io::Result<()> {
3562        // One-writer discipline vs teardown paths (bd-kdn7n item 2).
3563        let _output_guard = terminal_output_lock();
3564        let mut first_error = None;
3565        if self.in_sync_block {
3566            if self.capabilities.use_sync_output()
3567                && let Err(err) = self.writer().write_all(SYNC_END)
3568            {
3569                first_error = Some(err);
3570            }
3571            self.in_sync_block = false;
3572        }
3573        if self.cursor_saved {
3574            if let Err(err) = self.writer().write_all(CURSOR_RESTORE) {
3575                first_error.get_or_insert(err);
3576            }
3577            self.cursor_saved = false;
3578        }
3579        if self.scroll_region_active {
3580            if let Err(err) = self.writer().write_all(b"\x1b[r") {
3581                first_error.get_or_insert(err);
3582            }
3583            self.scroll_region_active = false;
3584        }
3585        if let Err(err) = self.writer().write_all(b"\x1b[2J\x1b[1;1H") {
3586            first_error.get_or_insert(err);
3587        }
3588        if let Err(err) = self.writer().flush() {
3589            first_error.get_or_insert(err);
3590        }
3591        self.prev_buffer = None;
3592        self.stale_frame = None;
3593        self.log_floor = None;
3594        self.overlay_open = None;
3595        self.decstbm_row_occupied = false;
3596        self.decstbm_col = 0;
3597        self.last_inline_region = None;
3598        self.cursor_ui_row = None;
3599        self.reset_diff_strategy();
3600        if let Some(err) = first_error {
3601            Err(err)
3602        } else {
3603            Ok(())
3604        }
3605    }
3606
3607    fn set_cursor_visibility(&mut self, visible: bool) -> io::Result<()> {
3608        if self.cursor_visible == visible {
3609            return Ok(());
3610        }
3611        self.cursor_visible = visible;
3612        if visible {
3613            self.writer().write_all(b"\x1b[?25h")?;
3614        } else {
3615            self.writer().write_all(b"\x1b[?25l")?;
3616        }
3617        Ok(())
3618    }
3619
3620    /// Hide the cursor.
3621    pub fn hide_cursor(&mut self) -> io::Result<()> {
3622        let _output_guard = terminal_output_lock();
3623        self.set_cursor_visibility(false)?;
3624        self.writer().flush()
3625    }
3626
3627    /// Show the cursor.
3628    pub fn show_cursor(&mut self) -> io::Result<()> {
3629        let _output_guard = terminal_output_lock();
3630        self.set_cursor_visibility(true)?;
3631        self.writer().flush()
3632    }
3633
3634    /// Queue an OSC 52 clipboard write in the presenter's existing output buffer.
3635    ///
3636    /// Call [`flush`](Self::flush) when no frame follows. Unsupported capability
3637    /// sets are skipped; invalid selections and oversized payloads are errors.
3638    pub fn write_osc52_set(
3639        &mut self,
3640        selection: ftui_core::osc52::ClipboardSelection,
3641        bytes: &[u8],
3642    ) -> io::Result<()> {
3643        let seq = ftui_core::osc52::encode_set(selection, bytes)
3644            .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
3645        self.write_osc52_control(selection, &seq, bytes.len().div_ceil(3) * 4)
3646    }
3647
3648    /// Queue an asynchronous OSC 52 clipboard read request.
3649    pub fn write_osc52_query(
3650        &mut self,
3651        selection: ftui_core::osc52::ClipboardSelection,
3652    ) -> io::Result<()> {
3653        let seq = ftui_core::osc52::encode_query(selection)
3654            .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
3655        self.write_osc52_control(selection, &seq, 0)
3656    }
3657
3658    fn write_osc52_control(
3659        &mut self,
3660        selection: ftui_core::osc52::ClipboardSelection,
3661        seq: &[u8],
3662        payload_b64_len: usize,
3663    ) -> io::Result<()> {
3664        let caps = self.capabilities;
3665        if !caps.osc52_clipboard {
3666            tracing::debug!(target: crate::telemetry_schema::TARGET_RUNTIME, event = "osc52_write", ?selection, skipped_unsupported = true);
3667            return Ok(());
3668        }
3669        let _output_guard = terminal_output_lock();
3670        ftui_core::mux_passthrough::mux_wrap(self.writer(), &caps, seq)?;
3671        tracing::debug!(target: crate::telemetry_schema::TARGET_RUNTIME, event = "osc52_write", ?selection, payload_b64_len,
3672            wrapped = caps.in_tmux || caps.in_screen, skipped_unsupported = false);
3673        Ok(())
3674    }
3675
3676    /// Flush any buffered output, including log lines batched for the
3677    /// overlay transport (streamed into scrollback, then the last frame is
3678    /// repainted below them).
3679    pub fn flush(&mut self) -> io::Result<()> {
3680        let _output_guard = terminal_output_lock();
3681        // Lines held across a resize wait for the next present (or new log
3682        // text): a resize is not a log write, so it must not erase.
3683        if !self.holding_logs_across_resize() {
3684            self.flush_pending_logs(true)?;
3685        }
3686        self.writer().flush()
3687    }
3688
3689    /// Lines are held across a resize and no frame is drawn at the new
3690    /// geometry yet (see `logs_held_across_resize`).
3691    fn holding_logs_across_resize(&self) -> bool {
3692        self.logs_held_across_resize && self.last_inline_region.is_none()
3693    }
3694
3695    /// Get the grapheme pool for interning complex characters.
3696    pub fn pool(&self) -> &GraphemePool {
3697        &self.pool
3698    }
3699
3700    /// Get mutable access to the grapheme pool.
3701    pub fn pool_mut(&mut self) -> &mut GraphemePool {
3702        &mut self.pool
3703    }
3704
3705    /// Get the link registry.
3706    pub fn links(&self) -> &LinkRegistry {
3707        &self.links
3708    }
3709
3710    /// Get mutable access to the link registry.
3711    pub fn links_mut(&mut self) -> &mut LinkRegistry {
3712        &mut self.links
3713    }
3714
3715    /// Apply the program's opt-in link lifetime policy at initialization.
3716    pub(crate) fn set_hyperlink_limit(&mut self, limit: usize) {
3717        self.links = LinkRegistry::with_frame_limit(limit);
3718        self.prev_buffer = None;
3719        self.reset_diff_strategy();
3720    }
3721
3722    /// Start a managed render while preserving the last presented frame's IDs.
3723    /// Spare/clone buffers are reset or overwritten before reuse, so they are
3724    /// not roots. Unmanaged registries leave all IDs untouched.
3725    pub(crate) fn begin_link_frame(&mut self) {
3726        if let Some(previous) = self.prev_buffer.as_ref() {
3727            self.links.begin_frame(&[previous]);
3728        } else {
3729            self.links.begin_frame(&[]);
3730        }
3731    }
3732
3733    /// Borrow the grapheme pool and link registry together.
3734    ///
3735    /// This avoids double-borrowing `self` at call sites that need both.
3736    pub fn pool_and_links_mut(&mut self) -> (&mut GraphemePool, &mut LinkRegistry) {
3737        (&mut self.pool, &mut self.links)
3738    }
3739
3740    /// Get the terminal capabilities.
3741    pub fn capabilities(&self) -> &TerminalCapabilities {
3742        &self.capabilities
3743    }
3744
3745    /// Consume the writer and return the underlying writer.
3746    ///
3747    /// Performs cleanup operations before returning.
3748    /// Returns `None` if the buffer could not be flushed.
3749    pub fn into_inner(mut self) -> Option<W> {
3750        self.cleanup();
3751        // Take the presenter before Drop runs (Drop will see None and skip cleanup)
3752        self.presenter.take()?.into_inner().ok()
3753    }
3754
3755    /// Perform garbage collection on the grapheme pool.
3756    ///
3757    /// Frees graphemes that are not referenced by the current front buffer (`prev_buffer`)
3758    /// or the optional `extra_buffer` (e.g. a pending render).
3759    ///
3760    /// This should be called periodically (e.g. every N frames) to prevent memory leaks
3761    /// in long-running applications with dynamic content.
3762    pub fn gc(&mut self, extra_buffer: Option<&Buffer>) {
3763        let mut buffers = Vec::with_capacity(2);
3764        if let Some(ref buf) = self.prev_buffer {
3765            buffers.push(buf);
3766        }
3767        if let Some(buf) = extra_buffer {
3768            buffers.push(buf);
3769        }
3770        self.pool.gc(&buffers);
3771    }
3772
3773    /// Estimate total memory usage in bytes (buffers + pools).
3774    pub fn estimate_memory_usage(&self) -> usize {
3775        let mut total = 0;
3776        // Buffers (16 bytes per cell)
3777        if let Some(b) = &self.prev_buffer {
3778            total += b.width() as usize * b.height() as usize * 16;
3779        }
3780        if let Some(b) = &self.spare_buffer {
3781            total += b.width() as usize * b.height() as usize * 16;
3782        }
3783        if let Some(b) = &self.clone_buf {
3784            total += b.width() as usize * b.height() as usize * 16;
3785        }
3786        // Grapheme pool (approx 32 bytes per slot: 24 for String + overhead)
3787        total += self.pool.capacity() * 32;
3788        // Link registry
3789        total += self.links.estimate_memory();
3790        total
3791    }
3792
3793    /// Best-effort cleanup when inline present fails mid-frame.
3794    ///
3795    /// This restores sync/cursor/scroll-region state without terminating the writer.
3796    fn best_effort_inline_cleanup(&mut self) {
3797        let Some(ref mut presenter) = self.presenter else {
3798            return;
3799        };
3800        presenter.finish_frame_best_effort();
3801        let writer = presenter.counting_writer_mut();
3802
3803        // Ensure erase operations clear to the terminal default background.
3804        // Without this, background color leakage occurs during cleanup.
3805        let _ = writer.write_all(SGR_BG_DEFAULT);
3806
3807        // Emit restorations unconditionally: write errors can occur after bytes
3808        // were partially written, so internal flags may be stale.
3809        if self.in_sync_block {
3810            if self.capabilities.use_sync_output() {
3811                let _ = writer.write_all(SYNC_END);
3812            }
3813            self.in_sync_block = false;
3814        }
3815
3816        let _ = writer.write_all(CURSOR_RESTORE);
3817        self.cursor_saved = false;
3818
3819        let _ = writer.write_all(b"\x1b[r");
3820        self.scroll_region_active = false;
3821
3822        let _ = writer.write_all(b"\x1b[?25h");
3823        self.cursor_visible = true;
3824        let _ = writer.flush();
3825    }
3826
3827    /// Internal cleanup on drop.
3828    fn cleanup(&mut self) {
3829        self.release_terminal_state();
3830        if let Some(ref mut trace) = self.render_trace {
3831            let _ = trace.finish(None);
3832        }
3833    }
3834
3835    /// Hand the terminal back ahead of a job-control stop: the same bytes as
3836    /// the drop-time cleanup, but the writer stays usable. The caller must
3837    /// then [`set_size`](Self::set_size) on resume, which drops the diff
3838    /// baseline and inline-region cache: the screen is not ours after a stop.
3839    pub(crate) fn release_for_suspend(&mut self) {
3840        self.release_terminal_state();
3841        // The shell owns the screen until resume; make room again before
3842        // the next inline frame.
3843        self.inline_rows_reserved = false;
3844    }
3845
3846    /// Close an open sync block, reset the scroll region, restore the saved
3847    /// cursor and show it, then flush.
3848    ///
3849    /// Inline teardown contract (bottom-anchored UI): batched log lines are
3850    /// streamed first, the final frame stays on screen, and the cursor is
3851    /// parked at the start of an empty row below it, so the shell's next
3852    /// output can never overwrite part of a UI row. Skipped while panicking
3853    /// apart from the parking (which only scrolls): the panic hook has
3854    /// already printed its message, and the stream would erase UI rows it
3855    /// may sit on.
3856    fn release_terminal_state(&mut self) {
3857        // Teardown bytes must not interleave with another thread's emission
3858        // batch (bd-kdn7n item 2); reentrant so Drop-under-lock is safe.
3859        let _output_guard = terminal_output_lock();
3860        if self.presenter.is_none() {
3861            return; // Presenter already taken (via into_inner)
3862        }
3863        if !std::thread::panicking() {
3864            // Lines held across a resize go below what the screen shows:
3865            // no UI is drawn at the new geometry, so nothing is erased.
3866            let without_ui = self.holding_logs_across_resize();
3867            let _ = self.stream_pending_logs(true, without_ui);
3868        }
3869        let bottom_inline = matches!(self.ui_anchor, UiAnchor::Bottom)
3870            && matches!(
3871                self.screen_mode,
3872                ScreenMode::Inline { .. } | ScreenMode::InlineAuto { .. }
3873            );
3874        // Row (1-indexed) to park on, and whether to scroll a fresh row in.
3875        let park = if !bottom_inline || self.term_height == 0 {
3876            None
3877        } else if self.last_inline_region.is_some() {
3878            Some((self.term_height, true))
3879        } else if let Some(floor) = self.log_floor {
3880            // No frame: park on the row after the last log line (scrolling
3881            // one in when that line is on the bottom row).
3882            if floor >= self.term_height {
3883                Some((self.term_height, true))
3884            } else {
3885                Some((floor.saturating_add(1), false))
3886            }
3887        } else {
3888            None
3889        };
3890        let bottom = self.bottom_addressed().then_some(self.term_height);
3891        let Some(presenter) = &mut self.presenter else {
3892            return;
3893        };
3894        presenter.finish_frame_best_effort();
3895        let writer = presenter.counting_writer_mut();
3896
3897        // Ensure erase operations clear to the terminal default background.
3898        let _ = writer.write_all(SGR_BG_DEFAULT);
3899
3900        // End any pending sync block
3901        if self.in_sync_block {
3902            if self.capabilities.use_sync_output() {
3903                let _ = writer.write_all(SYNC_END);
3904            }
3905            self.in_sync_block = false;
3906        }
3907
3908        // Reset scroll region BEFORE restoring the cursor: DECSTBM reset
3909        // homes the cursor to (1,1) on real terminals, so emitting it after
3910        // CURSOR_RESTORE would discard the deliberate final placement.
3911        if self.scroll_region_active {
3912            let _ = writer.write_all(b"\x1b[r");
3913            self.scroll_region_active = false;
3914        }
3915
3916        // Restore cursor if saved
3917        if self.cursor_saved {
3918            let _ = writer.write_all(CURSOR_RESTORE);
3919            self.cursor_saved = false;
3920        }
3921
3922        if let Some((row, scroll_fresh_row)) = park {
3923            let _ = write_row_address(writer, bottom, row.saturating_sub(1), 0);
3924            if scroll_fresh_row {
3925                let _ = writer.write_all(b"\r\n");
3926            }
3927        }
3928
3929        // Show cursor
3930        let _ = writer.write_all(b"\x1b[?25h");
3931        self.cursor_visible = true;
3932
3933        // Flush
3934        let _ = writer.flush();
3935    }
3936}
3937
3938impl<W: Write> Drop for TerminalWriter<W> {
3939    fn drop(&mut self) {
3940        // Decrement the inline-active gauge.
3941        if matches!(
3942            self.screen_mode,
3943            ScreenMode::Inline { .. } | ScreenMode::InlineAuto { .. }
3944        ) {
3945            INLINE_ACTIVE_WIDGETS.fetch_sub(1, Ordering::SeqCst);
3946        }
3947        self.cleanup();
3948    }
3949}
3950
3951#[cfg(test)]
3952mod tests {
3953    use super::*;
3954    use ftui_render::cell::{Cell, CellAttrs, CellContent, PackedRgba, StyleFlags};
3955    use std::cell::RefCell;
3956    use std::io;
3957    use std::path::PathBuf;
3958    use std::rc::Rc;
3959
3960    #[test]
3961    fn osc52_writer_buffers_wraps_and_rejects_invalid_requests() {
3962        use ftui_core::osc52::ClipboardSelection;
3963        for mode in 0..4 {
3964            let mut caps = TerminalCapabilities::basic();
3965            caps.osc52_clipboard = mode != 0;
3966            caps.in_tmux = mode == 2;
3967            caps.in_screen = mode == 3;
3968            let mut writer =
3969                TerminalWriter::new(Vec::new(), ScreenMode::AltScreen, UiAnchor::Bottom, caps);
3970            writer
3971                .write_osc52_set(ClipboardSelection::Clipboard, b"hi")
3972                .unwrap();
3973            writer
3974                .write_osc52_query(ClipboardSelection::Clipboard)
3975                .unwrap();
3976            assert!(
3977                writer.presenter.as_mut().unwrap().writer_mut().is_empty(),
3978                "small controls remain buffered"
3979            );
3980            writer.flush().unwrap();
3981            let bytes = writer.presenter.as_mut().unwrap().writer_mut().clone();
3982            let expected: &[u8] = match mode {
3983                0 => b"",
3984                1 => b"\x1b]52;c;aGk=\x07\x1b]52;c;?\x07",
3985                2 => b"\x1bPtmux;\x1b\x1b]52;c;aGk=\x07\x1b\\\x1bPtmux;\x1b\x1b]52;c;?\x07\x1b\\",
3986                _ => b"\x1bP\x1b]52;c;aGk=\x07\x1b\\\x1bP\x1b]52;c;?\x07\x1b\\",
3987            };
3988            assert_eq!(bytes, expected);
3989            assert_eq!(
3990                writer
3991                    .write_osc52_set(ClipboardSelection::Clipboard, &vec![0; 56_245])
3992                    .unwrap_err()
3993                    .kind(),
3994                io::ErrorKind::InvalidInput
3995            );
3996            assert_eq!(
3997                writer
3998                    .write_osc52_query(ClipboardSelection::CutBuffer(8))
3999                    .unwrap_err()
4000                    .kind(),
4001                io::ErrorKind::InvalidInput
4002            );
4003            writer.flush().unwrap();
4004            assert_eq!(writer.presenter.as_mut().unwrap().writer_mut(), &bytes);
4005        }
4006    }
4007
4008    /// Highest 1-based row a `CUP` in `output` addresses on a `height`-row
4009    /// terminal. A row of 9999 is the bottom-addressing sentinel: it means
4010    /// the last row, less any `CUU` right after it. Any other row is taken as
4011    /// written, so an accidental `CUP` past the bottom still shows up.
4012    fn max_cursor_row(output: &[u8], height: u16) -> u16 {
4013        let mut max_row = 0u16;
4014        let mut i = 0;
4015        while i + 2 < output.len() {
4016            if output[i] == 0x1b && output[i + 1] == b'[' {
4017                let mut j = i + 2;
4018                let mut row: u16 = 0;
4019                let mut saw_row = false;
4020                while j < output.len() && output[j].is_ascii_digit() {
4021                    saw_row = true;
4022                    row = row
4023                        .saturating_mul(10)
4024                        .saturating_add((output[j] - b'0') as u16);
4025                    j += 1;
4026                }
4027                if saw_row && j < output.len() && output[j] == b';' {
4028                    j += 1;
4029                    let mut saw_col = false;
4030                    while j < output.len() && output[j].is_ascii_digit() {
4031                        saw_col = true;
4032                        j += 1;
4033                    }
4034                    if saw_col && j < output.len() && output[j] == b'H' {
4035                        if row == 9999 {
4036                            let up = cursor_up_at(output, j + 1);
4037                            row = height.saturating_sub(up);
4038                        }
4039                        max_row = max_row.max(row);
4040                    }
4041                }
4042            }
4043            i += 1;
4044        }
4045        max_row
4046    }
4047
4048    /// The count of a `CSI n A` starting at `at` (`CSI A` is 1), else 0.
4049    fn cursor_up_at(output: &[u8], at: usize) -> u16 {
4050        let Some(rest) = output.get(at..).filter(|rest| rest.starts_with(b"\x1b[")) else {
4051            return 0;
4052        };
4053        let digits = rest[2..].iter().take_while(|b| b.is_ascii_digit()).count();
4054        if rest.get(2 + digits) != Some(&b'A') {
4055            return 0;
4056        }
4057        if digits == 0 {
4058            return 1;
4059        }
4060        std::str::from_utf8(&rest[2..2 + digits])
4061            .ok()
4062            .and_then(|n| n.parse().ok())
4063            .unwrap_or(0)
4064    }
4065
4066    fn basic_caps() -> TerminalCapabilities {
4067        TerminalCapabilities::basic()
4068    }
4069
4070    fn full_caps() -> TerminalCapabilities {
4071        let mut caps = TerminalCapabilities::basic();
4072        caps.color_depth = ColorDepth::TrueColor;
4073        caps.sync_output = true;
4074        caps
4075    }
4076
4077    fn find_nth(haystack: &[u8], needle: &[u8], nth: usize) -> Option<usize> {
4078        if nth == 0 {
4079            return None;
4080        }
4081        let mut count = 0;
4082        let mut i = 0;
4083        while i + needle.len() <= haystack.len() {
4084            if &haystack[i..i + needle.len()] == needle {
4085                count += 1;
4086                if count == nth {
4087                    return Some(i);
4088                }
4089            }
4090            i += 1;
4091        }
4092        None
4093    }
4094
4095    fn temp_evidence_path(label: &str) -> PathBuf {
4096        // Retain evidence even if the test panics, with a fresh directory per run.
4097        let dir = tempfile::Builder::new()
4098            .prefix(&format!("ftui-terminal-writer-{label}-"))
4099            .disable_cleanup(true)
4100            .tempdir()
4101            .expect("create retained evidence directory");
4102        dir.path().join("evidence.jsonl")
4103    }
4104
4105    #[derive(Default)]
4106    struct FaultState {
4107        bytes: Vec<u8>,
4108        write_calls: usize,
4109        injected_failure_triggered: bool,
4110    }
4111
4112    struct SingleWriteFaultWriter {
4113        state: Rc<RefCell<FaultState>>,
4114        fail_on_call: usize,
4115        max_chunk_len: usize,
4116    }
4117
4118    impl SingleWriteFaultWriter {
4119        fn new(state: Rc<RefCell<FaultState>>, fail_on_call: usize, max_chunk_len: usize) -> Self {
4120            Self {
4121                state,
4122                fail_on_call,
4123                max_chunk_len: max_chunk_len.max(1),
4124            }
4125        }
4126    }
4127
4128    impl Write for SingleWriteFaultWriter {
4129        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
4130            let mut state = self.state.borrow_mut();
4131            state.write_calls = state.write_calls.saturating_add(1);
4132            if !state.injected_failure_triggered && state.write_calls == self.fail_on_call {
4133                state.injected_failure_triggered = true;
4134                return Err(io::Error::other("injected partial-write fault"));
4135            }
4136
4137            let write_len = buf.len().min(self.max_chunk_len);
4138            state.bytes.extend_from_slice(&buf[..write_len]);
4139            Ok(write_len)
4140        }
4141
4142        fn flush(&mut self) -> io::Result<()> {
4143            Ok(())
4144        }
4145    }
4146
4147    #[test]
4148    fn new_creates_writer() {
4149        let output = Vec::new();
4150        let writer = TerminalWriter::new(
4151            output,
4152            ScreenMode::Inline { ui_height: 10 },
4153            UiAnchor::Bottom,
4154            basic_caps(),
4155        );
4156        assert_eq!(writer.ui_height(), 10);
4157    }
4158
4159    #[test]
4160    fn ui_start_row_bottom_anchor() {
4161        let output = Vec::new();
4162        let mut writer = TerminalWriter::new(
4163            output,
4164            ScreenMode::Inline { ui_height: 10 },
4165            UiAnchor::Bottom,
4166            basic_caps(),
4167        );
4168        writer.set_size(80, 24);
4169        assert_eq!(writer.ui_start_row(), 14); // 24 - 10 = 14
4170    }
4171
4172    #[test]
4173    fn ui_start_row_top_anchor() {
4174        let output = Vec::new();
4175        let mut writer = TerminalWriter::new(
4176            output,
4177            ScreenMode::Inline { ui_height: 10 },
4178            UiAnchor::Top,
4179            basic_caps(),
4180        );
4181        writer.set_size(80, 24);
4182        assert_eq!(writer.ui_start_row(), 0);
4183    }
4184
4185    #[test]
4186    fn ui_start_row_altscreen() {
4187        let output = Vec::new();
4188        let mut writer = TerminalWriter::new(
4189            output,
4190            ScreenMode::AltScreen,
4191            UiAnchor::Bottom,
4192            basic_caps(),
4193        );
4194        writer.set_size(80, 24);
4195        assert_eq!(writer.ui_start_row(), 0);
4196    }
4197
4198    #[test]
4199    fn present_ui_inline_saves_restores_cursor() {
4200        let mut output = Vec::new();
4201        {
4202            let mut writer = TerminalWriter::new(
4203                &mut output,
4204                ScreenMode::Inline { ui_height: 5 },
4205                UiAnchor::Bottom,
4206                basic_caps(),
4207            );
4208            writer.set_size(10, 10);
4209
4210            let buffer = Buffer::new(10, 5);
4211            writer.present_ui(&buffer, None, true).unwrap();
4212        }
4213
4214        // Should contain cursor save and restore
4215        assert!(output.windows(CURSOR_SAVE.len()).any(|w| w == CURSOR_SAVE));
4216        assert!(
4217            output
4218                .windows(CURSOR_RESTORE.len())
4219                .any(|w| w == CURSOR_RESTORE)
4220        );
4221    }
4222
4223    #[test]
4224    fn present_ui_with_sync_output() {
4225        let mut output = Vec::new();
4226        {
4227            let mut writer = TerminalWriter::new(
4228                &mut output,
4229                ScreenMode::Inline { ui_height: 5 },
4230                UiAnchor::Bottom,
4231                full_caps(),
4232            );
4233            writer.set_size(10, 10);
4234
4235            let buffer = Buffer::new(10, 5);
4236            writer.present_ui(&buffer, None, true).unwrap();
4237        }
4238
4239        // Should contain sync begin and end
4240        assert!(output.windows(SYNC_BEGIN.len()).any(|w| w == SYNC_BEGIN));
4241        assert!(output.windows(SYNC_END.len()).any(|w| w == SYNC_END));
4242    }
4243
4244    #[test]
4245    fn present_ui_altscreen_closes_stale_sync_block_when_policy_allows_sync() {
4246        let mut output = Vec::new();
4247        {
4248            let mut writer = TerminalWriter::new(
4249                &mut output,
4250                ScreenMode::AltScreen,
4251                UiAnchor::Bottom,
4252                full_caps(),
4253            );
4254            writer.set_size(8, 2);
4255            writer.in_sync_block = true;
4256
4257            let mut buffer = Buffer::new(8, 2);
4258            buffer.set_raw(0, 0, Cell::from_char('X'));
4259            writer.present_ui(&buffer, None, true).unwrap();
4260
4261            assert!(
4262                !writer.in_sync_block,
4263                "present_altscreen must close stale sync blocks"
4264            );
4265        }
4266
4267        assert!(
4268            output.windows(SYNC_END.len()).any(|w| w == SYNC_END),
4269            "sync end should be emitted when stale sync state is detected"
4270        );
4271    }
4272
4273    #[test]
4274    fn present_ui_altscreen_stale_sync_block_skips_sync_end_in_mux() {
4275        let mut output = Vec::new();
4276        {
4277            let mut writer = TerminalWriter::new(
4278                &mut output,
4279                ScreenMode::AltScreen,
4280                UiAnchor::Bottom,
4281                mux_caps(),
4282            );
4283            writer.set_size(8, 2);
4284            writer.in_sync_block = true;
4285
4286            let mut buffer = Buffer::new(8, 2);
4287            buffer.set_raw(0, 0, Cell::from_char('X'));
4288            writer.present_ui(&buffer, None, true).unwrap();
4289
4290            assert!(
4291                !writer.in_sync_block,
4292                "present_altscreen must clear stale sync state"
4293            );
4294        }
4295
4296        assert!(
4297            !output.windows(SYNC_END.len()).any(|w| w == SYNC_END),
4298            "sync end must be suppressed when policy disables synchronized output"
4299        );
4300    }
4301
4302    #[test]
4303    fn present_ui_altscreen_sanitizes_grapheme_escape_payloads() {
4304        let mut output = Vec::new();
4305        {
4306            let mut writer = TerminalWriter::new(
4307                &mut output,
4308                ScreenMode::AltScreen,
4309                UiAnchor::Bottom,
4310                basic_caps(),
4311            );
4312            writer.set_size(12, 1);
4313
4314            let gid = writer
4315                .pool_mut()
4316                .intern("ok\x1b]52;c;SGVsbG8=\x1b\\tail\u{009d}", 6);
4317            let mut buffer = Buffer::new(12, 1);
4318            buffer.set_raw(0, 0, Cell::new(CellContent::from_grapheme(gid)));
4319
4320            writer.present_ui(&buffer, None, true).unwrap();
4321        }
4322
4323        let output_str = String::from_utf8_lossy(&output);
4324        assert!(
4325            output_str.contains("oktail"),
4326            "sanitized grapheme content should preserve visible payload"
4327        );
4328        assert!(
4329            !output_str.contains("52;c;SGVsbG8"),
4330            "OSC payload must not be forwarded by alt-screen emitter"
4331        );
4332        assert!(
4333            !output_str.contains('\u{009d}'),
4334            "C1 controls must be stripped from alt-screen grapheme output"
4335        );
4336    }
4337
4338    #[test]
4339    fn present_ui_inline_skips_sync_output_in_mux() {
4340        let mut output = Vec::new();
4341        {
4342            let mut writer = TerminalWriter::new(
4343                &mut output,
4344                ScreenMode::Inline { ui_height: 5 },
4345                UiAnchor::Bottom,
4346                mux_caps(),
4347            );
4348            writer.set_size(10, 10);
4349
4350            let buffer = Buffer::new(10, 5);
4351            writer.present_ui(&buffer, None, true).unwrap();
4352        }
4353
4354        assert!(
4355            !output.windows(SYNC_BEGIN.len()).any(|w| w == SYNC_BEGIN),
4356            "sync begin must be suppressed in tmux/screen/zellij environments"
4357        );
4358        assert!(
4359            !output.windows(SYNC_END.len()).any(|w| w == SYNC_END),
4360            "sync end must be suppressed in tmux/screen/zellij environments"
4361        );
4362    }
4363
4364    #[test]
4365    fn present_ui_altscreen_skips_sync_output_in_mux() {
4366        let mut output = Vec::new();
4367        {
4368            let mut writer = TerminalWriter::new(
4369                &mut output,
4370                ScreenMode::AltScreen,
4371                UiAnchor::Bottom,
4372                mux_caps(),
4373            );
4374            writer.set_size(10, 10);
4375
4376            let buffer = Buffer::new(10, 5);
4377            writer.present_ui(&buffer, None, true).unwrap();
4378        }
4379
4380        assert!(
4381            !output.windows(SYNC_BEGIN.len()).any(|w| w == SYNC_BEGIN),
4382            "sync begin must be suppressed in tmux/screen/zellij environments"
4383        );
4384        assert!(
4385            !output.windows(SYNC_END.len()).any(|w| w == SYNC_END),
4386            "sync end must be suppressed in tmux/screen/zellij environments"
4387        );
4388    }
4389
4390    #[test]
4391    fn managed_hyperlinks_repaint_after_failed_borrowed_present() {
4392        let state = Rc::new(RefCell::new(FaultState::default()));
4393        let backend = SingleWriteFaultWriter::new(Rc::clone(&state), 1, 1);
4394        let mut caps = basic_caps();
4395        caps.osc8_hyperlinks = true;
4396        let mut writer =
4397            TerminalWriter::new(backend, ScreenMode::AltScreen, UiAnchor::Bottom, caps);
4398        writer.set_size(1, 1);
4399        writer.set_hyperlink_limit(1);
4400        writer.begin_link_frame();
4401        let old_id = writer.links_mut().register("https://failed.test");
4402        let mut buffer = Buffer::new(1, 1);
4403        buffer.set_raw(
4404            0,
4405            0,
4406            Cell::from_char('L').with_attrs(CellAttrs::new(StyleFlags::empty(), old_id)),
4407        );
4408        writer
4409            .present_ui(&buffer, None, false)
4410            .expect_err("write fault");
4411        assert!(state.borrow().injected_failure_triggered);
4412        assert!(writer.prev_buffer.is_none());
4413
4414        writer.begin_link_frame();
4415        let new_id = writer.links_mut().register("https://recovered.test");
4416        assert_eq!(new_id, old_id, "failed baseline permits safe reuse");
4417        buffer.set_raw(
4418            0,
4419            0,
4420            Cell::from_char('L').with_attrs(CellAttrs::new(StyleFlags::empty(), new_id)),
4421        );
4422        writer
4423            .present_ui(&buffer, None, false)
4424            .expect("recovered present");
4425        assert_eq!(writer.links().len(), 1);
4426        let bytes = state.borrow().bytes.clone();
4427        let output = String::from_utf8(bytes).unwrap();
4428        assert!(output.contains("\x1b]8;;https://recovered.test\x07L\x1b[0m\x1b]8;;\x07"));
4429        // BufWriter retains serialized bytes on the injected first-write
4430        // failure. Retrying may flush that old frame before the full repaint;
4431        // an I/O error is not a rollback. Require the final target, not absence
4432        // of the earlier frame's bytes. Inspect before Drop can clean up.
4433        let targets: Vec<_> = output
4434            .split("\x1b]8;;")
4435            .skip(1)
4436            .filter_map(|part| part.split_once('\x07'))
4437            .map(|(url, _)| url)
4438            .filter(|url| !url.is_empty())
4439            .collect();
4440        assert_eq!(targets, ["https://failed.test", "https://recovered.test"]);
4441        let mut terminal = ftui_render::terminal_model::TerminalModel::new(1, 1);
4442        terminal.process(output.as_bytes());
4443        let cell = terminal.cell(0, 0).unwrap();
4444        assert_eq!(cell.text, "L");
4445        assert_eq!(
4446            terminal.link_url(cell.link_id),
4447            Some("https://recovered.test")
4448        );
4449        assert!(!terminal.has_dangling_link());
4450    }
4451
4452    #[test]
4453    fn unmanaged_hyperlinks_keep_cached_ids_across_frame_preparation() {
4454        let mut writer = TerminalWriter::new(
4455            Vec::new(),
4456            ScreenMode::AltScreen,
4457            UiAnchor::Bottom,
4458            basic_caps(),
4459        );
4460        let id = writer.links_mut().register("https://cached.test");
4461        for _ in 0..3 {
4462            writer.begin_link_frame();
4463            assert_eq!(writer.links().get(id), Some("https://cached.test"));
4464        }
4465    }
4466
4467    #[test]
4468    fn present_ui_inline_skips_hyperlinks_in_mux() {
4469        let mut output = Vec::new();
4470        {
4471            let mut caps = mux_caps();
4472            caps.osc8_hyperlinks = true;
4473
4474            let mut writer = TerminalWriter::new(
4475                &mut output,
4476                ScreenMode::Inline { ui_height: 2 },
4477                UiAnchor::Bottom,
4478                caps,
4479            );
4480            writer.set_size(8, 4);
4481
4482            let link_id = writer.links_mut().register("https://example.com");
4483            let mut buffer = Buffer::new(8, 2);
4484            buffer.set_raw(
4485                0,
4486                0,
4487                Cell::from_char('L').with_attrs(CellAttrs::new(StyleFlags::empty(), link_id)),
4488            );
4489            writer.present_ui(&buffer, None, true).unwrap();
4490        }
4491
4492        assert!(
4493            !output.windows(b"\x1b]8;".len()).any(|w| w == b"\x1b]8;"),
4494            "OSC 8 sequences must be suppressed by mux hyperlink policy"
4495        );
4496    }
4497
4498    #[test]
4499    fn present_ui_inline_closes_hyperlinks_at_frame_end() {
4500        let mut output = Vec::new();
4501        {
4502            let mut caps = full_caps();
4503            caps.osc8_hyperlinks = true;
4504
4505            let mut writer = TerminalWriter::new(
4506                &mut output,
4507                ScreenMode::Inline { ui_height: 2 },
4508                UiAnchor::Bottom,
4509                caps,
4510            );
4511            writer.set_size(8, 4);
4512
4513            let link_id = writer.links_mut().register("https://example.com");
4514            let mut buffer = Buffer::new(8, 2);
4515            buffer.set_raw(
4516                0,
4517                0,
4518                Cell::from_char('L').with_attrs(CellAttrs::new(StyleFlags::empty(), link_id)),
4519            );
4520            writer.present_ui(&buffer, None, true).unwrap();
4521        }
4522
4523        let open = b"\x1b]8;;https://example.com\x07";
4524        let close = b"\x1b]8;;\x07";
4525        let open_pos = output
4526            .windows(open.len())
4527            .position(|window| window == open)
4528            .expect("expected OSC 8 open sequence");
4529        let close_pos = output
4530            .windows(close.len())
4531            .position(|window| window == close)
4532            .expect("expected OSC 8 close sequence");
4533        assert!(
4534            open_pos < close_pos,
4535            "hyperlink must close before frame end"
4536        );
4537    }
4538
4539    #[test]
4540    fn present_ui_altscreen_skips_hyperlinks_in_mux() {
4541        let mut output = Vec::new();
4542        {
4543            let mut caps = mux_caps();
4544            caps.osc8_hyperlinks = true;
4545
4546            let mut writer =
4547                TerminalWriter::new(&mut output, ScreenMode::AltScreen, UiAnchor::Bottom, caps);
4548            writer.set_size(8, 4);
4549
4550            let link_id = writer.links_mut().register("https://example.com");
4551            let mut buffer = Buffer::new(8, 2);
4552            buffer.set_raw(
4553                0,
4554                0,
4555                Cell::from_char('L').with_attrs(CellAttrs::new(StyleFlags::empty(), link_id)),
4556            );
4557            writer.present_ui(&buffer, None, true).unwrap();
4558        }
4559
4560        assert!(
4561            !output.windows(b"\x1b]8;".len()).any(|w| w == b"\x1b]8;"),
4562            "OSC 8 sequences must be suppressed by mux hyperlink policy"
4563        );
4564    }
4565
4566    #[test]
4567    fn present_ui_altscreen_closes_hyperlinks_at_frame_end() {
4568        let mut output = Vec::new();
4569        {
4570            let mut caps = full_caps();
4571            caps.osc8_hyperlinks = true;
4572
4573            let mut writer =
4574                TerminalWriter::new(&mut output, ScreenMode::AltScreen, UiAnchor::Bottom, caps);
4575            writer.set_size(8, 4);
4576
4577            let link_id = writer.links_mut().register("https://example.com");
4578            let mut buffer = Buffer::new(8, 2);
4579            buffer.set_raw(
4580                0,
4581                0,
4582                Cell::from_char('L').with_attrs(CellAttrs::new(StyleFlags::empty(), link_id)),
4583            );
4584            writer.present_ui(&buffer, None, true).unwrap();
4585        }
4586
4587        let open = b"\x1b]8;;https://example.com\x07";
4588        let close = b"\x1b]8;;\x07";
4589        let open_pos = output
4590            .windows(open.len())
4591            .position(|window| window == open)
4592            .expect("expected OSC 8 open sequence");
4593        let close_pos = output
4594            .windows(close.len())
4595            .position(|window| window == close)
4596            .expect("expected OSC 8 close sequence");
4597        assert!(
4598            open_pos < close_pos,
4599            "hyperlink must close before frame end"
4600        );
4601    }
4602
4603    #[test]
4604    fn present_ui_hides_cursor_when_requested() {
4605        let mut output = Vec::new();
4606        {
4607            let mut writer = TerminalWriter::new(
4608                &mut output,
4609                ScreenMode::AltScreen,
4610                UiAnchor::Bottom,
4611                basic_caps(),
4612            );
4613            writer.set_size(10, 5);
4614
4615            let buffer = Buffer::new(10, 5);
4616            writer.present_ui(&buffer, None, false).unwrap();
4617        }
4618
4619        assert!(
4620            output.windows(6).any(|w| w == b"\x1b[?25l"),
4621            "expected cursor hide sequence"
4622        );
4623    }
4624
4625    #[test]
4626    fn present_ui_visible_with_position_temporarily_hides_cursor() {
4627        let mut output = Vec::new();
4628        {
4629            let mut writer = TerminalWriter::new(
4630                &mut output,
4631                ScreenMode::AltScreen,
4632                UiAnchor::Bottom,
4633                basic_caps(),
4634            );
4635            writer.set_size(10, 5);
4636
4637            let buffer = Buffer::new(10, 5);
4638            writer.present_ui(&buffer, Some((0, 0)), true).unwrap();
4639        }
4640
4641        assert!(
4642            output.windows(6).any(|w| w == b"\x1b[?25l"),
4643            "expected cursor hide during frame emission"
4644        );
4645    }
4646
4647    #[test]
4648    fn present_ui_visible_without_position_hides_cursor() {
4649        let mut output = Vec::new();
4650        {
4651            let mut writer = TerminalWriter::new(
4652                &mut output,
4653                ScreenMode::AltScreen,
4654                UiAnchor::Bottom,
4655                basic_caps(),
4656            );
4657            writer.set_size(10, 5);
4658
4659            let buffer = Buffer::new(10, 5);
4660            writer.present_ui(&buffer, None, true).unwrap();
4661        }
4662
4663        assert!(
4664            output.windows(6).any(|w| w == b"\x1b[?25l"),
4665            "expected cursor hide sequence when no explicit cursor position exists"
4666        );
4667    }
4668
4669    #[test]
4670    fn write_log_in_inline_mode() {
4671        let mut output = Vec::new();
4672        {
4673            let mut writer = TerminalWriter::new(
4674                &mut output,
4675                ScreenMode::Inline { ui_height: 5 },
4676                UiAnchor::Bottom,
4677                basic_caps(),
4678            );
4679            writer.write_log("test log\n").unwrap();
4680        }
4681
4682        let output_str = String::from_utf8_lossy(&output);
4683        assert!(output_str.contains("test log"));
4684    }
4685
4686    #[test]
4687    fn write_log_in_altscreen_is_noop() {
4688        let mut output = Vec::new();
4689        {
4690            let mut writer = TerminalWriter::new(
4691                &mut output,
4692                ScreenMode::AltScreen,
4693                UiAnchor::Bottom,
4694                basic_caps(),
4695            );
4696            writer.write_log("test log\n").unwrap();
4697        }
4698
4699        let output_str = String::from_utf8_lossy(&output);
4700        // Should not contain log text (altscreen drops logs)
4701        assert!(!output_str.contains("test log"));
4702    }
4703
4704    #[test]
4705    fn clear_screen_resets_prev_buffer() {
4706        let mut output = Vec::new();
4707        let mut writer = TerminalWriter::new(
4708            &mut output,
4709            ScreenMode::AltScreen,
4710            UiAnchor::Bottom,
4711            basic_caps(),
4712        );
4713
4714        // Present a buffer
4715        let buffer = Buffer::new(10, 5);
4716        writer.present_ui(&buffer, None, true).unwrap();
4717        assert!(writer.prev_buffer.is_some());
4718
4719        // Clear screen should reset
4720        writer.clear_screen().unwrap();
4721        assert!(writer.prev_buffer.is_none());
4722    }
4723
4724    #[test]
4725    fn set_size_clears_prev_buffer() {
4726        let output = Vec::new();
4727        let mut writer = TerminalWriter::new(
4728            output,
4729            ScreenMode::AltScreen,
4730            UiAnchor::Bottom,
4731            basic_caps(),
4732        );
4733
4734        writer.prev_buffer = Some(Buffer::new(10, 10));
4735        writer.set_size(20, 20);
4736
4737        assert!(writer.prev_buffer.is_none());
4738    }
4739
4740    #[test]
4741    fn inline_auto_resize_clears_cached_height() {
4742        let output = Vec::new();
4743        let mut writer = TerminalWriter::new(
4744            output,
4745            ScreenMode::InlineAuto {
4746                min_height: 3,
4747                max_height: 8,
4748            },
4749            UiAnchor::Bottom,
4750            basic_caps(),
4751        );
4752
4753        writer.set_size(80, 24);
4754        writer.set_auto_ui_height(6);
4755        assert_eq!(writer.auto_ui_height(), Some(6));
4756        assert_eq!(writer.render_height_hint(), 6);
4757
4758        writer.set_size(100, 30);
4759        assert_eq!(writer.auto_ui_height(), None);
4760        assert_eq!(writer.render_height_hint(), 8);
4761    }
4762
4763    #[test]
4764    fn drop_cleanup_restores_cursor() {
4765        let mut output = Vec::new();
4766        {
4767            let mut writer = TerminalWriter::new(
4768                &mut output,
4769                ScreenMode::Inline { ui_height: 5 },
4770                UiAnchor::Bottom,
4771                basic_caps(),
4772            );
4773            writer.cursor_saved = true;
4774            // Dropped here
4775        }
4776
4777        // Should contain cursor restore
4778        assert!(
4779            output
4780                .windows(CURSOR_RESTORE.len())
4781                .any(|w| w == CURSOR_RESTORE)
4782        );
4783    }
4784
4785    #[test]
4786    fn drop_cleanup_ends_sync_block() {
4787        let mut output = Vec::new();
4788        {
4789            let mut writer = TerminalWriter::new(
4790                &mut output,
4791                ScreenMode::Inline { ui_height: 5 },
4792                UiAnchor::Bottom,
4793                full_caps(),
4794            );
4795            writer.in_sync_block = true;
4796            // Dropped here
4797        }
4798
4799        // Should contain sync end
4800        assert!(output.windows(SYNC_END.len()).any(|w| w == SYNC_END));
4801    }
4802
4803    #[test]
4804    fn drop_cleanup_skips_sync_end_in_mux_even_with_stale_state() {
4805        let mut output = Vec::new();
4806        {
4807            let mut writer = TerminalWriter::new(
4808                &mut output,
4809                ScreenMode::Inline { ui_height: 5 },
4810                UiAnchor::Bottom,
4811                mux_caps(),
4812            );
4813            writer.in_sync_block = true;
4814            // Dropped here
4815        }
4816
4817        assert!(
4818            !output.windows(SYNC_END.len()).any(|w| w == SYNC_END),
4819            "drop cleanup must not emit sync_end in mux environments"
4820        );
4821    }
4822
4823    #[test]
4824    fn present_multiple_frames_uses_diff() {
4825        use std::io::Cursor;
4826
4827        // Use Cursor<Vec<u8>> which allows us to track position
4828        let output = Cursor::new(Vec::new());
4829        let mut writer = TerminalWriter::new(
4830            output,
4831            ScreenMode::AltScreen,
4832            UiAnchor::Bottom,
4833            basic_caps(),
4834        );
4835        writer.set_size(10, 5);
4836
4837        // First frame - full draw
4838        let mut buffer1 = Buffer::new(10, 5);
4839        buffer1.set_raw(0, 0, Cell::from_char('A'));
4840        writer.present_ui(&buffer1, None, true).unwrap();
4841
4842        // Second frame - same content (diff is empty, minimal output)
4843        writer.present_ui(&buffer1, None, true).unwrap();
4844
4845        // Third frame - change one cell
4846        let mut buffer2 = buffer1.clone();
4847        buffer2.set_raw(1, 0, Cell::from_char('B'));
4848        writer.present_ui(&buffer2, None, true).unwrap();
4849
4850        // Test passes if it doesn't panic - the diffing is working
4851        // (Detailed output length verification would require more complex setup)
4852    }
4853
4854    #[test]
4855    fn cell_content_rendered_correctly() {
4856        let mut output = Vec::new();
4857        {
4858            let mut writer = TerminalWriter::new(
4859                &mut output,
4860                ScreenMode::AltScreen,
4861                UiAnchor::Bottom,
4862                basic_caps(),
4863            );
4864            writer.set_size(10, 5);
4865
4866            let mut buffer = Buffer::new(10, 5);
4867            buffer.set_raw(0, 0, Cell::from_char('H'));
4868            buffer.set_raw(1, 0, Cell::from_char('i'));
4869            buffer.set_raw(2, 0, Cell::from_char('!'));
4870            writer.present_ui(&buffer, None, true).unwrap();
4871        }
4872
4873        let output_str = String::from_utf8_lossy(&output);
4874        assert!(output_str.contains('H'));
4875        assert!(output_str.contains('i'));
4876        assert!(output_str.contains('!'));
4877    }
4878
4879    #[test]
4880    fn resize_reanchors_ui_region() {
4881        let output = Vec::new();
4882        let mut writer = TerminalWriter::new(
4883            output,
4884            ScreenMode::Inline { ui_height: 10 },
4885            UiAnchor::Bottom,
4886            basic_caps(),
4887        );
4888
4889        // Initial size: 80x24, UI at row 14 (24 - 10)
4890        writer.set_size(80, 24);
4891        assert_eq!(writer.ui_start_row(), 14);
4892
4893        // After resize to 80x40, UI should be at row 30 (40 - 10)
4894        writer.set_size(80, 40);
4895        assert_eq!(writer.ui_start_row(), 30);
4896
4897        // After resize to smaller 80x15, UI at row 5 (15 - 10)
4898        writer.set_size(80, 15);
4899        assert_eq!(writer.ui_start_row(), 5);
4900    }
4901
4902    #[test]
4903    fn inline_auto_height_clamps_and_uses_max_for_render() {
4904        let output = Vec::new();
4905        let mut writer = TerminalWriter::new(
4906            output,
4907            ScreenMode::InlineAuto {
4908                min_height: 3,
4909                max_height: 8,
4910            },
4911            UiAnchor::Bottom,
4912            basic_caps(),
4913        );
4914        writer.set_size(80, 24);
4915
4916        // Default to min height until measured.
4917        assert_eq!(writer.ui_height(), 3);
4918        assert_eq!(writer.auto_ui_height(), None);
4919
4920        // render_height_hint uses max to allow measurement when cache is empty.
4921        assert_eq!(writer.render_height_hint(), 8);
4922
4923        // Cache hit: render_height_hint uses cached height.
4924        writer.set_auto_ui_height(6);
4925        assert_eq!(writer.render_height_hint(), 6);
4926
4927        // Cache miss: clearing restores max hint.
4928        writer.clear_auto_ui_height();
4929        assert_eq!(writer.render_height_hint(), 8);
4930
4931        // Cache should still set when clamped to min.
4932        writer.set_auto_ui_height(3);
4933        assert_eq!(writer.auto_ui_height(), Some(3));
4934        assert_eq!(writer.ui_height(), 3);
4935
4936        writer.clear_auto_ui_height();
4937        assert_eq!(writer.render_height_hint(), 8);
4938
4939        // Clamp to max.
4940        writer.set_auto_ui_height(10);
4941        assert_eq!(writer.ui_height(), 8);
4942
4943        // Clamp to min.
4944        writer.set_auto_ui_height(1);
4945        assert_eq!(writer.ui_height(), 3);
4946    }
4947
4948    #[test]
4949    fn resize_with_top_anchor_stays_at_zero() {
4950        let output = Vec::new();
4951        let mut writer = TerminalWriter::new(
4952            output,
4953            ScreenMode::Inline { ui_height: 10 },
4954            UiAnchor::Top,
4955            basic_caps(),
4956        );
4957
4958        writer.set_size(80, 24);
4959        assert_eq!(writer.ui_start_row(), 0);
4960
4961        writer.set_size(80, 40);
4962        assert_eq!(writer.ui_start_row(), 0);
4963    }
4964
4965    #[test]
4966    fn inline_mode_never_clears_full_screen() {
4967        let mut output = Vec::new();
4968        {
4969            let mut writer = TerminalWriter::new(
4970                &mut output,
4971                ScreenMode::Inline { ui_height: 5 },
4972                UiAnchor::Bottom,
4973                basic_caps(),
4974            );
4975            writer.set_size(10, 10);
4976
4977            let buffer = Buffer::new(10, 5);
4978            writer.present_ui(&buffer, None, true).unwrap();
4979        }
4980
4981        // Should NOT contain full screen clear (ED2 = "\x1b[2J")
4982        let has_ed2 = output.windows(4).any(|w| w == b"\x1b[2J");
4983        assert!(!has_ed2, "Inline mode should never use full screen clear");
4984
4985        // Should contain individual line clears (EL = "\x1b[2K")
4986        assert!(output.windows(ERASE_LINE.len()).any(|w| w == ERASE_LINE));
4987    }
4988
4989    #[test]
4990    fn present_after_log_maintains_cursor_position() {
4991        let mut output = Vec::new();
4992        {
4993            let mut writer = TerminalWriter::new(
4994                &mut output,
4995                ScreenMode::Inline { ui_height: 5 },
4996                UiAnchor::Bottom,
4997                basic_caps(),
4998            );
4999            writer.set_size(10, 10);
5000
5001            // Present UI first
5002            let buffer = Buffer::new(10, 5);
5003            writer.present_ui(&buffer, None, true).unwrap();
5004
5005            // Write a log
5006            writer.write_log("log line\n").unwrap();
5007
5008            // Present UI again
5009            writer.present_ui(&buffer, None, true).unwrap();
5010        }
5011
5012        // Should have cursor save before each UI present. Overlay log
5013        // writes add their own balanced SAVE/RESTORE pair, so only a floor
5014        // is asserted here; balance itself is covered by the overlay tests.
5015        let save_count = output
5016            .windows(CURSOR_SAVE.len())
5017            .filter(|w| *w == CURSOR_SAVE)
5018            .count();
5019        assert!(
5020            save_count >= 2,
5021            "Should have saved cursor at least twice (once per present)"
5022        );
5023
5024        // Should have cursor restore after each UI present
5025        let restore_count = output
5026            .windows(CURSOR_RESTORE.len())
5027            .filter(|w| *w == CURSOR_RESTORE)
5028            .count();
5029        // At least 2 from presents, plus 1 from drop cleanup = 3
5030        assert!(
5031            restore_count >= 2,
5032            "Should have restored cursor at least twice"
5033        );
5034    }
5035
5036    #[test]
5037    fn ui_height_bounds_check() {
5038        let output = Vec::new();
5039        let mut writer = TerminalWriter::new(
5040            output,
5041            ScreenMode::Inline { ui_height: 100 },
5042            UiAnchor::Bottom,
5043            basic_caps(),
5044        );
5045
5046        // Terminal smaller than UI height
5047        writer.set_size(80, 10);
5048
5049        // Should saturate to 0, not underflow
5050        assert_eq!(writer.ui_start_row(), 0);
5051    }
5052
5053    #[test]
5054    fn inline_ui_height_clamped_to_terminal_height() {
5055        let mut output = Vec::new();
5056        {
5057            let mut writer = TerminalWriter::new(
5058                &mut output,
5059                ScreenMode::Inline { ui_height: 10 },
5060                UiAnchor::Bottom,
5061                basic_caps(),
5062            );
5063            writer.set_size(8, 3);
5064            let buffer = Buffer::new(8, 10);
5065            writer.present_ui(&buffer, None, true).unwrap();
5066        }
5067
5068        let max_row = max_cursor_row(&output, 3);
5069        assert!(
5070            max_row <= 3,
5071            "cursor row {} exceeds terminal height",
5072            max_row
5073        );
5074    }
5075
5076    #[test]
5077    fn inline_diff_frame_never_emits_below_the_fold() {
5078        // Regression: the incremental-diff branch emitted every diff run
5079        // unclipped. With ui_height > term_height, a change on a buffer row
5080        // below the fold produced a CUP past the physical bottom row, which
5081        // real terminals clamp — scribbling over the last visible row. The
5082        // full-redraw branch already clipped; the diff branch must too.
5083        let mut output = Vec::new();
5084        {
5085            let mut writer = TerminalWriter::new(
5086                &mut output,
5087                ScreenMode::Inline { ui_height: 20 },
5088                UiAnchor::Bottom,
5089                basic_caps(),
5090            );
5091            writer.set_size(80, 10); // terminal shorter than the UI
5092
5093            // Frame 1: full redraw (clipped by the existing logic).
5094            let buffer = Buffer::new(80, 20);
5095            writer.present_ui(&buffer, None, true).unwrap();
5096
5097            // Frame 2: change ONLY a below-the-fold row (row 19).
5098            let mut buffer2 = Buffer::new(80, 20);
5099            buffer2.set(0, 19, ftui_render::cell::Cell::from_char('B'));
5100            writer.present_ui(&buffer2, None, true).unwrap();
5101        }
5102
5103        let max_row = max_cursor_row(&output, 10);
5104        assert!(
5105            max_row <= 10,
5106            "diff frame emitted cursor row {max_row} past the 10-row terminal"
5107        );
5108        // The below-the-fold glyph must not appear anywhere in the output.
5109        assert!(
5110            !output.windows(1).any(|w| w == b"B"),
5111            "below-the-fold cell was emitted"
5112        );
5113    }
5114
5115    #[test]
5116    fn inline_shrink_clears_stale_rows() {
5117        let mut output = Vec::new();
5118        {
5119            let mut writer = TerminalWriter::new(
5120                &mut output,
5121                ScreenMode::InlineAuto {
5122                    min_height: 1,
5123                    max_height: 6,
5124                },
5125                UiAnchor::Bottom,
5126                basic_caps(),
5127            );
5128            writer.set_size(10, 10);
5129
5130            let buffer = Buffer::new(10, 6);
5131            writer.set_auto_ui_height(6);
5132            writer.present_ui(&buffer, None, true).unwrap();
5133
5134            writer.set_auto_ui_height(3);
5135            writer.present_ui(&buffer, None, true).unwrap();
5136        }
5137
5138        let second_save = find_nth(&output, CURSOR_SAVE, 2).expect("expected second cursor save");
5139        let after_save = &output[second_save..];
5140        let restore_idx = after_save
5141            .windows(CURSOR_RESTORE.len())
5142            .position(|w| w == CURSOR_RESTORE)
5143            .expect("expected cursor restore after second save");
5144        let segment = &after_save[..restore_idx];
5145        let erase_count = segment
5146            .windows(ERASE_LINE.len())
5147            .filter(|w| *w == ERASE_LINE)
5148            .count();
5149        let bg_reset_count = segment
5150            .windows(SGR_BG_DEFAULT.len())
5151            .filter(|w| *w == SGR_BG_DEFAULT)
5152            .count();
5153
5154        assert_eq!(erase_count, 6, "expected clears for stale + new rows");
5155        assert!(
5156            bg_reset_count >= 2,
5157            "expected background resets before row clears"
5158        );
5159    }
5160
5161    // --- Scroll-region optimization tests ---
5162
5163    /// Capabilities that enable scroll-region strategy (no mux, scroll_region + sync_output).
5164    fn scroll_region_caps() -> TerminalCapabilities {
5165        let mut caps = TerminalCapabilities::basic();
5166        caps.scroll_region = true;
5167        caps.sync_output = true;
5168        caps
5169    }
5170
5171    /// Capabilities for hybrid strategy (scroll_region but no sync_output).
5172    fn hybrid_caps() -> TerminalCapabilities {
5173        let mut caps = TerminalCapabilities::basic();
5174        caps.scroll_region = true;
5175        caps
5176    }
5177
5178    /// Capabilities that force overlay (in tmux even with scroll_region).
5179    fn mux_caps() -> TerminalCapabilities {
5180        let mut caps = TerminalCapabilities::basic();
5181        caps.scroll_region = true;
5182        caps.sync_output = true;
5183        caps.in_tmux = true;
5184        caps
5185    }
5186
5187    #[test]
5188    fn scroll_region_bounds_bottom_anchor() {
5189        let mut output = Vec::new();
5190        {
5191            let mut writer = TerminalWriter::new(
5192                &mut output,
5193                ScreenMode::Inline { ui_height: 5 },
5194                UiAnchor::Bottom,
5195                scroll_region_caps(),
5196            );
5197            writer.set_size(10, 10);
5198            let buffer = Buffer::new(10, 5);
5199            writer.present_ui(&buffer, None, true).unwrap();
5200        }
5201
5202        let seq = b"\x1b[1;5r";
5203        assert!(
5204            output.windows(seq.len()).any(|w| w == seq),
5205            "expected scroll region for bottom anchor"
5206        );
5207    }
5208
5209    #[test]
5210    fn scroll_region_bounds_top_anchor() {
5211        let mut output = Vec::new();
5212        {
5213            let mut writer = TerminalWriter::new(
5214                &mut output,
5215                ScreenMode::Inline { ui_height: 5 },
5216                UiAnchor::Top,
5217                scroll_region_caps(),
5218            );
5219            writer.set_size(10, 10);
5220            let buffer = Buffer::new(10, 5);
5221            writer.present_ui(&buffer, None, true).unwrap();
5222        }
5223
5224        let seq = b"\x1b[6;10r";
5225        assert!(
5226            output.windows(seq.len()).any(|w| w == seq),
5227            "expected scroll region for top anchor"
5228        );
5229        let cursor_seq = b"\x1b[6;1H";
5230        assert!(
5231            output.windows(cursor_seq.len()).any(|w| w == cursor_seq),
5232            "expected cursor move into log region for top anchor"
5233        );
5234    }
5235
5236    #[test]
5237    fn present_ui_inline_resets_style_before_cursor_restore() {
5238        let mut output = Vec::new();
5239        {
5240            let mut writer = TerminalWriter::new(
5241                &mut output,
5242                ScreenMode::Inline { ui_height: 2 },
5243                UiAnchor::Bottom,
5244                basic_caps(),
5245            );
5246            writer.set_size(5, 5);
5247            let mut buffer = Buffer::new(5, 2);
5248            buffer.set_raw(0, 0, Cell::from_char('X').with_fg(PackedRgba::RED));
5249            writer.present_ui(&buffer, None, true).unwrap();
5250        }
5251
5252        let seq = b"\x1b[0m\x1b8";
5253        assert!(
5254            output.windows(seq.len()).any(|w| w == seq),
5255            "expected SGR reset before cursor restore in inline mode"
5256        );
5257    }
5258
5259    /// Regression for the "0 DECSTBM under xterm-256color" audit finding:
5260    /// scroll-region capability without sync output selects `Hybrid`, and
5261    /// the first inline present emits the DECSTBM region. (The audit run
5262    /// emitted none because this repository's WezTerm session counts as a
5263    /// multiplexer, which selects overlay redraw; that is the mux rule.)
5264    #[test]
5265    fn hybrid_strategy_emits_decstbm_without_sync() {
5266        let mut caps = TerminalCapabilities::basic();
5267        caps.scroll_region = true;
5268        caps.sync_output = false;
5269        let mut output = Vec::new();
5270        {
5271            let mut w = TerminalWriter::new(
5272                &mut output,
5273                ScreenMode::Inline { ui_height: 3 },
5274                UiAnchor::Bottom,
5275                caps,
5276            );
5277            w.set_size(80, 24);
5278            assert_eq!(w.inline_strategy(), InlineStrategy::Hybrid);
5279            assert_eq!(w.scroll_region_verified(), None);
5280
5281            let mut buffer = Buffer::new(80, 3);
5282            buffer.set(0, 0, ftui_render::cell::Cell::from_char('H'));
5283            w.present_ui(&buffer, None, false).expect("present");
5284            assert!(w.scroll_region_active());
5285        }
5286        let out = String::from_utf8_lossy(&output).into_owned();
5287        assert!(
5288            out.contains("\x1b[1;21r"),
5289            "Hybrid must set DECSTBM 1..rows-ui_height; got: {out:?}"
5290        );
5291        assert!(
5292            !out.contains("\x1b[?2026h"),
5293            "no sync brackets without sync output; got: {out:?}"
5294        );
5295    }
5296
5297    /// A negative DECSTBM self-test verdict switches a scroll-region
5298    /// strategy to overlay redraw before the first frame and exports the
5299    /// fallback with the ledger; a positive verdict keeps it.
5300    #[test]
5301    fn unverified_scroll_region_falls_back_to_overlay_and_exports_evidence() {
5302        use ftui_core::caps_probe::ScrollRegionVerdict;
5303
5304        let mut caps = TerminalCapabilities::basic();
5305        caps.scroll_region = true;
5306        caps.sync_output = false;
5307
5308        // Honoured: nothing changes.
5309        let mut kept_output = Vec::new();
5310        {
5311            let mut kept = TerminalWriter::new(
5312                &mut kept_output,
5313                ScreenMode::Inline { ui_height: 3 },
5314                UiAnchor::Bottom,
5315                caps,
5316            );
5317            kept.set_scroll_region_verified(
5318                Some(ScrollRegionVerdict::Honoured { observed_row: 21 }),
5319                24,
5320                21,
5321            );
5322            assert_eq!(kept.inline_strategy(), InlineStrategy::Hybrid);
5323            assert_eq!(kept.scroll_region_verified(), Some(true));
5324            assert!(kept.strategy_fallback().is_none());
5325        }
5326
5327        // Ignored: fall back, remember the fallback until a sink attaches.
5328        let evidence_path = temp_evidence_path("scroll_region_fallback");
5329        let mut output = Vec::new();
5330        {
5331            let mut w = TerminalWriter::new(
5332                &mut output,
5333                ScreenMode::Inline { ui_height: 3 },
5334                UiAnchor::Bottom,
5335                caps,
5336            );
5337            w.set_size(80, 24);
5338            w.set_scroll_region_verified(
5339                Some(ScrollRegionVerdict::Ignored { observed_row: 24 }),
5340                24,
5341                21,
5342            );
5343            assert_eq!(w.inline_strategy(), InlineStrategy::OverlayRedraw);
5344            assert_eq!(w.scroll_region_verified(), Some(false));
5345            let fallback = w.strategy_fallback().expect("fallback recorded").clone();
5346            assert_eq!(fallback.from, InlineStrategy::Hybrid);
5347            assert_eq!(fallback.reason, "cpr_mismatch");
5348            assert_eq!(fallback.observed_row, Some(24));
5349            assert_eq!(fallback.expected_row, 21);
5350
5351            let mut buffer = Buffer::new(80, 3);
5352            buffer.set(0, 0, ftui_render::cell::Cell::from_char('O'));
5353            w.present_ui(&buffer, None, false).expect("present");
5354            assert!(!w.scroll_region_active());
5355
5356            let sink = crate::evidence_sink::EvidenceSink::from_config(
5357                &crate::evidence_sink::EvidenceSinkConfig::enabled_file(&evidence_path),
5358            )
5359            .expect("sink config")
5360            .expect("sink enabled");
5361            w.set_evidence_sink(Some(sink));
5362            w.export_capability_decisions();
5363            assert!(w.strategy_fallback().is_none(), "exported once");
5364        }
5365        let out = String::from_utf8_lossy(&output).into_owned();
5366        assert!(
5367            !out.contains("\x1b[1;21r"),
5368            "no DECSTBM after the fallback; got: {out:?}"
5369        );
5370        let contents = std::fs::read_to_string(&evidence_path).expect("evidence written");
5371        assert!(
5372            contents.contains(
5373                r#"{"event":"inline_strategy_fallback","from":"hybrid","to":"overlay_redraw","reason":"cpr_mismatch","observed_row":24,"expected_row":21,"rows":24,"region_bottom":21}"#
5374            ),
5375            "{contents}"
5376        );
5377        assert!(
5378            contents.contains(r#""event":"inline_strategy","strategy":"overlay_redraw""#)
5379                && contents.contains(r#""scroll_region_verified":false"#),
5380            "{contents}"
5381        );
5382
5383        // Timeout counts as not honoured too.
5384        let mut timed_out_output = Vec::new();
5385        {
5386            let mut timed_out = TerminalWriter::new(
5387                &mut timed_out_output,
5388                ScreenMode::Inline { ui_height: 3 },
5389                UiAnchor::Bottom,
5390                caps,
5391            );
5392            timed_out.set_scroll_region_verified(Some(ScrollRegionVerdict::NoReply), 24, 21);
5393            assert_eq!(timed_out.inline_strategy(), InlineStrategy::OverlayRedraw);
5394            assert_eq!(
5395                timed_out.strategy_fallback().map(|f| f.reason),
5396                Some("cpr_timeout")
5397            );
5398        }
5399    }
5400
5401    #[test]
5402    fn evidence_sink_exports_capability_decisions_and_inline_strategy() {
5403        use ftui_core::capability_override::PolicyOverrides;
5404        use ftui_core::caps_probe::{ProbeConfig, ProbeResult, decisions_from_probe};
5405
5406        // A terminal that was not on the allowlist but answered DECRPM 2026.
5407        let mut before = TerminalCapabilities::basic();
5408        before.scroll_region = true;
5409        let config = ProbeConfig {
5410            probe_da1: false,
5411            probe_da2: false,
5412            probe_background: false,
5413            probe_truecolor: false,
5414            probe_sync_output: true,
5415            ..ProbeConfig::default()
5416        };
5417        let result = ProbeResult {
5418            sync_output: Some(true),
5419            ..ProbeResult::default()
5420        };
5421        let mut after = before;
5422        after.refine_from_probe(&result);
5423        let decisions = decisions_from_probe(
5424            &before,
5425            &config,
5426            &result,
5427            PolicyOverrides::default(),
5428            &after,
5429        );
5430
5431        let evidence_path = temp_evidence_path("capability_decisions");
5432        let sink = crate::evidence_sink::EvidenceSink::from_config(
5433            &crate::evidence_sink::EvidenceSinkConfig::enabled_file(&evidence_path),
5434        )
5435        .expect("sink config")
5436        .expect("sink enabled");
5437
5438        // Ledger attached before the sink: rows must still come out once.
5439        let w = TerminalWriter::new(
5440            Vec::new(),
5441            ScreenMode::Inline { ui_height: 5 },
5442            UiAnchor::Bottom,
5443            after,
5444        )
5445        .with_capability_decisions(decisions.clone())
5446        .with_evidence_sink(sink.clone());
5447        assert_eq!(w.inline_strategy(), InlineStrategy::ScrollRegion);
5448        drop(w);
5449
5450        // Sink attached before the ledger: same result.
5451        let w = TerminalWriter::new(
5452            Vec::new(),
5453            ScreenMode::Inline { ui_height: 5 },
5454            UiAnchor::Bottom,
5455            after,
5456        )
5457        .with_evidence_sink(sink)
5458        .with_capability_decisions(decisions);
5459        drop(w);
5460
5461        let contents = std::fs::read_to_string(&evidence_path).expect("evidence file written");
5462        let lines: Vec<&str> = contents.lines().collect();
5463        assert_eq!(
5464            lines.len(),
5465            8,
5466            "3 decisions + 1 strategy row, twice: {contents}"
5467        );
5468        for block in lines.chunks(4) {
5469            assert!(
5470                block[0].contains(r#""capability":"true_color""#),
5471                "{}",
5472                block[0]
5473            );
5474            assert!(
5475                block[1].contains(r#""capability":"sync_output""#),
5476                "{}",
5477                block[1]
5478            );
5479            assert!(block[1].contains(r#""probe":"confirmed""#), "{}", block[1]);
5480            assert!(block[1].contains(r#""final":true"#), "{}", block[1]);
5481            assert!(
5482                block[2].contains(r#""capability":"scroll_region""#),
5483                "{}",
5484                block[2]
5485            );
5486            assert!(block[2].contains(r#""probe":"not_probed""#), "{}", block[2]);
5487            assert_eq!(
5488                block[3],
5489                r#"{"event":"inline_strategy","strategy":"scroll_region","use_scroll_region":true,"use_sync_output":true,"in_mux":false,"scroll_region_verified":null,"log_transport":"decstbm"}"#
5490            );
5491        }
5492    }
5493
5494    #[test]
5495    fn strategy_selected_from_capabilities() {
5496        // No capabilities → OverlayRedraw
5497        let w = TerminalWriter::new(
5498            Vec::new(),
5499            ScreenMode::Inline { ui_height: 5 },
5500            UiAnchor::Bottom,
5501            basic_caps(),
5502        );
5503        assert_eq!(w.inline_strategy(), InlineStrategy::OverlayRedraw);
5504
5505        // scroll_region + sync_output → ScrollRegion
5506        let w = TerminalWriter::new(
5507            Vec::new(),
5508            ScreenMode::Inline { ui_height: 5 },
5509            UiAnchor::Bottom,
5510            scroll_region_caps(),
5511        );
5512        assert_eq!(w.inline_strategy(), InlineStrategy::ScrollRegion);
5513
5514        // scroll_region only → Hybrid
5515        let w = TerminalWriter::new(
5516            Vec::new(),
5517            ScreenMode::Inline { ui_height: 5 },
5518            UiAnchor::Bottom,
5519            hybrid_caps(),
5520        );
5521        assert_eq!(w.inline_strategy(), InlineStrategy::Hybrid);
5522
5523        // In mux → OverlayRedraw even with all caps
5524        let w = TerminalWriter::new(
5525            Vec::new(),
5526            ScreenMode::Inline { ui_height: 5 },
5527            UiAnchor::Bottom,
5528            mux_caps(),
5529        );
5530        assert_eq!(w.inline_strategy(), InlineStrategy::OverlayRedraw);
5531    }
5532
5533    #[test]
5534    fn scroll_region_activated_on_present() {
5535        let mut output = Vec::new();
5536        {
5537            let mut writer = TerminalWriter::new(
5538                &mut output,
5539                ScreenMode::Inline { ui_height: 5 },
5540                UiAnchor::Bottom,
5541                scroll_region_caps(),
5542            );
5543            writer.set_size(80, 24);
5544            assert!(!writer.scroll_region_active());
5545
5546            let buffer = Buffer::new(80, 5);
5547            writer.present_ui(&buffer, None, true).unwrap();
5548            assert!(writer.scroll_region_active());
5549        }
5550
5551        // Should contain DECSTBM: ESC [ 1 ; 19 r (rows 1-19 are log region)
5552        let expected = b"\x1b[1;19r";
5553        assert!(
5554            output.windows(expected.len()).any(|w| w == expected),
5555            "Should set scroll region to rows 1-19"
5556        );
5557    }
5558
5559    #[test]
5560    fn scroll_region_not_activated_for_overlay() {
5561        let mut output = Vec::new();
5562        {
5563            let mut writer = TerminalWriter::new(
5564                &mut output,
5565                ScreenMode::Inline { ui_height: 5 },
5566                UiAnchor::Bottom,
5567                basic_caps(),
5568            );
5569            writer.set_size(80, 24);
5570
5571            let buffer = Buffer::new(80, 5);
5572            writer.present_ui(&buffer, None, true).unwrap();
5573            assert!(!writer.scroll_region_active());
5574        }
5575
5576        // Should NOT contain any scroll region setup
5577        let decstbm = b"\x1b[1;19r";
5578        assert!(
5579            !output.windows(decstbm.len()).any(|w| w == decstbm),
5580            "OverlayRedraw should not set scroll region"
5581        );
5582    }
5583
5584    #[test]
5585    fn scroll_region_not_activated_in_mux() {
5586        let mut output = Vec::new();
5587        {
5588            let mut writer = TerminalWriter::new(
5589                &mut output,
5590                ScreenMode::Inline { ui_height: 5 },
5591                UiAnchor::Bottom,
5592                mux_caps(),
5593            );
5594            writer.set_size(80, 24);
5595
5596            let buffer = Buffer::new(80, 5);
5597            writer.present_ui(&buffer, None, true).unwrap();
5598            assert!(!writer.scroll_region_active());
5599        }
5600
5601        // Should NOT contain scroll region setup despite having the capability
5602        let decstbm = b"\x1b[1;19r";
5603        assert!(
5604            !output.windows(decstbm.len()).any(|w| w == decstbm),
5605            "Mux environment should not use scroll region"
5606        );
5607    }
5608
5609    #[test]
5610    fn scroll_region_reset_on_cleanup() {
5611        let mut output = Vec::new();
5612        {
5613            let mut writer = TerminalWriter::new(
5614                &mut output,
5615                ScreenMode::Inline { ui_height: 5 },
5616                UiAnchor::Bottom,
5617                scroll_region_caps(),
5618            );
5619            writer.set_size(80, 24);
5620
5621            let buffer = Buffer::new(80, 5);
5622            writer.present_ui(&buffer, None, true).unwrap();
5623            // Dropped here - cleanup should reset scroll region
5624        }
5625
5626        // Should contain scroll region reset: ESC [ r
5627        let reset = b"\x1b[r";
5628        assert!(
5629            output.windows(reset.len()).any(|w| w == reset),
5630            "Cleanup should reset scroll region"
5631        );
5632    }
5633
5634    #[test]
5635    fn scroll_region_reset_on_resize() {
5636        let output = Vec::new();
5637        let mut writer = TerminalWriter::new(
5638            output,
5639            ScreenMode::Inline { ui_height: 5 },
5640            UiAnchor::Bottom,
5641            scroll_region_caps(),
5642        );
5643        writer.set_size(80, 24);
5644
5645        // Manually activate scroll region
5646        writer.activate_scroll_region(5).unwrap();
5647        assert!(writer.scroll_region_active());
5648
5649        // Resize should deactivate it
5650        writer.set_size(80, 40);
5651        assert!(!writer.scroll_region_active());
5652    }
5653
5654    #[test]
5655    fn scroll_region_reactivated_after_resize() {
5656        let mut output = Vec::new();
5657        {
5658            let mut writer = TerminalWriter::new(
5659                &mut output,
5660                ScreenMode::Inline { ui_height: 5 },
5661                UiAnchor::Bottom,
5662                scroll_region_caps(),
5663            );
5664            writer.set_size(80, 24);
5665
5666            // First present activates scroll region
5667            let buffer = Buffer::new(80, 5);
5668            writer.present_ui(&buffer, None, true).unwrap();
5669            assert!(writer.scroll_region_active());
5670
5671            // Resize deactivates
5672            writer.set_size(80, 40);
5673            assert!(!writer.scroll_region_active());
5674
5675            // Next present re-activates with new dimensions
5676            let buffer2 = Buffer::new(80, 5);
5677            writer.present_ui(&buffer2, None, true).unwrap();
5678            assert!(writer.scroll_region_active());
5679        }
5680
5681        // Should contain the new scroll region: ESC [ 1 ; 35 r (40 - 5 = 35)
5682        let new_region = b"\x1b[1;35r";
5683        assert!(
5684            output.windows(new_region.len()).any(|w| w == new_region),
5685            "Should set scroll region to new dimensions after resize"
5686        );
5687    }
5688
5689    #[test]
5690    fn notify_resize_transitions_live_scroll_region_to_overlay_redraw() {
5691        let mut output = Vec::new();
5692        {
5693            let mut writer = TerminalWriter::new(
5694                &mut output,
5695                ScreenMode::Inline { ui_height: 5 },
5696                UiAnchor::Bottom,
5697                scroll_region_caps(),
5698            );
5699            writer.set_size(80, 24);
5700
5701            let buffer = Buffer::new(80, 5);
5702            writer.present_ui(&buffer, Some((2, 3)), true).unwrap();
5703            assert!(writer.scroll_region_active());
5704            assert_eq!(writer.inline_strategy(), InlineStrategy::ScrollRegion);
5705
5706            writer.notify_resize(80, 30);
5707            assert!(!writer.scroll_region_active());
5708            assert_eq!(writer.inline_strategy(), InlineStrategy::OverlayRedraw);
5709        }
5710
5711        // Scroll region reset should be bracketed by DECSC/DECRC so cursor stays on the UI row.
5712        let saved_reset = b"\x1b7\x1b[r\x1b8";
5713        assert!(
5714            output.windows(saved_reset.len()).any(|w| w == saved_reset),
5715            "notify_resize should preserve cursor across DECSTBM reset"
5716        );
5717    }
5718
5719    #[test]
5720    fn hybrid_strategy_activates_scroll_region() {
5721        let mut output = Vec::new();
5722        {
5723            let mut writer = TerminalWriter::new(
5724                &mut output,
5725                ScreenMode::Inline { ui_height: 5 },
5726                UiAnchor::Bottom,
5727                hybrid_caps(),
5728            );
5729            writer.set_size(80, 24);
5730
5731            let buffer = Buffer::new(80, 5);
5732            writer.present_ui(&buffer, None, true).unwrap();
5733            assert!(writer.scroll_region_active());
5734        }
5735
5736        // Hybrid uses scroll region as internal optimization
5737        let expected = b"\x1b[1;19r";
5738        assert!(
5739            output.windows(expected.len()).any(|w| w == expected),
5740            "Hybrid should activate scroll region as optimization"
5741        );
5742    }
5743
5744    #[test]
5745    fn altscreen_does_not_activate_scroll_region() {
5746        let output = Vec::new();
5747        let mut writer = TerminalWriter::new(
5748            output,
5749            ScreenMode::AltScreen,
5750            UiAnchor::Bottom,
5751            scroll_region_caps(),
5752        );
5753        writer.set_size(80, 24);
5754
5755        let buffer = Buffer::new(80, 24);
5756        writer.present_ui(&buffer, None, true).unwrap();
5757        assert!(!writer.scroll_region_active());
5758    }
5759
5760    #[test]
5761    fn scroll_region_still_saves_restores_cursor() {
5762        let mut output = Vec::new();
5763        {
5764            let mut writer = TerminalWriter::new(
5765                &mut output,
5766                ScreenMode::Inline { ui_height: 5 },
5767                UiAnchor::Bottom,
5768                scroll_region_caps(),
5769            );
5770            writer.set_size(80, 24);
5771
5772            let buffer = Buffer::new(80, 5);
5773            writer.present_ui(&buffer, None, true).unwrap();
5774        }
5775
5776        // Even with scroll region, cursor save/restore is used for UI presents
5777        assert!(
5778            output.windows(CURSOR_SAVE.len()).any(|w| w == CURSOR_SAVE),
5779            "Scroll region mode should still save cursor"
5780        );
5781        assert!(
5782            output
5783                .windows(CURSOR_RESTORE.len())
5784                .any(|w| w == CURSOR_RESTORE),
5785            "Scroll region mode should still restore cursor"
5786        );
5787    }
5788
5789    // --- Log write cursor positioning tests (bd-xh8s) ---
5790
5791    /// Feed `bytes` to an independent VT emulator (`vt100`) of the given
5792    /// size; overlay-transport tests check the screen it shows, not bytes.
5793    fn vt_screen(bytes: &[u8], cols: u16, rows: u16) -> vt100::Parser {
5794        let size = |n| std::num::NonZeroU16::new(n).expect("vt100 screen size must be nonzero");
5795        let mut parser = vt100::Parser::new(size(rows), size(cols), 10_000);
5796        parser.process(bytes);
5797        parser
5798    }
5799
5800    /// Scrollback (oldest first) followed by the visible rows.
5801    fn vt_transcript(parser: &mut vt100::Parser) -> Vec<String> {
5802        let (rows, cols) = parser.screen().size();
5803        let (rows, cols) = (rows.get(), cols.get());
5804        parser.screen_mut().set_scrollback(usize::MAX);
5805        let mut offset = parser.screen().scrollback();
5806        let mut lines = Vec::new();
5807        while offset > 0 {
5808            parser.screen_mut().set_scrollback(offset);
5809            let take = offset.min(usize::from(rows));
5810            lines.extend(parser.screen().rows(0, cols).take(take));
5811            offset -= take;
5812        }
5813        parser.screen_mut().set_scrollback(0);
5814        lines.extend(parser.screen().rows(0, cols));
5815        lines.iter().map(|row| row.trim_end().to_string()).collect()
5816    }
5817
5818    /// A frame whose rows read `UI-row0`, `UI-row1`, ...
5819    fn marked_frame(width: u16, height: u16) -> Buffer {
5820        let mut buf = Buffer::new(width, height);
5821        for y in 0..height {
5822            for (x, ch) in format!("UI-row{y}").chars().enumerate() {
5823                buf.set_raw(x as u16, y, Cell::from_char(ch));
5824            }
5825        }
5826        buf
5827    }
5828
5829    #[test]
5830    fn write_log_streams_from_first_ui_row_bottom_anchor() {
5831        // Overlay transport: the stream starts on the UI's first row (20 of
5832        // 24 for a 5-row UI) after erasing to the end of the screen, and
5833        // ends every line with CR LF.
5834        let mut output = Vec::new();
5835        {
5836            let mut writer = TerminalWriter::new(
5837                &mut output,
5838                ScreenMode::Inline { ui_height: 5 },
5839                UiAnchor::Bottom,
5840                basic_caps(),
5841            );
5842            writer.set_size(80, 24);
5843            writer.write_log("test log\n").unwrap();
5844        }
5845
5846        assert!(
5847            // Row 20 of 24, addressed from the last row (4 rows up).
5848            contains_bytes(&output, b"\x1b[9999;1H\x1b[4A\x1b[Jtest log\r\n"),
5849            "log stream must start on the first UI row after erasing it"
5850        );
5851        let mut vt = vt_screen(&output, 80, 24);
5852        let rows = vt_transcript(&mut vt);
5853        assert_eq!(rows.iter().filter(|r| *r == "test log").count(), 1);
5854    }
5855
5856    #[test]
5857    fn write_log_positions_cursor_top_anchor() {
5858        // Verify log writes position cursor at the bottom of the log region
5859        // for top-anchored UI (log region is below UI).
5860        let mut output = Vec::new();
5861        {
5862            let mut writer = TerminalWriter::new(
5863                &mut output,
5864                ScreenMode::Inline { ui_height: 5 },
5865                UiAnchor::Top,
5866                basic_caps(),
5867            );
5868            writer.set_size(80, 24);
5869            writer.write_log("test log\n").unwrap();
5870        }
5871
5872        // For top-anchored with ui_height=5, term_height=24:
5873        // Log region is rows 6-24 (below UI)
5874        // Cursor should be positioned at row 24 (bottom of log region)
5875        let expected_pos = b"\x1b[24;1H";
5876        assert!(
5877            output
5878                .windows(expected_pos.len())
5879                .any(|w| w == expected_pos),
5880            "Log write should position cursor at row 24 for top anchor"
5881        );
5882    }
5883
5884    #[test]
5885    fn write_log_contains_text() {
5886        // Verify the log text is actually written after cursor positioning.
5887        let mut output = Vec::new();
5888        {
5889            let mut writer = TerminalWriter::new(
5890                &mut output,
5891                ScreenMode::Inline { ui_height: 5 },
5892                UiAnchor::Bottom,
5893                basic_caps(),
5894            );
5895            writer.set_size(80, 24);
5896            writer.write_log("hello world\n").unwrap();
5897        }
5898
5899        let output_str = String::from_utf8_lossy(&output);
5900        assert!(output_str.contains("hello world"));
5901    }
5902
5903    #[test]
5904    fn write_log_sanitizes_escape_injection_payloads() {
5905        let mut output = Vec::new();
5906        {
5907            let mut writer = TerminalWriter::new(
5908                &mut output,
5909                ScreenMode::Inline { ui_height: 5 },
5910                UiAnchor::Bottom,
5911                basic_caps(),
5912            );
5913            writer.set_size(80, 24);
5914            writer
5915                .write_log("safe\x1b]52;c;SGVsbG8=\x1b\\tail\u{009d}x\n")
5916                .unwrap();
5917        }
5918
5919        let output_str = String::from_utf8_lossy(&output);
5920        assert!(output_str.contains("safetailx"));
5921        assert!(
5922            !output_str.contains("52;c;SGVsbG8"),
5923            "OSC payload must not be forwarded to terminal output"
5924        );
5925        assert!(
5926            !output_str.contains('\u{009d}'),
5927            "C1 controls must be stripped from log output"
5928        );
5929    }
5930
5931    #[test]
5932    fn write_log_batches_consecutive_lines_into_one_stream() {
5933        // Lines written between presents share one stream (one UI repaint).
5934        let mut output = Vec::new();
5935        {
5936            let mut writer = TerminalWriter::new(
5937                &mut output,
5938                ScreenMode::Inline { ui_height: 5 },
5939                UiAnchor::Bottom,
5940                basic_caps(),
5941            );
5942            writer.set_size(80, 24);
5943            writer.write_log("first\n").unwrap();
5944            writer.write_log("second\n").unwrap();
5945            writer.flush().unwrap();
5946        }
5947
5948        let stream_start = b"\x1b[9999;1H\x1b[4A\x1b[J";
5949        let count = output
5950            .windows(stream_start.len())
5951            .filter(|w| *w == stream_start)
5952            .count();
5953        assert_eq!(count, 1, "both lines must go out in one stream");
5954        assert!(contains_bytes(&output, b"first\r\nsecond\r\n"));
5955    }
5956
5957    /// Log rows of a transcript: everything but blank and UI rows.
5958    fn log_rows(transcript: &[String]) -> Vec<&str> {
5959        transcript
5960            .iter()
5961            .map(String::as_str)
5962            .filter(|row| !row.is_empty() && !row.starts_with("UI-row"))
5963            .collect()
5964    }
5965
5966    #[test]
5967    fn overlay_logs_survive_a_resize_that_leaves_no_free_row() {
5968        // G48 drop path: lines accepted while a row was free stay queued
5969        // while a resize leaves the UI filling the terminal, and reach
5970        // scrollback exactly once, in order, after the next resize frees a
5971        // row again.
5972        let mut writer = TerminalWriter::new(
5973            Vec::new(),
5974            ScreenMode::Inline { ui_height: 5 },
5975            UiAnchor::Bottom,
5976            basic_caps(),
5977        );
5978        writer.set_size(80, 24);
5979        writer.present_ui(&marked_frame(80, 5), None, true).unwrap();
5980        writer.write_log("kept-1\nkept-2\n").unwrap();
5981        writer.set_size(80, 5);
5982        writer.flush().unwrap();
5983        assert_eq!(
5984            writer.pending_logs.len(),
5985            2,
5986            "lines must stay queued while the UI fills the terminal"
5987        );
5988        assert!(!contains_bytes(writer.writer().inner().get_ref(), b"kept-"));
5989
5990        writer.set_size(80, 24);
5991        writer.present_ui(&marked_frame(80, 5), None, true).unwrap();
5992        assert!(writer.pending_logs.is_empty());
5993        let mut vt = vt_screen(writer.writer().inner().get_ref(), 80, 24);
5994        let transcript = vt_transcript(&mut vt);
5995        assert_eq!(log_rows(&transcript), ["kept-1", "kept-2"]);
5996    }
5997
5998    /// Writes a line while an inline-auto UI fills the terminal, so the line
5999    /// is held (proptest_flicker_invariants seed cc 6c8ea6c1, ops 0-4).
6000    fn hold_a_log_line_while_the_ui_fills_the_terminal<W: Write>(writer: &mut TerminalWriter<W>) {
6001        writer.set_size(20, 5);
6002        writer.flush().unwrap();
6003        writer.set_auto_ui_height(5);
6004        writer.flush().unwrap();
6005        let frame = marked_frame(20, writer.ui_height());
6006        writer.present_ui(&frame, None, false).unwrap();
6007        writer.flush().unwrap();
6008        writer.set_auto_ui_height(1);
6009        writer.flush().unwrap();
6010        writer.write_log("held\n").unwrap();
6011        writer.flush().unwrap();
6012        assert!(
6013            !writer.pending_logs.is_empty(),
6014            "the line must be held while the displayed UI fills the terminal"
6015        );
6016    }
6017
6018    #[test]
6019    fn overlay_held_logs_do_not_stream_on_the_flush_after_a_resize() {
6020        // A resize is not a log write or a present: the flush after it must
6021        // not erase. Nothing is drawn at the new geometry yet, so the rows the
6022        // stream would vacate hold the terminal's reflowed content. The held
6023        // line streams at the next present, once.
6024        let mut writer = TerminalWriter::new(
6025            Vec::new(),
6026            ScreenMode::InlineAuto {
6027                min_height: 1,
6028                max_height: 10,
6029            },
6030            UiAnchor::Bottom,
6031            basic_caps(),
6032        );
6033        hold_a_log_line_while_the_ui_fills_the_terminal(&mut writer);
6034        let before = writer.writer().inner().get_ref().len();
6035        writer.set_size(20, 5);
6036        writer.flush().unwrap();
6037        let after_resize = writer.writer().inner().get_ref()[before..].to_vec();
6038        assert!(
6039            !contains_bytes(&after_resize, b"\x1b[J"),
6040            "the flush after a resize must not erase: {after_resize:?}"
6041        );
6042        assert!(
6043            !contains_bytes(&after_resize, b"held"),
6044            "the held line must wait for the next present: {after_resize:?}"
6045        );
6046
6047        let frame = marked_frame(20, writer.ui_height());
6048        writer.present_ui(&frame, None, false).unwrap();
6049        writer.flush().unwrap();
6050        assert!(writer.pending_logs.is_empty());
6051        let mut vt = vt_screen(writer.writer().inner().get_ref(), 20, 5);
6052        let transcript = vt_transcript(&mut vt);
6053        assert_eq!(log_rows(&transcript), ["held"]);
6054    }
6055
6056    #[test]
6057    fn overlay_held_logs_stream_without_erase_at_teardown_after_a_resize() {
6058        // Teardown right after the resize: the held line is written, not
6059        // lost, and nothing is erased (no UI is drawn at the new geometry).
6060        #[derive(Clone, Default)]
6061        struct SharedOut(std::sync::Arc<std::sync::Mutex<Vec<u8>>>);
6062        impl Write for SharedOut {
6063            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
6064                self.0.lock().unwrap().extend_from_slice(buf);
6065                Ok(buf.len())
6066            }
6067            fn flush(&mut self) -> io::Result<()> {
6068                Ok(())
6069            }
6070        }
6071
6072        let out = SharedOut::default();
6073        let mut writer = TerminalWriter::new(
6074            out.clone(),
6075            ScreenMode::InlineAuto {
6076                min_height: 1,
6077                max_height: 10,
6078            },
6079            UiAnchor::Bottom,
6080            basic_caps(),
6081        );
6082        hold_a_log_line_while_the_ui_fills_the_terminal(&mut writer);
6083        let before = out.0.lock().unwrap().len();
6084        writer.set_size(20, 5);
6085        drop(writer);
6086        let bytes = out.0.lock().unwrap().clone();
6087        let teardown = &bytes[before..];
6088        assert!(
6089            !contains_bytes(teardown, b"\x1b[J"),
6090            "teardown after a resize must not erase: {teardown:?}"
6091        );
6092        let mut vt = vt_screen(&bytes, 20, 5);
6093        let transcript = vt_transcript(&mut vt);
6094        assert_eq!(log_rows(&transcript), ["held"]);
6095    }
6096
6097    #[test]
6098    fn overlay_log_queue_is_bounded_and_counts_dropped_lines() {
6099        // While no row is free to stream them the queue keeps at most
6100        // OVERLAY_LOG_QUEUE_MAX_LINES lines: the oldest are dropped and
6101        // counted, the rest stream in order once a row is free.
6102        let mut writer = TerminalWriter::new(
6103            Vec::new(),
6104            ScreenMode::InlineAuto {
6105                min_height: 1,
6106                max_height: 24,
6107            },
6108            UiAnchor::Bottom,
6109            basic_caps(),
6110        );
6111        writer.set_size(80, 24);
6112        writer.set_auto_ui_height(24);
6113        writer
6114            .present_ui(&marked_frame(80, 24), None, true)
6115            .unwrap();
6116        // A pending shrink leaves rows free for new log lines, but the
6117        // displayed UI still fills the screen, so no stream can run yet.
6118        writer.set_auto_ui_height(5);
6119        let total = 2_000;
6120        for i in 0..total {
6121            writer.write_log(&format!("L{i:04}\n")).unwrap();
6122        }
6123        assert_eq!(writer.pending_logs.len(), OVERLAY_LOG_QUEUE_MAX_LINES);
6124        let dropped = total - OVERLAY_LOG_QUEUE_MAX_LINES;
6125        assert_eq!(writer.dropped_log_lines(), dropped as u64);
6126
6127        writer.present_ui(&marked_frame(80, 5), None, true).unwrap();
6128        writer.flush().unwrap();
6129        assert!(writer.pending_logs.is_empty());
6130        let mut vt = vt_screen(writer.writer().inner().get_ref(), 80, 24);
6131        let transcript = vt_transcript(&mut vt);
6132        let logs: Vec<&str> = log_rows(&transcript)
6133            .into_iter()
6134            .filter(|row| row.starts_with('L'))
6135            .collect();
6136        let expected: Vec<String> = (dropped..total).map(|i| format!("L{i:04}")).collect();
6137        assert_eq!(logs, expected);
6138    }
6139
6140    #[test]
6141    fn overlay_partial_log_stays_open_and_is_continued_on_its_row() {
6142        // G48: text without a newline is streamed with no line break after
6143        // it, and the next text continues the same row across a flush and a
6144        // present; complete lines still end with CR LF.
6145        let mut writer = TerminalWriter::new(
6146            Vec::new(),
6147            ScreenMode::Inline { ui_height: 5 },
6148            UiAnchor::Bottom,
6149            basic_caps(),
6150        );
6151        writer.set_size(80, 24);
6152        writer.present_ui(&marked_frame(80, 5), None, true).unwrap();
6153        writer.write_log_raw("first\npart:").unwrap();
6154        writer.flush().unwrap();
6155        let output = writer.writer().inner().get_ref().clone();
6156        assert!(contains_bytes(&output, b"first\r\n"));
6157        assert!(contains_bytes(&output, b"part:"));
6158        assert!(!contains_bytes(&output, b"part:\r"));
6159        assert!(!contains_bytes(&output, b"part:\n"));
6160
6161        writer.present_ui(&marked_frame(80, 5), None, true).unwrap();
6162        writer.write_log_raw("ial").unwrap();
6163        writer.flush().unwrap();
6164        writer.write_log_raw(" done\nnext\n").unwrap();
6165        writer.present_ui(&marked_frame(80, 5), None, true).unwrap();
6166
6167        let mut vt = vt_screen(writer.writer().inner().get_ref(), 80, 24);
6168        let transcript = vt_transcript(&mut vt);
6169        assert_eq!(log_rows(&transcript), ["first", "part:ial done", "next"]);
6170        let visible: Vec<String> = vt.screen().rows(0, 80).collect();
6171        for y in 0..5 {
6172            assert_eq!(visible[19 + y].trim_end(), format!("UI-row{y}"));
6173        }
6174    }
6175
6176    #[test]
6177    fn overlay_open_log_line_wraps_and_continues_above_the_ui() {
6178        // An open line that wraps keeps its rows above the UI, and its
6179        // continuation can wrap further.
6180        let mut writer = TerminalWriter::new(
6181            Vec::new(),
6182            ScreenMode::Inline { ui_height: 3 },
6183            UiAnchor::Bottom,
6184            basic_caps(),
6185        );
6186        writer.set_size(10, 12);
6187        writer.present_ui(&marked_frame(10, 3), None, true).unwrap();
6188        writer.write_log("abcdefghijklm").unwrap();
6189        writer.flush().unwrap();
6190        writer.write_log("nopqrstuvwxyz\nend\n").unwrap();
6191        writer.flush().unwrap();
6192
6193        let mut vt = vt_screen(writer.writer().inner().get_ref(), 10, 12);
6194        let transcript = vt_transcript(&mut vt);
6195        assert_eq!(
6196            log_rows(&transcript),
6197            ["abcdefghij", "klmnopqrst", "uvwxyz", "end"]
6198        );
6199        let visible: Vec<String> = vt.screen().rows(0, 10).collect();
6200        for y in 0..3 {
6201            assert_eq!(visible[9 + y].trim_end(), format!("UI-row{y}"));
6202        }
6203    }
6204
6205    #[test]
6206    fn overlay_open_log_line_is_not_continued_after_a_resize() {
6207        // A resize moves rows the writer cannot track: the next text starts
6208        // on a fresh row instead of continuing the open one.
6209        let mut writer = TerminalWriter::new(
6210            Vec::new(),
6211            ScreenMode::Inline { ui_height: 5 },
6212            UiAnchor::Bottom,
6213            basic_caps(),
6214        );
6215        writer.set_size(80, 24);
6216        writer.present_ui(&marked_frame(80, 5), None, true).unwrap();
6217        writer.write_log("open").unwrap();
6218        writer.flush().unwrap();
6219        assert!(writer.overlay_open.is_some());
6220        writer.set_size(80, 20);
6221        writer.present_ui(&marked_frame(80, 5), None, true).unwrap();
6222        let resized_at = writer.writer().inner().get_ref().len();
6223        writer.write_log("fresh\n").unwrap();
6224        writer.flush().unwrap();
6225        let output = writer.writer().inner().get_ref()[resized_at..].to_vec();
6226        // The stream starts on the UI's first row, at column 1.
6227        assert!(contains_bytes(
6228            &output,
6229            b"\x1b[9999;1H\x1b[4A\x1b[Jfresh\r\n"
6230        ));
6231    }
6232
6233    #[test]
6234    fn overlay_open_log_line_taller_than_the_free_rows_is_ended() {
6235        // An open line that would need more rows than the screen has above
6236        // the UI cannot stay open: it is ended like a complete line.
6237        let mut writer = TerminalWriter::new(
6238            Vec::new(),
6239            ScreenMode::Inline { ui_height: 5 },
6240            UiAnchor::Bottom,
6241            basic_caps(),
6242        );
6243        writer.set_size(10, 8);
6244        writer.present_ui(&marked_frame(10, 5), None, true).unwrap();
6245        let long = "x".repeat(40);
6246        writer.write_log(&long).unwrap();
6247        writer.flush().unwrap();
6248        assert!(writer.overlay_open.is_none());
6249        let mut expected = long.into_bytes();
6250        expected.extend_from_slice(b"\r\n");
6251        assert!(contains_bytes(writer.writer().inner().get_ref(), &expected));
6252    }
6253
6254    #[test]
6255    fn overlay_logical_line_after_open_text_starts_its_own_row() {
6256        // A logical line (a model log command) never continues open text.
6257        let mut writer = TerminalWriter::new(
6258            Vec::new(),
6259            ScreenMode::Inline { ui_height: 5 },
6260            UiAnchor::Bottom,
6261            basic_caps(),
6262        );
6263        writer.set_size(80, 24);
6264        writer.present_ui(&marked_frame(80, 5), None, true).unwrap();
6265        writer.write_log("open").unwrap();
6266        writer
6267            .write_log_line_with_mode("line", SanitizeMode::Strip)
6268            .unwrap();
6269        writer.flush().unwrap();
6270        assert!(contains_bytes(
6271            writer.writer().inner().get_ref(),
6272            b"open\r\nline\r\n"
6273        ));
6274        assert!(writer.overlay_open.is_none());
6275    }
6276
6277    #[test]
6278    fn overlay_open_log_line_without_ui_rows_continues_on_the_bottom_row() {
6279        // No UI rows: the newest line lives on the bottom row and open text
6280        // is continued there.
6281        let mut writer = TerminalWriter::new(
6282            Vec::new(),
6283            ScreenMode::Inline { ui_height: 0 },
6284            UiAnchor::Bottom,
6285            basic_caps(),
6286        );
6287        writer.set_size(20, 6);
6288        writer.write_log("ab").unwrap();
6289        writer.flush().unwrap();
6290        writer.write_log("cd\n").unwrap();
6291        writer.flush().unwrap();
6292        writer.write_log("ef\n").unwrap();
6293        writer.flush().unwrap();
6294
6295        let mut vt = vt_screen(writer.writer().inner().get_ref(), 20, 6);
6296        let transcript = vt_transcript(&mut vt);
6297        assert_eq!(log_rows(&transcript), ["abcd", "ef"]);
6298    }
6299
6300    #[test]
6301    fn write_log_after_present_ui_works_correctly() {
6302        // A log written after a present is streamed above the UI and the
6303        // frame is repainted below it.
6304        let mut writer = TerminalWriter::new(
6305            Vec::new(),
6306            ScreenMode::Inline { ui_height: 5 },
6307            UiAnchor::Bottom,
6308            basic_caps(),
6309        );
6310        writer.set_size(80, 24);
6311        writer.present_ui(&marked_frame(80, 5), None, true).unwrap();
6312        writer.write_log("after UI\n").unwrap();
6313        writer.flush().unwrap();
6314
6315        let vt = vt_screen(writer.writer().inner().get_ref(), 80, 24);
6316        let visible: Vec<String> = vt.screen().rows(0, 80).collect();
6317        assert_eq!(visible[18].trim_end(), "after UI");
6318        for y in 0..5 {
6319            assert_eq!(visible[19 + y].trim_end(), format!("UI-row{y}"));
6320        }
6321    }
6322
6323    #[test]
6324    fn write_log_ui_fills_terminal_is_noop() {
6325        // When UI fills the entire terminal, there's no log region.
6326        // Drop cleanup writes reset sequences (\x1b[0m, \x1b[?25h), so we
6327        // verify the output does not contain the log text itself.
6328        let mut output = Vec::new();
6329        {
6330            let mut writer = TerminalWriter::new(
6331                &mut output,
6332                ScreenMode::Inline { ui_height: 24 },
6333                UiAnchor::Bottom,
6334                basic_caps(),
6335            );
6336            writer.set_size(80, 24);
6337            writer.write_log("should still write\n").unwrap();
6338        }
6339        // Log text must NOT appear; only Drop cleanup sequences are expected.
6340        assert!(
6341            !output
6342                .windows(b"should still write".len())
6343                .any(|w| w == b"should still write"),
6344            "write_log should not emit log text when UI fills the terminal"
6345        );
6346    }
6347
6348    #[test]
6349    fn write_log_with_scroll_region_active() {
6350        // Verify log writes work correctly when scroll region is active.
6351        let mut output = Vec::new();
6352        {
6353            let mut writer = TerminalWriter::new(
6354                &mut output,
6355                ScreenMode::Inline { ui_height: 5 },
6356                UiAnchor::Bottom,
6357                scroll_region_caps(),
6358            );
6359            writer.set_size(80, 24);
6360
6361            // Present UI to activate scroll region
6362            let buffer = Buffer::new(80, 5);
6363            writer.present_ui(&buffer, None, true).unwrap();
6364            assert!(writer.scroll_region_active());
6365
6366            // Log write should still position cursor
6367            writer.write_log("with scroll region\n").unwrap();
6368        }
6369
6370        let output_str = String::from_utf8_lossy(&output);
6371        assert!(output_str.contains("with scroll region"));
6372    }
6373
6374    #[test]
6375    fn overlay_log_write_leaves_ui_rows_intact_bottom_anchor() {
6376        // The stream writes into the vacated UI rows on purpose; what must
6377        // hold is the screen: logs above the UI, the frame intact in rows
6378        // 20-24, and no UI row in scrollback.
6379        let mut writer = TerminalWriter::new(
6380            Vec::new(),
6381            ScreenMode::Inline { ui_height: 5 },
6382            UiAnchor::Bottom,
6383            basic_caps(),
6384        );
6385        writer.set_size(80, 24);
6386        writer.present_ui(&marked_frame(80, 5), None, true).unwrap();
6387        for i in 0..40 {
6388            writer.write_log(&format!("test {i:02}\n")).unwrap();
6389        }
6390        writer.flush().unwrap();
6391
6392        let mut vt = vt_screen(writer.writer().inner().get_ref(), 80, 24);
6393        let visible: Vec<String> = vt.screen().rows(0, 80).collect();
6394        assert_eq!(visible[18].trim_end(), "test 39");
6395        for y in 0..5 {
6396            assert_eq!(visible[19 + y].trim_end(), format!("UI-row{y}"));
6397        }
6398        let rows = vt_transcript(&mut vt);
6399        let logs: Vec<&String> = rows.iter().filter(|r| r.starts_with("test ")).collect();
6400        assert_eq!(logs.len(), 40, "every line exactly once");
6401        let ui_rows = rows.iter().filter(|r| r.starts_with("UI-")).count();
6402        assert_eq!(
6403            ui_rows, 5,
6404            "UI rows appear only on screen, never in history"
6405        );
6406    }
6407
6408    #[test]
6409    fn log_write_cursor_position_not_in_ui_region_top_anchor() {
6410        // Verify the cursor position for log writes is never in the UI region.
6411        // For top-anchored with ui_height=5, term_height=24:
6412        // UI region is rows 1-5 (1-indexed)
6413        // Log region is rows 6-24
6414        // Log cursor should be at row 24 (bottom of log region)
6415        let mut output = Vec::new();
6416        {
6417            let mut writer = TerminalWriter::new(
6418                &mut output,
6419                ScreenMode::Inline { ui_height: 5 },
6420                UiAnchor::Top,
6421                basic_caps(),
6422            );
6423            writer.set_size(80, 24);
6424            writer.write_log("test\n").unwrap();
6425        }
6426
6427        // Parse cursor position commands in output
6428        let mut found_row = None;
6429        let mut i = 0;
6430        while i + 2 < output.len() {
6431            if output[i] == 0x1b && output[i + 1] == b'[' {
6432                let mut j = i + 2;
6433                let mut row: u16 = 0;
6434                while j < output.len() && output[j].is_ascii_digit() {
6435                    row = row * 10 + (output[j] - b'0') as u16;
6436                    j += 1;
6437                }
6438                if j < output.len() && output[j] == b';' {
6439                    j += 1;
6440                    while j < output.len() && output[j].is_ascii_digit() {
6441                        j += 1;
6442                    }
6443                    if j < output.len() && output[j] == b'H' {
6444                        found_row = Some(row);
6445                    }
6446                }
6447            }
6448            i += 1;
6449        }
6450
6451        if let Some(row) = found_row {
6452            // UI region is rows 1-5
6453            assert!(
6454                row > 5,
6455                "Log cursor row {} should be above UI end row 5",
6456                row
6457            );
6458        }
6459    }
6460
6461    #[test]
6462    fn present_ui_positions_cursor_after_restore() {
6463        let mut output = Vec::new();
6464        {
6465            let mut writer = TerminalWriter::new(
6466                &mut output,
6467                ScreenMode::Inline { ui_height: 5 },
6468                UiAnchor::Bottom,
6469                basic_caps(),
6470            );
6471            writer.set_size(80, 24);
6472
6473            let buffer = Buffer::new(80, 5);
6474            // Request cursor at (2, 1) in UI coordinates
6475            writer.present_ui(&buffer, Some((2, 1)), true).unwrap();
6476        }
6477
6478        // UI starts at row 20 (24 - 5 + 1 = 20) (1-indexed)
6479        // Cursor requested at relative (2, 1) -> (x=3, y=2) (1-indexed)
6480        // Absolute position: y = 20 + 1 = 21, x = 3: the overlay UI counts
6481        // rows from the last one, so column 3 there and 3 rows up.
6482        let expected_pos = b"\x1b[9999;3H\x1b[3A";
6483
6484        // Find restore
6485        let restore_idx = find_nth(&output, CURSOR_RESTORE, 1).expect("expected cursor restore");
6486        let after_restore = &output[restore_idx..];
6487
6488        // Ensure cursor positioning happens *after* restore
6489        assert!(
6490            after_restore
6491                .windows(expected_pos.len())
6492                .any(|w| w == expected_pos),
6493            "Cursor positioning should happen after restore"
6494        );
6495    }
6496
6497    #[test]
6498    fn present_ui_inline_skips_cursor_position_when_x_is_out_of_bounds() {
6499        let mut output = Vec::new();
6500        {
6501            let mut writer = TerminalWriter::new(
6502                &mut output,
6503                ScreenMode::Inline { ui_height: 5 },
6504                UiAnchor::Bottom,
6505                basic_caps(),
6506            );
6507            writer.set_size(80, 24);
6508
6509            let buffer = Buffer::new(4, 5);
6510            writer.present_ui(&buffer, Some((4, 1)), true).unwrap();
6511        }
6512
6513        let restore_idx = find_nth(&output, CURSOR_RESTORE, 1).expect("expected cursor restore");
6514        let after_restore = &output[restore_idx..];
6515        let invalid_pos = b"\x1b[21;5H";
6516        assert!(
6517            !after_restore
6518                .windows(invalid_pos.len())
6519                .any(|w| w == invalid_pos),
6520            "inline cursor should not move to x outside the buffer width"
6521        );
6522    }
6523
6524    #[test]
6525    fn present_ui_inline_skips_cursor_position_when_y_is_below_buffer_height() {
6526        let mut output = Vec::new();
6527        {
6528            let mut writer = TerminalWriter::new(
6529                &mut output,
6530                ScreenMode::Inline { ui_height: 5 },
6531                UiAnchor::Bottom,
6532                basic_caps(),
6533            );
6534            writer.set_size(80, 24);
6535
6536            let buffer = Buffer::new(4, 2);
6537            writer.present_ui(&buffer, Some((1, 4)), true).unwrap();
6538        }
6539
6540        let restore_idx = find_nth(&output, CURSOR_RESTORE, 1).expect("expected cursor restore");
6541        let after_restore = &output[restore_idx..];
6542        let invalid_pos = b"\x1b[24;2H";
6543        assert!(
6544            !after_restore
6545                .windows(invalid_pos.len())
6546                .any(|w| w == invalid_pos),
6547            "inline cursor should not move below the buffer height just because the inline region is taller"
6548        );
6549    }
6550
6551    // =========================================================================
6552    // RuntimeDiffConfig tests
6553    // =========================================================================
6554
6555    #[test]
6556    fn runtime_diff_config_default() {
6557        let config = RuntimeDiffConfig::default();
6558        assert!(config.bayesian_enabled);
6559        assert!(config.dirty_rows_enabled);
6560        assert!(config.dirty_span_config.enabled);
6561        assert!(config.tile_diff_config.enabled);
6562        assert!(config.reset_on_resize);
6563        assert!(config.reset_on_invalidation);
6564        assert_eq!(config.full_redraw_interval_frames, 240);
6565    }
6566
6567    #[test]
6568    fn runtime_diff_config_builder() {
6569        let custom_span = DirtySpanConfig::default().with_max_spans_per_row(8);
6570        let tile_config = TileDiffConfig::default()
6571            .with_enabled(false)
6572            .with_tile_size(24, 12)
6573            .with_dense_tile_ratio(0.75)
6574            .with_max_tiles(2048);
6575        let config = RuntimeDiffConfig::new()
6576            .with_bayesian_enabled(false)
6577            .with_dirty_rows_enabled(false)
6578            .with_dirty_span_config(custom_span)
6579            .with_dirty_spans_enabled(false)
6580            .with_tile_diff_config(tile_config)
6581            .with_reset_on_resize(false)
6582            .with_reset_on_invalidation(false)
6583            .with_full_redraw_interval_frames(17);
6584
6585        assert!(!config.bayesian_enabled);
6586        assert!(!config.dirty_rows_enabled);
6587        assert!(!config.dirty_span_config.enabled);
6588        assert_eq!(config.dirty_span_config.max_spans_per_row, 8);
6589        assert!(!config.tile_diff_config.enabled);
6590        assert_eq!(config.tile_diff_config.tile_w, 24);
6591        assert_eq!(config.tile_diff_config.tile_h, 12);
6592        assert_eq!(config.tile_diff_config.max_tiles, 2048);
6593        assert!(!config.reset_on_resize);
6594        assert!(!config.reset_on_invalidation);
6595        assert_eq!(config.full_redraw_interval_frames, 17);
6596    }
6597
6598    #[test]
6599    fn with_diff_config_applies_strategy_config() {
6600        use ftui_render::diff_strategy::DiffStrategyConfig;
6601
6602        let strategy_config = DiffStrategyConfig {
6603            prior_alpha: 5.0,
6604            prior_beta: 5.0,
6605            ..Default::default()
6606        };
6607
6608        let runtime_config =
6609            RuntimeDiffConfig::default().with_strategy_config(strategy_config.clone());
6610
6611        let writer = TerminalWriter::with_diff_config(
6612            Vec::<u8>::new(),
6613            ScreenMode::AltScreen,
6614            UiAnchor::Bottom,
6615            basic_caps(),
6616            runtime_config,
6617        );
6618
6619        // Verify the strategy config was applied
6620        let (alpha, beta) = writer.diff_strategy().posterior_params();
6621        assert!((alpha - 5.0).abs() < 0.001);
6622        assert!((beta - 5.0).abs() < 0.001);
6623    }
6624
6625    #[test]
6626    fn with_diff_config_applies_tile_config() {
6627        let tile_config = TileDiffConfig::default()
6628            .with_enabled(false)
6629            .with_tile_size(32, 16)
6630            .with_max_tiles(1024);
6631        let runtime_config = RuntimeDiffConfig::default().with_tile_diff_config(tile_config);
6632
6633        let mut writer = TerminalWriter::with_diff_config(
6634            Vec::<u8>::new(),
6635            ScreenMode::AltScreen,
6636            UiAnchor::Bottom,
6637            basic_caps(),
6638            runtime_config,
6639        );
6640
6641        let applied = writer.diff_scratch.tile_config_mut();
6642        assert!(!applied.enabled);
6643        assert_eq!(applied.tile_w, 32);
6644        assert_eq!(applied.tile_h, 16);
6645        assert_eq!(applied.max_tiles, 1024);
6646    }
6647
6648    #[test]
6649    fn diff_config_accessor() {
6650        let config = RuntimeDiffConfig::default().with_bayesian_enabled(false);
6651
6652        let writer = TerminalWriter::with_diff_config(
6653            Vec::<u8>::new(),
6654            ScreenMode::AltScreen,
6655            UiAnchor::Bottom,
6656            basic_caps(),
6657            config,
6658        );
6659
6660        assert!(!writer.diff_config().bayesian_enabled);
6661    }
6662
6663    #[test]
6664    fn last_diff_strategy_updates_after_present() {
6665        let mut output = Vec::new();
6666        let mut writer = TerminalWriter::with_diff_config(
6667            &mut output,
6668            ScreenMode::AltScreen,
6669            UiAnchor::Bottom,
6670            basic_caps(),
6671            RuntimeDiffConfig::default(),
6672        );
6673        writer.set_size(10, 3);
6674
6675        let mut buffer = Buffer::new(10, 3);
6676        buffer.set_raw(0, 0, Cell::from_char('X'));
6677
6678        assert!(writer.last_diff_strategy().is_none());
6679        writer.present_ui(&buffer, None, false).unwrap();
6680        assert_eq!(writer.last_diff_strategy(), Some(DiffStrategy::FullRedraw));
6681
6682        buffer.set_raw(1, 1, Cell::from_char('Y'));
6683        writer.present_ui(&buffer, None, false).unwrap();
6684        assert!(writer.last_diff_strategy().is_some());
6685    }
6686
6687    #[test]
6688    fn full_redraw_interval_forces_terminal_resync() {
6689        let mut output = Vec::new();
6690        let mut writer = TerminalWriter::with_diff_config(
6691            &mut output,
6692            ScreenMode::AltScreen,
6693            UiAnchor::Bottom,
6694            basic_caps(),
6695            RuntimeDiffConfig::default()
6696                .with_bayesian_enabled(false)
6697                .with_full_redraw_interval_frames(1),
6698        );
6699        writer.set_size(4, 2);
6700
6701        let mut buffer = Buffer::new(4, 2);
6702        buffer.set_raw(0, 0, Cell::from_char('A'));
6703
6704        writer.present_ui(&buffer, None, false).unwrap();
6705        assert_eq!(writer.last_diff_strategy(), Some(DiffStrategy::FullRedraw));
6706
6707        writer.present_ui(&buffer, None, false).unwrap();
6708        assert_ne!(writer.last_diff_strategy(), Some(DiffStrategy::FullRedraw));
6709
6710        writer.present_ui(&buffer, None, false).unwrap();
6711        assert_eq!(writer.last_diff_strategy(), Some(DiffStrategy::FullRedraw));
6712    }
6713
6714    #[test]
6715    fn full_redraw_interval_emits_current_frame_after_incremental_baseline() {
6716        let state = Rc::new(RefCell::new(FaultState::default()));
6717        let writer_backend = SingleWriteFaultWriter::new(Rc::clone(&state), usize::MAX, 1);
6718        let mut writer = TerminalWriter::with_diff_config(
6719            writer_backend,
6720            ScreenMode::AltScreen,
6721            UiAnchor::Bottom,
6722            basic_caps(),
6723            RuntimeDiffConfig::default()
6724                .with_bayesian_enabled(false)
6725                .with_full_redraw_interval_frames(1),
6726        );
6727        writer.set_size(4, 2);
6728
6729        let mut buffer = Buffer::new(4, 2);
6730        buffer.set_raw(0, 0, Cell::from_char('Q'));
6731
6732        writer.present_ui(&buffer, None, false).unwrap();
6733        assert_eq!(writer.last_diff_strategy(), Some(DiffStrategy::FullRedraw));
6734
6735        buffer.set_raw(1, 0, Cell::from_char('Z'));
6736        writer.present_ui(&buffer, None, false).unwrap();
6737        assert_ne!(writer.last_diff_strategy(), Some(DiffStrategy::FullRedraw));
6738
6739        state.borrow_mut().bytes.clear();
6740        writer.present_ui(&buffer, None, false).unwrap();
6741        assert_eq!(writer.last_diff_strategy(), Some(DiffStrategy::FullRedraw));
6742
6743        let bytes = state.borrow().bytes.clone();
6744        assert!(
6745            bytes.windows(b"QZ".len()).any(|window| window == b"QZ"),
6746            "forced full redraw should emit adjacent current-frame cells"
6747        );
6748    }
6749
6750    #[test]
6751    fn full_redraw_interval_zero_disables_terminal_resync() {
6752        let mut output = Vec::new();
6753        let mut writer = TerminalWriter::with_diff_config(
6754            &mut output,
6755            ScreenMode::AltScreen,
6756            UiAnchor::Bottom,
6757            basic_caps(),
6758            RuntimeDiffConfig::default()
6759                .with_bayesian_enabled(false)
6760                .with_full_redraw_interval_frames(0),
6761        );
6762        writer.set_size(4, 2);
6763
6764        let mut buffer = Buffer::new(4, 2);
6765        buffer.set_raw(0, 0, Cell::from_char('A'));
6766
6767        writer.present_ui(&buffer, None, false).unwrap();
6768        assert_eq!(writer.last_diff_strategy(), Some(DiffStrategy::FullRedraw));
6769
6770        for _ in 0..5 {
6771            writer.present_ui(&buffer, None, false).unwrap();
6772            assert_ne!(writer.last_diff_strategy(), Some(DiffStrategy::FullRedraw));
6773        }
6774    }
6775
6776    #[test]
6777    fn full_redraw_max_interval_zero_forces_resync_every_frame() {
6778        // A zero wall-clock interval means "always due": every present must be a
6779        // full physical redraw, regardless of the frame counter. This is the
6780        // wall-clock bound that repairs terminal-state desync on an idle /
6781        // sparsely-rendering TUI where the frame counter advances too slowly.
6782        let mut output = Vec::new();
6783        let mut writer = TerminalWriter::with_diff_config(
6784            &mut output,
6785            ScreenMode::AltScreen,
6786            UiAnchor::Bottom,
6787            basic_caps(),
6788            RuntimeDiffConfig::default()
6789                .with_bayesian_enabled(false)
6790                // Disable the frame-count path to isolate the wall-clock bound.
6791                .with_full_redraw_interval_frames(0)
6792                .with_full_redraw_max_interval(Some(std::time::Duration::ZERO)),
6793        );
6794        writer.set_size(4, 2);
6795
6796        let mut buffer = Buffer::new(4, 2);
6797        buffer.set_raw(0, 0, Cell::from_char('A'));
6798
6799        // First frame is a full redraw (no prior baseline) and every subsequent
6800        // frame is forced full by the zero interval.
6801        for _ in 0..5 {
6802            writer.present_ui(&buffer, None, false).unwrap();
6803            assert_eq!(
6804                writer.last_diff_strategy(),
6805                Some(DiffStrategy::FullRedraw),
6806                "zero wall-clock interval must force a full redraw every frame"
6807            );
6808        }
6809    }
6810
6811    #[test]
6812    fn full_redraw_max_interval_none_keeps_incremental_after_baseline() {
6813        // The wall-clock bound is opt-in: with it unset (None) and the
6814        // frame-count path disabled, frames stay incremental after the initial
6815        // baseline full redraw — preserving the default sparse-diff behavior and
6816        // deterministic-test reproducibility.
6817        let mut output = Vec::new();
6818        let mut writer = TerminalWriter::with_diff_config(
6819            &mut output,
6820            ScreenMode::AltScreen,
6821            UiAnchor::Bottom,
6822            basic_caps(),
6823            RuntimeDiffConfig::default()
6824                .with_bayesian_enabled(false)
6825                .with_full_redraw_interval_frames(0)
6826                .with_full_redraw_max_interval(None),
6827        );
6828        writer.set_size(4, 2);
6829
6830        let mut buffer = Buffer::new(4, 2);
6831        buffer.set_raw(0, 0, Cell::from_char('A'));
6832
6833        writer.present_ui(&buffer, None, false).unwrap();
6834        assert_eq!(writer.last_diff_strategy(), Some(DiffStrategy::FullRedraw));
6835
6836        for _ in 0..5 {
6837            writer.present_ui(&buffer, None, false).unwrap();
6838            assert_ne!(
6839                writer.last_diff_strategy(),
6840                Some(DiffStrategy::FullRedraw),
6841                "no wall-clock bound must leave frames incremental after baseline"
6842            );
6843        }
6844    }
6845
6846    #[test]
6847    fn diff_decision_evidence_schema_includes_span_fields() {
6848        let evidence_path = temp_evidence_path("diff_decision_schema");
6849        let sink = EvidenceSink::from_config(
6850            &crate::evidence_sink::EvidenceSinkConfig::enabled_file(&evidence_path),
6851        )
6852        .expect("evidence sink config")
6853        .expect("evidence sink enabled");
6854
6855        let mut writer = TerminalWriter::with_diff_config(
6856            Vec::<u8>::new(),
6857            ScreenMode::AltScreen,
6858            UiAnchor::Bottom,
6859            basic_caps(),
6860            RuntimeDiffConfig::default(),
6861        )
6862        .with_evidence_sink(sink);
6863        writer.set_size(10, 3);
6864
6865        let mut buffer = Buffer::new(10, 3);
6866        buffer.set_raw(0, 0, Cell::from_char('X'));
6867        writer.present_ui(&buffer, None, false).unwrap();
6868
6869        buffer.set_raw(1, 1, Cell::from_char('Y'));
6870        writer.present_ui(&buffer, None, false).unwrap();
6871
6872        let jsonl = std::fs::read_to_string(&evidence_path).expect("read evidence jsonl");
6873        let line = jsonl
6874            .lines()
6875            .find(|line| line.contains("\"event\":\"diff_decision\""))
6876            .expect("diff_decision line");
6877        let value: serde_json::Value = serde_json::from_str(line).expect("valid json");
6878
6879        assert_eq!(
6880            value["schema_version"],
6881            crate::evidence_sink::EVIDENCE_SCHEMA_VERSION
6882        );
6883        assert_eq!(value["event"], "diff_decision");
6884        assert!(
6885            value["run_id"]
6886                .as_str()
6887                .map(|s| !s.is_empty())
6888                .unwrap_or(false),
6889            "run_id should be a non-empty string"
6890        );
6891        assert!(
6892            value["event_idx"].is_number(),
6893            "event_idx should be numeric"
6894        );
6895        assert_eq!(value["screen_mode"], "altscreen");
6896        assert!(value["cols"].is_number(), "cols should be numeric");
6897        assert!(value["rows"].is_number(), "rows should be numeric");
6898        assert!(
6899            value["span_count"].is_number(),
6900            "span_count should be numeric"
6901        );
6902        assert!(
6903            value["span_coverage_pct"].is_number(),
6904            "span_coverage_pct should be numeric"
6905        );
6906        assert!(
6907            value["tile_size"].is_number(),
6908            "tile_size should be numeric"
6909        );
6910        assert!(
6911            value["dirty_tile_count"].is_number(),
6912            "dirty_tile_count should be numeric"
6913        );
6914        assert!(
6915            value["skipped_tile_count"].is_number(),
6916            "skipped_tile_count should be numeric"
6917        );
6918        assert!(
6919            value["sat_build_cost_est"].is_number(),
6920            "sat_build_cost_est should be numeric"
6921        );
6922        assert!(
6923            value["skipped_tile_rows"].is_number(),
6924            "skipped_tile_rows should be numeric"
6925        );
6926        assert!(
6927            value["sat_queries"].is_number(),
6928            "sat_queries should be numeric"
6929        );
6930        assert!(
6931            value["fallback_reason"].is_string(),
6932            "fallback_reason should be string"
6933        );
6934        assert!(
6935            value["scan_cost_estimate"].is_number(),
6936            "scan_cost_estimate should be numeric"
6937        );
6938        assert!(
6939            value["max_span_len"].is_number(),
6940            "max_span_len should be numeric"
6941        );
6942        assert!(
6943            value["guard_reason"].is_string(),
6944            "guard_reason should be a string"
6945        );
6946        assert!(
6947            value["hysteresis_applied"].is_boolean(),
6948            "hysteresis_applied should be boolean"
6949        );
6950        assert!(
6951            value["hysteresis_ratio"].is_number(),
6952            "hysteresis_ratio should be numeric"
6953        );
6954        assert!(
6955            value["fallback_reason"].is_string(),
6956            "fallback_reason should be a string"
6957        );
6958        assert!(
6959            value["scan_cost_estimate"].is_number(),
6960            "scan_cost_estimate should be numeric"
6961        );
6962    }
6963
6964    #[test]
6965    fn diff_decision_has_regime_field() {
6966        let evidence_path = temp_evidence_path("diff_decision_has_regime");
6967        let sink = EvidenceSink::from_config(
6968            &crate::evidence_sink::EvidenceSinkConfig::enabled_file(&evidence_path),
6969        )
6970        .expect("evidence sink config")
6971        .expect("evidence sink enabled");
6972
6973        let mut writer = TerminalWriter::with_diff_config(
6974            Vec::<u8>::new(),
6975            ScreenMode::AltScreen,
6976            UiAnchor::Bottom,
6977            basic_caps(),
6978            RuntimeDiffConfig::default(),
6979        )
6980        .with_evidence_sink(sink);
6981        writer.set_size(10, 3);
6982
6983        let mut buffer = Buffer::new(10, 3);
6984        buffer.set_raw(0, 0, Cell::from_char('X'));
6985        writer.present_ui(&buffer, None, false).unwrap();
6986
6987        buffer.set_raw(1, 1, Cell::from_char('Y'));
6988        writer.present_ui(&buffer, None, false).unwrap();
6989
6990        let jsonl = std::fs::read_to_string(&evidence_path).expect("read evidence jsonl");
6991        let line = jsonl
6992            .lines()
6993            .find(|line| line.contains("\"event\":\"diff_decision\""))
6994            .expect("diff_decision line");
6995        let value: serde_json::Value = serde_json::from_str(line).expect("valid json");
6996
6997        assert_eq!(value["event"], "diff_decision");
6998        assert!(
6999            value.get("regime").is_some(),
7000            "diff_decision should contain 'regime'"
7001        );
7002        assert_eq!(value["regime"], "sparse");
7003        assert_eq!(writer.diff_regime(), DiffRegime::Sparse);
7004    }
7005
7006    #[test]
7007    fn diff_regime_transition_emitted_once_per_change() {
7008        let evidence_path = temp_evidence_path("diff_regime_transition_emitted");
7009        let sink = EvidenceSink::from_config(
7010            &crate::evidence_sink::EvidenceSinkConfig::enabled_file(&evidence_path),
7011        )
7012        .expect("evidence sink config")
7013        .expect("evidence sink enabled");
7014
7015        let mut writer = TerminalWriter::with_diff_config(
7016            Vec::<u8>::new(),
7017            ScreenMode::AltScreen,
7018            UiAnchor::Bottom,
7019            basic_caps(),
7020            RuntimeDiffConfig::default(),
7021        )
7022        .with_evidence_sink(sink);
7023        writer.set_size(10, 10);
7024
7025        let mut buffer = Buffer::new(10, 10);
7026        // Baseline frame (initial redraw, populates prev_buffer)
7027        writer.present_ui(&buffer, None, false).unwrap();
7028
7029        // Three sparse presents
7030        buffer.set_raw(0, 0, Cell::from_char('1'));
7031        writer.present_ui(&buffer, None, false).unwrap();
7032        assert_eq!(writer.diff_regime(), DiffRegime::Sparse);
7033
7034        buffer.set_raw(0, 1, Cell::from_char('2'));
7035        writer.present_ui(&buffer, None, false).unwrap();
7036        assert_eq!(writer.diff_regime(), DiffRegime::Sparse);
7037
7038        buffer.set_raw(0, 2, Cell::from_char('3'));
7039        writer.present_ui(&buffer, None, false).unwrap();
7040        assert_eq!(writer.diff_regime(), DiffRegime::Sparse);
7041
7042        // One full redraw (all cells modified -> ratio >= 0.60 -> DiffRegime::Redraw)
7043        for y in 0..10 {
7044            for x in 0..10 {
7045                buffer.set_raw(x, y, Cell::from_char('X'));
7046            }
7047        }
7048        writer.present_ui(&buffer, None, false).unwrap();
7049        assert_eq!(writer.diff_regime(), DiffRegime::Redraw);
7050
7051        // Sparse present again
7052        buffer.set_raw(0, 0, Cell::from_char('Z'));
7053        writer.present_ui(&buffer, None, false).unwrap();
7054        assert_eq!(writer.diff_regime(), DiffRegime::Sparse);
7055
7056        let jsonl = std::fs::read_to_string(&evidence_path).expect("read evidence jsonl");
7057        let transition_lines: Vec<&str> = jsonl
7058            .lines()
7059            .filter(|line| line.contains("\"event\":\"diff_regime_transition\""))
7060            .collect();
7061
7062        assert_eq!(
7063            transition_lines.len(),
7064            2,
7065            "expected exactly two transition lines, got: {transition_lines:?}"
7066        );
7067
7068        let first: serde_json::Value =
7069            serde_json::from_str(transition_lines[0]).expect("valid json first transition");
7070        assert_eq!(first["event"], "diff_regime_transition");
7071        assert_eq!(first["from"], "sparse");
7072        assert_eq!(first["to"], "redraw");
7073        assert_eq!(first["frames_in_previous"], 3);
7074
7075        let second: serde_json::Value =
7076            serde_json::from_str(transition_lines[1]).expect("valid json second transition");
7077        assert_eq!(second["event"], "diff_regime_transition");
7078        assert_eq!(second["from"], "redraw");
7079        assert_eq!(second["to"], "sparse");
7080        assert_eq!(second["frames_in_previous"], 1);
7081    }
7082
7083    #[test]
7084    fn diff_strategy_posterior_updates_with_total_cells() {
7085        let mut output = Vec::new();
7086        let mut writer = TerminalWriter::with_diff_config(
7087            &mut output,
7088            ScreenMode::AltScreen,
7089            UiAnchor::Bottom,
7090            basic_caps(),
7091            RuntimeDiffConfig::default(),
7092        );
7093        writer.set_size(10, 10);
7094
7095        let mut buffer = Buffer::new(10, 10);
7096        buffer.set_raw(0, 0, Cell::from_char('A'));
7097        writer.present_ui(&buffer, None, false).unwrap();
7098
7099        let mut buffer2 = Buffer::new(10, 10);
7100        for x in 0..10u16 {
7101            buffer2.set_raw(x, 0, Cell::from_char('X'));
7102        }
7103        writer.present_ui(&buffer2, None, false).unwrap();
7104
7105        let config = writer.diff_strategy().config().clone();
7106        let total_cells = 10usize * 10usize;
7107        let changed = 10usize;
7108        let alpha = config.prior_alpha * config.decay + changed as f64;
7109        let beta = config.prior_beta * config.decay + (total_cells - changed) as f64;
7110        let expected = alpha / (alpha + beta);
7111        let mean = writer.diff_strategy().posterior_mean();
7112        assert!(
7113            (mean - expected).abs() < 1e-9,
7114            "posterior mean should use total_cells; got {mean:.6}, expected {expected:.6}"
7115        );
7116    }
7117
7118    #[test]
7119    fn log_write_without_scroll_region_preserves_diff_strategy() {
7120        // Overlay log writes never scroll the screen (single erased-and-
7121        // rewritten line, no unqualified LF), so the displayed UI baseline
7122        // stays valid and the diff strategy posterior must be PRESERVED —
7123        // the old reset-to-priors behavior compensated for log-induced
7124        // scrolling that no longer happens.
7125        let mut output = Vec::new();
7126        {
7127            let config = RuntimeDiffConfig::default();
7128            let mut writer = TerminalWriter::with_diff_config(
7129                &mut output,
7130                ScreenMode::Inline { ui_height: 5 },
7131                UiAnchor::Bottom,
7132                basic_caps(), // no scroll region support
7133                config,
7134            );
7135            writer.set_size(80, 24);
7136
7137            // Present a frame and observe some changes to modify posterior
7138            let mut buffer = Buffer::new(80, 5);
7139            buffer.set_raw(0, 0, Cell::from_char('X'));
7140            writer.present_ui(&buffer, None, false).unwrap();
7141
7142            // Present another frame
7143            buffer.set_raw(1, 1, Cell::from_char('Y'));
7144            writer.present_ui(&buffer, None, false).unwrap();
7145
7146            let (alpha_before, beta_before) = writer.diff_strategy().posterior_params();
7147
7148            // Log write without scroll region must not disturb diff state
7149            assert!(!writer.scroll_region_active());
7150            writer.write_log("log message\n").unwrap();
7151
7152            let (alpha_after, beta_after) = writer.diff_strategy().posterior_params();
7153            assert!(
7154                (alpha_after - alpha_before).abs() < 0.01
7155                    && (beta_after - beta_before).abs() < 0.01,
7156                "posterior should be preserved across overlay log write: \
7157                 before=({}, {}), after=({}, {})",
7158                alpha_before,
7159                beta_before,
7160                alpha_after,
7161                beta_after
7162            );
7163        }
7164    }
7165
7166    #[test]
7167    fn log_write_with_scroll_region_preserves_diff_strategy() {
7168        // When scroll region is active, log writes should NOT reset diff strategy
7169        let mut output = Vec::new();
7170        {
7171            let config = RuntimeDiffConfig::default();
7172            let mut writer = TerminalWriter::with_diff_config(
7173                &mut output,
7174                ScreenMode::Inline { ui_height: 5 },
7175                UiAnchor::Bottom,
7176                scroll_region_caps(), // has scroll region support
7177                config,
7178            );
7179            writer.set_size(80, 24);
7180
7181            // Present frames to activate scroll region and update posterior
7182            let mut buffer = Buffer::new(80, 5);
7183            buffer.set_raw(0, 0, Cell::from_char('X'));
7184            writer.present_ui(&buffer, None, false).unwrap();
7185
7186            buffer.set_raw(1, 1, Cell::from_char('Y'));
7187            writer.present_ui(&buffer, None, false).unwrap();
7188
7189            assert!(writer.scroll_region_active());
7190
7191            // Get posterior before log write
7192            let (alpha_before, beta_before) = writer.diff_strategy().posterior_params();
7193
7194            // Log write with scroll region active should NOT reset
7195            writer.write_log("log message\n").unwrap();
7196
7197            let (alpha_after, beta_after) = writer.diff_strategy().posterior_params();
7198            assert!(
7199                (alpha_after - alpha_before).abs() < 0.01
7200                    && (beta_after - beta_before).abs() < 0.01,
7201                "posterior should be preserved with scroll region: before=({}, {}), after=({}, {})",
7202                alpha_before,
7203                beta_before,
7204                alpha_after,
7205                beta_after
7206            );
7207        }
7208    }
7209
7210    // --- Overlay log discipline regressions (bd-th0p6 / bd-le0q8) ---
7211
7212    #[test]
7213    fn sgr_overlay_matches_plain_width_policy_for_unicode_and_controls() {
7214        for text in [
7215            "\x1b[31m界界界!",
7216            "\x1b[31me\u{301}\x1b[32mclair",
7217            "\x1b[31m\u{301}leading\tspace\nignored",
7218            "\x1b[4:3m👩\u{200d}💻 work\rignored",
7219            "\x1b[31m\t\nignored",
7220        ] {
7221            for width in 0..12 {
7222                let styled = sgr_overlay_log_line(text, width);
7223                assert_eq!(
7224                    sanitize(&styled),
7225                    sanitize_overlay_log_line(&sanitize(text), width),
7226                    "text={text:?}, width={width}"
7227                );
7228                assert_eq!(sanitize_with(&styled, SanitizeMode::SgrOnly), styled);
7229            }
7230        }
7231    }
7232
7233    #[test]
7234    fn log_modes_route_through_both_inline_strategies_and_anchors() {
7235        for mode in [
7236            SanitizeMode::Strip,
7237            SanitizeMode::SgrOnly,
7238            SanitizeMode::Raw,
7239        ] {
7240            for anchor in [UiAnchor::Top, UiAnchor::Bottom] {
7241                for scroll_region in [false, true] {
7242                    let caps = if scroll_region {
7243                        scroll_region_caps()
7244                    } else {
7245                        basic_caps()
7246                    };
7247                    let mut writer = TerminalWriter::new(
7248                        Vec::new(),
7249                        ScreenMode::Inline { ui_height: 2 },
7250                        anchor,
7251                        caps,
7252                    );
7253                    writer.set_size(10, 8);
7254                    if scroll_region {
7255                        writer.present_ui(&Buffer::new(10, 2), None, true).unwrap();
7256                        assert!(writer.scroll_region_active());
7257                    }
7258                    writer.flush().unwrap();
7259                    let start = writer.writer().inner().get_ref().len();
7260                    let payload = "\x1b[31mcolored\x1b[2J\nsecond";
7261                    match mode {
7262                        SanitizeMode::Strip => writer.write_log(payload),
7263                        SanitizeMode::SgrOnly => writer.write_log_sgr_only(payload),
7264                        SanitizeMode::Raw => writer.write_log_raw(payload),
7265                    }
7266                    .unwrap();
7267                    writer.flush().unwrap();
7268                    let output = &writer.writer().inner().get_ref()[start..];
7269                    let output = std::str::from_utf8(output).unwrap();
7270                    assert!(output.contains("colored"));
7271                    assert_eq!(output.contains("\x1b[31m"), mode != SanitizeMode::Strip);
7272                    assert_eq!(output.contains("\x1b[2J"), mode == SanitizeMode::Raw);
7273                    // Only the top-anchored overlay keeps a single row; the
7274                    // region and the bottom-anchored stream keep every line.
7275                    let every_line = scroll_region || anchor == UiAnchor::Bottom;
7276                    assert_eq!(output.contains('\n'), every_line);
7277                    assert_eq!(output.contains("second"), every_line);
7278                    // Region: its bottom margin (row 6). Bottom overlay: the
7279                    // stream starts on the first UI row (7 of 8: one row
7280                    // above the last, addressed from the bottom). Top: row 8.
7281                    let log_row = match (anchor, scroll_region) {
7282                        (UiAnchor::Top, _) => "\x1b[8;1H",
7283                        (UiAnchor::Bottom, true) => "\x1b[6;1H",
7284                        (UiAnchor::Bottom, false) => "\x1b[9999;1H\x1b[A",
7285                    };
7286                    assert!(output.contains(log_row));
7287                    if mode == SanitizeMode::SgrOnly {
7288                        assert!(output.contains("colored\x1b[0m"));
7289                        match (anchor, scroll_region) {
7290                            (_, true) => assert!(output.contains("\x1b[0m\r\nsecond\x1b[0m")),
7291                            (UiAnchor::Bottom, false) => {
7292                                // "second" has no newline, so it stays open:
7293                                // only cursor addressing follows it.
7294                                let open = output.find("\x1b[0msecond\x1b[0m").unwrap();
7295                                assert!(!output[open..].contains(['\r', '\n']), "{output:?}");
7296                            }
7297                            (UiAnchor::Top, false) => {
7298                                assert!(output.ends_with("\x1b[0m\x1b8"));
7299                            }
7300                        }
7301                    }
7302                }
7303            }
7304        }
7305    }
7306
7307    #[test]
7308    fn sgr_overlay_streams_long_colored_lines_whole() {
7309        // The bottom-anchored stream lets the terminal wrap: nothing is
7310        // clamped or dropped, and styling is reset before each line end.
7311        let mut writer = TerminalWriter::new(
7312            Vec::new(),
7313            ScreenMode::Inline { ui_height: 5 },
7314            UiAnchor::Bottom,
7315            basic_caps(),
7316        );
7317        writer.set_size(80, 24);
7318        writer
7319            .write_log_sgr_only(&format!("\x1b[38:2::255:0:0m{}\ntail", "x".repeat(200)))
7320            .unwrap();
7321        let output = String::from_utf8(writer.into_inner().unwrap()).unwrap();
7322        assert_eq!(output.matches('x').count(), 200);
7323        assert!(output.contains("\x1b[38:2::255:0:0m"));
7324        assert!(output.contains(&format!("{}\x1b[0m\r\n", "x".repeat(200))));
7325        // "tail" has no newline: it stays open, followed by cursor
7326        // addressing rather than a line break.
7327        assert!(output.contains("\x1b[0mtail\x1b[0m\x1b["), "{output:?}");
7328        assert!(!output.contains("tail\x1b[0m\r\n"));
7329        let mut vt = vt_screen(output.as_bytes(), 80, 24);
7330        let joined = vt_transcript(&mut vt).concat();
7331        assert!(joined.contains(&format!("{}tail", "x".repeat(200))));
7332    }
7333
7334    #[test]
7335    fn log_modes_remain_noops_without_a_log_region() {
7336        for screen_mode in [ScreenMode::AltScreen, ScreenMode::Inline { ui_height: 24 }] {
7337            for mode in [
7338                SanitizeMode::Strip,
7339                SanitizeMode::SgrOnly,
7340                SanitizeMode::Raw,
7341            ] {
7342                let mut writer =
7343                    TerminalWriter::new(Vec::new(), screen_mode, UiAnchor::Bottom, basic_caps());
7344                writer.set_size(80, 24);
7345                writer
7346                    .write_log_with_mode("\x1b[2J\x1b[31mhidden\n", mode)
7347                    .unwrap();
7348                writer.flush().unwrap();
7349                assert!(writer.writer().inner().get_ref().is_empty());
7350            }
7351        }
7352    }
7353
7354    #[test]
7355    fn annotated_logs_are_resanitized_even_for_public_variants() {
7356        let mut writer = TerminalWriter::new(
7357            Vec::new(),
7358            ScreenMode::Inline { ui_height: 5 },
7359            UiAnchor::Bottom,
7360            basic_caps(),
7361        );
7362        let payload = "\x1b[31mtext\x1b[2J";
7363        for text in [
7364            Text::Sanitized(std::borrow::Cow::Borrowed(payload)),
7365            Text::SgrOnly(std::borrow::Cow::Borrowed(payload)),
7366            Text::trusted(payload),
7367        ] {
7368            writer.flush().unwrap();
7369            let start = writer.writer().inner().get_ref().len();
7370            writer.write_log_text(&text).unwrap();
7371            writer.flush().unwrap();
7372            let output = std::str::from_utf8(&writer.writer().inner().get_ref()[start..]).unwrap();
7373            assert_eq!(
7374                output.contains("\x1b[31m"),
7375                text.mode() != SanitizeMode::Strip
7376            );
7377            assert_eq!(output.contains("\x1b[2J"), text.mode() == SanitizeMode::Raw);
7378        }
7379    }
7380
7381    #[test]
7382    fn sgr_logs_render_color_and_leave_following_output_unstyled() {
7383        let mut writer = TerminalWriter::new(
7384            Vec::new(),
7385            ScreenMode::InlineAuto {
7386                min_height: 2,
7387                max_height: 4,
7388            },
7389            UiAnchor::Bottom,
7390            basic_caps(),
7391        );
7392        writer.set_size(20, 8);
7393        writer
7394            .write_log_sgr_only("\x1b[1;38;2;255;0;0mred\x1b[2J")
7395            .unwrap();
7396        writer.flush().unwrap();
7397        let mut vt = vt_screen(writer.writer().inner().get_ref(), 20, 8);
7398        // The streamed line ends directly above the UI rows.
7399        let row = writer.ui_start_row() - 1;
7400        let visible: Vec<String> = vt.screen().rows(0, 20).collect();
7401        assert!(visible[usize::from(row)].starts_with("red"));
7402        let cell = vt.screen().cell(row, 0).expect("cell");
7403        assert_eq!(cell.fgcolor(), vt100::Color::Rgb(255, 0, 0));
7404        assert!(cell.bold());
7405        // Output after the log carries no leftover styling.
7406        vt.process(b"\x1b[1;1Hplain");
7407        let plain = vt.screen().cell(0, 0).expect("cell");
7408        assert_eq!(plain.contents(), "p");
7409        assert_eq!(plain.fgcolor(), vt100::Color::Default);
7410        assert!(!plain.bold());
7411    }
7412
7413    #[test]
7414    fn sgr_log_write_failure_keeps_reset_pending_and_reports_the_error() {
7415        let state = Rc::new(RefCell::new(FaultState::default()));
7416        let output = SingleWriteFaultWriter::new(Rc::clone(&state), usize::MAX, 10);
7417        let mut writer = TerminalWriter::new(
7418            output,
7419            ScreenMode::Inline { ui_height: 2 },
7420            UiAnchor::Bottom,
7421            scroll_region_caps(),
7422        );
7423        writer.set_size(80, 24);
7424        writer.present_ui(&Buffer::new(80, 2), None, true).unwrap();
7425        writer.flush().unwrap();
7426        assert!(writer.scroll_region_active());
7427        // Two short writes drain the cursor/reset prefix; the third writes
7428        // the red SGR and some text. Fail on the fourth, with styling active.
7429        let fail_on_call = state.borrow().write_calls + 4;
7430        writer.writer().inner_mut().get_mut().fail_on_call = fail_on_call;
7431        let error = writer
7432            .write_log_sgr_only(&format!("\x1b[31m{}", "x".repeat(100_000)))
7433            .unwrap_err();
7434        assert_eq!(error.kind(), io::ErrorKind::Other);
7435        assert!(state.borrow().injected_failure_triggered);
7436        assert!(contains_bytes(&state.borrow().bytes, b"\x1b[31mxxxxx"));
7437        writer.flush().unwrap();
7438        assert!(state.borrow().bytes.ends_with(SGR_RESET));
7439    }
7440
7441    /// CONTRACT (G48): without a scroll region, a bottom-anchored write_log
7442    /// vacates the UI rows (erase to end of screen from the first UI row)
7443    /// before streaming, so no UI text can scroll into history, and every LF
7444    /// it emits is preceded by CR (raw mode has no ONLCR translation).
7445    #[test]
7446    fn overlay_write_log_vacates_ui_rows_then_streams_with_crlf() {
7447        let mut output = Vec::new();
7448        {
7449            let mut writer = TerminalWriter::new(
7450                &mut output,
7451                ScreenMode::Inline { ui_height: 5 },
7452                UiAnchor::Bottom,
7453                basic_caps(),
7454            );
7455            writer.set_size(80, 24);
7456            writer.present_ui(&marked_frame(80, 5), None, true).unwrap();
7457            writer.write_log("first line\n").unwrap();
7458            writer.flush().unwrap();
7459        }
7460
7461        // The first UI row, 20 of 24: 4 rows above the last.
7462        assert!(contains_bytes(
7463            &output,
7464            b"\x1b[9999;1H\x1b[4A\x1b[Jfirst line\r\n"
7465        ));
7466        for (i, _) in output.iter().enumerate().filter(|(_, b)| **b == b'\n') {
7467            assert!(i > 0 && output[i - 1] == b'\r', "bare LF at byte {i}");
7468        }
7469    }
7470
7471    /// CONTRACT (G48): every line of a multi-line payload reaches scrollback,
7472    /// in order (the pre-G48 overlay kept only the first).
7473    #[test]
7474    fn overlay_write_log_keeps_every_line_of_a_multiline_payload() {
7475        let mut output = Vec::new();
7476        {
7477            let mut writer = TerminalWriter::new(
7478                &mut output,
7479                ScreenMode::Inline { ui_height: 5 },
7480                UiAnchor::Bottom,
7481                basic_caps(),
7482            );
7483            writer.set_size(80, 24);
7484            writer.write_log("only me\nand the tail\n").unwrap();
7485        }
7486
7487        let mut vt = vt_screen(&output, 80, 24);
7488        let rows = vt_transcript(&mut vt);
7489        let first = rows
7490            .iter()
7491            .position(|r| r == "only me")
7492            .expect("first line");
7493        assert_eq!(rows[first + 1], "and the tail");
7494    }
7495
7496    /// CONTRACT (bd-th0p6 top-anchor): with a top-anchored UI and no scroll
7497    /// region, log writes park on the screen's bottom row but never emit LF,
7498    /// so nothing can push UI rows into scrollback.
7499    #[test]
7500    fn overlay_top_anchor_write_log_never_scrolls() {
7501        let mut output = Vec::new();
7502        {
7503            let mut writer = TerminalWriter::new(
7504                &mut output,
7505                ScreenMode::Inline { ui_height: 5 },
7506                UiAnchor::Top,
7507                basic_caps(),
7508            );
7509            writer.set_size(80, 24);
7510            writer.write_log("top anchored\n").unwrap();
7511        }
7512
7513        assert!(
7514            !output.contains(&b'\n'),
7515            "top-anchor overlay logs must not emit LF (screen-scroll hazard)"
7516        );
7517        assert!(
7518            contains_bytes(&output, b"\x1b[24;1H"),
7519            "log should target the screen's bottom row (below the UI)"
7520        );
7521        assert!(contains_bytes(&output, b"top anchored"));
7522    }
7523
7524    /// CONTRACT (G48): long lines are not clamped; the terminal wraps them
7525    /// above the UI, and the frame stays intact below.
7526    #[test]
7527    fn overlay_write_log_wraps_long_lines_without_touching_the_ui() {
7528        let mut writer = TerminalWriter::new(
7529            Vec::new(),
7530            ScreenMode::Inline { ui_height: 5 },
7531            UiAnchor::Bottom,
7532            basic_caps(),
7533        );
7534        writer.set_size(80, 24);
7535        writer.present_ui(&marked_frame(80, 5), None, true).unwrap();
7536        writer.write_log(&"x".repeat(100)).unwrap();
7537        writer.flush().unwrap();
7538
7539        let vt = vt_screen(writer.writer().inner().get_ref(), 80, 24);
7540        let visible: Vec<String> = vt.screen().rows(0, 80).collect();
7541        assert_eq!(visible[17], "x".repeat(80));
7542        assert_eq!(visible[18].trim_end(), "x".repeat(20));
7543        for y in 0..5 {
7544            assert_eq!(visible[19 + y].trim_end(), format!("UI-row{y}"));
7545        }
7546    }
7547
7548    /// When the pending inline-auto height shrinks, a log written before the
7549    /// next present lands above the *displayed* region (never inside it),
7550    /// and the next present draws the shrunk UI below it.
7551    #[test]
7552    fn inline_auto_shrink_positions_log_against_displayed_region() {
7553        let mut writer = TerminalWriter::new(
7554            Vec::new(),
7555            ScreenMode::InlineAuto {
7556                min_height: 1,
7557                max_height: 8,
7558            },
7559            UiAnchor::Bottom,
7560            basic_caps(),
7561        );
7562        writer.set_size(80, 24);
7563
7564        // Measure to the max: display an 8-row UI (rows 17-24, region
7565        // start 16, 0-indexed).
7566        writer.set_auto_ui_height(8);
7567        writer
7568            .present_ui(&marked_frame(80, 8), None, false)
7569            .unwrap();
7570
7571        // Remeasure drops the pending effective height to min=1 while rows
7572        // 17-24 are still physically on screen.
7573        writer.clear_auto_ui_height();
7574        writer.write_log("mid-flight\n").unwrap();
7575        writer.flush().unwrap();
7576
7577        assert!(
7578            contains_bytes(
7579                writer.writer().inner().get_ref(),
7580                // Row 17 of 24, addressed 7 rows above the last.
7581                b"\x1b[9999;1H\x1b[7A\x1b[Jmid-flight\r\n"
7582            ),
7583            "the stream starts on the displayed region's first row"
7584        );
7585        writer
7586            .present_ui(&marked_frame(80, 1), None, false)
7587            .unwrap();
7588        writer.flush().unwrap();
7589
7590        let vt = vt_screen(writer.writer().inner().get_ref(), 80, 24);
7591        let visible: Vec<String> = vt.screen().rows(0, 80).collect();
7592        assert_eq!(visible[15].trim_end(), "mid-flight");
7593        for row in &visible[16..23] {
7594            assert_eq!(row.trim_end(), "", "vacated rows hold no stale UI");
7595        }
7596        assert_eq!(visible[23].trim_end(), "UI-row0");
7597    }
7598
7599    #[test]
7600    fn inline_auto_single_log_row_uses_overlay_until_more_space_is_presented() {
7601        for anchor in [UiAnchor::Top, UiAnchor::Bottom] {
7602            let mut writer = TerminalWriter::new(
7603                Vec::new(),
7604                ScreenMode::InlineAuto {
7605                    min_height: 1,
7606                    max_height: 5,
7607                },
7608                anchor,
7609                scroll_region_caps(),
7610            );
7611            writer.set_size(20, 5);
7612            // Establish a valid region first, then replace it with geometry
7613            // that has only one free log row.
7614            writer.present_ui(&Buffer::new(20, 1), None, false).unwrap();
7615            assert!(writer.scroll_region_active());
7616            writer.set_auto_ui_height(4);
7617            writer.present_ui(&Buffer::new(20, 4), None, false).unwrap();
7618            assert!(
7619                !writer.scroll_region_active(),
7620                "DECSTBM cannot describe a single row"
7621            );
7622            let before = writer.writer().inner().get_ref().len();
7623            writer
7624                .write_log_sgr_only("\x1b[31mfirst\nsecond\n")
7625                .unwrap();
7626            writer.flush().unwrap();
7627            let output = &writer.writer().inner().get_ref()[before..];
7628            assert!(contains_bytes(output, b"first"));
7629            if anchor == UiAnchor::Top {
7630                // Top anchor: one overwritten row, never a scroll.
7631                assert!(!contains_bytes(output, b"second"));
7632                assert!(
7633                    !output.contains(&b'\n'),
7634                    "top-anchored single-row log must not scroll the screen"
7635                );
7636                assert!(contains_bytes(output, b"\x1b[5;1H"));
7637            } else {
7638                // Bottom anchor: streamed from the first UI row (2), both
7639                // lines kept; the scroll carries them past the one log row.
7640                assert!(contains_bytes(output, b"\x1b[2;1H\x1b[J"));
7641                assert!(contains_bytes(output, b"first\x1b[0m\r\n"));
7642                assert!(contains_bytes(output, b"second\x1b[0m\r\n"));
7643            }
7644
7645            writer.set_auto_ui_height(3);
7646            writer.present_ui(&Buffer::new(20, 3), None, false).unwrap();
7647            assert!(
7648                writer.scroll_region_active(),
7649                "two-row log area supports DECSTBM again"
7650            );
7651            let before = writer.writer().inner().get_ref().len();
7652            writer.write_log("first\nsecond\n").unwrap();
7653            writer.flush().unwrap();
7654            assert!(contains_bytes(
7655                &writer.writer().inner().get_ref()[before..],
7656                b"first\r\nsecond\r\n"
7657            ));
7658        }
7659    }
7660
7661    #[test]
7662    fn inline_auto_full_height_shrink_keeps_logs_out_until_present() {
7663        for caps in [basic_caps(), scroll_region_caps()] {
7664            for anchor in [UiAnchor::Top, UiAnchor::Bottom] {
7665                for clear_height in [false, true] {
7666                    for mode in [
7667                        SanitizeMode::Strip,
7668                        SanitizeMode::SgrOnly,
7669                        SanitizeMode::Raw,
7670                    ] {
7671                        let mut writer = TerminalWriter::new(
7672                            Vec::new(),
7673                            ScreenMode::InlineAuto {
7674                                min_height: 1,
7675                                max_height: 5,
7676                            },
7677                            anchor,
7678                            caps,
7679                        );
7680                        writer.set_size(20, 5);
7681                        writer.set_auto_ui_height(5);
7682                        writer.present_ui(&Buffer::new(20, 5), None, false).unwrap();
7683                        if clear_height {
7684                            writer.clear_auto_ui_height();
7685                        } else {
7686                            writer.set_auto_ui_height(1);
7687                        }
7688                        writer.flush().unwrap();
7689                        let before = writer.writer().inner().get_ref().len();
7690                        writer
7691                            .write_log_with_mode("\x1b[31mwaiting\n", mode)
7692                            .unwrap();
7693                        writer.flush().unwrap();
7694                        assert_eq!(
7695                            writer.writer().inner().get_ref().len(),
7696                            before,
7697                            "displayed UI still fills the screen: {anchor:?}, {mode:?}, clear={clear_height}"
7698                        );
7699
7700                        // Suppression ends when the smaller UI is actually
7701                        // displayed, for both scroll and overlay strategies.
7702                        writer.present_ui(&Buffer::new(20, 1), None, false).unwrap();
7703                        let before = writer.writer().inner().get_ref().len();
7704                        writer.write_log_with_mode("resumed", mode).unwrap();
7705                        writer.flush().unwrap();
7706                        assert!(contains_bytes(
7707                            &writer.writer().inner().get_ref()[before..],
7708                            b"resumed"
7709                        ));
7710                    }
7711                }
7712            }
7713        }
7714    }
7715
7716    /// CONTRACT: set_size invalidates the displayed-region cache — old
7717    /// geometry must not steer log positioning or shrink-erasure afterward.
7718    #[test]
7719    fn set_size_clears_last_inline_region() {
7720        let mut writer = TerminalWriter::new(
7721            Vec::new(),
7722            ScreenMode::Inline { ui_height: 5 },
7723            UiAnchor::Bottom,
7724            basic_caps(),
7725        );
7726        writer.set_size(80, 24);
7727        let buffer = Buffer::new(80, 5);
7728        writer.present_ui(&buffer, None, false).unwrap();
7729        assert!(writer.last_inline_region.is_some());
7730
7731        writer.set_size(80, 30);
7732        assert!(
7733            writer.last_inline_region.is_none(),
7734            "resize must invalidate the displayed-region cache"
7735        );
7736    }
7737    #[test]
7738    fn strategy_selection_config_flags_applied() {
7739        // Verify that RuntimeDiffConfig flags are correctly stored and accessible
7740        let config = RuntimeDiffConfig::default()
7741            .with_dirty_rows_enabled(false)
7742            .with_bayesian_enabled(false);
7743
7744        let writer = TerminalWriter::with_diff_config(
7745            Vec::<u8>::new(),
7746            ScreenMode::AltScreen,
7747            UiAnchor::Bottom,
7748            basic_caps(),
7749            config,
7750        );
7751
7752        // Config should be accessible
7753        assert!(!writer.diff_config().dirty_rows_enabled);
7754        assert!(!writer.diff_config().bayesian_enabled);
7755
7756        // Diff strategy should use the underlying strategy config
7757        let (alpha, beta) = writer.diff_strategy().posterior_params();
7758        // Default priors
7759        assert!((alpha - 1.0).abs() < 0.01);
7760        assert!((beta - 19.0).abs() < 0.01);
7761    }
7762
7763    #[test]
7764    fn resize_respects_reset_toggle() {
7765        // With reset_on_resize disabled, posterior should be preserved after resize
7766        let config = RuntimeDiffConfig::default().with_reset_on_resize(false);
7767
7768        let mut writer = TerminalWriter::with_diff_config(
7769            Vec::<u8>::new(),
7770            ScreenMode::AltScreen,
7771            UiAnchor::Bottom,
7772            basic_caps(),
7773            config,
7774        );
7775        writer.set_size(80, 24);
7776
7777        // Present frames to update posterior
7778        let mut buffer = Buffer::new(80, 24);
7779        buffer.set_raw(0, 0, Cell::from_char('X'));
7780        writer.present_ui(&buffer, None, false).unwrap();
7781
7782        let mut buffer2 = Buffer::new(80, 24);
7783        buffer2.set_raw(1, 1, Cell::from_char('Y'));
7784        writer.present_ui(&buffer2, None, false).unwrap();
7785
7786        // Posterior should have moved from initial priors
7787        let (alpha_before, beta_before) = writer.diff_strategy().posterior_params();
7788
7789        // Resize - with reset disabled, posterior should be preserved
7790        writer.set_size(100, 30);
7791
7792        let (alpha_after, beta_after) = writer.diff_strategy().posterior_params();
7793        assert!(
7794            (alpha_after - alpha_before).abs() < 0.01 && (beta_after - beta_before).abs() < 0.01,
7795            "posterior should be preserved when reset_on_resize=false"
7796        );
7797    }
7798
7799    // =========================================================================
7800    // Enum / Default / Debug tests
7801    // =========================================================================
7802
7803    #[test]
7804    fn screen_mode_default_is_altscreen() {
7805        assert_eq!(ScreenMode::default(), ScreenMode::AltScreen);
7806    }
7807
7808    #[test]
7809    fn screen_mode_debug_format() {
7810        let dbg = format!("{:?}", ScreenMode::Inline { ui_height: 7 });
7811        assert!(dbg.contains("Inline"));
7812        assert!(dbg.contains('7'));
7813    }
7814
7815    #[test]
7816    fn screen_mode_inline_auto_debug_format() {
7817        let dbg = format!(
7818            "{:?}",
7819            ScreenMode::InlineAuto {
7820                min_height: 3,
7821                max_height: 10
7822            }
7823        );
7824        assert!(dbg.contains("InlineAuto"));
7825    }
7826
7827    #[test]
7828    fn screen_mode_eq_inline_auto() {
7829        let a = ScreenMode::InlineAuto {
7830            min_height: 2,
7831            max_height: 8,
7832        };
7833        let b = ScreenMode::InlineAuto {
7834            min_height: 2,
7835            max_height: 8,
7836        };
7837        assert_eq!(a, b);
7838        let c = ScreenMode::InlineAuto {
7839            min_height: 2,
7840            max_height: 9,
7841        };
7842        assert_ne!(a, c);
7843    }
7844
7845    #[test]
7846    fn ui_anchor_default_is_bottom() {
7847        assert_eq!(UiAnchor::default(), UiAnchor::Bottom);
7848    }
7849
7850    #[test]
7851    fn ui_anchor_debug_format() {
7852        assert_eq!(format!("{:?}", UiAnchor::Top), "Top");
7853        assert_eq!(format!("{:?}", UiAnchor::Bottom), "Bottom");
7854    }
7855
7856    // =========================================================================
7857    // Accessor tests
7858    // =========================================================================
7859
7860    #[test]
7861    fn width_height_accessors() {
7862        let output = Vec::new();
7863        let mut writer = TerminalWriter::new(
7864            output,
7865            ScreenMode::AltScreen,
7866            UiAnchor::Bottom,
7867            basic_caps(),
7868        );
7869        // Default dimensions are 80x24
7870        assert_eq!(writer.width(), 80);
7871        assert_eq!(writer.height(), 24);
7872
7873        writer.set_size(120, 40);
7874        assert_eq!(writer.width(), 120);
7875        assert_eq!(writer.height(), 40);
7876    }
7877
7878    #[test]
7879    fn screen_mode_accessor() {
7880        let writer = TerminalWriter::new(
7881            Vec::new(),
7882            ScreenMode::Inline { ui_height: 5 },
7883            UiAnchor::Top,
7884            basic_caps(),
7885        );
7886        assert_eq!(writer.screen_mode(), ScreenMode::Inline { ui_height: 5 });
7887    }
7888
7889    #[test]
7890    fn capabilities_accessor() {
7891        let caps = full_caps();
7892        let writer = TerminalWriter::new(Vec::new(), ScreenMode::AltScreen, UiAnchor::Bottom, caps);
7893        assert!(writer.capabilities().supports_true_color());
7894        assert!(writer.capabilities().sync_output);
7895    }
7896
7897    // =========================================================================
7898    // into_inner tests
7899    // =========================================================================
7900
7901    #[test]
7902    fn into_inner_returns_writer() {
7903        let writer = TerminalWriter::new(
7904            Vec::new(),
7905            ScreenMode::AltScreen,
7906            UiAnchor::Bottom,
7907            basic_caps(),
7908        );
7909        let inner = writer.into_inner();
7910        assert!(inner.is_some());
7911    }
7912
7913    #[test]
7914    fn into_inner_performs_cleanup() {
7915        let mut writer = TerminalWriter::new(
7916            Vec::new(),
7917            ScreenMode::Inline { ui_height: 5 },
7918            UiAnchor::Bottom,
7919            basic_caps(),
7920        );
7921        writer.cursor_saved = true;
7922        writer.in_sync_block = false;
7923
7924        let inner = writer.into_inner().unwrap();
7925        // Cleanup should have written cursor restore
7926        assert!(
7927            inner
7928                .windows(CURSOR_RESTORE.len())
7929                .any(|w| w == CURSOR_RESTORE),
7930            "into_inner should perform cleanup before returning"
7931        );
7932    }
7933
7934    // =========================================================================
7935    // take_render_buffer tests
7936    // =========================================================================
7937
7938    #[test]
7939    fn take_render_buffer_creates_new_when_no_spare() {
7940        let mut writer = TerminalWriter::new(
7941            Vec::new(),
7942            ScreenMode::AltScreen,
7943            UiAnchor::Bottom,
7944            basic_caps(),
7945        );
7946        let buf = writer.take_render_buffer(80, 24);
7947        assert_eq!(buf.width(), 80);
7948        assert_eq!(buf.height(), 24);
7949    }
7950
7951    #[test]
7952    fn take_render_buffer_reuses_spare_on_match() {
7953        let mut writer = TerminalWriter::new(
7954            Vec::new(),
7955            ScreenMode::AltScreen,
7956            UiAnchor::Bottom,
7957            basic_caps(),
7958        );
7959        // Inject a spare buffer
7960        writer.spare_buffer = Some(Buffer::new(80, 24));
7961        assert!(writer.spare_buffer.is_some());
7962
7963        let buf = writer.take_render_buffer(80, 24);
7964        assert_eq!(buf.width(), 80);
7965        assert_eq!(buf.height(), 24);
7966        // Spare should have been taken
7967        assert!(writer.spare_buffer.is_none());
7968    }
7969
7970    #[test]
7971    fn take_render_buffer_ignores_spare_on_size_mismatch() {
7972        let mut writer = TerminalWriter::new(
7973            Vec::new(),
7974            ScreenMode::AltScreen,
7975            UiAnchor::Bottom,
7976            basic_caps(),
7977        );
7978        writer.spare_buffer = Some(Buffer::new(80, 24));
7979
7980        // Request different size - should create new, not reuse
7981        let buf = writer.take_render_buffer(100, 30);
7982        assert_eq!(buf.width(), 100);
7983        assert_eq!(buf.height(), 30);
7984    }
7985
7986    // =========================================================================
7987    // gc tests
7988    // =========================================================================
7989
7990    #[test]
7991    fn gc_with_no_prev_buffer() {
7992        let mut writer = TerminalWriter::new(
7993            Vec::new(),
7994            ScreenMode::AltScreen,
7995            UiAnchor::Bottom,
7996            basic_caps(),
7997        );
7998        assert!(writer.prev_buffer.is_none());
7999        // Should not panic
8000        writer.gc(None);
8001    }
8002
8003    #[test]
8004    fn gc_with_prev_buffer() {
8005        let mut writer = TerminalWriter::new(
8006            Vec::new(),
8007            ScreenMode::AltScreen,
8008            UiAnchor::Bottom,
8009            basic_caps(),
8010        );
8011        writer.prev_buffer = Some(Buffer::new(10, 5));
8012        // Should not panic
8013        writer.gc(None);
8014    }
8015
8016    // =========================================================================
8017    // hide_cursor / show_cursor tests
8018    // =========================================================================
8019
8020    #[test]
8021    fn hide_cursor_emits_sequence() {
8022        let mut output = Vec::new();
8023        {
8024            let mut writer = TerminalWriter::new(
8025                &mut output,
8026                ScreenMode::AltScreen,
8027                UiAnchor::Bottom,
8028                basic_caps(),
8029            );
8030            writer.hide_cursor().unwrap();
8031        }
8032        assert!(
8033            output.windows(6).any(|w| w == b"\x1b[?25l"),
8034            "hide_cursor should emit cursor hide sequence"
8035        );
8036    }
8037
8038    #[test]
8039    fn show_cursor_emits_sequence() {
8040        let mut output = Vec::new();
8041        {
8042            let mut writer = TerminalWriter::new(
8043                &mut output,
8044                ScreenMode::AltScreen,
8045                UiAnchor::Bottom,
8046                basic_caps(),
8047            );
8048            // First hide, then show
8049            writer.hide_cursor().unwrap();
8050            writer.show_cursor().unwrap();
8051        }
8052        assert!(
8053            output.windows(6).any(|w| w == b"\x1b[?25h"),
8054            "show_cursor should emit cursor show sequence"
8055        );
8056    }
8057
8058    #[test]
8059    fn hide_cursor_idempotent() {
8060        // Use Cursor<Vec<u8>> to own the writer
8061        use std::io::Cursor;
8062        let mut writer = TerminalWriter::new(
8063            Cursor::new(Vec::new()),
8064            ScreenMode::AltScreen,
8065            UiAnchor::Bottom,
8066            basic_caps(),
8067        );
8068        writer.hide_cursor().unwrap();
8069        let inner = writer.into_inner().unwrap().into_inner();
8070        let hide_count = inner.windows(6).filter(|w| *w == b"\x1b[?25l").count();
8071        // Should have exactly 1 hide (from hide_cursor) — Drop cleanup shows cursor (?25h)
8072        assert_eq!(
8073            hide_count, 1,
8074            "hide_cursor called once should emit exactly one hide sequence"
8075        );
8076    }
8077
8078    #[test]
8079    fn show_cursor_idempotent_when_already_visible() {
8080        use std::io::Cursor;
8081        let mut writer = TerminalWriter::new(
8082            Cursor::new(Vec::new()),
8083            ScreenMode::AltScreen,
8084            UiAnchor::Bottom,
8085            basic_caps(),
8086        );
8087        // Cursor starts visible — show should be noop
8088        writer.show_cursor().unwrap();
8089        let inner = writer.into_inner().unwrap().into_inner();
8090        // No ?25h should appear from show_cursor (only from cleanup)
8091        let show_count = inner.windows(6).filter(|w| *w == b"\x1b[?25h").count();
8092        assert!(
8093            show_count <= 1,
8094            "show_cursor when already visible should not add extra show sequences"
8095        );
8096    }
8097
8098    // =========================================================================
8099    // pool / links accessor tests
8100    // =========================================================================
8101
8102    #[test]
8103    fn pool_accessor() {
8104        let writer = TerminalWriter::new(
8105            Vec::new(),
8106            ScreenMode::AltScreen,
8107            UiAnchor::Bottom,
8108            basic_caps(),
8109        );
8110        // Pool should be accessible (just testing it doesn't panic)
8111        let _pool = writer.pool();
8112    }
8113
8114    #[test]
8115    fn pool_mut_accessor() {
8116        let mut writer = TerminalWriter::new(
8117            Vec::new(),
8118            ScreenMode::AltScreen,
8119            UiAnchor::Bottom,
8120            basic_caps(),
8121        );
8122        let _pool = writer.pool_mut();
8123    }
8124
8125    #[test]
8126    fn links_accessor() {
8127        let writer = TerminalWriter::new(
8128            Vec::new(),
8129            ScreenMode::AltScreen,
8130            UiAnchor::Bottom,
8131            basic_caps(),
8132        );
8133        let _links = writer.links();
8134    }
8135
8136    #[test]
8137    fn links_mut_accessor() {
8138        let mut writer = TerminalWriter::new(
8139            Vec::new(),
8140            ScreenMode::AltScreen,
8141            UiAnchor::Bottom,
8142            basic_caps(),
8143        );
8144        let _links = writer.links_mut();
8145    }
8146
8147    #[test]
8148    fn pool_and_links_mut_accessor() {
8149        let mut writer = TerminalWriter::new(
8150            Vec::new(),
8151            ScreenMode::AltScreen,
8152            UiAnchor::Bottom,
8153            basic_caps(),
8154        );
8155        let (_pool, _links) = writer.pool_and_links_mut();
8156    }
8157
8158    // =========================================================================
8159    // Helper function tests
8160    // =========================================================================
8161
8162    #[test]
8163    fn sanitize_auto_bounds_normal() {
8164        assert_eq!(sanitize_auto_bounds(3, 10), (3, 10));
8165    }
8166
8167    #[test]
8168    fn sanitize_auto_bounds_zero_min() {
8169        // min=0 should become 1
8170        assert_eq!(sanitize_auto_bounds(0, 10), (1, 10));
8171    }
8172
8173    #[test]
8174    fn sanitize_auto_bounds_max_less_than_min() {
8175        // max < min should be clamped to min
8176        assert_eq!(sanitize_auto_bounds(5, 3), (5, 5));
8177    }
8178
8179    #[test]
8180    fn sanitize_auto_bounds_both_zero() {
8181        assert_eq!(sanitize_auto_bounds(0, 0), (1, 1));
8182    }
8183
8184    #[test]
8185    fn diff_strategy_str_variants() {
8186        assert_eq!(diff_strategy_str(DiffStrategy::Full), "full");
8187        assert_eq!(diff_strategy_str(DiffStrategy::DirtyRows), "dirty");
8188        assert_eq!(diff_strategy_str(DiffStrategy::FullRedraw), "redraw");
8189    }
8190
8191    #[test]
8192    fn ui_anchor_str_variants() {
8193        assert_eq!(ui_anchor_str(UiAnchor::Bottom), "bottom");
8194        assert_eq!(ui_anchor_str(UiAnchor::Top), "top");
8195    }
8196
8197    #[test]
8198    fn json_escape_plain_text() {
8199        assert_eq!(json_escape("hello"), "hello");
8200    }
8201
8202    #[test]
8203    fn json_escape_special_chars() {
8204        assert_eq!(json_escape(r#"a"b"#), r#"a\"b"#);
8205        assert_eq!(json_escape("a\\b"), r#"a\\b"#);
8206        assert_eq!(json_escape("a\nb"), r#"a\nb"#);
8207        assert_eq!(json_escape("a\rb"), r#"a\rb"#);
8208        assert_eq!(json_escape("a\tb"), r#"a\tb"#);
8209    }
8210
8211    #[test]
8212    fn json_escape_control_chars() {
8213        let s = String::from("\x00\x01\x1f");
8214        let escaped = json_escape(&s);
8215        assert!(escaped.contains("\\u0000"));
8216        assert!(escaped.contains("\\u0001"));
8217        assert!(escaped.contains("\\u001F"));
8218    }
8219
8220    #[test]
8221    fn json_escape_unicode_passthrough() {
8222        assert_eq!(json_escape("caf\u{00e9}"), "caf\u{00e9}");
8223        assert_eq!(json_escape("\u{1f600}"), "\u{1f600}");
8224    }
8225
8226    // CountingWriter tests removed — the local CountingWriter was removed
8227    // in favour of ftui_render::counting_writer::CountingWriter (accessed via
8228    // Presenter). The render-crate CountingWriter has its own test suite.
8229
8230    #[test]
8231    fn counting_writer_into_inner() {
8232        let mut cw = CountingWriter::new(Vec::new());
8233        cw.write_all(b"data").unwrap();
8234        let inner = cw.into_inner();
8235        assert_eq!(inner, b"data");
8236    }
8237
8238    // =========================================================================
8239    // estimate_diff_scan_cost tests
8240    // =========================================================================
8241
8242    fn zero_span_stats() -> DirtySpanStats {
8243        DirtySpanStats {
8244            rows_full_dirty: 0,
8245            rows_with_spans: 0,
8246            total_spans: 0,
8247            overflows: 0,
8248            span_coverage_cells: 0,
8249            max_span_len: 0,
8250            max_spans_per_row: 4,
8251        }
8252    }
8253
8254    #[test]
8255    fn estimate_diff_scan_cost_full_strategy() {
8256        let stats = zero_span_stats();
8257        let (cost, label) = estimate_diff_scan_cost(DiffStrategy::Full, 0, 80, 24, &stats, None);
8258        assert_eq!(cost, 80 * 24);
8259        assert_eq!(label, "full_strategy");
8260    }
8261
8262    #[test]
8263    fn estimate_diff_scan_cost_full_redraw() {
8264        let stats = zero_span_stats();
8265        let (cost, label) =
8266            estimate_diff_scan_cost(DiffStrategy::FullRedraw, 5, 80, 24, &stats, None);
8267        assert_eq!(cost, 0);
8268        assert_eq!(label, "full_redraw");
8269    }
8270
8271    #[test]
8272    fn estimate_diff_scan_cost_dirty_rows_no_dirty() {
8273        let stats = zero_span_stats();
8274        let (cost, label) =
8275            estimate_diff_scan_cost(DiffStrategy::DirtyRows, 0, 80, 24, &stats, None);
8276        assert_eq!(cost, 0);
8277        assert_eq!(label, "no_dirty_rows");
8278    }
8279
8280    #[test]
8281    fn estimate_diff_scan_cost_dirty_rows_with_span_coverage() {
8282        let mut stats = zero_span_stats();
8283        stats.span_coverage_cells = 100;
8284        let (cost, label) =
8285            estimate_diff_scan_cost(DiffStrategy::DirtyRows, 5, 80, 24, &stats, None);
8286        assert_eq!(cost, 100);
8287        assert_eq!(label, "none");
8288    }
8289
8290    #[test]
8291    fn estimate_diff_scan_cost_dirty_rows_no_spans() {
8292        let stats = zero_span_stats();
8293        let (cost, label) =
8294            estimate_diff_scan_cost(DiffStrategy::DirtyRows, 5, 80, 24, &stats, None);
8295        assert_eq!(cost, 5 * 80);
8296        assert_eq!(label, "no_spans");
8297    }
8298
8299    #[test]
8300    fn estimate_diff_scan_cost_dirty_rows_overflow_with_span() {
8301        let mut stats = zero_span_stats();
8302        stats.span_coverage_cells = 150;
8303        stats.overflows = 1;
8304        let (cost, label) =
8305            estimate_diff_scan_cost(DiffStrategy::DirtyRows, 5, 80, 24, &stats, None);
8306        assert_eq!(cost, 150);
8307        assert_eq!(label, "span_overflow");
8308    }
8309
8310    #[test]
8311    fn estimate_diff_scan_cost_dirty_rows_overflow_no_span() {
8312        let mut stats = zero_span_stats();
8313        stats.overflows = 1;
8314        let (cost, label) =
8315            estimate_diff_scan_cost(DiffStrategy::DirtyRows, 5, 80, 24, &stats, None);
8316        assert_eq!(cost, 5 * 80);
8317        assert_eq!(label, "span_overflow");
8318    }
8319
8320    #[test]
8321    fn estimate_diff_scan_cost_tile_skip() {
8322        let stats = zero_span_stats();
8323        let tile = TileDiffStats {
8324            width: 80,
8325            height: 24,
8326            tile_w: 16,
8327            tile_h: 8,
8328            tiles_x: 5,
8329            tiles_y: 3,
8330            total_tiles: 15,
8331            dirty_cells: 10,
8332            dirty_tiles: 2,
8333            dirty_cell_ratio: 0.005,
8334            dirty_tile_ratio: 0.13,
8335            scanned_tiles: 2,
8336            skipped_tiles: 13,
8337            sat_build_cells: 1920,
8338            scan_cells_estimate: 42,
8339            skipped_tile_rows: 1,
8340            sat_queries: 3,
8341            fallback: None,
8342        };
8343        let (cost, label) =
8344            estimate_diff_scan_cost(DiffStrategy::DirtyRows, 5, 80, 24, &stats, Some(tile));
8345        assert_eq!(cost, 42);
8346        assert_eq!(label, "tile_skip");
8347    }
8348
8349    #[test]
8350    fn estimate_diff_scan_cost_tile_with_fallback_uses_spans() {
8351        let mut stats = zero_span_stats();
8352        stats.span_coverage_cells = 200;
8353        let tile = TileDiffStats {
8354            width: 80,
8355            height: 24,
8356            tile_w: 16,
8357            tile_h: 8,
8358            tiles_x: 5,
8359            tiles_y: 3,
8360            total_tiles: 15,
8361            dirty_cells: 10,
8362            dirty_tiles: 2,
8363            dirty_cell_ratio: 0.005,
8364            dirty_tile_ratio: 0.13,
8365            scanned_tiles: 2,
8366            skipped_tiles: 13,
8367            sat_build_cells: 1920,
8368            scan_cells_estimate: 42,
8369            skipped_tile_rows: 0,
8370            sat_queries: 0,
8371            fallback: Some(TileDiffFallback::SmallScreen),
8372        };
8373        let (cost, label) =
8374            estimate_diff_scan_cost(DiffStrategy::DirtyRows, 5, 80, 24, &stats, Some(tile));
8375        // Tile has fallback, so falls through to span logic
8376        assert_eq!(cost, 200);
8377        assert_eq!(label, "none");
8378    }
8379
8380    // =========================================================================
8381    // InlineAuto edge cases
8382    // =========================================================================
8383
8384    #[test]
8385    fn inline_auto_bounds_accessor() {
8386        let mut writer = TerminalWriter::new(
8387            Vec::new(),
8388            ScreenMode::InlineAuto {
8389                min_height: 3,
8390                max_height: 10,
8391            },
8392            UiAnchor::Bottom,
8393            basic_caps(),
8394        );
8395        writer.set_size(80, 24);
8396        let bounds = writer.inline_auto_bounds();
8397        assert_eq!(bounds, Some((3, 10)));
8398    }
8399
8400    #[test]
8401    fn inline_auto_bounds_clamped_to_terminal() {
8402        let mut writer = TerminalWriter::new(
8403            Vec::new(),
8404            ScreenMode::InlineAuto {
8405                min_height: 3,
8406                max_height: 50,
8407            },
8408            UiAnchor::Bottom,
8409            basic_caps(),
8410        );
8411        writer.set_size(80, 20);
8412        let bounds = writer.inline_auto_bounds();
8413        assert_eq!(bounds, Some((3, 20)));
8414    }
8415
8416    #[test]
8417    fn inline_auto_bounds_returns_none_for_non_auto() {
8418        let writer = TerminalWriter::new(
8419            Vec::new(),
8420            ScreenMode::Inline { ui_height: 5 },
8421            UiAnchor::Bottom,
8422            basic_caps(),
8423        );
8424        assert_eq!(writer.inline_auto_bounds(), None);
8425
8426        let writer2 = TerminalWriter::new(
8427            Vec::new(),
8428            ScreenMode::AltScreen,
8429            UiAnchor::Bottom,
8430            basic_caps(),
8431        );
8432        assert_eq!(writer2.inline_auto_bounds(), None);
8433    }
8434
8435    #[test]
8436    fn auto_ui_height_returns_none_for_non_auto() {
8437        let writer = TerminalWriter::new(
8438            Vec::new(),
8439            ScreenMode::Inline { ui_height: 5 },
8440            UiAnchor::Bottom,
8441            basic_caps(),
8442        );
8443        assert_eq!(writer.auto_ui_height(), None);
8444    }
8445
8446    #[test]
8447    fn render_height_hint_altscreen() {
8448        let mut writer = TerminalWriter::new(
8449            Vec::new(),
8450            ScreenMode::AltScreen,
8451            UiAnchor::Bottom,
8452            basic_caps(),
8453        );
8454        writer.set_size(80, 24);
8455        assert_eq!(writer.render_height_hint(), 24);
8456    }
8457
8458    #[test]
8459    fn render_height_hint_inline_fixed() {
8460        let mut writer = TerminalWriter::new(
8461            Vec::new(),
8462            ScreenMode::Inline { ui_height: 7 },
8463            UiAnchor::Bottom,
8464            basic_caps(),
8465        );
8466        assert_eq!(writer.render_height_hint(), 7);
8467        writer.set_size(80, 3);
8468        assert_eq!(writer.render_height_hint(), 3);
8469        writer.set_size(80, 24);
8470        assert_eq!(writer.render_height_hint(), 7);
8471        let mut oversized = TerminalWriter::new(
8472            Vec::new(),
8473            ScreenMode::Inline {
8474                ui_height: u16::MAX,
8475            },
8476            UiAnchor::Bottom,
8477            basic_caps(),
8478        );
8479        oversized.set_size(80, 24);
8480        assert_eq!(oversized.render_height_hint(), 24);
8481    }
8482
8483    // =========================================================================
8484    // RuntimeDiffConfig builder edge cases
8485    // =========================================================================
8486
8487    #[test]
8488    fn runtime_diff_config_tile_skip_toggle() {
8489        let config = RuntimeDiffConfig::new().with_tile_skip_enabled(false);
8490        assert!(!config.tile_diff_config.enabled);
8491    }
8492
8493    #[test]
8494    fn runtime_diff_config_dirty_spans_toggle() {
8495        let config = RuntimeDiffConfig::new().with_dirty_spans_enabled(false);
8496        assert!(!config.dirty_span_config.enabled);
8497    }
8498
8499    // =========================================================================
8500    // present_ui edge cases
8501    // =========================================================================
8502
8503    #[test]
8504    fn present_ui_altscreen_no_cursor_save_restore() {
8505        let mut output = Vec::new();
8506        {
8507            let mut writer = TerminalWriter::new(
8508                &mut output,
8509                ScreenMode::AltScreen,
8510                UiAnchor::Bottom,
8511                basic_caps(),
8512            );
8513            writer.set_size(10, 5);
8514            let buffer = Buffer::new(10, 5);
8515            writer.present_ui(&buffer, None, true).unwrap();
8516        }
8517
8518        // AltScreen should NOT use cursor save/restore (those are inline-mode specific)
8519        let save_count = output
8520            .windows(CURSOR_SAVE.len())
8521            .filter(|w| *w == CURSOR_SAVE)
8522            .count();
8523        assert_eq!(save_count, 0, "AltScreen should not save cursor");
8524    }
8525
8526    #[test]
8527    fn clear_screen_emits_ed2() {
8528        let mut output = Vec::new();
8529        {
8530            let mut writer = TerminalWriter::new(
8531                &mut output,
8532                ScreenMode::AltScreen,
8533                UiAnchor::Bottom,
8534                basic_caps(),
8535            );
8536            writer.clear_screen().unwrap();
8537        }
8538        assert!(
8539            output.windows(4).any(|w| w == b"\x1b[2J"),
8540            "clear_screen should emit ED2 sequence"
8541        );
8542    }
8543
8544    #[test]
8545    fn clear_screen_resets_active_scroll_region_before_clearing() {
8546        let mut output = Vec::new();
8547        {
8548            let mut writer = TerminalWriter::new(
8549                &mut output,
8550                ScreenMode::Inline { ui_height: 5 },
8551                UiAnchor::Bottom,
8552                scroll_region_caps(),
8553            );
8554            writer.set_size(80, 24);
8555
8556            let buffer = Buffer::new(80, 5);
8557            writer.present_ui(&buffer, None, true).unwrap();
8558            assert!(writer.scroll_region_active());
8559
8560            writer.clear_screen().unwrap();
8561            assert!(
8562                !writer.scroll_region_active(),
8563                "clear_screen should leave no active scroll region"
8564            );
8565        }
8566
8567        let reset_idx = output
8568            .windows(b"\x1b[r".len())
8569            .position(|w| w == b"\x1b[r")
8570            .expect("expected scroll-region reset");
8571        let clear_idx = output
8572            .windows(b"\x1b[2J".len())
8573            .position(|w| w == b"\x1b[2J")
8574            .expect("expected full clear");
8575        assert!(
8576            reset_idx < clear_idx,
8577            "clear_screen should reset DECSTBM before full-screen clear"
8578        );
8579    }
8580
8581    #[test]
8582    fn clear_screen_restores_saved_cursor_before_clearing() {
8583        let mut output = Vec::new();
8584        {
8585            let mut writer = TerminalWriter::new(
8586                &mut output,
8587                ScreenMode::Inline { ui_height: 5 },
8588                UiAnchor::Bottom,
8589                basic_caps(),
8590            );
8591            writer.cursor_saved = true;
8592
8593            writer.clear_screen().unwrap();
8594            assert!(
8595                !writer.cursor_saved,
8596                "clear_screen should clear stale saved-cursor state"
8597            );
8598        }
8599
8600        let restore_idx = output
8601            .windows(CURSOR_RESTORE.len())
8602            .position(|w| w == CURSOR_RESTORE)
8603            .expect("expected cursor restore");
8604        let clear_idx = output
8605            .windows(b"\x1b[2J".len())
8606            .position(|w| w == b"\x1b[2J")
8607            .expect("expected full clear");
8608        assert!(
8609            restore_idx < clear_idx,
8610            "clear_screen should restore any saved cursor before clearing"
8611        );
8612    }
8613
8614    #[test]
8615    fn clear_screen_closes_stale_sync_block_before_clearing() {
8616        let mut output = Vec::new();
8617        {
8618            let mut writer = TerminalWriter::new(
8619                &mut output,
8620                ScreenMode::Inline { ui_height: 5 },
8621                UiAnchor::Bottom,
8622                full_caps(),
8623            );
8624            writer.in_sync_block = true;
8625
8626            writer.clear_screen().unwrap();
8627            assert!(
8628                !writer.in_sync_block,
8629                "clear_screen should clear stale sync-block state"
8630            );
8631        }
8632
8633        let sync_end_idx = output
8634            .windows(SYNC_END.len())
8635            .position(|w| w == SYNC_END)
8636            .expect("expected sync end");
8637        let clear_idx = output
8638            .windows(b"\x1b[2J".len())
8639            .position(|w| w == b"\x1b[2J")
8640            .expect("expected full clear");
8641        assert!(
8642            sync_end_idx < clear_idx,
8643            "clear_screen should end any open sync block before clearing"
8644        );
8645    }
8646
8647    #[test]
8648    fn clear_screen_skips_sync_end_in_mux_while_clearing_stale_state() {
8649        let mut output = Vec::new();
8650        {
8651            let mut writer = TerminalWriter::new(
8652                &mut output,
8653                ScreenMode::Inline { ui_height: 5 },
8654                UiAnchor::Bottom,
8655                mux_caps(),
8656            );
8657            writer.in_sync_block = true;
8658
8659            writer.clear_screen().unwrap();
8660            assert!(
8661                !writer.in_sync_block,
8662                "clear_screen should clear stale sync state even when sync output is disabled"
8663            );
8664        }
8665
8666        assert!(
8667            !output.windows(SYNC_END.len()).any(|w| w == SYNC_END),
8668            "clear_screen must not emit sync_end in mux environments"
8669        );
8670        assert!(
8671            output.windows(b"\x1b[2J".len()).any(|w| w == b"\x1b[2J"),
8672            "clear_screen should still clear the screen"
8673        );
8674    }
8675
8676    #[test]
8677    fn clear_screen_invalidates_cached_state_even_when_flush_fails() {
8678        let state = Rc::new(RefCell::new(FaultState::default()));
8679        let writer_backend = SingleWriteFaultWriter::new(Rc::clone(&state), 1, 1);
8680        let mut writer = TerminalWriter::new(
8681            writer_backend,
8682            ScreenMode::Inline { ui_height: 5 },
8683            UiAnchor::Bottom,
8684            basic_caps(),
8685        );
8686        writer.cursor_saved = true;
8687        writer.prev_buffer = Some(Buffer::new(4, 2));
8688        writer.last_inline_region = Some(InlineRegion {
8689            start: 19,
8690            height: 5,
8691        });
8692        writer.last_diff_strategy = Some(DiffStrategy::DirtyRows);
8693
8694        let err = writer
8695            .clear_screen()
8696            .expect_err("expected injected flush write failure");
8697        assert_eq!(err.kind(), io::ErrorKind::Other);
8698        assert!(state.borrow().injected_failure_triggered);
8699        assert!(
8700            writer.prev_buffer.is_none(),
8701            "clear_screen should invalidate cached frame state after flush failure"
8702        );
8703        assert!(
8704            writer.last_inline_region.is_none(),
8705            "clear_screen should drop inline region cache after flush failure"
8706        );
8707        assert!(
8708            writer.last_diff_strategy.is_none(),
8709            "clear_screen should reset diff strategy after flush failure"
8710        );
8711    }
8712
8713    #[test]
8714    fn present_ui_retry_after_write_failure_forces_repaint() {
8715        let state = Rc::new(RefCell::new(FaultState::default()));
8716        let writer_backend = SingleWriteFaultWriter::new(Rc::clone(&state), 1, 1);
8717        let mut writer = TerminalWriter::new(
8718            writer_backend,
8719            ScreenMode::AltScreen,
8720            UiAnchor::Bottom,
8721            basic_caps(),
8722        );
8723        writer.set_size(4, 2);
8724
8725        let mut buffer = Buffer::new(4, 2);
8726        buffer.set_raw(0, 0, Cell::from_char('A'));
8727
8728        let err = writer
8729            .present_ui(&buffer, None, true)
8730            .expect_err("first present should hit the injected write fault");
8731        assert_eq!(err.kind(), io::ErrorKind::Other);
8732        assert!(
8733            writer.prev_buffer.is_none(),
8734            "failed present must not advance the diff baseline"
8735        );
8736
8737        writer
8738            .present_ui(&buffer, None, true)
8739            .expect("retry after transient failure should succeed");
8740
8741        let bytes = state.borrow().bytes.clone();
8742        assert!(
8743            bytes.contains(&b'A'),
8744            "retry should emit the missing cell content after a failed present"
8745        );
8746    }
8747
8748    #[test]
8749    fn present_ui_write_failure_with_existing_baseline_invalidates_diff_state() {
8750        let state = Rc::new(RefCell::new(FaultState::default()));
8751        let writer_backend = SingleWriteFaultWriter::new(Rc::clone(&state), 1, 1);
8752        let mut writer = TerminalWriter::new(
8753            writer_backend,
8754            ScreenMode::AltScreen,
8755            UiAnchor::Bottom,
8756            basic_caps(),
8757        );
8758        writer.set_size(4, 2);
8759
8760        let mut previous = Buffer::new(4, 2);
8761        previous.set_raw(0, 0, Cell::from_char('A'));
8762        writer.prev_buffer = Some(previous);
8763        writer.last_inline_region = Some(InlineRegion {
8764            start: 0,
8765            height: 2,
8766        });
8767        writer.last_diff_strategy = Some(DiffStrategy::DirtyRows);
8768        writer.frames_since_full_redraw = 7;
8769
8770        let mut buffer = Buffer::new(4, 2);
8771        buffer.set_raw(0, 0, Cell::from_char('B'));
8772
8773        let err = writer
8774            .present_ui(&buffer, None, true)
8775            .expect_err("present should hit the injected write fault");
8776        assert_eq!(err.kind(), io::ErrorKind::Other);
8777        assert!(
8778            writer.prev_buffer.is_none(),
8779            "failed present with a prior baseline must force the next frame to repaint"
8780        );
8781        assert!(
8782            writer.last_inline_region.is_none(),
8783            "failed present must drop inline-region assumptions"
8784        );
8785        assert_eq!(writer.last_diff_strategy(), None);
8786        assert_eq!(writer.frames_since_full_redraw, 0);
8787
8788        writer
8789            .present_ui(&buffer, None, true)
8790            .expect("retry after transient failure should succeed");
8791        assert_eq!(writer.last_diff_strategy(), Some(DiffStrategy::FullRedraw));
8792    }
8793
8794    #[test]
8795    fn set_size_resets_scroll_region_and_spare_buffer() {
8796        let output = Vec::new();
8797        let mut writer = TerminalWriter::new(
8798            output,
8799            ScreenMode::Inline { ui_height: 5 },
8800            UiAnchor::Bottom,
8801            basic_caps(),
8802        );
8803        writer.spare_buffer = Some(Buffer::new(80, 24));
8804        writer.set_size(100, 30);
8805        assert!(writer.spare_buffer.is_none());
8806    }
8807
8808    // =========================================================================
8809    // Inline active widgets gauge tests (bd-1q5.15)
8810    // =========================================================================
8811
8812    /// Mutex to serialize gauge tests against concurrent inline writer
8813    /// creation/destruction in other tests.
8814    static GAUGE_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
8815
8816    #[test]
8817    fn inline_active_widgets_gauge_increments_for_inline_mode() {
8818        let _lock = GAUGE_TEST_LOCK
8819            .lock()
8820            .unwrap_or_else(|err| err.into_inner());
8821
8822        // Other tests may create/drop inline writers concurrently.
8823        // Retry until we observe one uncontended +1/-1 transition.
8824        for _ in 0..64 {
8825            let before = inline_active_widgets();
8826            let writer = TerminalWriter::new(
8827                Vec::new(),
8828                ScreenMode::Inline { ui_height: 5 },
8829                UiAnchor::Bottom,
8830                basic_caps(),
8831            );
8832            let after_create = inline_active_widgets();
8833            drop(writer);
8834            let after_drop = inline_active_widgets();
8835
8836            if after_create == before.saturating_add(1) && after_drop == before {
8837                return;
8838            }
8839            std::thread::yield_now();
8840        }
8841
8842        panic!("failed to observe uncontended inline gauge +1/-1 transition");
8843    }
8844
8845    #[test]
8846    fn inline_active_widgets_gauge_increments_for_inline_auto_mode() {
8847        let _lock = GAUGE_TEST_LOCK
8848            .lock()
8849            .unwrap_or_else(|err| err.into_inner());
8850
8851        for _ in 0..64 {
8852            let before = inline_active_widgets();
8853            let writer = TerminalWriter::new(
8854                Vec::new(),
8855                ScreenMode::InlineAuto {
8856                    min_height: 2,
8857                    max_height: 10,
8858                },
8859                UiAnchor::Bottom,
8860                basic_caps(),
8861            );
8862            let after_create = inline_active_widgets();
8863            drop(writer);
8864            let after_drop = inline_active_widgets();
8865
8866            if after_create == before.saturating_add(1) && after_drop == before {
8867                return;
8868            }
8869            std::thread::yield_now();
8870        }
8871
8872        panic!("failed to observe uncontended inline-auto gauge +1/-1 transition");
8873    }
8874
8875    #[test]
8876    fn inline_active_widgets_gauge_unchanged_for_altscreen() {
8877        let _lock = GAUGE_TEST_LOCK
8878            .lock()
8879            .unwrap_or_else(|err| err.into_inner());
8880
8881        for _ in 0..64 {
8882            let before = inline_active_widgets();
8883            let writer = TerminalWriter::new(
8884                Vec::new(),
8885                ScreenMode::AltScreen,
8886                UiAnchor::Bottom,
8887                basic_caps(),
8888            );
8889            let after_create = inline_active_widgets();
8890            drop(writer);
8891            let after_drop = inline_active_widgets();
8892
8893            if after_create == before && after_drop == before {
8894                return;
8895            }
8896            std::thread::yield_now();
8897        }
8898
8899        panic!("failed to observe stable altscreen gauge behavior");
8900    }
8901
8902    // =========================================================================
8903    // Inline scrollback preservation tests (bd-1q5.16)
8904    // =========================================================================
8905
8906    /// CSI ?1049h — the alternate-screen enter sequence that must NEVER appear
8907    /// in inline mode output.
8908    const ALTSCREEN_ENTER: &[u8] = b"\x1b[?1049h";
8909
8910    /// CSI ?1049l — the alternate-screen exit sequence.
8911    const ALTSCREEN_EXIT: &[u8] = b"\x1b[?1049l";
8912
8913    /// Helper: returns true if `haystack` contains the byte subsequence `needle`.
8914    fn contains_bytes(haystack: &[u8], needle: &[u8]) -> bool {
8915        haystack.windows(needle.len()).any(|w| w == needle)
8916    }
8917
8918    #[test]
8919    fn inline_render_never_emits_altscreen_enter() {
8920        // The defining contract of inline mode: CSI ?1049h must not appear.
8921        let mut output = Vec::new();
8922        {
8923            let mut writer = TerminalWriter::new(
8924                &mut output,
8925                ScreenMode::Inline { ui_height: 5 },
8926                UiAnchor::Bottom,
8927                basic_caps(),
8928            );
8929            writer.set_size(80, 24);
8930
8931            let buffer = Buffer::new(80, 5);
8932            writer.present_ui(&buffer, None, true).unwrap();
8933            writer.write_log("hello\n").unwrap();
8934            // Second present to exercise diff path
8935            writer.present_ui(&buffer, None, true).unwrap();
8936        }
8937
8938        assert!(
8939            !contains_bytes(&output, ALTSCREEN_ENTER),
8940            "inline mode must never emit CSI ?1049h (alternate screen enter)"
8941        );
8942        assert!(
8943            !contains_bytes(&output, ALTSCREEN_EXIT),
8944            "inline mode must never emit CSI ?1049l (alternate screen exit)"
8945        );
8946    }
8947
8948    #[test]
8949    fn inline_auto_render_never_emits_altscreen_enter() {
8950        let mut output = Vec::new();
8951        {
8952            let mut writer = TerminalWriter::new(
8953                &mut output,
8954                ScreenMode::InlineAuto {
8955                    min_height: 3,
8956                    max_height: 10,
8957                },
8958                UiAnchor::Bottom,
8959                basic_caps(),
8960            );
8961            writer.set_size(80, 24);
8962
8963            let buffer = Buffer::new(80, 5);
8964            writer.present_ui(&buffer, None, true).unwrap();
8965        }
8966
8967        assert!(
8968            !contains_bytes(&output, ALTSCREEN_ENTER),
8969            "InlineAuto mode must never emit CSI ?1049h"
8970        );
8971    }
8972
8973    #[test]
8974    fn inline_scrollback_preserved_after_present() {
8975        // Scrollback preservation means log text written before present_ui
8976        // survives the UI render pass. We verify the output buffer contains
8977        // both the log text and cursor save/restore (the contract that
8978        // guarantees scrollback isn't disturbed).
8979        let mut output = Vec::new();
8980        {
8981            let mut writer = TerminalWriter::new(
8982                &mut output,
8983                ScreenMode::Inline { ui_height: 5 },
8984                UiAnchor::Bottom,
8985                basic_caps(),
8986            );
8987            writer.set_size(80, 24);
8988
8989            writer.write_log("scrollback line A\n").unwrap();
8990            writer.write_log("scrollback line B\n").unwrap();
8991
8992            let buffer = Buffer::new(80, 5);
8993            writer.present_ui(&buffer, None, true).unwrap();
8994
8995            // Another log after render should also work
8996            writer.write_log("scrollback line C\n").unwrap();
8997        }
8998
8999        let text = String::from_utf8_lossy(&output);
9000        assert!(text.contains("scrollback line A"), "first log must survive");
9001        assert!(
9002            text.contains("scrollback line B"),
9003            "second log must survive"
9004        );
9005        assert!(
9006            text.contains("scrollback line C"),
9007            "post-render log must survive"
9008        );
9009
9010        // Cursor save/restore must bracket the UI render to leave
9011        // scrollback position untouched.
9012        assert!(
9013            contains_bytes(&output, CURSOR_SAVE),
9014            "present_ui must save cursor to protect scrollback"
9015        );
9016        assert!(
9017            contains_bytes(&output, CURSOR_RESTORE),
9018            "present_ui must restore cursor to protect scrollback"
9019        );
9020    }
9021
9022    #[test]
9023    fn multiple_inline_writers_coexist() {
9024        // Two independent inline writers should each manage their own state
9025        // without interfering. Uses owned Vec writers so each can be
9026        // independently dropped and inspected.
9027        let mut writer_a = TerminalWriter::new(
9028            Vec::new(),
9029            ScreenMode::Inline { ui_height: 3 },
9030            UiAnchor::Bottom,
9031            basic_caps(),
9032        );
9033        writer_a.set_size(40, 12);
9034
9035        let mut writer_b = TerminalWriter::new(
9036            Vec::new(),
9037            ScreenMode::Inline { ui_height: 5 },
9038            UiAnchor::Bottom,
9039            basic_caps(),
9040        );
9041        writer_b.set_size(80, 24);
9042
9043        // Both can render independently without panicking
9044        let buf_a = Buffer::new(40, 3);
9045        let buf_b = Buffer::new(80, 5);
9046        writer_a.present_ui(&buf_a, None, true).unwrap();
9047        writer_b.present_ui(&buf_b, None, true).unwrap();
9048
9049        // Second render pass (diff path) also works
9050        writer_a.present_ui(&buf_a, None, true).unwrap();
9051        writer_b.present_ui(&buf_b, None, true).unwrap();
9052
9053        // Both drop cleanly (no panic, no double-free)
9054        drop(writer_a);
9055        drop(writer_b);
9056    }
9057
9058    #[test]
9059    fn multiple_inline_writers_gauge_tracks_both() {
9060        // Verify the gauge correctly tracks two simultaneous inline writers.
9061        let _lock = GAUGE_TEST_LOCK
9062            .lock()
9063            .unwrap_or_else(|err| err.into_inner());
9064
9065        for _ in 0..64 {
9066            let before = inline_active_widgets();
9067            let writer_a = TerminalWriter::new(
9068                Vec::new(),
9069                ScreenMode::Inline { ui_height: 3 },
9070                UiAnchor::Bottom,
9071                basic_caps(),
9072            );
9073            let after_a = inline_active_widgets();
9074
9075            let writer_b = TerminalWriter::new(
9076                Vec::new(),
9077                ScreenMode::Inline { ui_height: 5 },
9078                UiAnchor::Bottom,
9079                basic_caps(),
9080            );
9081            let after_b = inline_active_widgets();
9082
9083            drop(writer_a);
9084            let after_drop_a = inline_active_widgets();
9085
9086            drop(writer_b);
9087            let after_drop_b = inline_active_widgets();
9088
9089            if after_a == before.saturating_add(1)
9090                && after_b == before.saturating_add(2)
9091                && after_drop_a == before.saturating_add(1)
9092                && after_drop_b == before
9093            {
9094                return;
9095            }
9096            std::thread::yield_now();
9097        }
9098
9099        panic!("failed to observe uncontended two-writer gauge transitions");
9100    }
9101
9102    #[test]
9103    fn resize_during_inline_mode_preserves_scrollback() {
9104        // Resize should re-anchor the UI region without emitting
9105        // alternate screen sequences and should allow continued rendering.
9106        let mut output = Vec::new();
9107        {
9108            let mut writer = TerminalWriter::new(
9109                &mut output,
9110                ScreenMode::Inline { ui_height: 5 },
9111                UiAnchor::Bottom,
9112                basic_caps(),
9113            );
9114            writer.set_size(80, 24);
9115
9116            let buffer = Buffer::new(80, 5);
9117            writer.present_ui(&buffer, None, true).unwrap();
9118
9119            // Simulate resize
9120            writer.set_size(100, 30);
9121            assert_eq!(writer.ui_start_row(), 25); // 30 - 5
9122
9123            // Render again after resize
9124            let buffer2 = Buffer::new(100, 5);
9125            writer.present_ui(&buffer2, None, true).unwrap();
9126
9127            // Log still works after resize
9128            writer.write_log("post-resize log\n").unwrap();
9129        }
9130
9131        let text = String::from_utf8_lossy(&output);
9132        assert!(text.contains("post-resize log"));
9133        assert!(
9134            !contains_bytes(&output, ALTSCREEN_ENTER),
9135            "resize must not trigger alternate screen"
9136        );
9137    }
9138
9139    #[test]
9140    fn resize_shrink_during_inline_mode_clamps_correctly() {
9141        // Shrinking the terminal so UI region overlaps should still work
9142        // without alternate screen sequences.
9143        let mut output = Vec::new();
9144        {
9145            let mut writer = TerminalWriter::new(
9146                &mut output,
9147                ScreenMode::Inline { ui_height: 10 },
9148                UiAnchor::Bottom,
9149                basic_caps(),
9150            );
9151            writer.set_size(80, 24);
9152            assert_eq!(writer.ui_start_row(), 14);
9153
9154            // Shrink terminal to smaller than UI height
9155            writer.set_size(80, 8);
9156            assert_eq!(writer.ui_start_row(), 0); // 8 - 10 would underflow, clamped to 0
9157
9158            // Rendering should still work (height clamped to terminal)
9159            let buffer = Buffer::new(80, 8);
9160            writer.present_ui(&buffer, None, true).unwrap();
9161        }
9162
9163        assert!(
9164            !contains_bytes(&output, ALTSCREEN_ENTER),
9165            "shrunken terminal must not switch to altscreen"
9166        );
9167    }
9168
9169    #[test]
9170    fn inline_render_emits_tracing_span_fields() {
9171        // Verify the inline.render span is entered during present_ui in inline
9172        // mode by checking that the tracing infrastructure is invoked.
9173        // We use a tracing subscriber to capture span creation.
9174        use std::sync::Arc;
9175        use std::sync::atomic::AtomicBool;
9176
9177        struct SpanChecker {
9178            saw_inline_render: Arc<AtomicBool>,
9179        }
9180
9181        impl tracing::Subscriber for SpanChecker {
9182            fn enabled(&self, _metadata: &tracing::Metadata<'_>) -> bool {
9183                true
9184            }
9185            fn new_span(&self, span: &tracing::span::Attributes<'_>) -> tracing::span::Id {
9186                if span.metadata().name() == "inline.render" {
9187                    self.saw_inline_render
9188                        .store(true, std::sync::atomic::Ordering::SeqCst);
9189                }
9190                tracing::span::Id::from_u64(1)
9191            }
9192            fn record(&self, _span: &tracing::span::Id, _values: &tracing::span::Record<'_>) {}
9193            fn record_follows_from(&self, _span: &tracing::span::Id, _follows: &tracing::span::Id) {
9194            }
9195            fn event(&self, _event: &tracing::Event<'_>) {}
9196            fn enter(&self, _span: &tracing::span::Id) {}
9197            fn exit(&self, _span: &tracing::span::Id) {}
9198        }
9199
9200        let saw_it = Arc::new(AtomicBool::new(false));
9201
9202        // Span callsite interest caches are process-global while this
9203        // dispatcher is thread-local: a parallel test can race the
9204        // info_span!("inline.render") callsite into caching "not enabled"
9205        // even after a rebuild (bd-r2qx8). Retry with a fresh subscriber and
9206        // a fresh rebuild each round; a neighbor can only win the race
9207        // transiently, never persistently.
9208        for _ in 0..8 {
9209            saw_it.store(false, std::sync::atomic::Ordering::SeqCst);
9210            let subscriber = SpanChecker {
9211                saw_inline_render: Arc::clone(&saw_it),
9212            };
9213
9214            let _guard = tracing::subscriber::set_default(subscriber);
9215            tracing::callsite::rebuild_interest_cache();
9216
9217            let mut output = Vec::new();
9218            {
9219                let mut writer = TerminalWriter::new(
9220                    &mut output,
9221                    ScreenMode::Inline { ui_height: 5 },
9222                    UiAnchor::Bottom,
9223                    basic_caps(),
9224                );
9225                writer.set_size(80, 24);
9226
9227                let buffer = Buffer::new(80, 5);
9228                writer.present_ui(&buffer, None, true).unwrap();
9229            }
9230
9231            if saw_it.load(std::sync::atomic::Ordering::SeqCst) {
9232                return;
9233            }
9234        }
9235
9236        assert!(
9237            saw_it.load(std::sync::atomic::Ordering::SeqCst),
9238            "present_ui in inline mode must emit an inline.render tracing span"
9239        );
9240    }
9241
9242    #[test]
9243    fn inline_render_no_altscreen_with_scroll_region_strategy() {
9244        // Even with scroll region caps, inline mode must not emit altscreen.
9245        let mut output = Vec::new();
9246        {
9247            let mut writer = TerminalWriter::new(
9248                &mut output,
9249                ScreenMode::Inline { ui_height: 5 },
9250                UiAnchor::Bottom,
9251                scroll_region_caps(),
9252            );
9253            writer.set_size(80, 24);
9254
9255            let buffer = Buffer::new(80, 5);
9256            writer.present_ui(&buffer, None, true).unwrap();
9257            writer.present_ui(&buffer, None, true).unwrap();
9258        }
9259
9260        assert!(
9261            !contains_bytes(&output, ALTSCREEN_ENTER),
9262            "scroll region strategy must never emit altscreen enter"
9263        );
9264    }
9265
9266    #[test]
9267    fn inline_render_no_altscreen_with_hybrid_strategy() {
9268        let mut output = Vec::new();
9269        {
9270            let mut writer = TerminalWriter::new(
9271                &mut output,
9272                ScreenMode::Inline { ui_height: 5 },
9273                UiAnchor::Bottom,
9274                hybrid_caps(),
9275            );
9276            writer.set_size(80, 24);
9277
9278            let buffer = Buffer::new(80, 5);
9279            writer.present_ui(&buffer, None, true).unwrap();
9280        }
9281
9282        assert!(
9283            !contains_bytes(&output, ALTSCREEN_ENTER),
9284            "hybrid strategy must never emit altscreen enter"
9285        );
9286    }
9287
9288    #[test]
9289    fn inline_render_no_altscreen_with_mux_strategy() {
9290        let mut output = Vec::new();
9291        {
9292            let mut writer = TerminalWriter::new(
9293                &mut output,
9294                ScreenMode::Inline { ui_height: 5 },
9295                UiAnchor::Bottom,
9296                mux_caps(),
9297            );
9298            writer.set_size(80, 24);
9299
9300            let buffer = Buffer::new(80, 5);
9301            writer.present_ui(&buffer, None, true).unwrap();
9302        }
9303
9304        assert!(
9305            !contains_bytes(&output, ALTSCREEN_ENTER),
9306            "mux (overlay) strategy must never emit altscreen enter"
9307        );
9308    }
9309
9310    #[test]
9311    fn test_altscreen_wide_char_rendering() {
9312        use ftui_render::cell::Cell;
9313        let mut output = Vec::new();
9314        {
9315            let mut writer = TerminalWriter::new(
9316                &mut output,
9317                ScreenMode::AltScreen,
9318                UiAnchor::Bottom,
9319                basic_caps(),
9320            );
9321            writer.set_size(10, 5);
9322
9323            let mut buf = Buffer::new(10, 1);
9324            // Wide char at x=0 (width 2)
9325            buf.set_raw(0, 0, Cell::from_char('中'));
9326            // x=1 is implicitly CONTINUATION from Buffer::new init (or empty)
9327            // Wait, set_raw only sets one cell.
9328            // But Presenter logic depends on Buffer content.
9329            // For the test, we want to simulate the state where we have a wide char.
9330            // The proper way is to use `set` which handles continuations, or manually set them.
9331            buf.set(0, 0, Cell::from_char('中')); // This sets x=0 to '中', x=1 to CONTINUATION
9332
9333            // Force a diff by having a different previous buffer
9334            let prev = Buffer::new(10, 1);
9335            writer.prev_buffer = Some(prev);
9336
9337            writer.present_ui(&buf, None, true).unwrap();
9338        }
9339
9340        let output_str = String::from_utf8_lossy(&output);
9341
9342        // Should contain '中'
9343        assert!(output_str.contains('中'));
9344
9345        // Should NOT contain a space immediately after '中' (if it was treated as orphan)
9346        // Since '中' is e4 b8 ad (3 bytes).
9347        let bytes = output_str.as_bytes();
9348        let pos = bytes.windows(3).position(|w| w == "中".as_bytes());
9349        assert!(pos.is_some());
9350
9351        // Check byte after '中'
9352        let after = pos.unwrap() + 3;
9353        if after < bytes.len() {
9354            // It might be ANSI sequence or nothing. It should NOT be space (0x20).
9355            assert_ne!(
9356                bytes[after], 0x20,
9357                "Wide char continuation clobbered with space"
9358            );
9359        }
9360    }
9361
9362    // =========================================================================
9363    // NON-INTERFERENCE CONTRACT TESTS (bd-1bavy)
9364    //
9365    // These tests verify that terminal mode behavior and ownership semantics
9366    // are preserved under lifecycle changes. The Asupersync migration MUST
9367    // keep all these guarantees intact.
9368    // =========================================================================
9369
9370    /// CONTRACT: INLINE_ACTIVE_WIDGETS gauge increments on inline writer
9371    /// creation and decrements on drop. Net effect of create+drop is zero.
9372    /// Note: Tests use relative deltas because the global counter is shared.
9373    #[test]
9374    fn noninterference_inline_gauge_balanced_across_lifecycle() {
9375        let _lock = GAUGE_TEST_LOCK
9376            .lock()
9377            .unwrap_or_else(|err| err.into_inner());
9378
9379        for _ in 0..64 {
9380            let before = inline_active_widgets();
9381            let writer = TerminalWriter::new(
9382                Vec::new(),
9383                ScreenMode::Inline { ui_height: 3 },
9384                UiAnchor::Bottom,
9385                basic_caps(),
9386            );
9387            let during = inline_active_widgets();
9388            drop(writer);
9389            let after = inline_active_widgets();
9390
9391            if during == before.saturating_add(1) && after == before {
9392                return;
9393            }
9394            std::thread::yield_now();
9395        }
9396
9397        panic!("failed to observe stable inline lifecycle gauge transition");
9398    }
9399
9400    /// CONTRACT: AltScreen writers do NOT affect the inline gauge.
9401    /// Verified by checking the ScreenMode match in the Drop impl.
9402    /// (Note: the global atomic gauge is tested for inline modes in
9403    /// other tests; here we just verify the code path distinction.)
9404    #[test]
9405    fn noninterference_altscreen_does_not_affect_inline_gauge() {
9406        let _lock = GAUGE_TEST_LOCK
9407            .lock()
9408            .unwrap_or_else(|err| err.into_inner());
9409
9410        // The contract is verified structurally: ScreenMode::AltScreen does
9411        // not match the inline pattern in both the constructor (fetch_add)
9412        // and the Drop impl (fetch_sub). We verify this by checking that
9413        // creating and immediately dropping an AltScreen writer round-trips
9414        // without affecting the delta observed from a controlled inline writer.
9415        let mut observed_stable = false;
9416        for _ in 0..64 {
9417            let before = inline_active_widgets();
9418            drop(TerminalWriter::new(
9419                Vec::new(),
9420                ScreenMode::AltScreen,
9421                UiAnchor::Bottom,
9422                basic_caps(),
9423            ));
9424            let after = inline_active_widgets();
9425
9426            if after == before {
9427                observed_stable = true;
9428                break;
9429            }
9430            std::thread::yield_now();
9431        }
9432
9433        assert!(
9434            observed_stable,
9435            "failed to observe stable altscreen lifecycle gauge transition"
9436        );
9437
9438        // Also verify the structural contract directly:
9439        assert!(
9440            !matches!(
9441                ScreenMode::AltScreen,
9442                ScreenMode::Inline { .. } | ScreenMode::InlineAuto { .. }
9443            ),
9444            "AltScreen must not match inline patterns"
9445        );
9446    }
9447
9448    /// CONTRACT: InlineAuto also tracks the inline gauge correctly.
9449    #[test]
9450    fn noninterference_inline_auto_gauge_balanced() {
9451        let _lock = GAUGE_TEST_LOCK
9452            .lock()
9453            .unwrap_or_else(|err| err.into_inner());
9454
9455        for _ in 0..64 {
9456            let before = inline_active_widgets();
9457            let writer = TerminalWriter::new(
9458                Vec::new(),
9459                ScreenMode::InlineAuto {
9460                    min_height: 3,
9461                    max_height: 10,
9462                },
9463                UiAnchor::Bottom,
9464                basic_caps(),
9465            );
9466            let during = inline_active_widgets();
9467            drop(writer);
9468            let after = inline_active_widgets();
9469
9470            if during == before.saturating_add(1) && after == before {
9471                return;
9472            }
9473            std::thread::yield_now();
9474        }
9475
9476        panic!("failed to observe stable inline-auto lifecycle gauge transition");
9477    }
9478
9479    /// CONTRACT: into_inner() performs cleanup before releasing the writer.
9480    /// The returned output must contain cursor-show and flush.
9481    #[test]
9482    fn noninterference_into_inner_performs_cleanup() {
9483        let _lock = GAUGE_TEST_LOCK
9484            .lock()
9485            .unwrap_or_else(|err| err.into_inner());
9486
9487        let cursor_show = b"\x1b[?25h";
9488        for _ in 0..64 {
9489            let before_gauge = inline_active_widgets();
9490
9491            let mut writer = TerminalWriter::new(
9492                Vec::new(),
9493                ScreenMode::Inline { ui_height: 5 },
9494                UiAnchor::Bottom,
9495                basic_caps(),
9496            );
9497            writer.set_size(80, 24);
9498
9499            let during_gauge = inline_active_widgets();
9500            let output = writer.into_inner().expect("should return writer");
9501            let after_gauge = inline_active_widgets();
9502
9503            if during_gauge == before_gauge.saturating_add(1) && after_gauge == before_gauge {
9504                assert!(
9505                    output.windows(cursor_show.len()).any(|w| w == cursor_show),
9506                    "into_inner must emit cursor show during cleanup"
9507                );
9508                return;
9509            }
9510            std::thread::yield_now();
9511        }
9512
9513        panic!("failed to observe stable into_inner gauge transition");
9514    }
9515
9516    /// CONTRACT: Cleanup output from inline mode must contain cursor restore
9517    /// (DEC 8) if cursor was saved during present.
9518    #[test]
9519    fn noninterference_inline_cleanup_restores_cursor_after_present() {
9520        let mut output = Vec::new();
9521        {
9522            let mut writer = TerminalWriter::new(
9523                &mut output,
9524                ScreenMode::Inline { ui_height: 5 },
9525                UiAnchor::Bottom,
9526                basic_caps(),
9527            );
9528            writer.set_size(80, 24);
9529
9530            let buffer = Buffer::new(80, 5);
9531            writer.present_ui(&buffer, None, true).unwrap();
9532
9533            // Writer will be dropped here, triggering cleanup
9534        }
9535
9536        // Count cursor save/restore pairs
9537        let saves = output
9538            .windows(CURSOR_SAVE.len())
9539            .filter(|w| *w == CURSOR_SAVE)
9540            .count();
9541        let restores = output
9542            .windows(CURSOR_RESTORE.len())
9543            .filter(|w| *w == CURSOR_RESTORE)
9544            .count();
9545
9546        assert!(saves > 0, "present must save cursor");
9547        assert!(
9548            restores >= saves,
9549            "cleanup must ensure all cursor saves are restored: {saves} saves, {restores} restores"
9550        );
9551    }
9552
9553    /// CONTRACT: AltScreen cleanup must show cursor. It must NOT emit
9554    /// cursor restore or scroll region reset (those are inline-only).
9555    #[test]
9556    fn noninterference_altscreen_cleanup_minimal() {
9557        let mut output = Vec::new();
9558        {
9559            let mut writer = TerminalWriter::new(
9560                &mut output,
9561                ScreenMode::AltScreen,
9562                UiAnchor::Bottom,
9563                basic_caps(),
9564            );
9565            writer.set_size(80, 24);
9566
9567            let mut buffer = Buffer::new(80, 24);
9568            buffer.set_raw(0, 0, Cell::from_char('A'));
9569            writer.present_ui(&buffer, None, true).unwrap();
9570        }
9571
9572        // Must contain cursor show
9573        let cursor_show = b"\x1b[?25h";
9574        assert!(
9575            output.windows(cursor_show.len()).any(|w| w == cursor_show),
9576            "AltScreen cleanup must show cursor"
9577        );
9578
9579        // Must NOT contain scroll region reset (inline-only)
9580        // (scroll region was never activated for AltScreen)
9581        // This is verified by the scroll_region_active flag being false
9582    }
9583
9584    /// CONTRACT: Rapid present/log interleaving in inline mode must not
9585    /// corrupt the output stream. Each present must be complete and each
9586    /// log must be sanitized.
9587    #[test]
9588    fn noninterference_rapid_present_log_interleave() {
9589        let mut output = Vec::new();
9590        {
9591            let mut writer = TerminalWriter::new(
9592                &mut output,
9593                ScreenMode::Inline { ui_height: 3 },
9594                UiAnchor::Bottom,
9595                basic_caps(),
9596            );
9597            writer.set_size(40, 12);
9598
9599            for i in 0..10 {
9600                let mut buffer = Buffer::new(40, 3);
9601                buffer.set_raw(0, 0, Cell::from_char(char::from(b'A' + (i % 26))));
9602                writer.present_ui(&buffer, None, true).unwrap();
9603                writer.write_log(&format!("log-{i}")).unwrap();
9604            }
9605        }
9606
9607        // Output must contain cursor show (cleanup ran)
9608        let cursor_show = b"\x1b[?25h";
9609        assert!(
9610            output.windows(cursor_show.len()).any(|w| w == cursor_show),
9611            "cleanup must complete after rapid interleaving"
9612        );
9613
9614        // Output must not contain unmatched escape sequences
9615        // (simple check: no bare ESC at end without terminator)
9616        let output_len = output.len();
9617        if output_len > 1 {
9618            let last_esc = output.iter().rposition(|&b| b == 0x1b);
9619            if let Some(pos) = last_esc {
9620                // If the last ESC is within 10 bytes of the end, verify it's a complete sequence
9621                if output_len - pos < 10 {
9622                    // Should be part of cursor show or similar short sequence
9623                    assert!(
9624                        output_len - pos >= 3,
9625                        "truncated escape sequence at end of output"
9626                    );
9627                }
9628            }
9629        }
9630    }
9631
9632    /// CONTRACT: Resize between presents must not leave stale diff state.
9633    /// The first present after resize must produce valid output.
9634    #[test]
9635    fn noninterference_resize_between_presents_clears_diff_state() {
9636        let mut output = Vec::new();
9637        {
9638            let mut writer = TerminalWriter::new(
9639                &mut output,
9640                ScreenMode::Inline { ui_height: 5 },
9641                UiAnchor::Bottom,
9642                basic_caps(),
9643            );
9644            writer.set_size(80, 24);
9645
9646            // First present at 80x5
9647            let buffer1 = Buffer::new(80, 5);
9648            writer.present_ui(&buffer1, None, true).unwrap();
9649
9650            // Resize
9651            writer.set_size(120, 30);
9652            assert!(
9653                writer.prev_buffer.is_none(),
9654                "set_size must clear prev_buffer to invalidate diff"
9655            );
9656
9657            // Second present at 120x5 — must not panic or produce corrupt output
9658            let buffer2 = Buffer::new(120, 5);
9659            writer.present_ui(&buffer2, None, true).unwrap();
9660        }
9661
9662        // If we got here without panic, the resize was handled correctly
9663        let cursor_show = b"\x1b[?25h";
9664        assert!(
9665            output.windows(cursor_show.len()).any(|w| w == cursor_show),
9666            "output must be valid after resize"
9667        );
9668    }
9669
9670    /// CONTRACT: Multiple writers can be created sequentially on the same
9671    /// output without interference. Each writer's cleanup must be complete
9672    /// before the next writer starts.
9673    #[test]
9674    fn noninterference_sequential_writers_clean_handoff() {
9675        let mut output = Vec::new();
9676
9677        // First writer: Inline mode
9678        {
9679            let mut writer = TerminalWriter::new(
9680                &mut output,
9681                ScreenMode::Inline { ui_height: 3 },
9682                UiAnchor::Bottom,
9683                basic_caps(),
9684            );
9685            writer.set_size(40, 12);
9686            let buffer = Buffer::new(40, 3);
9687            writer.present_ui(&buffer, None, true).unwrap();
9688            // Dropped: cleanup runs
9689        }
9690
9691        let inline_end = output.len();
9692
9693        // Second writer: AltScreen mode on same output
9694        {
9695            let mut writer = TerminalWriter::new(
9696                &mut output,
9697                ScreenMode::AltScreen,
9698                UiAnchor::Bottom,
9699                basic_caps(),
9700            );
9701            writer.set_size(40, 12);
9702            let mut buffer = Buffer::new(40, 12);
9703            buffer.set_raw(0, 0, Cell::from_char('Z'));
9704            writer.present_ui(&buffer, None, true).unwrap();
9705            // Dropped: cleanup runs
9706        }
9707
9708        // Both cleanups must have produced cursor show
9709        let cursor_show = b"\x1b[?25h";
9710        let first_show = output[..inline_end]
9711            .windows(cursor_show.len())
9712            .any(|w| w == cursor_show);
9713        let second_show = output[inline_end..]
9714            .windows(cursor_show.len())
9715            .any(|w| w == cursor_show);
9716
9717        assert!(first_show, "first writer must show cursor on cleanup");
9718        assert!(second_show, "second writer must show cursor on cleanup");
9719    }
9720
9721    /// CONTRACT: present_ui_owned must produce identical output to present_ui
9722    /// for the same buffer content. The only difference should be performance.
9723    #[test]
9724    fn noninterference_present_ui_owned_matches_present_ui() {
9725        let mut output_borrowed = Vec::new();
9726        let mut output_owned = Vec::new();
9727
9728        let mut buffer = Buffer::new(20, 5);
9729        buffer.set_raw(0, 0, Cell::from_char('H'));
9730        buffer.set_raw(1, 0, Cell::from_char('i'));
9731
9732        // Borrowed path
9733        {
9734            let mut writer = TerminalWriter::new(
9735                &mut output_borrowed,
9736                ScreenMode::Inline { ui_height: 5 },
9737                UiAnchor::Bottom,
9738                basic_caps(),
9739            );
9740            writer.set_size(20, 10);
9741            writer.present_ui(&buffer, None, true).unwrap();
9742        }
9743
9744        // Owned path
9745        {
9746            let mut writer = TerminalWriter::new(
9747                &mut output_owned,
9748                ScreenMode::Inline { ui_height: 5 },
9749                UiAnchor::Bottom,
9750                basic_caps(),
9751            );
9752            writer.set_size(20, 10);
9753            writer.present_ui_owned(buffer, None, true).unwrap();
9754        }
9755
9756        // Both must contain cursor save/restore
9757        assert!(
9758            output_borrowed
9759                .windows(CURSOR_SAVE.len())
9760                .any(|w| w == CURSOR_SAVE),
9761            "borrowed path must save cursor"
9762        );
9763        assert!(
9764            output_owned
9765                .windows(CURSOR_SAVE.len())
9766                .any(|w| w == CURSOR_SAVE),
9767            "owned path must save cursor"
9768        );
9769
9770        // Both must contain the 'H' character
9771        assert!(
9772            output_borrowed.windows(1).any(|w| w == b"H"),
9773            "borrowed path must render content"
9774        );
9775        assert!(
9776            output_owned.windows(1).any(|w| w == b"H"),
9777            "owned path must render content"
9778        );
9779    }
9780
9781    /// CONTRACT: write_log is a no-op in AltScreen mode but works in inline.
9782    /// This behavioral difference must be preserved.
9783    #[test]
9784    fn noninterference_write_log_mode_behavior_preserved() {
9785        // Inline: write_log produces output
9786        let mut inline_output = Vec::new();
9787        {
9788            let mut writer = TerminalWriter::new(
9789                &mut inline_output,
9790                ScreenMode::Inline { ui_height: 3 },
9791                UiAnchor::Bottom,
9792                basic_caps(),
9793            );
9794            writer.set_size(40, 12);
9795            writer.write_log("hello").unwrap();
9796        }
9797        assert!(
9798            inline_output.windows(5).any(|w| w == b"hello"),
9799            "inline write_log must produce output"
9800        );
9801
9802        // AltScreen: write_log is silent
9803        let mut alt_output = Vec::new();
9804        {
9805            let mut writer = TerminalWriter::new(
9806                &mut alt_output,
9807                ScreenMode::AltScreen,
9808                UiAnchor::Bottom,
9809                basic_caps(),
9810            );
9811            writer.set_size(40, 12);
9812            writer.write_log("hello").unwrap();
9813        }
9814        // The output should not contain "hello" text from write_log
9815        // (it will contain cleanup sequences)
9816        let has_hello = alt_output.windows(5).any(|w| w == b"hello");
9817        assert!(!has_hello, "AltScreen write_log must be silent (no-op)");
9818    }
9819
9820    /// CONTRACT: Sync output sequences are balanced (begin/end) across
9821    /// multiple present calls. An open sync block must never leak.
9822    #[test]
9823    fn noninterference_sync_output_balanced_across_multiple_presents() {
9824        let mut output = Vec::new();
9825        {
9826            let mut writer = TerminalWriter::new(
9827                &mut output,
9828                ScreenMode::Inline { ui_height: 3 },
9829                UiAnchor::Bottom,
9830                full_caps(),
9831            );
9832            writer.set_size(20, 10);
9833
9834            for _ in 0..5 {
9835                let buffer = Buffer::new(20, 3);
9836                writer.present_ui(&buffer, None, true).unwrap();
9837            }
9838            // Writer drop triggers cleanup
9839        }
9840
9841        let begins = output
9842            .windows(SYNC_BEGIN.len())
9843            .filter(|w| *w == SYNC_BEGIN)
9844            .count();
9845        let ends = output
9846            .windows(SYNC_END.len())
9847            .filter(|w| *w == SYNC_END)
9848            .count();
9849
9850        assert!(begins > 0, "sync-capable writer must emit SYNC_BEGIN");
9851        assert_eq!(
9852            begins, ends,
9853            "sync blocks must be balanced: {begins} begins, {ends} ends"
9854        );
9855    }
9856
9857    /// CONTRACT: InlineAuto effective_ui_height is clamped to terminal height.
9858    /// A writer with max_height > terminal height must clamp without panic.
9859    #[test]
9860    fn noninterference_inline_auto_height_clamped_without_panic() {
9861        let mut output = Vec::new();
9862        {
9863            let mut writer = TerminalWriter::new(
9864                &mut output,
9865                ScreenMode::InlineAuto {
9866                    min_height: 3,
9867                    max_height: 100,
9868                },
9869                UiAnchor::Bottom,
9870                basic_caps(),
9871            );
9872            // Terminal is only 10 rows tall
9873            writer.set_size(80, 10);
9874
9875            // effective_ui_height for InlineAuto clamps to term_height
9876            let effective = writer.effective_ui_height();
9877            assert!(
9878                effective <= 10,
9879                "InlineAuto effective_ui_height must clamp to terminal height, got {effective}"
9880            );
9881
9882            let buffer = Buffer::new(80, effective);
9883            writer.present_ui(&buffer, None, true).unwrap();
9884        }
9885    }
9886
9887    /// CONTRACT: Inline mode with ui_height > terminal height must not panic
9888    /// during present. The rendering path handles this gracefully.
9889    #[test]
9890    fn noninterference_inline_oversized_height_no_panic() {
9891        let mut output = Vec::new();
9892        {
9893            let mut writer = TerminalWriter::new(
9894                &mut output,
9895                ScreenMode::Inline { ui_height: 100 },
9896                UiAnchor::Bottom,
9897                basic_caps(),
9898            );
9899            writer.set_size(80, 10);
9900
9901            // Inline effective_ui_height returns raw value without clamping
9902            // but the rendering path must handle this without panic
9903            let buffer = Buffer::new(80, 10);
9904            // This should not panic even though ui_height > term_height
9905            let result = writer.present_ui(&buffer, None, true);
9906            assert!(
9907                result.is_ok(),
9908                "present_ui must not panic with oversized ui_height"
9909            );
9910        }
9911    }
9912
9913    // ── Render-certificate integration (bd-6b9nr) ───────────────────────────
9914
9915    fn present_sequence(certified: bool) -> (Vec<u8>, Vec<String>) {
9916        let config = RuntimeDiffConfig {
9917            certified_skips: certified,
9918            // Deterministic strategy behavior for the byte-equality comparison.
9919            bayesian_enabled: false,
9920            ..RuntimeDiffConfig::default()
9921        };
9922        let mut writer = TerminalWriter::with_diff_config(
9923            Vec::new(),
9924            ScreenMode::Inline { ui_height: 4 },
9925            UiAnchor::Bottom,
9926            full_caps(),
9927            config,
9928        );
9929        writer.set_size(24, 12);
9930
9931        let mut certificates = Vec::new();
9932        for frame in 0..4u16 {
9933            let mut buffer = Buffer::new(24, 4);
9934            if frame > 0 {
9935                buffer.clear_dirty();
9936            }
9937            match frame {
9938                // Frame 0: initial paint (all rows dirty by construction).
9939                0 => {}
9940                // Frame 1: identical content — zero dirty rows.
9941                1 => {}
9942                // Frame 2: sparse update on two rows.
9943                2 => {
9944                    buffer.set(3, 1, ftui_render::cell::Cell::from_char('X'));
9945                    buffer.set(9, 3, ftui_render::cell::Cell::from_char('Y'));
9946                }
9947                // Frame 3: another sparse update.
9948                _ => {
9949                    buffer.set(3, 1, ftui_render::cell::Cell::from_char('Z'));
9950                }
9951            }
9952            writer
9953                .present_ui_owned(buffer, None, false)
9954                .expect("present");
9955            certificates.push(
9956                writer
9957                    .last_render_certificate()
9958                    .map(|c| format!("{}:{:?}", c.level.label(), c.causes.clone()))
9959                    .unwrap_or_else(|| "none".to_string()),
9960            );
9961        }
9962        (writer.into_inner().expect("writer sink"), certificates)
9963    }
9964
9965    #[test]
9966    fn certified_path_is_byte_identical_to_legacy_dirty_path() {
9967        let (certified_bytes, _) = present_sequence(true);
9968        let (legacy_bytes, _) = present_sequence(false);
9969        assert_eq!(
9970            certified_bytes, legacy_bytes,
9971            "certified diff path changed visible output"
9972        );
9973    }
9974
9975    #[test]
9976    fn zero_dirty_frame_earns_a_skip_all_certificate() {
9977        let (_, certificates) = present_sequence(true);
9978        // Frame 1 re-presents identical content with zero dirty rows.
9979        assert!(
9980            certificates[1].starts_with("skip-all"),
9981            "frame 1 certificate was {}",
9982            certificates[1]
9983        );
9984        // Sparse frames narrow to their dirty rows.
9985        assert!(
9986            certificates[2].starts_with("narrow-to-dirty"),
9987            "frame 2 certificate was {}",
9988            certificates[2]
9989        );
9990    }
9991
9992    #[test]
9993    fn certificates_name_full_work_causes() {
9994        let (_, certificates) = present_sequence(true);
9995        // Frame 0 has no previous buffer: full redraw with a named cause.
9996        assert!(
9997            certificates[0].contains("no-previous-frame"),
9998            "frame 0 certificate was {}",
9999            certificates[0]
10000        );
10001    }
10002
10003    #[test]
10004    fn legacy_path_records_no_certificate() {
10005        let (_, certificates) = present_sequence(false);
10006        // The dirty-rows frames record None when certified skips are off
10007        // (frame 0/resize paths still certify full work explicitly).
10008        assert_eq!(certificates[2], "none");
10009        assert_eq!(certificates[3], "none");
10010    }
10011
10012    #[test]
10013    fn bottom_addressed_inline_trims_trailing_blanks_and_clears_shortened_rows() {
10014        let mut writer = TerminalWriter::new(
10015            Vec::new(),
10016            ScreenMode::Inline { ui_height: 2 },
10017            UiAnchor::Bottom,
10018            basic_caps(),
10019        );
10020        writer.set_size(40, 10);
10021
10022        let mut frame1 = Buffer::new(40, 2);
10023        for (x, ch) in "status-long".chars().enumerate() {
10024            frame1.set(x as u16, 0, ftui_render::cell::Cell::from_char(ch));
10025        }
10026        assert_eq!(row_occupied_width(&frame1, 0), 11);
10027        assert_eq!(row_occupied_width(&frame1, 1), 0);
10028        writer.present_ui_owned(frame1, None, false).unwrap();
10029
10030        let mut frame2 = Buffer::new(40, 2);
10031        for (x, ch) in "brief".chars().enumerate() {
10032            frame2.set(x as u16, 0, ftui_render::cell::Cell::from_char(ch));
10033        }
10034        assert_eq!(row_occupied_width(&frame2, 0), 5);
10035        writer.present_ui_owned(frame2, None, false).unwrap();
10036
10037        let bytes = writer.into_inner().unwrap();
10038        let output = String::from_utf8_lossy(&bytes);
10039        assert!(
10040            !output.contains("status-long "),
10041            "full redraw must not pad trailing uncolored spaces: {output:?}"
10042        );
10043        assert!(
10044            output.contains("brief") && output.contains("\x1b[K"),
10045            "shortened incremental row must emit EL after occupied width: {output:?}"
10046        );
10047    }
10048}