Skip to main content

ftui_runtime/
program.rs

1#![forbid(unsafe_code)]
2
3//! Bubbletea/Elm-style runtime for terminal applications.
4//!
5//! The program runtime manages the update/view loop, handling events and
6//! rendering frames. It separates state (Model) from rendering (View) and
7//! provides a command pattern for side effects.
8//!
9//! # Example
10//!
11//! ```ignore
12//! use ftui_runtime::program::{Model, Cmd};
13//! use ftui_core::event::Event;
14//! use ftui_render::frame::Frame;
15//!
16//! struct Counter {
17//!     count: i32,
18//! }
19//!
20//! enum Msg {
21//!     Increment,
22//!     Decrement,
23//!     Quit,
24//! }
25//!
26//! impl From<Event> for Msg {
27//!     fn from(event: Event) -> Self {
28//!         match event {
29//!             Event::Key(k) if k.is_char('q') => Msg::Quit,
30//!             Event::Key(k) if k.is_char('+') => Msg::Increment,
31//!             Event::Key(k) if k.is_char('-') => Msg::Decrement,
32//!             _ => Msg::Increment, // Default
33//!         }
34//!     }
35//! }
36//!
37//! impl Model for Counter {
38//!     type Message = Msg;
39//!
40//!     fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
41//!         match msg {
42//!             Msg::Increment => { self.count += 1; Cmd::none() }
43//!             Msg::Decrement => { self.count -= 1; Cmd::none() }
44//!             Msg::Quit => Cmd::quit(),
45//!         }
46//!     }
47//!
48//!     fn view(&self, frame: &mut Frame) {
49//!         // Render counter value to frame
50//!     }
51//! }
52//! ```
53
54use crate::StorageResult;
55use crate::evidence_sink::{EvidenceSink, EvidenceSinkConfig};
56use crate::evidence_telemetry::{
57    BudgetDecisionSnapshot, ConformalSnapshot, ResizeDecisionSnapshot, set_budget_snapshot,
58    set_resize_snapshot,
59};
60use crate::input_fairness::{FairnessDecision, FairnessEventType, InputFairnessGuard};
61use crate::input_macro::{EventRecorder, InputMacro};
62use crate::locale::LocaleContext;
63use crate::queueing_scheduler::{EstimateSource, QueueingScheduler, SchedulerConfig, WeightSource};
64use crate::render_trace::RenderTraceConfig;
65use crate::resize_coalescer::{CoalesceAction, CoalescerConfig, ResizeCoalescer};
66use crate::state_persistence::StateRegistry;
67use crate::subscription::SubscriptionManager;
68pub use crate::terminal_presenter::TerminalPresenter;
69use crate::terminal_writer::{RuntimeDiffConfig, ScreenMode, TerminalWriter, UiAnchor};
70use crate::voi_sampling::{VoiConfig, VoiSampler};
71use crate::{BucketKey, ConformalConfig, ConformalPrediction, ConformalPredictor, ConformalStatus};
72#[cfg(feature = "asupersync-executor")]
73use asupersync::runtime::{BlockingTaskHandle, Runtime as AsupersyncRuntime, RuntimeBuilder};
74use ftui_a11y::tree::{A11yTree, A11yTreeBuilder, ScreenReaderAnnouncement, ScreenReaderPolicy};
75use ftui_backend::{BackendEventSource, BackendFeatures, BackendPresenter};
76use ftui_core::event::{
77    Event, KeyCode, KeyEvent, KeyEventKind, Modifiers, MouseButton, MouseEvent, MouseEventKind,
78};
79use ftui_core::terminal_capabilities::TerminalCapabilities;
80#[cfg(feature = "crossterm-compat")]
81use ftui_core::terminal_session::{SessionOptions, TerminalSession};
82use ftui_layout::{
83    PANE_DRAG_RESIZE_DEFAULT_HYSTERESIS, PANE_DRAG_RESIZE_DEFAULT_THRESHOLD, PaneCancelReason,
84    PaneDragResizeMachine, PaneDragResizeMachineError, PaneDragResizeState,
85    PaneDragResizeTransition, PaneInertialThrow, PaneLayout, PaneModifierSnapshot,
86    PaneMotionVector, PaneNodeKind, PanePointerButton, PanePointerPosition,
87    PanePressureSnapProfile, PaneResizeDirection, PaneResizeTarget, PaneSemanticInputEvent,
88    PaneSemanticInputEventKind, PaneTree, Rect, SplitAxis,
89};
90use ftui_render::arena::FrameArena;
91use ftui_render::budget::{
92    BudgetControllerConfig, BudgetDecision, BudgetDecisionReason, DegradationLevel,
93    FrameBudgetConfig, RenderBudget,
94};
95use ftui_render::buffer::Buffer;
96use ftui_render::diff_strategy::DiffStrategy;
97use ftui_render::frame::{Frame, HitData, HitId, HitRegion, WidgetBudget, WidgetSignal};
98use ftui_render::frame_guardrails::{
99    AlertSeverity, FrameGuardrails, GuardrailKind, GuardrailsConfig,
100};
101use ftui_render::sanitize::{SanitizeMode, Text};
102use std::any::Any;
103use std::collections::HashMap;
104use std::io::{self, Stdout};
105use std::panic::{self, AssertUnwindSafe};
106use std::sync::Arc;
107
108/// Check for pending termination signal. Returns `None` when crossterm is not
109/// enabled (headless / wasm builds don't install signal handlers).
110#[inline]
111fn check_termination_signal() -> Option<i32> {
112    ftui_core::shutdown_signal::pending_termination_signal()
113}
114
115/// Clear the pending termination signal.
116#[inline]
117fn clear_termination_signal() {
118    ftui_core::shutdown_signal::clear_pending_termination_signal();
119}
120
121/// Name of the terminal backend that [`AppBuilder::run`] and `Program::open`
122/// select in this build: `"native"` (ftui-tty, Unix), `"crossterm"`, or
123/// `"none"` when neither backend feature was compiled (in which case
124/// `Program::open` and `DefaultProgram` do not exist).
125#[cfg(all(feature = "native-backend", unix))]
126pub const DEFAULT_BACKEND: &str = "native";
127/// Name of the terminal backend that [`AppBuilder::run`] and `Program::open`
128/// select in this build: `"native"` (ftui-tty, Unix), `"crossterm"`, or
129/// `"none"` when neither backend feature was compiled (in which case
130/// `Program::open` and `DefaultProgram` do not exist).
131#[cfg(all(
132    feature = "crossterm-compat",
133    not(all(feature = "native-backend", unix))
134))]
135pub const DEFAULT_BACKEND: &str = "crossterm";
136/// Name of the terminal backend that [`AppBuilder::run`] and `Program::open`
137/// select in this build: `"native"` (ftui-tty, Unix), `"crossterm"`, or
138/// `"none"` when neither backend feature was compiled (in which case
139/// `Program::open` and `DefaultProgram` do not exist).
140#[cfg(not(any(all(feature = "native-backend", unix), feature = "crossterm-compat")))]
141pub const DEFAULT_BACKEND: &str = "none";
142
143/// Error text returned by [`AppBuilder::run`] when no terminal backend was compiled.
144pub const NO_BACKEND_MESSAGE: &str =
145    "no terminal backend compiled: enable `native-backend` (unix) or `crossterm-compat`";
146
147/// The concrete [`Program`] type that `Program::open` returns in this build.
148#[cfg(all(feature = "native-backend", unix))]
149pub type DefaultProgram<M> = Program<M, ftui_tty::TtyBackend, TerminalPresenter<Stdout>>;
150/// The concrete [`Program`] type that `Program::open` returns in this build.
151#[cfg(all(
152    feature = "crossterm-compat",
153    not(all(feature = "native-backend", unix))
154))]
155pub type DefaultProgram<M> = Program<M, CrosstermEventSource, TerminalPresenter<Stdout>>;
156
157/// Ask the live terminal what environment detection could not establish.
158///
159/// Runs once per interactive session, after raw mode is active, and only
160/// for the two capabilities that matter for correctness and that identity
161/// heuristics routinely get wrong:
162///
163/// - **Truecolor**, when detection settled on 256 colors: an `ssh` hop
164///   forwards `TERM` but strips `COLORTERM`/`TERM_PROGRAM`, so a truecolor
165///   terminal is mis-detected. The XTGETTCAP `RGB` query round-trips to the
166///   real terminal. Restricted to the 256-color case so explicit monochrome
167///   policy (`NO_COLOR`, dumb/vt100) can never be upgraded.
168/// - **Synchronized output (DEC 2026)**, when the identity allowlist did not
169///   enable it: plain `xterm-256color`, iTerm2, VS Code and every terminal
170///   behind ssh support flicker-free frames but were rendered without them.
171///   The DECRPM `?2026$p` query is authoritative. Skipped inside a
172///   multiplexer, where `use_sync_output()` would veto the result anyway.
173///
174/// Every probe is bounded by a timeout, fail-open (a non-answer changes
175/// nothing) and upgrade-only. `FTUI_CAPS_PROBE=0` disables probing.
176#[cfg(any(all(feature = "native-backend", unix), feature = "crossterm-compat"))]
177fn probe_live_terminal(
178    capabilities: &mut ftui_core::terminal_capabilities::TerminalCapabilities,
179) -> Vec<ftui_core::caps_probe::CapabilityDecision> {
180    use ftui_core::caps_probe::{
181        ProbeConfig, ProbeResult, decisions_from_probe, probe_capabilities,
182    };
183
184    let before = *capabilities;
185    let probing_disabled = std::env::var_os("FTUI_CAPS_PROBE").is_some_and(|value| value == "0");
186    let wants_truecolor = !probing_disabled
187        && capabilities.color_depth == ftui_core::terminal_capabilities::ColorDepth::Ansi256;
188    let wants_sync_output =
189        !probing_disabled && !capabilities.sync_output && !capabilities.in_any_mux();
190    let config = ProbeConfig {
191        timeout: std::time::Duration::from_millis(300),
192        probe_da1: false,
193        probe_da2: false,
194        probe_background: false,
195        probe_truecolor: wants_truecolor,
196        probe_sync_output: wants_sync_output,
197    };
198    let probe = if wants_truecolor || wants_sync_output {
199        let probe = probe_capabilities(&config);
200        capabilities.refine_from_probe(&probe);
201        probe
202    } else {
203        ProbeResult::default()
204    };
205    // The operator switches (sync output, scroll region, OSC 52) outrank
206    // everything, including a terminal that answers the probe positively.
207    // (`with_overrides()` applied them once already; re-applying after the
208    // probe is what makes them win over a positive answer.)
209    let overrides = ftui_core::capability_override::apply_env_policy_overrides(capabilities);
210    #[cfg(feature = "tracing")]
211    tracing::debug!(
212        target: crate::telemetry_schema::TARGET_RUNTIME,
213        probed_truecolor = wants_truecolor,
214        probed_sync_output = wants_sync_output,
215        truecolor = ?probe.true_color,
216        sync_output = ?probe.sync_output,
217        "live terminal capability probe"
218    );
219    // Every session gets a decision ledger, probed or not, so the evidence
220    // file always says why sync output / scroll regions are on or off.
221    decisions_from_probe(&before, &config, &probe, overrides, capabilities)
222}
223
224/// Outcome of the DECSTBM self-test for the writer: the verdict (or `None`
225/// when the test did not run) plus the geometry it was judged against.
226#[cfg(any(all(feature = "native-backend", unix), feature = "crossterm-compat"))]
227struct ScrollRegionCheck {
228    verdict: Option<ftui_core::caps_probe::ScrollRegionVerdict>,
229    rows: u16,
230    region_bottom: u16,
231}
232
233/// Run the DECSTBM self-test (`caps_probe::probe_scroll_region`) when the
234/// selected inline strategy is going to rely on a scroll region. Runs right
235/// after `probe_live_terminal`, with raw mode on and no input reader alive,
236/// so the reply cannot race the event loop. Skipped for the alternate
237/// screen, when the terminal is a multiplexer or lacks the capability
238/// (overlay redraw is selected anyway), when `FTUI_SCROLL_REGION=1` trusts
239/// the region explicitly, when `FTUI_CAPS_PROBE=0` disables probing, or
240/// when the UI leaves no region to test.
241#[cfg(any(all(feature = "native-backend", unix), feature = "crossterm-compat"))]
242fn verify_scroll_region(
243    capabilities: &ftui_core::terminal_capabilities::TerminalCapabilities,
244    screen_mode: ScreenMode,
245    size: Option<(u16, u16)>,
246) -> ScrollRegionCheck {
247    use ftui_core::inline_mode::InlineStrategy;
248
249    let ui_height = match screen_mode {
250        ScreenMode::Inline { ui_height } => ui_height,
251        ScreenMode::InlineAuto { max_height, .. } => max_height,
252        ScreenMode::AltScreen => 0,
253    };
254    let rows = size.map_or(0, |(_, rows)| rows);
255    let region_bottom = rows.saturating_sub(ui_height);
256    let skip = ScrollRegionCheck {
257        verdict: None,
258        rows,
259        region_bottom,
260    };
261    if ui_height == 0 || rows == 0 {
262        return skip;
263    }
264    if !matches!(
265        InlineStrategy::select(capabilities),
266        InlineStrategy::ScrollRegion | InlineStrategy::Hybrid
267    ) {
268        return skip;
269    }
270    let env = |name: &str| std::env::var_os(name);
271    if env("FTUI_CAPS_PROBE").is_some_and(|value| value == "0")
272        || env("FTUI_SCROLL_REGION").is_some_and(|value| value == "1")
273    {
274        return skip;
275    }
276    let verdict = ftui_core::caps_probe::probe_scroll_region(
277        rows,
278        ui_height,
279        std::time::Duration::from_millis(150),
280    );
281    #[cfg(feature = "tracing")]
282    tracing::debug!(
283        target: crate::telemetry_schema::span::RENDER_SCROLL_REGION,
284        rows,
285        region_bottom,
286        verdict = ?verdict,
287        "DECSTBM self-test"
288    );
289    ScrollRegionCheck {
290        verdict,
291        rows,
292        region_bottom,
293    }
294}
295
296/// Run a program to completion and translate a signal-termination error into
297/// the conventional `128 + signal` process exit, after the program (and with it
298/// the terminal session) has been dropped and the terminal restored.
299///
300/// Shared by every [`AppBuilder`] run method so the three backend paths cannot
301/// drift in how they honor the `SignalTerminationError` contract.
302#[cfg(any(all(feature = "native-backend", unix), feature = "crossterm-compat"))]
303fn finish_run<M, E, P>(mut program: Program<M, E, P>) -> io::Result<()>
304where
305    M: Model,
306    E: BackendEventSource<Error = io::Error>,
307    P: BackendPresenter<Error = io::Error>,
308{
309    let result = program.run();
310    if let Err(ref err) = result
311        && let Some(signal) = signal_termination_from_error(err)
312    {
313        drop(program);
314        std::process::exit(128 + signal);
315    }
316    result
317}
318use std::sync::mpsc;
319use std::thread::{self, JoinHandle};
320use tracing::{debug, debug_span, info, info_span, trace};
321use web_time::{Duration, Instant};
322
323/// The accessibility tree built for one rendered frame, handed to
324/// [`Model::on_accessibility`] whenever the tree changed (requires
325/// [`ProgramConfig::accessibility`]).
326#[derive(Debug, Clone, Copy)]
327pub struct AccessibilityFrame<'a> {
328    /// Index of the frame the tree was built from.
329    pub frame_idx: u64,
330    /// The tree: the nodes widgets pushed during `view`, with the first
331    /// parentless node as the root unless the view set one explicitly.
332    pub tree: &'a A11yTree,
333    /// Reading order: node IDs in widget push order.
334    pub order: &'a [u64],
335    /// Screen-reader announcements derived from the diff against the
336    /// previous frame, bounded by the configured [`ScreenReaderPolicy`].
337    pub announcements: &'a [ScreenReaderAnnouncement],
338    /// Announcements the policy cap dropped this frame.
339    pub dropped: usize,
340}
341
342impl AccessibilityFrame<'_> {
343    /// Indented, one-node-per-line dump of the tree in reading order.
344    #[must_use]
345    pub fn dump(&self) -> String {
346        self.tree.dump_text(self.order)
347    }
348}
349
350/// The Model trait defines application state and behavior.
351///
352/// Implementations define how the application responds to events
353/// and renders its current state.
354pub trait Model: Sized {
355    /// The message type for this model.
356    ///
357    /// Messages represent actions that update the model state.
358    /// Must be convertible from terminal events.
359    type Message: From<Event> + Send + 'static;
360
361    /// Initialize the model with startup commands.
362    ///
363    /// Called once when the program starts. Return commands to execute
364    /// initial side effects like loading data.
365    fn init(&mut self) -> Cmd<Self::Message> {
366        Cmd::none()
367    }
368
369    /// Update the model in response to a message.
370    ///
371    /// This is the core state transition function. Returns commands
372    /// for any side effects that should be executed.
373    fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message>;
374
375    /// Render the current state to a frame.
376    ///
377    /// Called after updates when the UI needs to be redrawn.
378    fn view(&self, frame: &mut Frame);
379
380    /// Declare active subscriptions.
381    ///
382    /// Called after each `update()`. The runtime compares the returned set
383    /// (by `SubId`) against currently running subscriptions and starts/stops
384    /// as needed. Returning an empty vec stops all subscriptions.
385    ///
386    /// # Default
387    ///
388    /// Returns an empty vec (no subscriptions).
389    fn subscriptions(&self) -> Vec<Box<dyn crate::subscription::Subscription<Self::Message>>> {
390        vec![]
391    }
392
393    /// React to a recognized gesture: click, double/triple click, long
394    /// press, drag start/move/end/cancel, or key chord (see
395    /// [`SemanticEvent`](ftui_core::semantic_event::SemanticEvent)).
396    ///
397    /// Only called when [`ProgramConfig::gestures`] is set. The runtime then
398    /// feeds every input event through a
399    /// [`GestureRecognizer`](ftui_core::gesture::GestureRecognizer) after the
400    /// ordinary `update()` call and delivers each recognized gesture here;
401    /// long presses are checked once per tick. Raw events keep flowing to
402    /// `update()` unchanged, so enabling gestures never alters existing
403    /// behavior. Default: ignore gestures.
404    fn on_gesture(
405        &mut self,
406        gesture: ftui_core::semantic_event::SemanticEvent,
407    ) -> Cmd<Self::Message> {
408        let _ = gesture;
409        Cmd::none()
410    }
411
412    /// React to a changed accessibility tree: inspect the tree the last
413    /// frame produced and the screen-reader announcements derived from its
414    /// diff (see [`AccessibilityFrame`]). Typical uses: mirror the
415    /// announcements into an on-screen live region or a screen-reader
416    /// bridge, or expose the tree in a debug panel.
417    ///
418    /// Only called when [`ProgramConfig::accessibility`] is set, and only
419    /// for frames whose tree differs from the previous one; it runs after
420    /// the frame was presented and the runtime schedules one more frame
421    /// so state changed here is rendered. Default: ignore.
422    fn on_accessibility(&mut self, a11y: AccessibilityFrame<'_>) -> Cmd<Self::Message> {
423        let _ = a11y;
424        Cmd::none()
425    }
426
427    /// Downcast to [`ScreenTickDispatch`](crate::tick_strategy::ScreenTickDispatch)
428    /// for per-screen tick control.
429    ///
430    /// Override this to return `Some(self)` in multi-screen Models. The runtime
431    /// will then consult the active [`TickStrategy`](crate::tick_strategy::TickStrategy)
432    /// for each inactive screen instead of ticking monolithically.
433    ///
434    /// Default: `None` (all screens tick every frame, backwards-compatible).
435    fn as_screen_tick_dispatch(
436        &mut self,
437    ) -> Option<&mut dyn crate::tick_strategy::ScreenTickDispatch> {
438        None
439    }
440
441    /// Called before the runtime exits, whether via [`Cmd::Quit`] or signal.
442    ///
443    /// Return cleanup commands (e.g., saving state, closing connections).
444    /// The runtime executes these before teardown.
445    ///
446    /// # Migration rationale
447    ///
448    /// Source frameworks use `componentWillUnmount`, `useEffect` cleanup, or
449    /// `beforeDestroy` hooks. This provides an equivalent lifecycle point.
450    fn on_shutdown(&mut self) -> Cmd<Self::Message> {
451        Cmd::none()
452    }
453
454    /// Called when a runtime, command, or background subscription error occurs.
455    ///
456    /// Return commands for error recovery or graceful degradation. The
457    /// `error` string contains the error description. Fatal runtime and
458    /// command errors still terminate after this hook runs; isolated
459    /// subscription failures may recover and keep the program running.
460    ///
461    /// # Migration rationale
462    ///
463    /// Source frameworks use `componentDidCatch`, error boundaries, or
464    /// `onError` hooks. This provides an equivalent error recovery point.
465    fn on_error(&mut self, _error: &str) -> Cmd<Self::Message> {
466        Cmd::none()
467    }
468}
469
470/// Default weight assigned to background tasks.
471const DEFAULT_TASK_WEIGHT: f64 = 1.0;
472
473/// Frames between soft-tier memory capacity trims.
474///
475/// A soft alert fires on retained capacity; trimming (arena rebuild +
476/// grapheme-pool gc) releases it so the sensor can move again, but trimming
477/// every alerting frame would thrash allocations when usage hovers near the
478/// limit. One trim per 60 alerting frames bounds that churn (bd-1za0z).
479const SOFT_TRIM_COOLDOWN_FRAMES: u64 = 60;
480
481/// Default estimated task cost (ms) used for scheduling.
482const DEFAULT_TASK_ESTIMATE_MS: f64 = 10.0;
483
484/// Scheduling metadata for background tasks.
485#[derive(Debug, Clone)]
486pub struct TaskSpec {
487    /// Task weight (importance). Higher = more priority.
488    pub weight: f64,
489    /// Estimated task cost in milliseconds.
490    pub estimate_ms: f64,
491    /// Optional task name for evidence logging.
492    pub name: Option<String>,
493}
494
495impl Default for TaskSpec {
496    fn default() -> Self {
497        Self {
498            weight: DEFAULT_TASK_WEIGHT,
499            estimate_ms: DEFAULT_TASK_ESTIMATE_MS,
500            name: None,
501        }
502    }
503}
504
505impl TaskSpec {
506    /// Create a task spec with an explicit weight and estimate.
507    #[must_use]
508    pub fn new(weight: f64, estimate_ms: f64) -> Self {
509        Self {
510            weight,
511            estimate_ms,
512            name: None,
513        }
514    }
515
516    /// Attach a task name for diagnostics.
517    #[must_use]
518    pub fn with_name(mut self, name: impl Into<String>) -> Self {
519        self.name = Some(name.into());
520        self
521    }
522}
523
524/// Per-frame timing data for profiling.
525#[derive(Debug, Clone, Copy)]
526pub struct FrameTiming {
527    pub frame_idx: u64,
528    pub update_us: u64,
529    pub render_us: u64,
530    pub diff_us: u64,
531    pub present_us: u64,
532    pub total_us: u64,
533}
534
535#[derive(Debug)]
536struct SignalTerminationError {
537    signal: i32,
538}
539
540impl std::fmt::Display for SignalTerminationError {
541    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
542        write!(f, "terminated by signal {}", self.signal)
543    }
544}
545
546impl std::error::Error for SignalTerminationError {}
547
548/// If this error represents an interrupted runtime terminated by a signal,
549/// return the signal number (e.g. 15 for SIGTERM, 2 for SIGINT).
550#[must_use]
551pub fn signal_termination_from_error(err: &io::Error) -> Option<i32> {
552    err.get_ref()
553        .and_then(|inner| inner.downcast_ref::<SignalTerminationError>())
554        .map(|inner| inner.signal)
555}
556
557/// Sink for frame timing events.
558pub trait FrameTimingSink: Send + Sync {
559    fn record_frame(&self, timing: &FrameTiming);
560}
561
562/// Configuration for frame timing capture.
563#[derive(Clone)]
564pub struct FrameTimingConfig {
565    pub sink: Arc<dyn FrameTimingSink>,
566}
567
568impl FrameTimingConfig {
569    #[must_use]
570    pub fn new(sink: Arc<dyn FrameTimingSink>) -> Self {
571        Self { sink }
572    }
573}
574
575impl std::fmt::Debug for FrameTimingConfig {
576    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
577        f.debug_struct("FrameTimingConfig")
578            .field("sink", &"<dyn FrameTimingSink>")
579            .finish()
580    }
581}
582
583/// Clipboard requests captured by host-driven runners and test simulators.
584#[derive(Debug, Clone, PartialEq, Eq)]
585pub enum ClipboardRequest {
586    /// Copy text to the system clipboard.
587    Set(String),
588    /// Request clipboard text; the host delivers an `Event::Clipboard` reply.
589    Get,
590}
591
592/// Commands represent side effects to be executed by the runtime.
593///
594/// Commands are returned from `init()` and `update()` to trigger
595/// actions like quitting, sending messages, or scheduling ticks.
596#[derive(Default)]
597pub enum Cmd<M> {
598    /// No operation.
599    #[default]
600    None,
601    /// Quit the application.
602    Quit,
603    /// Execute multiple commands as a batch (currently sequential).
604    Batch(Vec<Cmd<M>>),
605    /// Execute commands sequentially.
606    Sequence(Vec<Cmd<M>>),
607    /// Send a message to the model.
608    Msg(M),
609    /// Schedule a tick after a duration.
610    Tick(Duration),
611    /// Write a log message to the terminal output.
612    ///
613    /// This writes to the scrollback region in inline mode, or is ignored/handled
614    /// appropriately in alternate screen mode. The policy is applied at the
615    /// output boundary. Prefer [`Cmd::log`] or [`Cmd::log_sgr_only`]; raw output
616    /// is an explicit opt-in that can corrupt terminal state.
617    Log { text: String, mode: SanitizeMode },
618    /// Execute a blocking operation on a background thread.
619    ///
620    /// When effect queue scheduling is enabled, tasks are enqueued and executed
621    /// in Smith-rule order on a dedicated worker thread. Otherwise the closure
622    /// runs on a spawned thread immediately. The return value is sent back
623    /// as a message to the model.
624    Task(TaskSpec, Box<dyn FnOnce() -> M + Send>),
625    /// Save widget state to the persistence registry.
626    ///
627    /// Triggers a flush of the state registry to the storage backend.
628    /// No-op if persistence is not configured.
629    SaveState,
630    /// Restore widget state from the persistence registry.
631    ///
632    /// Triggers a load from the storage backend and updates the cache.
633    /// No-op if persistence is not configured. Returns a message via
634    /// callback if state was successfully restored.
635    RestoreState,
636    /// Toggle mouse capture at runtime.
637    ///
638    /// Instructs the terminal session to enable or disable mouse event capture.
639    /// No-op in test simulators.
640    SetMouseCapture(bool),
641    /// Copy text using OSC 52 on supported terminals.
642    SetClipboard(String),
643    /// Request clipboard text asynchronously as an `Event::Clipboard` reply.
644    /// Unsupported terminals may ignore the request; no reply is guaranteed.
645    GetClipboard,
646    /// Replace the tick strategy at runtime.
647    ///
648    /// Takes ownership of a boxed strategy. Use when switching from one
649    /// strategy to another (e.g., `Uniform` โ†’ `Predictive` after loading
650    /// persisted transition data).
651    SetTickStrategy(Box<dyn crate::tick_strategy::TickStrategy>),
652}
653
654impl<M: std::fmt::Debug> std::fmt::Debug for Cmd<M> {
655    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
656        match self {
657            Self::None => write!(f, "None"),
658            Self::Quit => write!(f, "Quit"),
659            Self::Batch(cmds) => f.debug_tuple("Batch").field(cmds).finish(),
660            Self::Sequence(cmds) => f.debug_tuple("Sequence").field(cmds).finish(),
661            Self::Msg(m) => f.debug_tuple("Msg").field(m).finish(),
662            Self::Tick(d) => f.debug_tuple("Tick").field(d).finish(),
663            Self::Log { text, mode } => f.debug_tuple("Log").field(text).field(mode).finish(),
664            Self::Task(spec, _) => f.debug_struct("Task").field("spec", spec).finish(),
665            Self::SaveState => write!(f, "SaveState"),
666            Self::RestoreState => write!(f, "RestoreState"),
667            Self::SetMouseCapture(b) => write!(f, "SetMouseCapture({b})"),
668            Self::SetClipboard(text) => f
669                .debug_struct("SetClipboard")
670                .field("bytes", &text.len())
671                .finish(),
672            Self::GetClipboard => write!(f, "GetClipboard"),
673            Self::SetTickStrategy(s) => write!(f, "SetTickStrategy({})", s.name()),
674        }
675    }
676}
677
678impl<M> Cmd<M> {
679    /// Create a no-op command.
680    #[inline]
681    pub fn none() -> Self {
682        Self::None
683    }
684
685    /// Create a quit command.
686    #[inline]
687    pub fn quit() -> Self {
688        Self::Quit
689    }
690
691    /// Create a message command.
692    #[inline]
693    pub fn msg(m: M) -> Self {
694        Self::Msg(m)
695    }
696
697    /// Create a log command.
698    ///
699    /// The message will be sanitized and written to the terminal log (scrollback).
700    /// A newline is appended if not present.
701    #[inline]
702    pub fn log(msg: impl Into<String>) -> Self {
703        Self::Log {
704            text: msg.into(),
705            mode: SanitizeMode::Strip,
706        }
707    }
708
709    /// Log colored text while filtering cursor, clipboard and terminal controls.
710    ///
711    /// The native writer permits only bounded SGR styling and resets styles at
712    /// each line/write. As with [`Self::log`], native output normalizes newlines
713    /// to CRLF and appends a final newline; overlay mode displays only the first
714    /// width-clamped line. Capturing hosts retain logical text without adding
715    /// terminal newlines or reset sequences.
716    #[inline]
717    pub fn log_sgr_only(msg: impl Into<String>) -> Self {
718        Self::Log {
719            text: msg.into(),
720            mode: SanitizeMode::SgrOnly,
721        }
722    }
723
724    /// Log trusted text, including arbitrary terminal commands.
725    ///
726    /// The caller asserts the contents are trusted. Cursor movement, mode
727    /// changes and clearing can corrupt inline chrome. Prefer
728    /// [`Self::log_sgr_only`] for compiler/test output. This is a logical log
729    /// message: native CRLF normalization and final-newline insertion still
730    /// apply, so this is not a byte-transparent transport.
731    #[inline]
732    pub fn log_raw(msg: impl Into<String>) -> Self {
733        Self::Log {
734            text: msg.into(),
735            mode: SanitizeMode::Raw,
736        }
737    }
738
739    /// Log annotated text using its explicit output policy.
740    ///
741    /// The output boundary reapplies the policy even when the marker was
742    /// constructed directly. See [`Self::log_raw`] for trusted-text behavior.
743    pub fn log_text(text: Text<'_>) -> Self {
744        Self::Log {
745            text: text.as_str().to_owned(),
746            mode: text.mode(),
747        }
748    }
749
750    /// Create a batch of commands.
751    pub fn batch(cmds: Vec<Self>) -> Self {
752        if cmds.is_empty() {
753            Self::None
754        } else if cmds.len() == 1 {
755            cmds.into_iter().next().unwrap_or(Self::None)
756        } else {
757            Self::Batch(cmds)
758        }
759    }
760
761    /// Create a sequence of commands.
762    pub fn sequence(cmds: Vec<Self>) -> Self {
763        if cmds.is_empty() {
764            Self::None
765        } else if cmds.len() == 1 {
766            cmds.into_iter().next().unwrap_or(Self::None)
767        } else {
768            Self::Sequence(cmds)
769        }
770    }
771
772    /// Return a stable name for telemetry and tracing.
773    #[inline]
774    pub fn type_name(&self) -> &'static str {
775        match self {
776            Self::None => "None",
777            Self::Quit => "Quit",
778            Self::Batch(_) => "Batch",
779            Self::Sequence(_) => "Sequence",
780            Self::Msg(_) => "Msg",
781            Self::Tick(_) => "Tick",
782            Self::Log { .. } => "Log",
783            Self::Task(..) => "Task",
784            Self::SaveState => "SaveState",
785            Self::RestoreState => "RestoreState",
786            Self::SetMouseCapture(_) => "SetMouseCapture",
787            Self::SetClipboard(_) => "SetClipboard",
788            Self::GetClipboard => "GetClipboard",
789            Self::SetTickStrategy(_) => "SetTickStrategy",
790        }
791    }
792
793    /// Create a tick command.
794    #[inline]
795    pub fn tick(duration: Duration) -> Self {
796        Self::Tick(duration)
797    }
798
799    /// Create a background task command.
800    ///
801    /// The closure runs on a spawned thread (or the effect queue worker when
802    /// scheduling is enabled). When it completes, the returned message is
803    /// sent back to the model's `update()`.
804    pub fn task<F>(f: F) -> Self
805    where
806        F: FnOnce() -> M + Send + 'static,
807    {
808        Self::Task(TaskSpec::default(), Box::new(f))
809    }
810
811    /// Create a background task command with explicit scheduling metadata.
812    pub fn task_with_spec<F>(spec: TaskSpec, f: F) -> Self
813    where
814        F: FnOnce() -> M + Send + 'static,
815    {
816        Self::Task(spec, Box::new(f))
817    }
818
819    /// Create a background task command with explicit weight and estimate.
820    pub fn task_weighted<F>(weight: f64, estimate_ms: f64, f: F) -> Self
821    where
822        F: FnOnce() -> M + Send + 'static,
823    {
824        Self::Task(TaskSpec::new(weight, estimate_ms), Box::new(f))
825    }
826
827    /// Create a named background task command.
828    pub fn task_named<F>(name: impl Into<String>, f: F) -> Self
829    where
830        F: FnOnce() -> M + Send + 'static,
831    {
832        Self::Task(TaskSpec::default().with_name(name), Box::new(f))
833    }
834
835    /// Replace the active tick strategy at runtime.
836    ///
837    /// Use when switching strategies (e.g., `Uniform` โ†’ `Predictive` after
838    /// loading persisted transition data).
839    pub fn set_tick_strategy(strategy: impl crate::tick_strategy::TickStrategy + 'static) -> Self {
840        Self::SetTickStrategy(Box::new(strategy))
841    }
842
843    /// Create a save state command.
844    ///
845    /// Triggers a flush of the state registry to the storage backend.
846    /// No-op if persistence is not configured.
847    #[inline]
848    pub fn save_state() -> Self {
849        Self::SaveState
850    }
851
852    /// Create a restore state command.
853    ///
854    /// Triggers a load from the storage backend.
855    /// No-op if persistence is not configured.
856    #[inline]
857    pub fn restore_state() -> Self {
858        Self::RestoreState
859    }
860
861    /// Create a mouse capture toggle command.
862    ///
863    /// Instructs the runtime to enable or disable mouse event capture on the
864    /// underlying terminal session.
865    #[inline]
866    pub fn set_mouse_capture(enabled: bool) -> Self {
867        Self::SetMouseCapture(enabled)
868    }
869
870    /// Copy text to the system clipboard through the runtime's output owner.
871    pub fn set_clipboard(text: impl Into<String>) -> Self {
872        Self::SetClipboard(text.into())
873    }
874
875    /// Request clipboard text. Handle `Event::Clipboard` for the reply.
876    pub fn get_clipboard() -> Self {
877        Self::GetClipboard
878    }
879
880    /// Count the number of atomic commands in this command.
881    ///
882    /// Returns 0 for None, 1 for atomic commands, and recursively counts for Batch/Sequence.
883    pub fn count(&self) -> usize {
884        match self {
885            Self::None => 0,
886            Self::Batch(cmds) | Self::Sequence(cmds) => cmds.iter().map(Self::count).sum(),
887            _ => 1,
888        }
889    }
890}
891
892/// Resize handling behavior for the runtime.
893#[derive(Debug, Clone, Copy, PartialEq, Eq)]
894pub enum ResizeBehavior {
895    /// Apply resize immediately (no debounce, no placeholder).
896    Immediate,
897    /// Coalesce resize events for continuous reflow.
898    Throttled,
899}
900
901impl ResizeBehavior {
902    const fn uses_coalescer(self) -> bool {
903        matches!(self, ResizeBehavior::Throttled)
904    }
905}
906
907/// Policy controlling when terminal mouse capture is enabled.
908///
909/// Mouse capture can steal normal scrollback interaction in inline mode.
910/// `Auto` keeps inline mode scrollback-safe while still enabling mouse in
911/// alt-screen mode.
912#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
913pub enum MouseCapturePolicy {
914    /// Enable in alt-screen mode, disable in inline modes.
915    #[default]
916    Auto,
917    /// Always enable mouse capture.
918    On,
919    /// Always disable mouse capture.
920    Off,
921}
922
923impl MouseCapturePolicy {
924    /// Resolve the policy to a concrete mouse-capture toggle.
925    #[must_use]
926    pub const fn resolve(self, screen_mode: ScreenMode) -> bool {
927        match self {
928            Self::Auto => matches!(screen_mode, ScreenMode::AltScreen),
929            Self::On => true,
930            Self::Off => false,
931        }
932    }
933}
934
935const PANE_TERMINAL_DEFAULT_HIT_THICKNESS: u16 = 3;
936const PANE_TERMINAL_TARGET_AXIS_MASK: u64 = 0b1;
937
938/// One splitter handle region in terminal cell-space.
939#[derive(Debug, Clone, Copy, PartialEq, Eq)]
940pub struct PaneTerminalSplitterHandle {
941    /// Semantic resize target represented by this handle.
942    pub target: PaneResizeTarget,
943    /// Cell-space hit rectangle for this handle.
944    pub rect: Rect,
945    /// Split boundary coordinate used for deterministic nearest-target ranking.
946    pub boundary: i32,
947}
948
949/// Build deterministic splitter handle regions for terminal hit-testing.
950///
951/// Handles are emitted in split-id order and are clamped to the split rect.
952#[must_use]
953pub fn pane_terminal_splitter_handles(
954    tree: &PaneTree,
955    layout: &PaneLayout,
956    hit_thickness: u16,
957) -> Vec<PaneTerminalSplitterHandle> {
958    let thickness = if hit_thickness == 0 {
959        PANE_TERMINAL_DEFAULT_HIT_THICKNESS
960    } else {
961        hit_thickness
962    };
963    let mut handles = Vec::new();
964    for node in tree.nodes() {
965        let PaneNodeKind::Split(split) = &node.kind else {
966            continue;
967        };
968        let Some(split_rect) = layout.rect(node.id) else {
969            continue;
970        };
971        if split_rect.is_empty() {
972            continue;
973        }
974        let Some(first_rect) = layout.rect(split.first) else {
975            continue;
976        };
977        let Some(second_rect) = layout.rect(split.second) else {
978            continue;
979        };
980
981        let boundary_u16 = match split.axis {
982            SplitAxis::Horizontal => {
983                // Horizontal split => left/right panes => vertical splitter line.
984                if second_rect.x == split_rect.x {
985                    first_rect.right()
986                } else {
987                    second_rect.x
988                }
989            }
990            SplitAxis::Vertical => {
991                // Vertical split => top/bottom panes => horizontal splitter line.
992                if second_rect.y == split_rect.y {
993                    first_rect.bottom()
994                } else {
995                    second_rect.y
996                }
997            }
998        };
999        let Some(rect) = splitter_hit_rect(split.axis, split_rect, boundary_u16, thickness) else {
1000            continue;
1001        };
1002        handles.push(PaneTerminalSplitterHandle {
1003            target: PaneResizeTarget {
1004                split_id: node.id,
1005                axis: split.axis,
1006            },
1007            rect,
1008            boundary: i32::from(boundary_u16),
1009        });
1010    }
1011    handles
1012}
1013
1014/// Resolve a semantic splitter target from a terminal cell position.
1015///
1016/// If multiple handles overlap, chooses deterministically by:
1017/// 1) smallest distance to the splitter boundary, then
1018/// 2) smaller split_id, then
1019/// 3) horizontal axis before vertical axis.
1020#[must_use]
1021pub fn pane_terminal_resolve_splitter_target(
1022    handles: &[PaneTerminalSplitterHandle],
1023    x: u16,
1024    y: u16,
1025) -> Option<PaneResizeTarget> {
1026    let px = i32::from(x);
1027    let py = i32::from(y);
1028    let mut best: Option<((u32, u64, u8), PaneResizeTarget)> = None;
1029
1030    for handle in handles {
1031        if !rect_contains_cell(handle.rect, x, y) {
1032            continue;
1033        }
1034        let distance = match handle.target.axis {
1035            SplitAxis::Horizontal => px.abs_diff(handle.boundary),
1036            SplitAxis::Vertical => py.abs_diff(handle.boundary),
1037        };
1038        let axis_rank = match handle.target.axis {
1039            SplitAxis::Horizontal => 0,
1040            SplitAxis::Vertical => 1,
1041        };
1042        let key = (distance, handle.target.split_id.get(), axis_rank);
1043        if best.as_ref().is_none_or(|(best_key, _)| key < *best_key) {
1044            best = Some((key, handle.target));
1045        }
1046    }
1047
1048    best.map(|(_, target)| target)
1049}
1050
1051/// Register pane splitter handles into the frame hit-grid.
1052///
1053/// Each handle is registered as `HitRegion::Handle` with encoded target data.
1054/// Returns number of successfully-registered regions.
1055pub fn register_pane_terminal_splitter_hits(
1056    frame: &mut Frame,
1057    handles: &[PaneTerminalSplitterHandle],
1058    hit_id_base: u32,
1059) -> usize {
1060    let mut registered = 0usize;
1061    for (idx, handle) in handles.iter().enumerate() {
1062        let Ok(offset) = u32::try_from(idx) else {
1063            break;
1064        };
1065        let hit_id = HitId::new(hit_id_base.saturating_add(offset));
1066        if frame.register_hit(
1067            handle.rect,
1068            hit_id,
1069            HitRegion::Handle,
1070            encode_pane_resize_target(handle.target),
1071        ) {
1072            registered = registered.saturating_add(1);
1073        }
1074    }
1075    registered
1076}
1077
1078/// Decode pane resize target from a hit-grid tuple produced by pane handle registration.
1079#[must_use]
1080pub fn pane_terminal_target_from_hit(hit: (HitId, HitRegion, HitData)) -> Option<PaneResizeTarget> {
1081    let (_, region, data) = hit;
1082    if region != HitRegion::Handle {
1083        return None;
1084    }
1085    decode_pane_resize_target(data)
1086}
1087
1088fn splitter_hit_rect(
1089    axis: SplitAxis,
1090    split_rect: Rect,
1091    boundary: u16,
1092    thickness: u16,
1093) -> Option<Rect> {
1094    let half = thickness.saturating_sub(1) / 2;
1095    match axis {
1096        SplitAxis::Horizontal => {
1097            let start = boundary.saturating_sub(half).max(split_rect.x);
1098            let end = boundary
1099                .saturating_add(thickness.saturating_sub(half))
1100                .min(split_rect.right());
1101            let width = end.saturating_sub(start);
1102            (width > 0 && split_rect.height > 0).then_some(Rect::new(
1103                start,
1104                split_rect.y,
1105                width,
1106                split_rect.height,
1107            ))
1108        }
1109        SplitAxis::Vertical => {
1110            let start = boundary.saturating_sub(half).max(split_rect.y);
1111            let end = boundary
1112                .saturating_add(thickness.saturating_sub(half))
1113                .min(split_rect.bottom());
1114            let height = end.saturating_sub(start);
1115            (height > 0 && split_rect.width > 0).then_some(Rect::new(
1116                split_rect.x,
1117                start,
1118                split_rect.width,
1119                height,
1120            ))
1121        }
1122    }
1123}
1124
1125fn rect_contains_cell(rect: Rect, x: u16, y: u16) -> bool {
1126    x >= rect.x && x < rect.right() && y >= rect.y && y < rect.bottom()
1127}
1128
1129fn encode_pane_resize_target(target: PaneResizeTarget) -> HitData {
1130    let axis = match target.axis {
1131        SplitAxis::Horizontal => 0_u64,
1132        SplitAxis::Vertical => PANE_TERMINAL_TARGET_AXIS_MASK,
1133    };
1134    (target.split_id.get() << 1) | axis
1135}
1136
1137fn decode_pane_resize_target(data: HitData) -> Option<PaneResizeTarget> {
1138    let axis = if data & PANE_TERMINAL_TARGET_AXIS_MASK == 0 {
1139        SplitAxis::Horizontal
1140    } else {
1141        SplitAxis::Vertical
1142    };
1143    let split_id = ftui_layout::PaneId::new(data >> 1).ok()?;
1144    Some(PaneResizeTarget { split_id, axis })
1145}
1146
1147// ============================================================================
1148// Pane capability matrix for multiplexer / terminal compat (bd-6u66i)
1149// ============================================================================
1150
1151/// Which multiplexer environment the terminal is running inside.
1152#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1153pub enum PaneMuxEnvironment {
1154    /// No multiplexer detected โ€” direct terminal access.
1155    None,
1156    /// tmux (TMUX env var set, or DA2 terminal type 84).
1157    Tmux,
1158    /// GNU Screen (STY env var set, or DA2 terminal type 83).
1159    Screen,
1160    /// Zellij (ZELLIJ env var set).
1161    Zellij,
1162    /// WezTerm mux-served pane/session.
1163    WeztermMux,
1164}
1165
1166/// Resolved capability matrix describing which pane interaction features
1167/// are available in the current terminal + multiplexer environment.
1168///
1169/// Derived from [`ftui_core::terminal_capabilities::TerminalCapabilities`]
1170/// via [`PaneCapabilityMatrix::from_capabilities`].
1171/// The adapter uses this to decide which code-paths are safe and which
1172/// need deterministic fallbacks.
1173#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1174pub struct PaneCapabilityMatrix {
1175    /// Detected multiplexer environment.
1176    pub mux: PaneMuxEnvironment,
1177
1178    // --- Mouse input capabilities ---
1179    /// SGR (1006) extended mouse protocol available.
1180    /// Without this, mouse coordinates are limited to 223 columns/rows.
1181    pub mouse_sgr: bool,
1182    /// Mouse drag events are reliably delivered.
1183    /// False in some screen versions where drag tracking is incomplete.
1184    pub mouse_drag_reliable: bool,
1185    /// Mouse button events include correct button identity on release.
1186    /// X10/normal mode sends button 3 for all releases; SGR preserves it.
1187    pub mouse_button_discrimination: bool,
1188
1189    // --- Focus / lifecycle ---
1190    /// Terminal delivers CSI I / CSI O focus events.
1191    pub focus_events: bool,
1192    /// Bracketed paste mode available (affects interaction cancel heuristics).
1193    pub bracketed_paste: bool,
1194
1195    // --- Rendering affordances ---
1196    /// Unicode box-drawing glyphs available for splitter rendering.
1197    pub unicode_box_drawing: bool,
1198    /// True-color support for splitter highlight/drag feedback.
1199    pub true_color: bool,
1200
1201    // --- Fallback summary ---
1202    /// One or more pane features are degraded due to environment constraints.
1203    pub degraded: bool,
1204}
1205
1206/// Human-readable description of a known limitation and its fallback.
1207#[derive(Debug, Clone, PartialEq, Eq)]
1208pub struct PaneCapabilityLimitation {
1209    /// Short identifier (e.g. `"mouse_drag_unreliable"`).
1210    pub id: &'static str,
1211    /// What the limitation is.
1212    pub description: &'static str,
1213    /// What the adapter does instead.
1214    pub fallback: &'static str,
1215}
1216
1217impl PaneCapabilityMatrix {
1218    /// Derive the pane capability matrix from terminal capabilities.
1219    ///
1220    /// This is the single source of truth for which pane features are
1221    /// available. All fallback decisions flow from this matrix.
1222    #[must_use]
1223    pub fn from_capabilities(
1224        caps: &ftui_core::terminal_capabilities::TerminalCapabilities,
1225    ) -> Self {
1226        let mux = if caps.in_tmux {
1227            PaneMuxEnvironment::Tmux
1228        } else if caps.in_screen {
1229            PaneMuxEnvironment::Screen
1230        } else if caps.in_zellij {
1231            PaneMuxEnvironment::Zellij
1232        } else if caps.in_wezterm_mux {
1233            PaneMuxEnvironment::WeztermMux
1234        } else {
1235            PaneMuxEnvironment::None
1236        };
1237
1238        let mouse_sgr = caps.mouse_sgr;
1239
1240        // GNU Screen has historically unreliable drag event delivery.
1241        // tmux and zellij forward drags correctly in modern versions.
1242        let mouse_drag_reliable = !matches!(mux, PaneMuxEnvironment::Screen);
1243
1244        // Button discrimination requires SGR mouse protocol.
1245        // Without it, X10/normal mode reports button 3 for all releases.
1246        let mouse_button_discrimination = mouse_sgr;
1247
1248        // Focus events are conservatively disabled in any mux context.
1249        let focus_events = caps.focus_events && !caps.in_any_mux();
1250
1251        let bracketed_paste = caps.bracketed_paste;
1252        let unicode_box_drawing = caps.unicode_box_drawing;
1253        let true_color = caps.supports_true_color();
1254
1255        let degraded =
1256            !mouse_sgr || !mouse_drag_reliable || !mouse_button_discrimination || !focus_events;
1257
1258        Self {
1259            mux,
1260            mouse_sgr,
1261            mouse_drag_reliable,
1262            mouse_button_discrimination,
1263            focus_events,
1264            bracketed_paste,
1265            unicode_box_drawing,
1266            true_color,
1267            degraded,
1268        }
1269    }
1270
1271    /// Whether pane drag interactions should be enabled at all.
1272    ///
1273    /// Drag requires at minimum mouse event support. If drag events
1274    /// are unreliable (e.g. GNU Screen), drag is disabled and the
1275    /// adapter falls back to keyboard-only resize.
1276    #[must_use]
1277    pub const fn drag_enabled(&self) -> bool {
1278        self.mouse_drag_reliable
1279    }
1280
1281    /// Whether focus-loss auto-cancel is effective.
1282    ///
1283    /// When focus events are unavailable, the adapter cannot detect
1284    /// window blur โ€” interactions must rely on timeout or explicit
1285    /// keyboard cancel instead.
1286    #[must_use]
1287    pub const fn focus_cancel_effective(&self) -> bool {
1288        self.focus_events
1289    }
1290
1291    /// Collect all active limitations with their fallback descriptions.
1292    #[must_use]
1293    pub fn limitations(&self) -> Vec<PaneCapabilityLimitation> {
1294        let mut out = Vec::new();
1295
1296        if !self.mouse_sgr {
1297            out.push(PaneCapabilityLimitation {
1298                id: "no_sgr_mouse",
1299                description: "SGR mouse protocol not available; coordinates limited to 223 columns/rows",
1300                fallback: "Pane splitters beyond column 223 are unreachable by mouse; use keyboard resize",
1301            });
1302        }
1303
1304        if !self.mouse_drag_reliable {
1305            out.push(PaneCapabilityLimitation {
1306                id: "mouse_drag_unreliable",
1307                description: "Mouse drag events are unreliably delivered (e.g. GNU Screen)",
1308                fallback: "Mouse drag disabled; use keyboard arrow keys to resize panes",
1309            });
1310        }
1311
1312        if !self.mouse_button_discrimination {
1313            out.push(PaneCapabilityLimitation {
1314                id: "no_button_discrimination",
1315                description: "Mouse release events do not identify which button was released",
1316                fallback: "Any mouse release cancels the active drag; multi-button interactions unavailable",
1317            });
1318        }
1319
1320        if !self.focus_events {
1321            out.push(PaneCapabilityLimitation {
1322                id: "no_focus_events",
1323                description: "Terminal does not deliver focus-in/focus-out events",
1324                fallback: "Focus-loss auto-cancel disabled; use Escape key to cancel active drag",
1325            });
1326        }
1327
1328        out
1329    }
1330}
1331
1332/// Configuration for terminal-to-pane semantic input translation.
1333///
1334/// This adapter normalizes terminal `Event` streams into
1335/// `PaneSemanticInputEvent` values accepted by `PaneDragResizeMachine`.
1336#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1337pub struct PaneTerminalAdapterConfig {
1338    /// Drag start threshold in pane-local units.
1339    pub drag_threshold: u16,
1340    /// Drag update hysteresis threshold in pane-local units.
1341    pub update_hysteresis: u16,
1342    /// Mouse button required to begin a drag sequence.
1343    pub activation_button: PanePointerButton,
1344    /// Minimum drag delta (Manhattan distance, cells) before forwarding
1345    /// updates while already in the dragging state.
1346    pub drag_update_coalesce_distance: u16,
1347    /// Cancel active interactions on focus loss.
1348    pub cancel_on_focus_lost: bool,
1349    /// Cancel active interactions on terminal resize.
1350    pub cancel_on_resize: bool,
1351}
1352
1353impl Default for PaneTerminalAdapterConfig {
1354    fn default() -> Self {
1355        Self {
1356            drag_threshold: PANE_DRAG_RESIZE_DEFAULT_THRESHOLD,
1357            update_hysteresis: PANE_DRAG_RESIZE_DEFAULT_HYSTERESIS,
1358            activation_button: PanePointerButton::Primary,
1359            drag_update_coalesce_distance: 2,
1360            cancel_on_focus_lost: true,
1361            cancel_on_resize: true,
1362        }
1363    }
1364}
1365
1366#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1367struct PaneTerminalActivePointer {
1368    pointer_id: u32,
1369    target: PaneResizeTarget,
1370    button: PanePointerButton,
1371    last_position: PanePointerPosition,
1372    cumulative_delta_x: i32,
1373    cumulative_delta_y: i32,
1374    direction_changes: u16,
1375    sample_count: u32,
1376    previous_step_delta_x: i32,
1377    previous_step_delta_y: i32,
1378    start_time: Instant,
1379}
1380
1381/// Lifecycle phase observed while translating a terminal event.
1382#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1383pub enum PaneTerminalLifecyclePhase {
1384    MouseDown,
1385    MouseDrag,
1386    MouseMove,
1387    MouseUp,
1388    MouseScroll,
1389    KeyResize,
1390    KeyCancel,
1391    FocusLoss,
1392    ResizeInterrupt,
1393    Other,
1394}
1395
1396/// Deterministic reason a terminal event did not map to pane semantics.
1397#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1398pub enum PaneTerminalIgnoredReason {
1399    MissingTarget,
1400    NoActivePointer,
1401    PointerButtonMismatch,
1402    ActivationButtonRequired,
1403    WindowNotFocused,
1404    UnsupportedKey,
1405    FocusGainNoop,
1406    ResizeNoop,
1407    DragCoalesced,
1408    NonSemanticEvent,
1409    MachineRejectedEvent,
1410}
1411
1412/// Translation outcome for one raw terminal event.
1413#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1414pub enum PaneTerminalLogOutcome {
1415    SemanticForwarded,
1416    SemanticForwardedAfterRecovery,
1417    Ignored(PaneTerminalIgnoredReason),
1418}
1419
1420/// Structured translation log entry for one raw terminal event.
1421#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1422pub struct PaneTerminalLogEntry {
1423    pub phase: PaneTerminalLifecyclePhase,
1424    pub sequence: Option<u64>,
1425    pub pointer_id: Option<u32>,
1426    pub target: Option<PaneResizeTarget>,
1427    pub recovery_cancel_sequence: Option<u64>,
1428    pub outcome: PaneTerminalLogOutcome,
1429}
1430
1431/// Output of one terminal event translation step.
1432///
1433/// `recovery_*` fields are populated when the adapter first emits an internal
1434/// cancel (for stale/missing mouse-up recovery) and then forwards the incoming
1435/// event as a fresh semantic event.
1436#[derive(Debug, Clone, PartialEq)]
1437pub struct PaneTerminalDispatch {
1438    pub primary_event: Option<PaneSemanticInputEvent>,
1439    pub primary_transition: Option<PaneDragResizeTransition>,
1440    pub motion: Option<PaneMotionVector>,
1441    pub inertial_throw: Option<PaneInertialThrow>,
1442    pub projected_position: Option<PanePointerPosition>,
1443    pub recovery_event: Option<PaneSemanticInputEvent>,
1444    pub recovery_transition: Option<PaneDragResizeTransition>,
1445    pub log: PaneTerminalLogEntry,
1446}
1447
1448impl PaneTerminalDispatch {
1449    fn ignored(
1450        phase: PaneTerminalLifecyclePhase,
1451        reason: PaneTerminalIgnoredReason,
1452        pointer_id: Option<u32>,
1453        target: Option<PaneResizeTarget>,
1454    ) -> Self {
1455        Self {
1456            primary_event: None,
1457            primary_transition: None,
1458            motion: None,
1459            inertial_throw: None,
1460            projected_position: None,
1461            recovery_event: None,
1462            recovery_transition: None,
1463            log: PaneTerminalLogEntry {
1464                phase,
1465                sequence: None,
1466                pointer_id,
1467                target,
1468                recovery_cancel_sequence: None,
1469                outcome: PaneTerminalLogOutcome::Ignored(reason),
1470            },
1471        }
1472    }
1473
1474    fn forwarded(
1475        phase: PaneTerminalLifecyclePhase,
1476        pointer_id: Option<u32>,
1477        target: Option<PaneResizeTarget>,
1478        event: PaneSemanticInputEvent,
1479        transition: PaneDragResizeTransition,
1480    ) -> Self {
1481        let sequence = Some(event.sequence);
1482        Self {
1483            primary_event: Some(event),
1484            primary_transition: Some(transition),
1485            motion: None,
1486            inertial_throw: None,
1487            projected_position: None,
1488            recovery_event: None,
1489            recovery_transition: None,
1490            log: PaneTerminalLogEntry {
1491                phase,
1492                sequence,
1493                pointer_id,
1494                target,
1495                recovery_cancel_sequence: None,
1496                outcome: PaneTerminalLogOutcome::SemanticForwarded,
1497            },
1498        }
1499    }
1500
1501    /// Derive dynamic snap profile from translated pointer motion.
1502    #[must_use]
1503    pub fn pressure_snap_profile(&self) -> Option<PanePressureSnapProfile> {
1504        self.motion.map(PanePressureSnapProfile::from_motion)
1505    }
1506}
1507
1508/// Deterministic terminal adapter mapping raw `Event` values into
1509/// schema-validated pane semantic interaction events.
1510#[derive(Debug, Clone)]
1511pub struct PaneTerminalAdapter {
1512    machine: PaneDragResizeMachine,
1513    config: PaneTerminalAdapterConfig,
1514    active: Option<PaneTerminalActivePointer>,
1515    window_focused: bool,
1516    next_sequence: u64,
1517}
1518
1519impl PaneTerminalAdapter {
1520    /// Construct a new adapter with validated drag thresholds.
1521    pub fn new(config: PaneTerminalAdapterConfig) -> Result<Self, PaneDragResizeMachineError> {
1522        let config = PaneTerminalAdapterConfig {
1523            drag_update_coalesce_distance: config.drag_update_coalesce_distance.max(1),
1524            ..config
1525        };
1526        let machine = PaneDragResizeMachine::new_with_hysteresis(
1527            config.drag_threshold,
1528            config.update_hysteresis,
1529        )?;
1530        Ok(Self {
1531            machine,
1532            config,
1533            active: None,
1534            window_focused: true,
1535            next_sequence: 1,
1536        })
1537    }
1538
1539    /// Adapter configuration.
1540    #[must_use]
1541    pub const fn config(&self) -> PaneTerminalAdapterConfig {
1542        self.config
1543    }
1544
1545    /// Active pointer id currently tracked by the adapter, if any.
1546    #[must_use]
1547    pub fn active_pointer_id(&self) -> Option<u32> {
1548        self.active.map(|active| active.pointer_id)
1549    }
1550
1551    /// Whether the host window is currently focused.
1552    #[must_use]
1553    pub const fn window_focused(&self) -> bool {
1554        self.window_focused
1555    }
1556
1557    /// Current pane drag/resize machine state.
1558    #[must_use]
1559    pub const fn machine_state(&self) -> PaneDragResizeState {
1560        self.machine.state()
1561    }
1562
1563    /// Translate one raw terminal event into pane semantic event(s).
1564    ///
1565    /// `target_hint` is provided by host hit-testing (upcoming pane-terminal
1566    /// tasks). Pointer drag/move/up reuse active target continuity once armed.
1567    pub fn translate(
1568        &mut self,
1569        event: &Event,
1570        target_hint: Option<PaneResizeTarget>,
1571    ) -> PaneTerminalDispatch {
1572        match event {
1573            Event::Mouse(mouse) => self.translate_mouse(*mouse, target_hint),
1574            Event::Key(key) => self.translate_key(*key, target_hint),
1575            Event::Focus(focused) => self.translate_focus(*focused),
1576            Event::Resize { .. } => self.translate_resize(),
1577            _ => PaneTerminalDispatch::ignored(
1578                PaneTerminalLifecyclePhase::Other,
1579                PaneTerminalIgnoredReason::NonSemanticEvent,
1580                None,
1581                target_hint,
1582            ),
1583        }
1584    }
1585
1586    /// Translate one raw terminal event while resolving splitter targets from
1587    /// terminal hit regions.
1588    ///
1589    /// This is a convenience wrapper for host code that already has splitter
1590    /// handle regions from [`pane_terminal_splitter_handles`].
1591    pub fn translate_with_handles(
1592        &mut self,
1593        event: &Event,
1594        handles: &[PaneTerminalSplitterHandle],
1595    ) -> PaneTerminalDispatch {
1596        let active_target = self.active.map(|active| active.target);
1597        let target_hint = match event {
1598            Event::Mouse(mouse) => {
1599                let resolved = pane_terminal_resolve_splitter_target(handles, mouse.x, mouse.y);
1600                match mouse.kind {
1601                    MouseEventKind::Down(_)
1602                    | MouseEventKind::ScrollUp
1603                    | MouseEventKind::ScrollDown
1604                    | MouseEventKind::ScrollLeft
1605                    | MouseEventKind::ScrollRight => resolved,
1606                    MouseEventKind::Drag(_) | MouseEventKind::Moved | MouseEventKind::Up(_) => {
1607                        resolved.or(active_target)
1608                    }
1609                }
1610            }
1611            Event::Key(_) => active_target,
1612            _ => None,
1613        };
1614        self.translate(event, target_hint)
1615    }
1616
1617    fn translate_mouse(
1618        &mut self,
1619        mouse: MouseEvent,
1620        target_hint: Option<PaneResizeTarget>,
1621    ) -> PaneTerminalDispatch {
1622        let position = mouse_position(mouse);
1623        let modifiers = pane_modifiers(mouse.modifiers);
1624        match mouse.kind {
1625            MouseEventKind::Down(button) => {
1626                let pane_button = pane_button(button);
1627                if pane_button != self.config.activation_button {
1628                    return PaneTerminalDispatch::ignored(
1629                        PaneTerminalLifecyclePhase::MouseDown,
1630                        PaneTerminalIgnoredReason::ActivationButtonRequired,
1631                        Some(pointer_id_for_button(pane_button)),
1632                        target_hint,
1633                    );
1634                }
1635                let Some(target) = target_hint else {
1636                    return PaneTerminalDispatch::ignored(
1637                        PaneTerminalLifecyclePhase::MouseDown,
1638                        PaneTerminalIgnoredReason::MissingTarget,
1639                        Some(pointer_id_for_button(pane_button)),
1640                        None,
1641                    );
1642                };
1643
1644                let recovery = self.cancel_active_internal(PaneCancelReason::PointerCancel);
1645                let pointer_id = pointer_id_for_button(pane_button);
1646                let kind = PaneSemanticInputEventKind::PointerDown {
1647                    target,
1648                    pointer_id,
1649                    button: pane_button,
1650                    position,
1651                };
1652                let mut dispatch = self.forward_semantic(
1653                    PaneTerminalLifecyclePhase::MouseDown,
1654                    Some(pointer_id),
1655                    Some(target),
1656                    kind,
1657                    modifiers,
1658                );
1659                if dispatch.primary_transition.is_some() {
1660                    self.active = Some(PaneTerminalActivePointer {
1661                        pointer_id,
1662                        target,
1663                        button: pane_button,
1664                        last_position: position,
1665                        cumulative_delta_x: 0,
1666                        cumulative_delta_y: 0,
1667                        direction_changes: 0,
1668                        sample_count: 0,
1669                        previous_step_delta_x: 0,
1670                        previous_step_delta_y: 0,
1671                        start_time: Instant::now(),
1672                    });
1673                }
1674                if let Some((cancel_event, cancel_transition)) = recovery {
1675                    dispatch.recovery_event = Some(cancel_event);
1676                    dispatch.recovery_transition = Some(cancel_transition);
1677                    dispatch.log.recovery_cancel_sequence =
1678                        dispatch.recovery_event.as_ref().map(|event| event.sequence);
1679                    if matches!(
1680                        dispatch.log.outcome,
1681                        PaneTerminalLogOutcome::SemanticForwarded
1682                    ) {
1683                        dispatch.log.outcome =
1684                            PaneTerminalLogOutcome::SemanticForwardedAfterRecovery;
1685                    }
1686                }
1687                dispatch
1688            }
1689            MouseEventKind::Drag(button) => {
1690                let pane_button = pane_button(button);
1691                let Some(active) = self.active else {
1692                    return PaneTerminalDispatch::ignored(
1693                        PaneTerminalLifecyclePhase::MouseDrag,
1694                        PaneTerminalIgnoredReason::NoActivePointer,
1695                        Some(pointer_id_for_button(pane_button)),
1696                        target_hint,
1697                    );
1698                };
1699                if active.button != pane_button {
1700                    return PaneTerminalDispatch::ignored(
1701                        PaneTerminalLifecyclePhase::MouseDrag,
1702                        PaneTerminalIgnoredReason::PointerButtonMismatch,
1703                        Some(pointer_id_for_button(pane_button)),
1704                        Some(active.target),
1705                    );
1706                }
1707                self.apply_pointer_motion(
1708                    active,
1709                    position,
1710                    modifiers,
1711                    PaneTerminalLifecyclePhase::MouseDrag,
1712                )
1713            }
1714            MouseEventKind::Moved => {
1715                let Some(active) = self.active else {
1716                    return PaneTerminalDispatch::ignored(
1717                        PaneTerminalLifecyclePhase::MouseMove,
1718                        PaneTerminalIgnoredReason::NoActivePointer,
1719                        None,
1720                        target_hint,
1721                    );
1722                };
1723                self.apply_pointer_motion(
1724                    active,
1725                    position,
1726                    modifiers,
1727                    PaneTerminalLifecyclePhase::MouseMove,
1728                )
1729            }
1730            MouseEventKind::Up(button) => {
1731                let pane_button = pane_button(button);
1732                let Some(active) = self.active else {
1733                    return PaneTerminalDispatch::ignored(
1734                        PaneTerminalLifecyclePhase::MouseUp,
1735                        PaneTerminalIgnoredReason::NoActivePointer,
1736                        Some(pointer_id_for_button(pane_button)),
1737                        target_hint,
1738                    );
1739                };
1740                if active.button != pane_button {
1741                    return PaneTerminalDispatch::ignored(
1742                        PaneTerminalLifecyclePhase::MouseUp,
1743                        PaneTerminalIgnoredReason::PointerButtonMismatch,
1744                        Some(pointer_id_for_button(pane_button)),
1745                        Some(active.target),
1746                    );
1747                }
1748                let kind = PaneSemanticInputEventKind::PointerUp {
1749                    target: active.target,
1750                    pointer_id: active.pointer_id,
1751                    button: active.button,
1752                    position,
1753                };
1754                let mut dispatch = self.forward_semantic(
1755                    PaneTerminalLifecyclePhase::MouseUp,
1756                    Some(active.pointer_id),
1757                    Some(active.target),
1758                    kind,
1759                    modifiers,
1760                );
1761                if dispatch.primary_transition.is_some() {
1762                    let duration = active.start_time.elapsed().as_millis() as u32;
1763                    let motion = PaneMotionVector::from_delta(
1764                        active.cumulative_delta_x,
1765                        active.cumulative_delta_y,
1766                        duration,
1767                        active.direction_changes,
1768                    );
1769                    let inertial_throw = PaneInertialThrow::from_motion(motion);
1770                    dispatch.motion = Some(motion);
1771                    dispatch.projected_position = Some(inertial_throw.projected_pointer(position));
1772                    dispatch.inertial_throw = Some(inertial_throw);
1773                    self.active = None;
1774                }
1775                dispatch
1776            }
1777            MouseEventKind::ScrollUp
1778            | MouseEventKind::ScrollDown
1779            | MouseEventKind::ScrollLeft
1780            | MouseEventKind::ScrollRight => {
1781                let target = target_hint.or(self.active.map(|active| active.target));
1782                let Some(target) = target else {
1783                    return PaneTerminalDispatch::ignored(
1784                        PaneTerminalLifecyclePhase::MouseScroll,
1785                        PaneTerminalIgnoredReason::MissingTarget,
1786                        None,
1787                        None,
1788                    );
1789                };
1790                let lines = match mouse.kind {
1791                    MouseEventKind::ScrollUp | MouseEventKind::ScrollLeft => -1,
1792                    MouseEventKind::ScrollDown | MouseEventKind::ScrollRight => 1,
1793                    _ => unreachable!("handled by outer match"),
1794                };
1795                let kind = PaneSemanticInputEventKind::WheelNudge { target, lines };
1796                self.forward_semantic(
1797                    PaneTerminalLifecyclePhase::MouseScroll,
1798                    None,
1799                    Some(target),
1800                    kind,
1801                    modifiers,
1802                )
1803            }
1804        }
1805    }
1806
1807    /// Shared motion bookkeeping for the `Drag` and `Moved` mouse arms.
1808    ///
1809    /// Once each arm's arm-specific guards pass (`Drag` additionally checks the
1810    /// pressed button), both perform byte-identical work: compute the step
1811    /// delta, honor drag coalescing, fold direction-change and cumulative-motion
1812    /// tracking into `active`, forward a `PointerMove`, and โ€” only on a committed
1813    /// transition โ€” advance `last_position` and attach the motion vector. The
1814    /// sole caller-specific input is `phase` (`MouseDrag` vs `MouseMove`), used
1815    /// for both the coalesced-ignore and the forwarded event so each caller's
1816    /// diagnostics are unchanged. This is a pure extraction of the two
1817    /// previously-duplicated arm bodies โ€” event ordering and semantics are
1818    /// identical, and the single shared path is cheaper to audit and roll back.
1819    fn apply_pointer_motion(
1820        &mut self,
1821        mut active: PaneTerminalActivePointer,
1822        position: PanePointerPosition,
1823        modifiers: PaneModifierSnapshot,
1824        phase: PaneTerminalLifecyclePhase,
1825    ) -> PaneTerminalDispatch {
1826        let delta_x = position.x.saturating_sub(active.last_position.x);
1827        let delta_y = position.y.saturating_sub(active.last_position.y);
1828        if self.should_coalesce_drag(delta_x, delta_y) {
1829            return PaneTerminalDispatch::ignored(
1830                phase,
1831                PaneTerminalIgnoredReason::DragCoalesced,
1832                Some(active.pointer_id),
1833                Some(active.target),
1834            );
1835        }
1836        if active.sample_count > 0 {
1837            let flipped_x = delta_x.signum() != 0
1838                && active.previous_step_delta_x.signum() != 0
1839                && delta_x.signum() != active.previous_step_delta_x.signum();
1840            let flipped_y = delta_y.signum() != 0
1841                && active.previous_step_delta_y.signum() != 0
1842                && delta_y.signum() != active.previous_step_delta_y.signum();
1843            if flipped_x || flipped_y {
1844                active.direction_changes = active.direction_changes.saturating_add(1);
1845            }
1846        }
1847        active.cumulative_delta_x = active.cumulative_delta_x.saturating_add(delta_x);
1848        active.cumulative_delta_y = active.cumulative_delta_y.saturating_add(delta_y);
1849        active.sample_count = active.sample_count.saturating_add(1);
1850        active.previous_step_delta_x = delta_x;
1851        active.previous_step_delta_y = delta_y;
1852        let kind = PaneSemanticInputEventKind::PointerMove {
1853            target: active.target,
1854            pointer_id: active.pointer_id,
1855            position,
1856            delta_x,
1857            delta_y,
1858        };
1859        let mut dispatch = self.forward_semantic(
1860            phase,
1861            Some(active.pointer_id),
1862            Some(active.target),
1863            kind,
1864            modifiers,
1865        );
1866        if dispatch.primary_transition.is_some() {
1867            active.last_position = position;
1868            self.active = Some(active);
1869            let duration = active.start_time.elapsed().as_millis() as u32;
1870            dispatch.motion = Some(PaneMotionVector::from_delta(
1871                active.cumulative_delta_x,
1872                active.cumulative_delta_y,
1873                duration,
1874                active.direction_changes,
1875            ));
1876        }
1877        dispatch
1878    }
1879
1880    fn translate_key(
1881        &mut self,
1882        key: KeyEvent,
1883        target_hint: Option<PaneResizeTarget>,
1884    ) -> PaneTerminalDispatch {
1885        if !self.window_focused {
1886            return PaneTerminalDispatch::ignored(
1887                PaneTerminalLifecyclePhase::KeyResize,
1888                PaneTerminalIgnoredReason::WindowNotFocused,
1889                self.active_pointer_id(),
1890                target_hint.or(self.active.map(|active| active.target)),
1891            );
1892        }
1893        if key.kind == KeyEventKind::Release {
1894            return PaneTerminalDispatch::ignored(
1895                PaneTerminalLifecyclePhase::Other,
1896                PaneTerminalIgnoredReason::UnsupportedKey,
1897                None,
1898                target_hint,
1899            );
1900        }
1901        if matches!(key.code, KeyCode::Escape) {
1902            return self.cancel_active_dispatch(
1903                PaneTerminalLifecyclePhase::KeyCancel,
1904                PaneCancelReason::EscapeKey,
1905                PaneTerminalIgnoredReason::NoActivePointer,
1906            );
1907        }
1908        let target = target_hint.or(self.active.map(|active| active.target));
1909        let Some(target) = target else {
1910            return PaneTerminalDispatch::ignored(
1911                PaneTerminalLifecyclePhase::KeyResize,
1912                PaneTerminalIgnoredReason::MissingTarget,
1913                None,
1914                None,
1915            );
1916        };
1917        let Some(direction) = keyboard_resize_direction(key.code, target.axis) else {
1918            return PaneTerminalDispatch::ignored(
1919                PaneTerminalLifecyclePhase::KeyResize,
1920                PaneTerminalIgnoredReason::UnsupportedKey,
1921                None,
1922                Some(target),
1923            );
1924        };
1925        let units = keyboard_resize_units(key.modifiers);
1926        let kind = PaneSemanticInputEventKind::KeyboardResize {
1927            target,
1928            direction,
1929            units,
1930        };
1931        self.forward_semantic(
1932            PaneTerminalLifecyclePhase::KeyResize,
1933            self.active_pointer_id(),
1934            Some(target),
1935            kind,
1936            pane_modifiers(key.modifiers),
1937        )
1938    }
1939
1940    fn translate_focus(&mut self, focused: bool) -> PaneTerminalDispatch {
1941        if focused {
1942            self.window_focused = true;
1943            return PaneTerminalDispatch::ignored(
1944                PaneTerminalLifecyclePhase::Other,
1945                PaneTerminalIgnoredReason::FocusGainNoop,
1946                self.active_pointer_id(),
1947                self.active.map(|active| active.target),
1948            );
1949        }
1950        self.window_focused = false;
1951        if !self.config.cancel_on_focus_lost {
1952            return PaneTerminalDispatch::ignored(
1953                PaneTerminalLifecyclePhase::FocusLoss,
1954                PaneTerminalIgnoredReason::ResizeNoop,
1955                self.active_pointer_id(),
1956                self.active.map(|active| active.target),
1957            );
1958        }
1959        self.cancel_active_dispatch(
1960            PaneTerminalLifecyclePhase::FocusLoss,
1961            PaneCancelReason::FocusLost,
1962            PaneTerminalIgnoredReason::NoActivePointer,
1963        )
1964    }
1965
1966    fn translate_resize(&mut self) -> PaneTerminalDispatch {
1967        if !self.config.cancel_on_resize {
1968            return PaneTerminalDispatch::ignored(
1969                PaneTerminalLifecyclePhase::ResizeInterrupt,
1970                PaneTerminalIgnoredReason::ResizeNoop,
1971                self.active_pointer_id(),
1972                self.active.map(|active| active.target),
1973            );
1974        }
1975        self.cancel_active_dispatch(
1976            PaneTerminalLifecyclePhase::ResizeInterrupt,
1977            PaneCancelReason::Programmatic,
1978            PaneTerminalIgnoredReason::ResizeNoop,
1979        )
1980    }
1981
1982    fn cancel_active_dispatch(
1983        &mut self,
1984        phase: PaneTerminalLifecyclePhase,
1985        reason: PaneCancelReason,
1986        no_active_reason: PaneTerminalIgnoredReason,
1987    ) -> PaneTerminalDispatch {
1988        let Some(active) = self.active else {
1989            return PaneTerminalDispatch::ignored(phase, no_active_reason, None, None);
1990        };
1991        let kind = PaneSemanticInputEventKind::Cancel {
1992            target: Some(active.target),
1993            reason,
1994        };
1995        let dispatch = self.forward_semantic(
1996            phase,
1997            Some(active.pointer_id),
1998            Some(active.target),
1999            kind,
2000            PaneModifierSnapshot::default(),
2001        );
2002        if dispatch.primary_transition.is_some() {
2003            self.active = None;
2004        }
2005        dispatch
2006    }
2007
2008    fn cancel_active_internal(
2009        &mut self,
2010        reason: PaneCancelReason,
2011    ) -> Option<(PaneSemanticInputEvent, PaneDragResizeTransition)> {
2012        let active = self.active?;
2013        let kind = PaneSemanticInputEventKind::Cancel {
2014            target: Some(active.target),
2015            reason,
2016        };
2017        let result = self
2018            .apply_semantic(kind, PaneModifierSnapshot::default())
2019            .ok();
2020        if result.is_some() {
2021            self.active = None;
2022        }
2023        result
2024    }
2025
2026    fn forward_semantic(
2027        &mut self,
2028        phase: PaneTerminalLifecyclePhase,
2029        pointer_id: Option<u32>,
2030        target: Option<PaneResizeTarget>,
2031        kind: PaneSemanticInputEventKind,
2032        modifiers: PaneModifierSnapshot,
2033    ) -> PaneTerminalDispatch {
2034        match self.apply_semantic(kind, modifiers) {
2035            Ok((event, transition)) => {
2036                PaneTerminalDispatch::forwarded(phase, pointer_id, target, event, transition)
2037            }
2038            Err(_) => PaneTerminalDispatch::ignored(
2039                phase,
2040                PaneTerminalIgnoredReason::MachineRejectedEvent,
2041                pointer_id,
2042                target,
2043            ),
2044        }
2045    }
2046
2047    fn apply_semantic(
2048        &mut self,
2049        kind: PaneSemanticInputEventKind,
2050        modifiers: PaneModifierSnapshot,
2051    ) -> Result<(PaneSemanticInputEvent, PaneDragResizeTransition), PaneDragResizeMachineError>
2052    {
2053        let mut event = PaneSemanticInputEvent::new(self.next_sequence(), kind);
2054        event.modifiers = modifiers;
2055        let transition = self.machine.apply_event(&event)?;
2056        Ok((event, transition))
2057    }
2058
2059    fn next_sequence(&mut self) -> u64 {
2060        let sequence = self.next_sequence;
2061        self.next_sequence = self.next_sequence.saturating_add(1);
2062        sequence
2063    }
2064
2065    fn should_coalesce_drag(&self, delta_x: i32, delta_y: i32) -> bool {
2066        if !matches!(self.machine.state(), PaneDragResizeState::Dragging { .. }) {
2067            return false;
2068        }
2069        let movement = delta_x
2070            .unsigned_abs()
2071            .saturating_add(delta_y.unsigned_abs());
2072        movement < u32::from(self.config.drag_update_coalesce_distance)
2073    }
2074
2075    /// Force-cancel any active pane interaction and return diagnostic info.
2076    ///
2077    /// This is the safety-valve for cleanup paths (RAII guard drops, signal
2078    /// handlers, panic hooks) where constructing a proper semantic event is
2079    /// not feasible. It resets both the underlying drag/resize state machine
2080    /// and the adapter's active-pointer tracking.
2081    ///
2082    /// Returns `None` if no interaction was active.
2083    pub fn force_cancel_all(&mut self) -> Option<PaneCleanupDiagnostics> {
2084        let was_active = self.active.is_some();
2085        let machine_state_before = self.machine.state();
2086        let machine_transition = self.machine.force_cancel();
2087        let active_pointer = self.active.take();
2088        if !was_active && machine_transition.is_none() {
2089            return None;
2090        }
2091        Some(PaneCleanupDiagnostics {
2092            had_active_pointer: was_active,
2093            active_pointer_id: active_pointer.map(|a| a.pointer_id),
2094            machine_state_before,
2095            machine_transition,
2096        })
2097    }
2098}
2099
2100/// Structured diagnostics emitted when pane interaction state is force-cleaned.
2101///
2102/// Fields mirror the pane layout types which are already `Serialize`/`Deserialize`,
2103/// so callers can convert this struct to JSON for evidence logging.
2104#[derive(Debug, Clone, PartialEq, Eq)]
2105pub struct PaneCleanupDiagnostics {
2106    /// Whether the adapter had an active pointer tracker when cleanup ran.
2107    pub had_active_pointer: bool,
2108    /// The pointer ID that was active (if any).
2109    pub active_pointer_id: Option<u32>,
2110    /// The machine state before force-cancel was applied.
2111    pub machine_state_before: PaneDragResizeState,
2112    /// The transition produced by force-cancel, or `None` if the machine
2113    /// was already idle.
2114    pub machine_transition: Option<PaneDragResizeTransition>,
2115}
2116
2117/// RAII guard that ensures pane interaction state is cleanly canceled on drop.
2118///
2119/// When a pane interaction session is active and the guard drops (due to
2120/// panic, scope exit, or any other unwind), it force-cancels any in-progress
2121/// drag/resize and collects cleanup diagnostics.
2122///
2123/// # Usage
2124///
2125/// ```ignore
2126/// let guard = PaneInteractionGuard::new(&mut adapter);
2127/// // ... pane interaction event loop ...
2128/// // If this scope panics, guard's Drop will force-cancel the drag machine
2129/// let diagnostics = guard.finish(); // explicit clean finish
2130/// ```
2131pub struct PaneInteractionGuard<'a> {
2132    adapter: &'a mut PaneTerminalAdapter,
2133    finished: bool,
2134    diagnostics: Option<PaneCleanupDiagnostics>,
2135}
2136
2137impl<'a> PaneInteractionGuard<'a> {
2138    /// Create a new guard wrapping the given adapter.
2139    pub fn new(adapter: &'a mut PaneTerminalAdapter) -> Self {
2140        Self {
2141            adapter,
2142            finished: false,
2143            diagnostics: None,
2144        }
2145    }
2146
2147    /// Access the wrapped adapter for normal event translation.
2148    pub fn adapter(&mut self) -> &mut PaneTerminalAdapter {
2149        self.adapter
2150    }
2151
2152    /// Explicitly finish the guard, returning any cleanup diagnostics.
2153    ///
2154    /// Calling `finish()` is optional โ€” the guard will also clean up on drop.
2155    /// However, `finish()` gives the caller access to the diagnostics.
2156    pub fn finish(mut self) -> Option<PaneCleanupDiagnostics> {
2157        self.finished = true;
2158        let diagnostics = self.adapter.force_cancel_all();
2159        self.diagnostics = diagnostics.clone();
2160        diagnostics
2161    }
2162}
2163
2164impl Drop for PaneInteractionGuard<'_> {
2165    fn drop(&mut self) {
2166        if !self.finished {
2167            self.diagnostics = self.adapter.force_cancel_all();
2168        }
2169    }
2170}
2171
2172fn pane_button(button: MouseButton) -> PanePointerButton {
2173    match button {
2174        MouseButton::Left => PanePointerButton::Primary,
2175        MouseButton::Right => PanePointerButton::Secondary,
2176        MouseButton::Middle => PanePointerButton::Middle,
2177    }
2178}
2179
2180fn pointer_id_for_button(button: PanePointerButton) -> u32 {
2181    match button {
2182        PanePointerButton::Primary => 1,
2183        PanePointerButton::Secondary => 2,
2184        PanePointerButton::Middle => 3,
2185    }
2186}
2187
2188fn mouse_position(mouse: MouseEvent) -> PanePointerPosition {
2189    PanePointerPosition::new(i32::from(mouse.x), i32::from(mouse.y))
2190}
2191
2192fn pane_modifiers(modifiers: Modifiers) -> PaneModifierSnapshot {
2193    PaneModifierSnapshot {
2194        shift: modifiers.contains(Modifiers::SHIFT),
2195        alt: modifiers.contains(Modifiers::ALT),
2196        ctrl: modifiers.contains(Modifiers::CTRL),
2197        meta: modifiers.contains(Modifiers::SUPER),
2198    }
2199}
2200
2201fn keyboard_resize_direction(code: KeyCode, axis: SplitAxis) -> Option<PaneResizeDirection> {
2202    match (axis, code) {
2203        (SplitAxis::Horizontal, KeyCode::Left) => Some(PaneResizeDirection::Decrease),
2204        (SplitAxis::Horizontal, KeyCode::Right) => Some(PaneResizeDirection::Increase),
2205        (SplitAxis::Vertical, KeyCode::Up) => Some(PaneResizeDirection::Decrease),
2206        (SplitAxis::Vertical, KeyCode::Down) => Some(PaneResizeDirection::Increase),
2207        (_, KeyCode::Char('-')) => Some(PaneResizeDirection::Decrease),
2208        (_, KeyCode::Char('+') | KeyCode::Char('=')) => Some(PaneResizeDirection::Increase),
2209        _ => None,
2210    }
2211}
2212
2213fn keyboard_resize_units(modifiers: Modifiers) -> u16 {
2214    if modifiers.contains(Modifiers::SHIFT) {
2215        5
2216    } else {
2217        1
2218    }
2219}
2220
2221/// Configuration for state persistence in the program runtime.
2222///
2223/// Controls when and how widget state is saved/restored.
2224#[derive(Clone)]
2225pub struct PersistenceConfig {
2226    /// State registry for persistence. If None, persistence is disabled.
2227    pub registry: Option<std::sync::Arc<StateRegistry>>,
2228    /// Interval for periodic checkpoint saves. None disables checkpoints.
2229    pub checkpoint_interval: Option<Duration>,
2230    /// Automatically load state on program start.
2231    pub auto_load: bool,
2232    /// Automatically save state on program exit.
2233    pub auto_save: bool,
2234}
2235
2236impl Default for PersistenceConfig {
2237    fn default() -> Self {
2238        Self {
2239            registry: None,
2240            checkpoint_interval: None,
2241            auto_load: true,
2242            auto_save: true,
2243        }
2244    }
2245}
2246
2247impl std::fmt::Debug for PersistenceConfig {
2248    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2249        f.debug_struct("PersistenceConfig")
2250            .field(
2251                "registry",
2252                &self.registry.as_ref().map(|r| r.backend_name()),
2253            )
2254            .field("checkpoint_interval", &self.checkpoint_interval)
2255            .field("auto_load", &self.auto_load)
2256            .field("auto_save", &self.auto_save)
2257            .finish()
2258    }
2259}
2260
2261impl PersistenceConfig {
2262    /// Create a disabled persistence config.
2263    #[must_use]
2264    pub fn disabled() -> Self {
2265        Self::default()
2266    }
2267
2268    /// Create a persistence config with the given registry.
2269    #[must_use]
2270    pub fn with_registry(registry: std::sync::Arc<StateRegistry>) -> Self {
2271        Self {
2272            registry: Some(registry),
2273            ..Default::default()
2274        }
2275    }
2276
2277    /// Set the checkpoint interval.
2278    #[must_use]
2279    pub fn checkpoint_every(mut self, interval: Duration) -> Self {
2280        self.checkpoint_interval = Some(interval);
2281        self
2282    }
2283
2284    /// Enable or disable auto-load on start.
2285    #[must_use]
2286    pub fn auto_load(mut self, enabled: bool) -> Self {
2287        self.auto_load = enabled;
2288        self
2289    }
2290
2291    /// Enable or disable auto-save on exit.
2292    #[must_use]
2293    pub fn auto_save(mut self, enabled: bool) -> Self {
2294        self.auto_save = enabled;
2295        self
2296    }
2297}
2298
2299/// Configuration for widget refresh selection under render budget.
2300///
2301/// Defaults are conservative and deterministic:
2302/// - enabled: true
2303/// - staleness_window_ms: 1_000
2304/// - starve_ms: 3_000
2305/// - max_starved_per_frame: 2
2306/// - max_drop_fraction: 1.0 (disabled)
2307/// - weights: priority 1.0, staleness 0.5, focus 0.75, interaction 0.5
2308/// - starve_boost: 1.5
2309/// - min_cost_us: 1.0
2310#[derive(Debug, Clone)]
2311pub struct WidgetRefreshConfig {
2312    /// Enable budgeted widget refresh selection.
2313    pub enabled: bool,
2314    /// Staleness decay window (ms) used to normalize staleness scores.
2315    pub staleness_window_ms: u64,
2316    /// Staleness threshold that triggers starvation guard (ms).
2317    pub starve_ms: u64,
2318    /// Maximum number of starved widgets to force in per frame.
2319    pub max_starved_per_frame: usize,
2320    /// Maximum fraction of non-essential widgets that may be dropped.
2321    /// Set to 1.0 to disable the guardrail.
2322    pub max_drop_fraction: f32,
2323    /// Weight for base priority signal.
2324    pub weight_priority: f32,
2325    /// Weight for staleness signal.
2326    pub weight_staleness: f32,
2327    /// Weight for focus boost.
2328    pub weight_focus: f32,
2329    /// Weight for interaction boost.
2330    pub weight_interaction: f32,
2331    /// Additive boost to value for starved widgets.
2332    pub starve_boost: f32,
2333    /// Minimum cost (us) to avoid divide-by-zero.
2334    pub min_cost_us: f32,
2335}
2336
2337impl Default for WidgetRefreshConfig {
2338    fn default() -> Self {
2339        Self {
2340            enabled: true,
2341            staleness_window_ms: 1_000,
2342            starve_ms: 3_000,
2343            max_starved_per_frame: 2,
2344            max_drop_fraction: 1.0,
2345            weight_priority: 1.0,
2346            weight_staleness: 0.5,
2347            weight_focus: 0.75,
2348            weight_interaction: 0.5,
2349            starve_boost: 1.5,
2350            min_cost_us: 1.0,
2351        }
2352    }
2353}
2354
2355/// Configuration for effect queue scheduling.
2356#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2357pub enum TaskExecutorBackend {
2358    /// Spawn one native thread per task and reap finished handles on the main loop.
2359    #[default]
2360    Spawned,
2361    /// Route tasks through the runtime's queueing scheduler.
2362    EffectQueue,
2363    /// Route blocking task closures through an Asupersync blocking pool.
2364    #[cfg(feature = "asupersync-executor")]
2365    Asupersync,
2366}
2367
2368/// Default task executor backend for [`RuntimeLane::Legacy`] and [`RuntimeLane::Structured`].
2369///
2370/// Benchmarked in `benches/effect_backend_bench.rs` and documented in
2371/// `docs/perf/effect_backend_2026-10-19.md`.
2372pub const DEFAULT_TASK_BACKEND: TaskExecutorBackend = TaskExecutorBackend::Spawned;
2373
2374#[derive(Debug, Clone)]
2375pub struct EffectQueueConfig {
2376    /// Whether effect queue scheduling is enabled.
2377    ///
2378    /// This legacy convenience flag is kept in sync with `backend`. New code
2379    /// should prefer `backend` for executor selection.
2380    pub enabled: bool,
2381    /// Which task executor backend to use for `Cmd::Task`.
2382    pub backend: TaskExecutorBackend,
2383    /// Scheduler configuration (Smith's rule by default).
2384    pub scheduler: SchedulerConfig,
2385    /// Maximum queue depth before backpressure kicks in (bd-2zd0a).
2386    ///
2387    /// When the queue depth exceeds this limit, new tasks are dropped with
2388    /// a `tracing::warn!` and the `effects_queue_dropped` counter increments.
2389    /// A value of `0` means unbounded (no backpressure).
2390    pub max_queue_depth: usize,
2391    /// Whether the backend selection was set explicitly by the caller.
2392    explicit_backend: bool,
2393}
2394
2395impl Default for EffectQueueConfig {
2396    fn default() -> Self {
2397        let scheduler = SchedulerConfig {
2398            smith_enabled: true,
2399            force_fifo: false,
2400            preemptive: false,
2401            aging_factor: 0.0,
2402            wait_starve_ms: 0.0,
2403            enable_logging: false,
2404            ..Default::default()
2405        };
2406        Self {
2407            enabled: matches!(DEFAULT_TASK_BACKEND, TaskExecutorBackend::EffectQueue),
2408            backend: DEFAULT_TASK_BACKEND,
2409            scheduler,
2410            max_queue_depth: 0,
2411            explicit_backend: false,
2412        }
2413    }
2414}
2415
2416impl EffectQueueConfig {
2417    /// Enable effect queue scheduling with the provided scheduler config.
2418    #[must_use]
2419    pub fn with_enabled(mut self, enabled: bool) -> Self {
2420        self.enabled = enabled;
2421        self.backend = if enabled {
2422            TaskExecutorBackend::EffectQueue
2423        } else {
2424            TaskExecutorBackend::Spawned
2425        };
2426        self.explicit_backend = true;
2427        self
2428    }
2429
2430    /// Select the task executor backend for `Cmd::Task`.
2431    #[must_use]
2432    pub fn with_backend(mut self, backend: TaskExecutorBackend) -> Self {
2433        self.enabled = matches!(backend, TaskExecutorBackend::EffectQueue);
2434        self.backend = backend;
2435        self.explicit_backend = true;
2436        self
2437    }
2438
2439    /// Override the scheduler configuration.
2440    #[must_use]
2441    pub fn with_scheduler(mut self, scheduler: SchedulerConfig) -> Self {
2442        self.scheduler = scheduler;
2443        self
2444    }
2445
2446    /// Set the maximum queue depth for backpressure (bd-2zd0a).
2447    ///
2448    /// When the queue depth exceeds this limit, new tasks are dropped.
2449    /// A value of `0` means unbounded (no backpressure, the default).
2450    #[must_use]
2451    pub fn with_max_queue_depth(mut self, depth: usize) -> Self {
2452        self.max_queue_depth = depth;
2453        self
2454    }
2455
2456    #[must_use]
2457    fn uses_legacy_default_backend(&self) -> bool {
2458        !self.explicit_backend && !self.enabled && self.backend == DEFAULT_TASK_BACKEND
2459    }
2460}
2461
2462/// Immediate event-drain policy for the runtime main loop.
2463///
2464/// When a poll reports readiness, the runtime drains events by repeatedly
2465/// checking `poll_event(Duration::ZERO)` to avoid latency between buffered
2466/// inputs. This policy bounds that immediate-drain path so bursty workloads do
2467/// not devolve into zero-timeout spin storms.
2468#[derive(Debug, Clone)]
2469pub struct ImmediateDrainConfig {
2470    /// Maximum consecutive zero-timeout polls allowed in a single burst window.
2471    pub max_zero_timeout_polls_per_burst: usize,
2472    /// Maximum wall-clock time spent in a single immediate-drain burst window.
2473    pub max_burst_duration: Duration,
2474    /// Non-zero poll timeout used when the burst window budget is exhausted.
2475    pub backoff_timeout: Duration,
2476}
2477
2478impl Default for ImmediateDrainConfig {
2479    fn default() -> Self {
2480        Self {
2481            max_zero_timeout_polls_per_burst: 64,
2482            max_burst_duration: Duration::from_millis(2),
2483            backoff_timeout: Duration::from_millis(1),
2484        }
2485    }
2486}
2487
2488/// Runtime counters for immediate-drain behavior.
2489#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2490pub struct ImmediateDrainStats {
2491    /// Number of event-drain bursts observed.
2492    pub bursts: u64,
2493    /// Total zero-timeout polls executed (`poll_event(Duration::ZERO)`).
2494    pub zero_timeout_polls: u64,
2495    /// Total non-zero backoff polls executed after exhausting burst budget.
2496    pub backoff_polls: u64,
2497    /// Number of bursts that hit the configured immediate-drain cap.
2498    pub capped_bursts: u64,
2499    /// Max number of zero-timeout polls seen in a single burst window.
2500    pub max_zero_timeout_polls_in_burst: u64,
2501}
2502
2503/// User-visible runtime mode reported by the conservative load governor.
2504///
2505/// These modes mirror the `bd-8vstx` runtime contract:
2506///
2507/// - `Healthy`: admit all work normally; no explicit fallback is active.
2508/// - `Stressed`: strict work is preserved while visible/coalescible or
2509///   background work may be slowed before user-visible ambiguity appears.
2510/// - `Degraded`: bounded fallback is active; strict interactive semantics
2511///   still hold while background/best-effort work is deferred or dropped.
2512/// - `Recovered`: a degraded interval has closed after the configured
2513///   hysteresis window; the next steady interval returns to `Healthy`.
2514/// - `Unsafe`: a strict semantic guarantee cannot be preserved, so optimistic
2515///   degradation must stop and the caller must surface explicit failure.
2516#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2517pub enum RuntimeLoadMode {
2518    /// No sustained pressure and no active fallback.
2519    Healthy,
2520    /// Elevated pressure while strict guarantees still hold.
2521    Stressed,
2522    /// Explicit bounded fallback is active.
2523    Degraded,
2524    /// Recovery interval has been observed and reported.
2525    Recovered,
2526    /// A strict semantic guarantee was violated.
2527    Unsafe,
2528}
2529
2530impl RuntimeLoadMode {
2531    /// Stable string for evidence logs.
2532    #[inline]
2533    #[must_use]
2534    pub const fn as_str(self) -> &'static str {
2535        match self {
2536            Self::Healthy => "healthy",
2537            Self::Stressed => "stressed",
2538            Self::Degraded => "degraded",
2539            Self::Recovered => "recovered",
2540            Self::Unsafe => "unsafe",
2541        }
2542    }
2543}
2544
2545/// Pressure envelope inferred from measured runtime signals.
2546#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2547pub enum RuntimePressureClass {
2548    /// Within steady-state envelope.
2549    SteadyState,
2550    /// Early overload band; bounded coalescing/deferment may begin.
2551    SoftOverload,
2552    /// Degraded band; explicit fallback is active.
2553    HardOverload,
2554    /// Terminal strict-semantics failure.
2555    Unsafe,
2556}
2557
2558impl RuntimePressureClass {
2559    /// Stable string for evidence logs.
2560    #[inline]
2561    #[must_use]
2562    pub const fn as_str(self) -> &'static str {
2563        match self {
2564            Self::SteadyState => "steady_state",
2565            Self::SoftOverload => "soft_overload",
2566            Self::HardOverload => "hard_overload",
2567            Self::Unsafe => "unsafe",
2568        }
2569    }
2570}
2571
2572/// Work disposition allowed by the current runtime mode.
2573#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2574pub enum RuntimeWorkDisposition {
2575    /// Admit all work normally.
2576    AdmitAll,
2577    /// Preserve strict work; coalesce visible work and slow background work.
2578    CoalesceVisibleDeferBackground,
2579    /// Preserve strict work; defer background work and drop best-effort work.
2580    DeferBackgroundDropBestEffort,
2581    /// Re-admit deferred work after the hysteresis window closed.
2582    ReadmitAfterHysteresis,
2583    /// Stop optimistic degradation because a strict guarantee failed.
2584    FailFastStrictGuarantee,
2585}
2586
2587impl RuntimeWorkDisposition {
2588    /// Stable string for evidence logs.
2589    #[inline]
2590    #[must_use]
2591    pub const fn as_str(self) -> &'static str {
2592        match self {
2593            Self::AdmitAll => "admit_all",
2594            Self::CoalesceVisibleDeferBackground => "coalesce_visible_defer_background",
2595            Self::DeferBackgroundDropBestEffort => "defer_background_drop_best_effort",
2596            Self::ReadmitAfterHysteresis => "readmit_after_hysteresis",
2597            Self::FailFastStrictGuarantee => "fail_fast_strict_guarantee",
2598        }
2599    }
2600}
2601
2602/// Conservative policy for classifying runtime load.
2603///
2604/// The first runtime governor intentionally uses one primary control family:
2605/// render-budget degradation and explicit coalescing/admission evidence. Queue
2606/// watermarks are advisory inputs when a queue cap exists; when the queue is
2607/// uncapped, frame-budget and coalescer signals drive fallback classification.
2608#[derive(Debug, Clone, Copy, PartialEq)]
2609pub struct LoadGovernorPolicy {
2610    /// Queue occupancy ratio that enters `stressed`.
2611    pub stressed_queue_watermark: f64,
2612    /// Queue occupancy ratio that enters `degraded`.
2613    pub degraded_queue_watermark: f64,
2614    /// Queue occupancy ratio required before closing a degraded interval.
2615    pub recovery_queue_watermark: f64,
2616    /// Consecutive steady intervals required before reporting recovery.
2617    pub recovery_intervals: u8,
2618    /// Frame-time ratio over budget that enters `stressed` when uncapped.
2619    pub budget_overrun_soft_ratio: f64,
2620}
2621
2622impl Default for LoadGovernorPolicy {
2623    fn default() -> Self {
2624        Self {
2625            stressed_queue_watermark: 0.5,
2626            degraded_queue_watermark: 0.8,
2627            recovery_queue_watermark: 0.25,
2628            recovery_intervals: 3,
2629            budget_overrun_soft_ratio: 1.0,
2630        }
2631    }
2632}
2633
2634impl LoadGovernorPolicy {
2635    #[must_use]
2636    fn normalized(self) -> Self {
2637        let recovery = normalize_ratio(self.recovery_queue_watermark, 0.25);
2638        let stressed = normalize_ratio(self.stressed_queue_watermark, 0.5).max(recovery);
2639        let degraded = normalize_ratio(self.degraded_queue_watermark, 0.8).max(stressed);
2640        Self {
2641            recovery_queue_watermark: recovery,
2642            stressed_queue_watermark: stressed,
2643            degraded_queue_watermark: degraded,
2644            recovery_intervals: self.recovery_intervals.max(1),
2645            budget_overrun_soft_ratio: normalize_positive_ratio(
2646                self.budget_overrun_soft_ratio,
2647                1.0,
2648            ),
2649        }
2650    }
2651}
2652
2653#[inline]
2654fn normalize_ratio(value: f64, fallback: f64) -> f64 {
2655    if value.is_finite() {
2656        value.clamp(0.0, 1.0)
2657    } else {
2658        fallback
2659    }
2660}
2661
2662#[inline]
2663fn normalize_positive_ratio(value: f64, fallback: f64) -> f64 {
2664    if value.is_finite() && value > 0.0 {
2665        value
2666    } else {
2667        fallback
2668    }
2669}
2670
2671/// Conservative runtime load-governor configuration.
2672///
2673/// The first runtime governor keeps one primary control objective:
2674/// responsiveness under render pressure. It drives adaptive render degradation
2675/// through `RenderBudget`, classifies runtime mode with queue/coalescer inputs,
2676/// and emits replayable evidence for the allowed work disposition. Disabling
2677/// this config falls back to the legacy threshold path.
2678#[derive(Debug, Clone, PartialEq)]
2679pub struct LoadGovernorConfig {
2680    /// Whether the adaptive governor is active.
2681    pub enabled: bool,
2682    /// Controller used to decide degrade/upgrade transitions from frame timing.
2683    pub budget_controller: BudgetControllerConfig,
2684    /// Runtime-mode and work-disposition classification policy.
2685    pub policy: LoadGovernorPolicy,
2686}
2687
2688impl Default for LoadGovernorConfig {
2689    fn default() -> Self {
2690        Self {
2691            enabled: true,
2692            budget_controller: BudgetControllerConfig::default(),
2693            policy: LoadGovernorPolicy::default(),
2694        }
2695    }
2696}
2697
2698impl LoadGovernorConfig {
2699    /// Create an enabled governor with conservative defaults.
2700    #[must_use]
2701    pub fn enabled() -> Self {
2702        Self::default()
2703    }
2704
2705    /// Disable the governor and use the legacy render-budget threshold path.
2706    #[must_use]
2707    pub fn disabled() -> Self {
2708        Self {
2709            enabled: false,
2710            budget_controller: BudgetControllerConfig::default(),
2711            policy: LoadGovernorPolicy::default(),
2712        }
2713    }
2714
2715    /// Toggle governor activation.
2716    #[must_use]
2717    pub fn with_enabled(mut self, enabled: bool) -> Self {
2718        self.enabled = enabled;
2719        self
2720    }
2721
2722    /// Replace the adaptive budget controller configuration.
2723    #[must_use]
2724    pub fn with_budget_controller(mut self, config: BudgetControllerConfig) -> Self {
2725        self.budget_controller = config;
2726        self
2727    }
2728
2729    /// Replace the runtime-mode classification policy.
2730    #[must_use]
2731    pub fn with_policy(mut self, policy: LoadGovernorPolicy) -> Self {
2732        self.policy = policy.normalized();
2733        self
2734    }
2735}
2736
2737#[derive(Debug, Clone, Copy)]
2738struct LoadGovernorObservation {
2739    frame_time_us: f64,
2740    budget_us: f64,
2741    degradation: DegradationLevel,
2742    queue: crate::effect_system::QueueTelemetry,
2743    resize_coalescing_active: bool,
2744    strict_semantics_violation: bool,
2745}
2746
2747#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2748struct LoadGovernorSnapshot {
2749    mode: RuntimeLoadMode,
2750    mode_before: RuntimeLoadMode,
2751    pressure_class: RuntimePressureClass,
2752    disposition: RuntimeWorkDisposition,
2753    reason_code: &'static str,
2754    transition: bool,
2755    strict_semantics_preserved: bool,
2756    queue_in_flight: u64,
2757    queue_max_depth: Option<usize>,
2758    queue_dropped_delta: u64,
2759    resize_coalescing_active: bool,
2760    recovery_intervals_observed: u8,
2761    recovery_intervals_required: u8,
2762    deferred_work_total: u64,
2763    coalesced_work_total: u64,
2764    dropped_work_total: u64,
2765}
2766
2767#[derive(Debug, Clone)]
2768struct LoadGovernorState {
2769    enabled: bool,
2770    policy: LoadGovernorPolicy,
2771    max_queue_depth: usize,
2772    mode: RuntimeLoadMode,
2773    recovery_intervals_observed: u8,
2774    last_queue_dropped: u64,
2775    queue_baseline_initialized: bool,
2776    deferred_work_total: u64,
2777    coalesced_work_total: u64,
2778    dropped_work_total: u64,
2779}
2780
2781impl LoadGovernorState {
2782    fn new(config: LoadGovernorConfig, max_queue_depth: usize) -> Self {
2783        Self {
2784            enabled: config.enabled,
2785            policy: config.policy.normalized(),
2786            max_queue_depth,
2787            mode: RuntimeLoadMode::Healthy,
2788            recovery_intervals_observed: 0,
2789            last_queue_dropped: 0,
2790            queue_baseline_initialized: false,
2791            deferred_work_total: 0,
2792            coalesced_work_total: 0,
2793            dropped_work_total: 0,
2794        }
2795    }
2796
2797    fn observe(&mut self, observation: LoadGovernorObservation) -> LoadGovernorSnapshot {
2798        if !self.enabled {
2799            return self.snapshot(
2800                RuntimeLoadMode::Healthy,
2801                RuntimeLoadMode::Healthy,
2802                RuntimePressureClass::SteadyState,
2803                RuntimeWorkDisposition::AdmitAll,
2804                "governor_disabled",
2805                false,
2806                true,
2807                observation,
2808                0,
2809            );
2810        }
2811
2812        let dropped_delta = self.queue_dropped_delta(observation.queue.dropped);
2813        let pressure = self.classify_pressure(observation, dropped_delta);
2814        let mode_before = self.mode;
2815        let reason_code = self.reason_code(observation, pressure, dropped_delta);
2816
2817        match pressure {
2818            RuntimePressureClass::Unsafe => {
2819                self.mode = RuntimeLoadMode::Unsafe;
2820                self.recovery_intervals_observed = 0;
2821            }
2822            // Strict-semantics failure is terminal: once Unsafe is entered the
2823            // governor latches there regardless of later pressure (this mirrors
2824            // the `Unsafe => {}` arm in `observe_steady_interval`, which already
2825            // refuses to recover Unsafe under steady load). Without this guard,
2826            // a subsequent overload interval would downgrade Unsafe to
2827            // Degraded/Stressed and then recover to Healthy, silently escaping
2828            // the fail-fast guarantee. Only an explicit reset clears Unsafe.
2829            _ if self.mode == RuntimeLoadMode::Unsafe => {
2830                self.recovery_intervals_observed = 0;
2831            }
2832            RuntimePressureClass::HardOverload => {
2833                self.mode = RuntimeLoadMode::Degraded;
2834                self.recovery_intervals_observed = 0;
2835            }
2836            RuntimePressureClass::SoftOverload => {
2837                if self.mode != RuntimeLoadMode::Degraded {
2838                    self.mode = RuntimeLoadMode::Stressed;
2839                }
2840                self.recovery_intervals_observed = 0;
2841            }
2842            RuntimePressureClass::SteadyState => self.observe_steady_interval(),
2843        }
2844
2845        self.record_work_disposition(observation, dropped_delta);
2846        let disposition = Self::disposition_for_mode(self.mode);
2847        self.snapshot(
2848            self.mode,
2849            mode_before,
2850            pressure,
2851            disposition,
2852            if self.mode == RuntimeLoadMode::Unsafe {
2853                // Whether freshly violated this interval or latched from a prior
2854                // one, the terminal cause is always the strict-semantics failure.
2855                "strict_semantics_violation"
2856            } else if self.mode == RuntimeLoadMode::Recovered {
2857                "recovery_hysteresis_satisfied"
2858            } else if mode_before == RuntimeLoadMode::Recovered
2859                && self.mode == RuntimeLoadMode::Healthy
2860            {
2861                "recovered_interval_closed"
2862            } else {
2863                reason_code
2864            },
2865            mode_before != self.mode,
2866            // Reflect the latched mode, not the instantaneous pressure: once the
2867            // governor is Unsafe, strict semantics stay unpreserved even on an
2868            // interval whose raw pressure classified lower.
2869            self.mode != RuntimeLoadMode::Unsafe,
2870            observation,
2871            dropped_delta,
2872        )
2873    }
2874
2875    fn queue_dropped_delta(&mut self, dropped_total: u64) -> u64 {
2876        if !self.queue_baseline_initialized {
2877            self.queue_baseline_initialized = true;
2878            self.last_queue_dropped = dropped_total;
2879            return 0;
2880        }
2881        let delta = dropped_total.saturating_sub(self.last_queue_dropped);
2882        self.last_queue_dropped = dropped_total;
2883        delta
2884    }
2885
2886    fn classify_pressure(
2887        &self,
2888        observation: LoadGovernorObservation,
2889        dropped_delta: u64,
2890    ) -> RuntimePressureClass {
2891        if observation.strict_semantics_violation {
2892            return RuntimePressureClass::Unsafe;
2893        }
2894        if dropped_delta > 0
2895            || self
2896                .queue_ratio(observation.queue.in_flight)
2897                .is_some_and(|ratio| ratio >= self.policy.degraded_queue_watermark)
2898            || observation.degradation > DegradationLevel::Full
2899        {
2900            return RuntimePressureClass::HardOverload;
2901        }
2902        if self
2903            .queue_ratio(observation.queue.in_flight)
2904            .is_some_and(|ratio| ratio >= self.policy.stressed_queue_watermark)
2905            || observation.resize_coalescing_active
2906            || observation.frame_time_us
2907                > observation.budget_us * self.policy.budget_overrun_soft_ratio
2908        {
2909            return RuntimePressureClass::SoftOverload;
2910        }
2911        RuntimePressureClass::SteadyState
2912    }
2913
2914    fn observe_steady_interval(&mut self) {
2915        match self.mode {
2916            RuntimeLoadMode::Degraded => {
2917                self.recovery_intervals_observed = self
2918                    .recovery_intervals_observed
2919                    .saturating_add(1)
2920                    .min(self.policy.recovery_intervals);
2921                if self.recovery_intervals_observed >= self.policy.recovery_intervals {
2922                    self.mode = RuntimeLoadMode::Recovered;
2923                }
2924            }
2925            RuntimeLoadMode::Recovered | RuntimeLoadMode::Stressed => {
2926                self.mode = RuntimeLoadMode::Healthy;
2927                self.recovery_intervals_observed = 0;
2928            }
2929            RuntimeLoadMode::Healthy => {
2930                self.recovery_intervals_observed = 0;
2931            }
2932            RuntimeLoadMode::Unsafe => {}
2933        }
2934    }
2935
2936    fn record_work_disposition(
2937        &mut self,
2938        observation: LoadGovernorObservation,
2939        dropped_delta: u64,
2940    ) {
2941        if dropped_delta > 0 {
2942            self.dropped_work_total = self.dropped_work_total.saturating_add(dropped_delta);
2943        }
2944        match self.mode {
2945            RuntimeLoadMode::Stressed => {
2946                if observation.resize_coalescing_active {
2947                    self.coalesced_work_total = self.coalesced_work_total.saturating_add(1);
2948                }
2949            }
2950            RuntimeLoadMode::Degraded => {
2951                self.deferred_work_total = self.deferred_work_total.saturating_add(1);
2952                if observation.resize_coalescing_active {
2953                    self.coalesced_work_total = self.coalesced_work_total.saturating_add(1);
2954                }
2955            }
2956            RuntimeLoadMode::Healthy | RuntimeLoadMode::Recovered | RuntimeLoadMode::Unsafe => {}
2957        }
2958    }
2959
2960    fn reason_code(
2961        &self,
2962        observation: LoadGovernorObservation,
2963        pressure: RuntimePressureClass,
2964        dropped_delta: u64,
2965    ) -> &'static str {
2966        match pressure {
2967            RuntimePressureClass::Unsafe => "strict_semantics_violation",
2968            RuntimePressureClass::HardOverload if dropped_delta > 0 => "effect_queue_drop",
2969            RuntimePressureClass::HardOverload
2970                if self
2971                    .queue_ratio(observation.queue.in_flight)
2972                    .is_some_and(|ratio| ratio >= self.policy.degraded_queue_watermark) =>
2973            {
2974                "queue_degraded_watermark"
2975            }
2976            RuntimePressureClass::HardOverload => "budget_degradation_active",
2977            RuntimePressureClass::SoftOverload
2978                if self
2979                    .queue_ratio(observation.queue.in_flight)
2980                    .is_some_and(|ratio| ratio >= self.policy.stressed_queue_watermark) =>
2981            {
2982                "queue_stressed_watermark"
2983            }
2984            RuntimePressureClass::SoftOverload if observation.resize_coalescing_active => {
2985                "resize_coalescing_active"
2986            }
2987            RuntimePressureClass::SoftOverload => "frame_budget_overrun",
2988            RuntimePressureClass::SteadyState if self.mode == RuntimeLoadMode::Degraded => {
2989                "recovery_hysteresis_pending"
2990            }
2991            RuntimePressureClass::SteadyState => "steady_state",
2992        }
2993    }
2994
2995    fn queue_ratio(&self, in_flight: u64) -> Option<f64> {
2996        (self.max_queue_depth > 0).then(|| in_flight as f64 / self.max_queue_depth as f64)
2997    }
2998
2999    const fn disposition_for_mode(mode: RuntimeLoadMode) -> RuntimeWorkDisposition {
3000        match mode {
3001            RuntimeLoadMode::Healthy => RuntimeWorkDisposition::AdmitAll,
3002            RuntimeLoadMode::Stressed => RuntimeWorkDisposition::CoalesceVisibleDeferBackground,
3003            RuntimeLoadMode::Degraded => RuntimeWorkDisposition::DeferBackgroundDropBestEffort,
3004            RuntimeLoadMode::Recovered => RuntimeWorkDisposition::ReadmitAfterHysteresis,
3005            RuntimeLoadMode::Unsafe => RuntimeWorkDisposition::FailFastStrictGuarantee,
3006        }
3007    }
3008
3009    // Internal constructor that gathers all snapshot fields in one place; the
3010    // wide signature is intentional (a builder would add indirection for a
3011    // private helper). Pre-existing lint, unrelated to the #78 fix.
3012    #[allow(clippy::too_many_arguments)]
3013    fn snapshot(
3014        &self,
3015        mode: RuntimeLoadMode,
3016        mode_before: RuntimeLoadMode,
3017        pressure_class: RuntimePressureClass,
3018        disposition: RuntimeWorkDisposition,
3019        reason_code: &'static str,
3020        transition: bool,
3021        strict_semantics_preserved: bool,
3022        observation: LoadGovernorObservation,
3023        dropped_delta: u64,
3024    ) -> LoadGovernorSnapshot {
3025        LoadGovernorSnapshot {
3026            mode,
3027            mode_before,
3028            pressure_class,
3029            disposition,
3030            reason_code,
3031            transition,
3032            strict_semantics_preserved,
3033            queue_in_flight: observation.queue.in_flight,
3034            queue_max_depth: (self.max_queue_depth > 0).then_some(self.max_queue_depth),
3035            queue_dropped_delta: dropped_delta,
3036            resize_coalescing_active: observation.resize_coalescing_active,
3037            recovery_intervals_observed: self.recovery_intervals_observed,
3038            recovery_intervals_required: self.policy.recovery_intervals,
3039            deferred_work_total: self.deferred_work_total,
3040            coalesced_work_total: self.coalesced_work_total,
3041            dropped_work_total: self.dropped_work_total,
3042        }
3043    }
3044}
3045
3046/// Runtime lane for the Asupersync migration rollout.
3047///
3048/// Controls which subscription/effect execution backend is active.
3049/// The default is `Structured`, reflecting the completed CancellationToken migration (bd-3tmu4).
3050///
3051/// # Migration rollout
3052///
3053/// 1. `Legacy` โ€” pre-migration thread-based subscriptions with manual stop coordination
3054/// 2. `Structured` โ€” CancellationToken-backed subscriptions (current default after bd-3tmu4)
3055/// 3. `Asupersync` โ€” Asupersync blocking-task execution with structured subscriptions
3056///
3057/// Selection is logged at startup so operators can tell which lane is active.
3058/// Without `asupersync-executor`, requesting `Asupersync` falls back to `Structured`.
3059/// Executor initialization errors are returned to the caller.
3060#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
3061pub enum RuntimeLane {
3062    /// Pre-migration behavior: thread-based subscriptions with manual stop coordination.
3063    /// This is the safe default that preserves all existing semantics.
3064    Legacy,
3065    /// Structured cancellation: subscriptions use CancellationToken internally.
3066    /// Externally observable behavior is identical to Legacy.
3067    #[default]
3068    Structured,
3069    /// Execute tasks through the Asupersync blocking pool, retaining structured
3070    /// subscription cancellation. Requires the `asupersync-executor` feature;
3071    /// without it, falls back to Structured with a warning.
3072    Asupersync,
3073}
3074
3075impl RuntimeLane {
3076    /// Whether [`Self::Asupersync`] is backed by a real executor in this
3077    /// build, rather than falling back to [`Self::Structured`].
3078    ///
3079    /// Exposed because a feature flag is invisible to downstream crates:
3080    /// `#[cfg(feature = "asupersync-executor")]` in a crate that merely
3081    /// *depends* on `ftui-runtime` tests that crate's own features, not
3082    /// these. Without this, such a crate can only hard-code one of the two
3083    /// behaviours and be wrong in the other build - which is exactly what
3084    /// `ftui-harness`'s `runbook_step4_promote_to_enabled` did.
3085    #[must_use]
3086    pub const fn asupersync_available() -> bool {
3087        cfg!(feature = "asupersync-executor")
3088    }
3089
3090    /// Resolve the effective lane, applying fallback rules.
3091    ///
3092    /// Asupersync is available when `asupersync-executor` is compiled in -
3093    /// see [`Self::asupersync_available`]. Otherwise, its tasks use
3094    /// Structured's default executor.
3095    #[must_use]
3096    pub fn resolve(self) -> Self {
3097        #[cfg(not(feature = "asupersync-executor"))]
3098        if self == Self::Asupersync {
3099            tracing::warn!(
3100                target: crate::telemetry_schema::TARGET_RUNTIME,
3101                requested = "asupersync",
3102                resolved = "structured",
3103                missing_feature = "asupersync-executor",
3104                "Asupersync lane requires asupersync-executor; falling back to structured cancellation"
3105            );
3106            return Self::Structured;
3107        }
3108        self
3109    }
3110
3111    /// Returns a human-readable label for logging.
3112    #[must_use]
3113    pub fn label(self) -> &'static str {
3114        match self {
3115            Self::Legacy => "legacy",
3116            Self::Structured => "structured",
3117            Self::Asupersync => "asupersync",
3118        }
3119    }
3120
3121    /// Check if this lane uses structured cancellation (CancellationToken).
3122    #[must_use]
3123    pub fn uses_structured_cancellation(self) -> bool {
3124        matches!(self, Self::Structured | Self::Asupersync)
3125    }
3126
3127    /// Resolve the default task executor backend for this lane.
3128    ///
3129    /// # Input-lag regression fix (#78)
3130    ///
3131    /// The `Structured` lane changes *subscription cancellation* semantics
3132    /// (CancellationToken-backed stop signals in `subscription.rs`); it must
3133    /// NOT also collapse `Cmd::Task` concurrency. Earlier this returned
3134    /// `EffectQueue`, which routed every `Cmd::Task` through a single
3135    /// `effect_queue_loop` worker thread with a Smith's-rule (SPT) scheduler,
3136    /// serializing all tasks. Apps that forward PTY output via per-pane
3137    /// `Cmd::task` polling loops (e.g. 10ms drains) then contended for one
3138    /// serialized worker, adding per-keystroke head-of-line latency versus
3139    /// v0.2.1, where each `Cmd::task` got its own `std::thread::spawn`.
3140    ///
3141    /// Structured cancellation does not depend on the effect queue (stop
3142    /// signals are token-backed regardless of executor backend), so the two
3143    /// concerns are decoupled here: `Structured` keeps the structured
3144    /// cancellation semantics but restores per-task-thread (`Spawned`)
3145    /// execution. Apps that explicitly opt into `EffectQueue` still get it
3146    /// (the lane default only applies when the app uses the legacy default
3147    /// backend โ€” see `EffectQueueConfig::uses_legacy_default_backend`).
3148    #[must_use]
3149    pub fn task_executor_backend(self) -> TaskExecutorBackend {
3150        #[cfg(feature = "asupersync-executor")]
3151        if self == Self::Asupersync {
3152            return TaskExecutorBackend::Asupersync;
3153        }
3154        // Structured cancellation does not serialize tasks. An unavailable
3155        // Asupersync lane resolves to Structured before backend selection.
3156        DEFAULT_TASK_BACKEND
3157    }
3158
3159    /// Read the lane from the `FTUI_RUNTIME_LANE` environment variable.
3160    ///
3161    /// Accepted values (case-insensitive): `legacy`, `structured`, `asupersync`.
3162    /// Returns `None` if the variable is unset or contains an unrecognized value.
3163    #[must_use]
3164    pub fn from_env() -> Option<Self> {
3165        let val = std::env::var("FTUI_RUNTIME_LANE").ok()?;
3166        Self::parse(&val)
3167    }
3168
3169    /// Parse a lane name (case-insensitive).
3170    ///
3171    /// Returns `None` for unrecognized values.
3172    #[must_use]
3173    pub fn parse(s: &str) -> Option<Self> {
3174        match s.to_ascii_lowercase().as_str() {
3175            "legacy" => Some(Self::Legacy),
3176            "structured" => Some(Self::Structured),
3177            "asupersync" => Some(Self::Asupersync),
3178            _ => {
3179                tracing::warn!(
3180                    target: crate::telemetry_schema::TARGET_RUNTIME,
3181                    value = s,
3182                    "RuntimeLane::parse: unrecognized value"
3183                );
3184                None
3185            }
3186        }
3187    }
3188}
3189
3190/// Rollout policy for the Asupersync migration (bd-2crbt).
3191///
3192/// Controls how the runtime lane transition is managed:
3193///
3194/// - `Off` โ€” use only the configured lane, no shadow comparison.
3195/// - `Shadow` โ€” run both baseline and candidate lanes, compare outputs,
3196///   but use only the baseline lane for actual rendering. Evidence is emitted
3197///   to the configured JSONL sink for operator review.
3198/// - `Enabled` โ€” use the candidate lane for rendering (requires prior shadow
3199///   evidence showing deterministic match).
3200///
3201/// The policy is logged at startup and can be overridden via the
3202/// `FTUI_ROLLOUT_POLICY` environment variable (`off`, `shadow`, `enabled`).
3203#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
3204pub enum RolloutPolicy {
3205    /// No rollout activity โ€” use the configured lane directly.
3206    #[default]
3207    Off,
3208    /// Shadow-run comparison mode: run both lanes, emit evidence, use baseline.
3209    Shadow,
3210    /// Candidate lane is live โ€” requires prior shadow evidence.
3211    Enabled,
3212}
3213
3214impl RolloutPolicy {
3215    /// Read the policy from the `FTUI_ROLLOUT_POLICY` environment variable.
3216    ///
3217    /// Accepted values (case-insensitive): `off`, `shadow`, `enabled`.
3218    /// Returns `None` if unset or unrecognized.
3219    #[must_use]
3220    pub fn from_env() -> Option<Self> {
3221        let val = std::env::var("FTUI_ROLLOUT_POLICY").ok()?;
3222        Self::parse(&val)
3223    }
3224
3225    /// Parse a rollout policy name (case-insensitive).
3226    ///
3227    /// Returns `None` for unrecognized values.
3228    #[must_use]
3229    pub fn parse(s: &str) -> Option<Self> {
3230        match s.to_ascii_lowercase().as_str() {
3231            "off" => Some(Self::Off),
3232            "shadow" => Some(Self::Shadow),
3233            "enabled" => Some(Self::Enabled),
3234            _ => {
3235                tracing::warn!(
3236                    target: crate::telemetry_schema::TARGET_RUNTIME,
3237                    value = s,
3238                    "RolloutPolicy::parse: unrecognized value"
3239                );
3240                None
3241            }
3242        }
3243    }
3244
3245    /// Returns a human-readable label for logging.
3246    #[must_use]
3247    pub fn label(self) -> &'static str {
3248        match self {
3249            Self::Off => "off",
3250            Self::Shadow => "shadow",
3251            Self::Enabled => "enabled",
3252        }
3253    }
3254
3255    /// Whether this policy involves shadow comparison.
3256    #[must_use]
3257    pub fn is_shadow(self) -> bool {
3258        matches!(self, Self::Shadow)
3259    }
3260}
3261
3262impl std::fmt::Display for RolloutPolicy {
3263    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3264        f.write_str(self.label())
3265    }
3266}
3267
3268impl std::fmt::Display for RuntimeLane {
3269    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3270        f.write_str(self.label())
3271    }
3272}
3273
3274/// Configuration for the program runtime.
3275#[derive(Debug, Clone)]
3276pub struct ProgramConfig {
3277    /// Screen mode (inline or alternate screen).
3278    pub screen_mode: ScreenMode,
3279    /// UI anchor for inline mode.
3280    pub ui_anchor: UiAnchor,
3281    /// Optional maximum distinct hyperlinks admitted per rendered frame.
3282    ///
3283    /// Retains at most twice this many registry slots so the last presented
3284    /// frame keeps stable IDs during diffing. Excess links render as plain
3285    /// text. Models opting in must register URLs on each view, rather than
3286    /// cache numeric link IDs across frames. `None` preserves unmanaged IDs;
3287    /// `Some(0)` disables link registration. The limit is clamped to half the
3288    /// 24-bit ID space. Applying it to an existing writer invalidates its IDs
3289    /// and presentation baseline.
3290    pub hyperlink_limit: Option<usize>,
3291    /// Frame budget configuration.
3292    pub budget: FrameBudgetConfig,
3293    /// Runtime load-governor configuration.
3294    pub load_governor: LoadGovernorConfig,
3295    /// Diff strategy configuration for the terminal writer.
3296    pub diff_config: RuntimeDiffConfig,
3297    /// Evidence JSONL sink configuration.
3298    pub evidence_sink: EvidenceSinkConfig,
3299    /// Render-trace recorder configuration.
3300    pub render_trace: RenderTraceConfig,
3301    /// Optional frame timing sink.
3302    pub frame_timing: Option<FrameTimingConfig>,
3303    /// Conformal predictor configuration for frame-time risk gating.
3304    pub conformal_config: Option<ConformalConfig>,
3305    /// Locale context used for rendering.
3306    pub locale_context: LocaleContext,
3307    /// Input poll timeout.
3308    pub poll_timeout: Duration,
3309    /// Immediate event-drain policy for burst handling.
3310    pub immediate_drain: ImmediateDrainConfig,
3311    /// Resize coalescer configuration.
3312    pub resize_coalescer: CoalescerConfig,
3313    /// Resize handling behavior (immediate/throttled).
3314    pub resize_behavior: ResizeBehavior,
3315    /// Forced terminal size override (when set, resize events are ignored).
3316    pub forced_size: Option<(u16, u16)>,
3317    /// Mouse capture policy (`Auto`, `On`, `Off`).
3318    ///
3319    /// `Auto` is inline-safe: off in inline modes, on in alt-screen mode.
3320    pub mouse_capture_policy: MouseCapturePolicy,
3321    /// Enable bracketed paste.
3322    pub bracketed_paste: bool,
3323    /// Enable focus reporting.
3324    pub focus_reporting: bool,
3325    /// Enable Kitty keyboard protocol (repeat/release events).
3326    pub kitty_keyboard: bool,
3327    /// State persistence configuration.
3328    pub persistence: PersistenceConfig,
3329    /// Inline auto UI height remeasurement policy.
3330    pub inline_auto_remeasure: Option<InlineAutoRemeasureConfig>,
3331    /// Gesture recognition (clicks, drags, long press, chords) delivered to
3332    /// [`Model::on_gesture`]; `None` (the default) runs no recognizer.
3333    pub gestures: Option<ftui_core::gesture::GestureConfig>,
3334    /// Accessibility tree collection. When set, every rendered frame builds
3335    /// an [`A11yTree`] from the nodes widgets push into the [`Frame`], diffs
3336    /// it against the previous frame and derives screen-reader
3337    /// announcements under this policy. Tracing and evidence export metadata
3338    /// only by default; [`Model::on_accessibility`] receives the complete
3339    /// local announcements. `None` (the default) collects nothing and adds
3340    /// no per-frame work.
3341    pub accessibility: Option<ScreenReaderPolicy>,
3342    /// Include announcement text in the explicitly configured evidence sink.
3343    ///
3344    /// Defaults to `false`: evidence rows contain `"text": null`. Enable only
3345    /// for an intentional local content capture; labels and edited text may
3346    /// be sensitive. Ordinary tracing never includes announcement content,
3347    /// and this setting does not change the local accessibility callback.
3348    pub accessibility_evidence_text: bool,
3349    /// Widget refresh selection configuration.
3350    pub widget_refresh: WidgetRefreshConfig,
3351    /// Effect queue scheduling configuration.
3352    pub effect_queue: EffectQueueConfig,
3353    /// Frame guardrails configuration (memory + queue safety limits).
3354    pub guardrails: GuardrailsConfig,
3355    /// Install signal handlers for cleanup on SIGINT/SIGTERM/SIGHUP.
3356    ///
3357    /// Defaults to `true` for application safety. Set to `false` in tests or
3358    /// when the embedding application manages signals.
3359    pub intercept_signals: bool,
3360    /// Handle job-control stops (SIGTSTP, SIGTTIN, SIGTTOU): hand the terminal
3361    /// back to the shell before the process stops and restore it, with a full
3362    /// repaint, when it is continued (`docs/spec/suspend-resume.md`).
3363    ///
3364    /// Defaults to `true`. Takes effect only with [`intercept_signals`](Self::intercept_signals)
3365    /// and a backend that can release its terminal session (the native TTY
3366    /// backend); elsewhere the signals keep their default action, which stops
3367    /// the process with the terminal still in raw mode.
3368    pub job_control: bool,
3369    /// Treat a Ctrl-Z key press as a request to suspend (default: `false`).
3370    ///
3371    /// Raw mode turns off the terminal's own Ctrl-Z handling, so the key
3372    /// arrives as an ordinary event. It is off by default because Ctrl-Z is
3373    /// undo in `TextArea` and in the showcase's editors; with it on, the key
3374    /// never reaches the model. Requires [`job_control`](Self::job_control).
3375    pub ctrl_z_suspends: bool,
3376    /// Optional tick strategy for selective background screen ticking.
3377    ///
3378    /// When `None` (default), all screens tick every frame (current behavior).
3379    /// When set, the runtime consults the strategy for each inactive screen.
3380    pub tick_strategy: Option<crate::tick_strategy::TickStrategyKind>,
3381    /// Runtime execution lane for the Asupersync migration rollout.
3382    ///
3383    /// Controls which subscription/effect backend is active.
3384    /// Defaults to `Structured` (CancellationToken-backed, current migration state).
3385    /// Logged at startup so operators can identify the active lane.
3386    pub runtime_lane: RuntimeLane,
3387    /// Rollout policy for the Asupersync migration (bd-2crbt).
3388    ///
3389    /// Controls whether shadow-run comparison is active during this session.
3390    /// When `Shadow`, both the baseline and candidate lanes run in parallel
3391    /// and evidence is emitted; rendering uses the baseline lane only.
3392    pub rollout_policy: RolloutPolicy,
3393    /// Coalesce high-frequency mouse moves and consecutive same-direction scrolls.
3394    ///
3395    /// When `false` (the default), every input event triggers a model update.
3396    /// When `true`, mouse move bursts and consecutive same-direction scroll
3397    /// events are coalesced so intermediate states do not trigger redundant
3398    /// updates and renders. The recognizer still receives all raw events.
3399    pub event_coalescing: bool,
3400    /// Opt into SGR-Pixels (`DECSET ?1016h`) mouse reporting when mouse capture
3401    /// is enabled (`false` by default).
3402    pub pixel_mouse: bool,
3403    /// Forward [`Event::TerminalResponse`] (DCS/APC/XTWINOPS replies) to
3404    /// [`Model::update`] instead of consuming them inside `Program` (`false`
3405    /// by default).
3406    pub deliver_terminal_responses: bool,
3407}
3408
3409impl Default for ProgramConfig {
3410    fn default() -> Self {
3411        Self {
3412            screen_mode: ScreenMode::Inline { ui_height: 4 },
3413            ui_anchor: UiAnchor::Bottom,
3414            hyperlink_limit: None,
3415            budget: FrameBudgetConfig::default(),
3416            load_governor: LoadGovernorConfig::default(),
3417            diff_config: RuntimeDiffConfig::default(),
3418            evidence_sink: EvidenceSinkConfig::default(),
3419            render_trace: RenderTraceConfig::default(),
3420            frame_timing: None,
3421            // Conformal frame-time risk gating is on by default: the predictor
3422            // only starts gating once a bucket has `min_samples` (20) real
3423            // frame timings, so a fresh program renders at full fidelity
3424            // during warm-up and degrades only on measured evidence. Use
3425            // `without_conformal()` to opt out.
3426            conformal_config: Some(ConformalConfig::default()),
3427            locale_context: LocaleContext::global(),
3428            poll_timeout: Duration::from_millis(100),
3429            immediate_drain: ImmediateDrainConfig::default(),
3430            resize_coalescer: CoalescerConfig::default(),
3431            resize_behavior: ResizeBehavior::Throttled,
3432            forced_size: None,
3433            mouse_capture_policy: MouseCapturePolicy::Auto,
3434            bracketed_paste: true,
3435            focus_reporting: false,
3436            kitty_keyboard: false,
3437            persistence: PersistenceConfig::default(),
3438            inline_auto_remeasure: None,
3439            gestures: None,
3440            accessibility: None,
3441            accessibility_evidence_text: false,
3442            widget_refresh: WidgetRefreshConfig::default(),
3443            effect_queue: EffectQueueConfig::default(),
3444            guardrails: GuardrailsConfig::default(),
3445            intercept_signals: true,
3446            job_control: true,
3447            ctrl_z_suspends: false,
3448            tick_strategy: None,
3449            runtime_lane: RuntimeLane::default(),
3450            rollout_policy: RolloutPolicy::default(),
3451            event_coalescing: false,
3452            pixel_mouse: false,
3453            deliver_terminal_responses: false,
3454        }
3455    }
3456}
3457
3458impl ProgramConfig {
3459    /// Create config for fullscreen applications.
3460    pub fn fullscreen() -> Self {
3461        Self {
3462            screen_mode: ScreenMode::AltScreen,
3463            ..Default::default()
3464        }
3465    }
3466
3467    /// Create config for inline mode with specified height.
3468    pub fn inline(height: u16) -> Self {
3469        Self {
3470            screen_mode: ScreenMode::Inline { ui_height: height },
3471            ..Default::default()
3472        }
3473    }
3474
3475    /// Create config for inline mode with automatic UI height.
3476    pub fn inline_auto(min_height: u16, max_height: u16) -> Self {
3477        Self {
3478            screen_mode: ScreenMode::InlineAuto {
3479                min_height,
3480                max_height,
3481            },
3482            inline_auto_remeasure: Some(InlineAutoRemeasureConfig::default()),
3483            ..Default::default()
3484        }
3485    }
3486
3487    /// Run a gesture recognizer over the input stream and deliver recognized
3488    /// gestures to [`Model::on_gesture`]. Mouse gestures need mouse capture
3489    /// (see [`Self::with_mouse_capture_policy`]).
3490    #[must_use]
3491    pub fn with_gestures(mut self, config: ftui_core::gesture::GestureConfig) -> Self {
3492        self.gestures = Some(config);
3493        self
3494    }
3495
3496    /// Coalesce high-frequency mouse moves and consecutive same-direction scrolls.
3497    ///
3498    /// When enabled, mouse move bursts and same-direction scrolls are coalesced
3499    /// so intermediate positions do not trigger individual model updates and renders.
3500    /// Pending events are flushed at the end of ready event bursts, before
3501    /// non-coalescable events, and on ticks. Raw events are still fed to the
3502    /// gesture recognizer before coalescing.
3503    #[must_use]
3504    pub fn with_event_coalescing(mut self, enabled: bool) -> Self {
3505        self.event_coalescing = enabled;
3506        self
3507    }
3508
3509    /// Opt into SGR-Pixels (`DECSET ?1016h`) mouse reporting.
3510    #[must_use]
3511    pub fn with_pixel_mouse(mut self, enabled: bool) -> Self {
3512        self.pixel_mouse = enabled;
3513        self
3514    }
3515
3516    /// Forward [`Event::TerminalResponse`] replies to [`Model::update`].
3517    #[must_use]
3518    pub fn with_deliver_terminal_responses(mut self, enabled: bool) -> Self {
3519        self.deliver_terminal_responses = enabled;
3520        self
3521    }
3522
3523    /// Build an accessibility tree every frame and derive screen-reader
3524    /// announcements under `policy` (see [`Self::accessibility`]). Read the
3525    /// results through [`Program::accessibility_tree`] and
3526    /// [`Program::accessibility_announcements`].
3527    #[must_use]
3528    pub fn with_accessibility(mut self, policy: ScreenReaderPolicy) -> Self {
3529        self.accessibility = Some(policy);
3530        self
3531    }
3532
3533    /// Opt into announcement content in the configured evidence sink.
3534    /// See [`Self::accessibility_evidence_text`] for the privacy contract.
3535    #[must_use]
3536    pub fn with_accessibility_evidence_text(mut self, include_text: bool) -> Self {
3537        self.accessibility_evidence_text = include_text;
3538        self
3539    }
3540
3541    /// Enable mouse support.
3542    #[must_use]
3543    pub fn with_mouse(mut self) -> Self {
3544        self.mouse_capture_policy = MouseCapturePolicy::On;
3545        self
3546    }
3547
3548    /// Set mouse capture policy.
3549    #[must_use]
3550    pub fn with_mouse_capture_policy(mut self, policy: MouseCapturePolicy) -> Self {
3551        self.mouse_capture_policy = policy;
3552        self
3553    }
3554
3555    /// Force mouse capture enabled/disabled regardless of screen mode.
3556    #[must_use]
3557    pub fn with_mouse_enabled(mut self, enabled: bool) -> Self {
3558        self.mouse_capture_policy = if enabled {
3559            MouseCapturePolicy::On
3560        } else {
3561            MouseCapturePolicy::Off
3562        };
3563        self
3564    }
3565
3566    /// Resolve mouse capture using the configured policy and screen mode.
3567    #[must_use]
3568    pub const fn resolved_mouse_capture(&self) -> bool {
3569        self.mouse_capture_policy.resolve(self.screen_mode)
3570    }
3571
3572    /// Set the budget configuration.
3573    #[must_use]
3574    pub fn with_budget(mut self, budget: FrameBudgetConfig) -> Self {
3575        self.budget = budget;
3576        self
3577    }
3578
3579    /// Bound per-frame hyperlink admission and retire unused URLs.
3580    /// See [`Self::hyperlink_limit`] for the ID lifetime contract.
3581    #[must_use]
3582    pub fn with_hyperlink_limit(mut self, limit: usize) -> Self {
3583        self.hyperlink_limit = Some(limit);
3584        self
3585    }
3586
3587    /// Set the runtime load-governor configuration.
3588    #[must_use]
3589    pub fn with_load_governor(mut self, config: LoadGovernorConfig) -> Self {
3590        self.load_governor = config;
3591        self
3592    }
3593
3594    /// Disable the adaptive load governor and use legacy render-budget behavior.
3595    #[must_use]
3596    pub fn without_load_governor(mut self) -> Self {
3597        self.load_governor = LoadGovernorConfig::disabled();
3598        self
3599    }
3600
3601    /// Set the diff strategy configuration for the terminal writer.
3602    #[must_use]
3603    pub fn with_diff_config(mut self, diff_config: RuntimeDiffConfig) -> Self {
3604        self.diff_config = diff_config;
3605        self
3606    }
3607
3608    /// Set the evidence JSONL sink configuration.
3609    #[must_use]
3610    pub fn with_evidence_sink(mut self, config: EvidenceSinkConfig) -> Self {
3611        self.evidence_sink = config;
3612        self
3613    }
3614
3615    /// Set the render-trace recorder configuration.
3616    #[must_use]
3617    pub fn with_render_trace(mut self, config: RenderTraceConfig) -> Self {
3618        self.render_trace = config;
3619        self
3620    }
3621
3622    /// Set a frame timing sink for per-frame profiling.
3623    #[must_use]
3624    pub fn with_frame_timing(mut self, config: FrameTimingConfig) -> Self {
3625        self.frame_timing = Some(config);
3626        self
3627    }
3628
3629    /// Enable conformal frame-time risk gating with the given config.
3630    #[must_use]
3631    pub fn with_conformal_config(mut self, config: ConformalConfig) -> Self {
3632        self.conformal_config = Some(config);
3633        self
3634    }
3635
3636    /// Disable conformal frame-time risk gating.
3637    #[must_use]
3638    pub fn without_conformal(mut self) -> Self {
3639        self.conformal_config = None;
3640        self
3641    }
3642
3643    /// Set the locale context used for rendering.
3644    #[must_use]
3645    pub fn with_locale_context(mut self, locale_context: LocaleContext) -> Self {
3646        self.locale_context = locale_context;
3647        self
3648    }
3649
3650    /// Set the base locale used for rendering.
3651    #[must_use]
3652    pub fn with_locale(mut self, locale: impl Into<crate::locale::Locale>) -> Self {
3653        self.locale_context = LocaleContext::new(locale);
3654        self
3655    }
3656
3657    /// Set the widget refresh selection configuration.
3658    #[must_use]
3659    pub fn with_widget_refresh(mut self, config: WidgetRefreshConfig) -> Self {
3660        self.widget_refresh = config;
3661        self
3662    }
3663
3664    /// Set the effect queue scheduling configuration.
3665    #[must_use]
3666    pub fn with_effect_queue(mut self, config: EffectQueueConfig) -> Self {
3667        self.effect_queue = config;
3668        self
3669    }
3670
3671    /// Set the resize coalescer configuration.
3672    #[must_use]
3673    pub fn with_resize_coalescer(mut self, config: CoalescerConfig) -> Self {
3674        self.resize_coalescer = config;
3675        self
3676    }
3677
3678    /// Set the resize handling behavior.
3679    #[must_use]
3680    pub fn with_resize_behavior(mut self, behavior: ResizeBehavior) -> Self {
3681        self.resize_behavior = behavior;
3682        self
3683    }
3684
3685    /// Force a fixed terminal size (cols, rows). Resize events are ignored.
3686    #[must_use]
3687    pub fn with_forced_size(mut self, width: u16, height: u16) -> Self {
3688        let width = width.max(1);
3689        let height = height.max(1);
3690        self.forced_size = Some((width, height));
3691        self
3692    }
3693
3694    /// Clear any forced terminal size override.
3695    #[must_use]
3696    pub fn without_forced_size(mut self) -> Self {
3697        self.forced_size = None;
3698        self
3699    }
3700
3701    /// Toggle legacy immediate-resize behavior for migration.
3702    #[must_use]
3703    pub fn with_legacy_resize(mut self, enabled: bool) -> Self {
3704        if enabled {
3705            self.resize_behavior = ResizeBehavior::Immediate;
3706        }
3707        self
3708    }
3709
3710    /// Set the persistence configuration.
3711    #[must_use]
3712    pub fn with_persistence(mut self, persistence: PersistenceConfig) -> Self {
3713        self.persistence = persistence;
3714        self
3715    }
3716
3717    /// Enable persistence with the given registry.
3718    #[must_use]
3719    pub fn with_registry(mut self, registry: std::sync::Arc<StateRegistry>) -> Self {
3720        self.persistence = PersistenceConfig::with_registry(registry);
3721        self
3722    }
3723
3724    /// Enable inline auto UI height remeasurement with the given policy.
3725    #[must_use]
3726    pub fn with_inline_auto_remeasure(mut self, config: InlineAutoRemeasureConfig) -> Self {
3727        self.inline_auto_remeasure = Some(config);
3728        self
3729    }
3730
3731    /// Disable inline auto UI height remeasurement.
3732    #[must_use]
3733    pub fn without_inline_auto_remeasure(mut self) -> Self {
3734        self.inline_auto_remeasure = None;
3735        self
3736    }
3737
3738    /// Enable or disable signal interception (SIGHUP/SIGTERM/SIGINT) for cleanup.
3739    #[must_use]
3740    pub fn with_signal_interception(mut self, enabled: bool) -> Self {
3741        self.intercept_signals = enabled;
3742        self
3743    }
3744
3745    /// Enable or disable job-control handling (SIGTSTP/SIGTTIN/SIGTTOU).
3746    /// See [`ProgramConfig::job_control`].
3747    #[must_use]
3748    pub fn with_job_control(mut self, enabled: bool) -> Self {
3749        self.job_control = enabled;
3750        self
3751    }
3752
3753    /// Make a Ctrl-Z key press suspend the program instead of reaching the
3754    /// model. See [`ProgramConfig::ctrl_z_suspends`].
3755    #[must_use]
3756    pub fn with_ctrl_z_suspend(mut self, enabled: bool) -> Self {
3757        self.ctrl_z_suspends = enabled;
3758        self
3759    }
3760
3761    /// Set frame guardrails configuration.
3762    #[must_use]
3763    pub fn with_guardrails(mut self, config: GuardrailsConfig) -> Self {
3764        self.guardrails = config;
3765        self
3766    }
3767
3768    /// Set the immediate event-drain policy for burst handling.
3769    #[must_use]
3770    pub fn with_immediate_drain(mut self, config: ImmediateDrainConfig) -> Self {
3771        self.immediate_drain = config;
3772        self
3773    }
3774
3775    /// Set the tick strategy for selective background screen ticking.
3776    ///
3777    /// When set, the runtime consults the strategy to decide which inactive
3778    /// screens should tick on each frame. Without a strategy, all screens
3779    /// tick every frame (backwards-compatible default).
3780    ///
3781    /// ```ignore
3782    /// ProgramConfig::default()
3783    ///     .with_tick_strategy(TickStrategyKind::Uniform { divisor: 5 })
3784    /// ```
3785    #[must_use]
3786    pub fn with_tick_strategy(mut self, strategy: crate::tick_strategy::TickStrategyKind) -> Self {
3787        self.tick_strategy = Some(strategy);
3788        self
3789    }
3790
3791    /// Set the runtime execution lane.
3792    #[must_use]
3793    pub fn with_lane(mut self, lane: RuntimeLane) -> Self {
3794        self.runtime_lane = lane;
3795        self
3796    }
3797
3798    /// Set the rollout policy for the Asupersync migration.
3799    #[must_use]
3800    pub fn with_rollout_policy(mut self, policy: RolloutPolicy) -> Self {
3801        self.rollout_policy = policy;
3802        self
3803    }
3804
3805    /// Apply environment-variable overrides for lane and rollout policy.
3806    ///
3807    /// Reads `FTUI_RUNTIME_LANE` and `FTUI_ROLLOUT_POLICY`. Unset variables
3808    /// are ignored. Unrecognized values emit a `tracing::warn` and are
3809    /// ignored (the programmatic default or prior builder value is retained).
3810    #[must_use]
3811    pub fn with_env_overrides(self) -> Self {
3812        self.with_env_values(
3813            std::env::var("FTUI_RUNTIME_LANE").ok().as_deref(),
3814            std::env::var("FTUI_ROLLOUT_POLICY").ok().as_deref(),
3815        )
3816    }
3817
3818    #[must_use]
3819    fn with_env_values(mut self, lane: Option<&str>, rollout_policy: Option<&str>) -> Self {
3820        if let Some(lane) = lane.and_then(RuntimeLane::parse) {
3821            self.runtime_lane = lane;
3822        }
3823        if let Some(policy) = rollout_policy.and_then(RolloutPolicy::parse) {
3824            self.rollout_policy = policy;
3825        }
3826        self
3827    }
3828
3829    #[must_use]
3830    fn resolved_effect_queue_config(&self, resolved_lane: RuntimeLane) -> EffectQueueConfig {
3831        if !self.effect_queue.uses_legacy_default_backend() {
3832            return self.effect_queue.clone();
3833        }
3834
3835        self.effect_queue
3836            .clone()
3837            .with_backend(resolved_lane.task_executor_backend())
3838    }
3839}
3840
3841fn render_budget_from_program_config(config: &ProgramConfig) -> RenderBudget {
3842    let budget = RenderBudget::from_config(&config.budget);
3843    if config.load_governor.enabled {
3844        let mut controller = config.load_governor.budget_controller.clone();
3845        controller.target = config.budget.total;
3846        budget.with_controller(controller)
3847    } else {
3848        budget
3849    }
3850}
3851
3852enum EffectCommand<M> {
3853    Enqueue(TaskSpec, Box<dyn FnOnce() -> M + Send>),
3854    Shutdown,
3855}
3856
3857#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3858enum EffectLoopControl {
3859    Continue,
3860    ShutdownRequested,
3861}
3862
3863struct EffectQueue<M: Send + 'static> {
3864    sender: mpsc::Sender<EffectCommand<M>>,
3865    handle: Option<JoinHandle<()>>,
3866    closed: bool,
3867    /// Tasks handed to the queue and not finished โ€” still in the channel,
3868    /// accepted by the loop, or running. Incremented by `enqueue`,
3869    /// decremented by the loop when a task finishes or is dropped; read by
3870    /// the frame guardrail.
3871    outstanding: std::sync::Arc<std::sync::atomic::AtomicUsize>,
3872    /// `EffectQueueConfig::max_queue_depth` (0 = unbounded), enforced at
3873    /// submission. The loop runs one task at a time, so a check on the loop
3874    /// side alone let any number of submissions pile up in the unbounded
3875    /// channel while a long task ran (bd-g00-root-epic-ewths.50.1).
3876    max_depth: usize,
3877}
3878
3879impl<M: Send + 'static> EffectQueue<M> {
3880    fn start(
3881        config: EffectQueueConfig,
3882        result_sender: mpsc::Sender<M>,
3883        evidence_sink: Option<EvidenceSink>,
3884    ) -> io::Result<Self> {
3885        let (tx, rx) = mpsc::channel::<EffectCommand<M>>();
3886        let outstanding = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
3887        let loop_outstanding = std::sync::Arc::clone(&outstanding);
3888        let max_depth = config.max_queue_depth;
3889        let handle = thread::Builder::new()
3890            .name("ftui-effects".into())
3891            .spawn(move || {
3892                effect_queue_loop(config, rx, result_sender, evidence_sink, &loop_outstanding);
3893            })?;
3894
3895        Ok(Self {
3896            sender: tx,
3897            handle: Some(handle),
3898            closed: false,
3899            outstanding,
3900            max_depth,
3901        })
3902    }
3903
3904    /// Tasks handed to the queue that have not finished.
3905    fn in_flight(&self) -> usize {
3906        self.outstanding.load(std::sync::atomic::Ordering::Acquire)
3907    }
3908
3909    fn enqueue(&self, spec: TaskSpec, task: Box<dyn FnOnce() -> M + Send>) {
3910        use std::sync::atomic::Ordering;
3911        if self.closed {
3912            crate::effect_system::record_queue_drop("post_shutdown");
3913            tracing::debug!(
3914                target: crate::telemetry_schema::TARGET_EFFECT,
3915                "rejecting task enqueue after effect queue shutdown"
3916            );
3917            return;
3918        }
3919        let max_depth = self.max_depth;
3920        let admitted = self
3921            .outstanding
3922            .try_update(Ordering::AcqRel, Ordering::Acquire, |n| {
3923                (max_depth == 0 || n < max_depth).then_some(n + 1)
3924            })
3925            .is_ok();
3926        if !admitted {
3927            crate::effect_system::record_queue_drop("backpressure");
3928            return;
3929        }
3930        if self
3931            .sender
3932            .send(EffectCommand::Enqueue(spec, task))
3933            .is_err()
3934        {
3935            release_outstanding(&self.outstanding);
3936            crate::effect_system::record_queue_drop("channel_closed");
3937        }
3938    }
3939
3940    /// Timeout for the effect-queue thread to finish after sending Shutdown.
3941    const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(2);
3942    /// Poll interval when waiting for the effect-queue thread (bd-170o5).
3943    ///
3944    /// This sleep-poll pattern is the idiomatic Rust approach for bounded
3945    /// thread joins โ€” `JoinHandle` has no `join_timeout` in stable Rust.
3946    /// 1ms is chosen to minimize shutdown latency while avoiding spin.
3947    const SHUTDOWN_POLL: Duration = Duration::from_millis(1);
3948
3949    fn shutdown(&mut self) {
3950        self.closed = true;
3951        let _ = self.sender.send(EffectCommand::Shutdown);
3952        if let Some(handle) = self.handle.take() {
3953            let start = Instant::now();
3954            // Fast path: most shutdowns complete nearly instantly after the
3955            // Shutdown command is drained. Check once before entering poll loop.
3956            if handle.is_finished() {
3957                let _ = handle.join();
3958                let elapsed_us = start.elapsed().as_micros() as u64;
3959                tracing::debug!(
3960                    target: crate::telemetry_schema::TARGET_RUNTIME,
3961                    elapsed_us,
3962                    "effect-queue shutdown (fast path)"
3963                );
3964                return;
3965            }
3966            // Slow path: bounded poll loop for in-flight tasks (bd-170o5).
3967            while !handle.is_finished() {
3968                if start.elapsed() >= Self::SHUTDOWN_TIMEOUT {
3969                    tracing::warn!(
3970                        target: crate::telemetry_schema::TARGET_RUNTIME,
3971                        timeout_ms = Self::SHUTDOWN_TIMEOUT.as_millis() as u64,
3972                        "effect-queue thread did not stop within timeout; detaching"
3973                    );
3974                    return;
3975                }
3976                thread::sleep(Self::SHUTDOWN_POLL);
3977            }
3978            let _ = handle.join();
3979            let elapsed_us = start.elapsed().as_micros() as u64;
3980            tracing::debug!(
3981                target: crate::telemetry_schema::TARGET_RUNTIME,
3982                elapsed_us,
3983                "effect-queue shutdown (slow path)"
3984            );
3985        }
3986    }
3987}
3988
3989impl<M: Send + 'static> Drop for EffectQueue<M> {
3990    fn drop(&mut self) {
3991        self.shutdown();
3992    }
3993}
3994
3995struct SpawnTaskExecutor<M: Send + 'static> {
3996    result_sender: mpsc::Sender<M>,
3997    evidence_sink: Option<EvidenceSink>,
3998    handles: Vec<JoinHandle<()>>,
3999    /// Backpressure bound on in-flight spawned threads (`0` = unbounded),
4000    /// matching the EffectQueue / asupersync lanes.
4001    max_queue_depth: usize,
4002    /// Tasks shed by backpressure or post-shutdown rejection.
4003    dropped: u64,
4004    closed: bool,
4005}
4006
4007impl<M: Send + 'static> SpawnTaskExecutor<M> {
4008    const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(2);
4009    /// Poll interval for bounded thread joins (bd-170o5).
4010    ///
4011    /// Same rationale as `EffectQueue::SHUTDOWN_POLL` โ€” `JoinHandle` has no
4012    /// `join_timeout` in stable Rust, so we poll `is_finished()` with a
4013    /// 1ms sleep to minimize shutdown latency while avoiding spin.
4014    const SHUTDOWN_POLL: Duration = Duration::from_millis(1);
4015
4016    fn new(
4017        result_sender: mpsc::Sender<M>,
4018        evidence_sink: Option<EvidenceSink>,
4019        max_queue_depth: usize,
4020    ) -> Self {
4021        Self {
4022            result_sender,
4023            evidence_sink,
4024            handles: Vec::new(),
4025            max_queue_depth,
4026            dropped: 0,
4027            closed: false,
4028        }
4029    }
4030
4031    fn submit(&mut self, task: Box<dyn FnOnce() -> M + Send>) {
4032        if self.closed {
4033            self.dropped += 1;
4034            crate::effect_system::record_queue_drop("post_shutdown");
4035            tracing::debug!(
4036                target: crate::telemetry_schema::TARGET_EFFECT,
4037                "rejecting spawned task submit after shutdown"
4038            );
4039            return;
4040        }
4041        // Join finished threads first so the in-flight depth used for
4042        // backpressure reflects only tasks that are still running.
4043        self.reap_finished();
4044        // Backpressure: bound the number of in-flight spawned threads. The
4045        // `with_max_queue_depth` contract promises drops + counters for every
4046        // backend; this lane previously spawned unboundedly and counted
4047        // nothing. `0` means unbounded.
4048        if self.max_queue_depth > 0 && self.handles.len() >= self.max_queue_depth {
4049            self.dropped += 1;
4050            crate::effect_system::record_queue_drop("backpressure");
4051            emit_task_executor_backpressure_evidence(
4052                self.evidence_sink.as_ref(),
4053                "spawned",
4054                "drop",
4055                self.handles.len(),
4056                self.max_queue_depth,
4057                self.dropped,
4058            );
4059            return;
4060        }
4061        crate::effect_system::record_queue_enqueue(self.handles.len() as u64 + 1);
4062        let sender = self.result_sender.clone();
4063        let evidence_sink = self.evidence_sink.clone();
4064        let handle = thread::spawn(move || {
4065            let _ = run_task_closure(task, "spawned", evidence_sink.as_ref(), &sender);
4066            crate::effect_system::record_queue_processed();
4067        });
4068        self.handles.push(handle);
4069    }
4070
4071    fn reap_finished(&mut self) {
4072        if self.handles.is_empty() {
4073            return;
4074        }
4075
4076        let mut i = 0;
4077        while i < self.handles.len() {
4078            if self.handles[i].is_finished() {
4079                let handle = self.handles.swap_remove(i);
4080                let _ = handle.join();
4081            } else {
4082                i += 1;
4083            }
4084        }
4085    }
4086
4087    fn shutdown(&mut self) {
4088        self.closed = true;
4089        let start = Instant::now();
4090        // Fast path: reap any already-finished handles first.
4091        self.reap_finished();
4092        if self.handles.is_empty() {
4093            let elapsed_us = start.elapsed().as_micros() as u64;
4094            tracing::debug!(
4095                target: crate::telemetry_schema::TARGET_RUNTIME,
4096                elapsed_us,
4097                "spawn-executor shutdown (fast path, all tasks already finished)"
4098            );
4099            return;
4100        }
4101        // Slow path: bounded poll loop for in-flight tasks (bd-170o5).
4102        let pending_at_start = self.handles.len();
4103        while self.handles.iter().any(|handle| !handle.is_finished()) {
4104            if start.elapsed() >= Self::SHUTDOWN_TIMEOUT {
4105                let still_pending = self
4106                    .handles
4107                    .iter()
4108                    .filter(|handle| !handle.is_finished())
4109                    .count();
4110                tracing::warn!(
4111                    target: crate::telemetry_schema::TARGET_RUNTIME,
4112                    timeout_ms = Self::SHUTDOWN_TIMEOUT.as_millis() as u64,
4113                    pending_handles = still_pending,
4114                    "background task threads did not stop within timeout; detaching"
4115                );
4116                self.handles.clear();
4117                return;
4118            }
4119            thread::sleep(Self::SHUTDOWN_POLL);
4120        }
4121        self.reap_finished();
4122        let elapsed_us = start.elapsed().as_micros() as u64;
4123        tracing::debug!(
4124            target: crate::telemetry_schema::TARGET_RUNTIME,
4125            elapsed_us,
4126            pending_at_start,
4127            "spawn-executor shutdown (slow path)"
4128        );
4129    }
4130}
4131
4132#[cfg(feature = "asupersync-executor")]
4133struct AsupersyncTaskExecutor<M: Send + 'static> {
4134    result_sender: mpsc::Sender<M>,
4135    evidence_sink: Option<EvidenceSink>,
4136    runtime: AsupersyncRuntime,
4137    handles: Vec<BlockingTaskHandle>,
4138    /// Backpressure cap on in-flight blocking tasks (`0` = unbounded). Mirrors
4139    /// the `EffectQueue` lane's `max_queue_depth` so both backends shed load and
4140    /// report queue telemetry identically.
4141    max_queue_depth: usize,
4142    /// Total tasks rejected by backpressure or post-shutdown submission.
4143    dropped: u64,
4144    closed: bool,
4145}
4146
4147#[cfg(feature = "asupersync-executor")]
4148impl<M: Send + 'static> AsupersyncTaskExecutor<M> {
4149    const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(2);
4150
4151    fn new(
4152        result_sender: mpsc::Sender<M>,
4153        evidence_sink: Option<EvidenceSink>,
4154        max_queue_depth: usize,
4155    ) -> io::Result<Self> {
4156        let max_threads = thread::available_parallelism().map_or(1, |count| count.get().max(1));
4157        let runtime = RuntimeBuilder::new()
4158            .blocking_threads(1, max_threads)
4159            .thread_name_prefix("ftui-asupersync-task")
4160            .build()
4161            .map_err(|error| {
4162                io::Error::other(format!("asupersync runtime init failed: {error}"))
4163            })?;
4164
4165        Ok(Self {
4166            result_sender,
4167            evidence_sink,
4168            runtime,
4169            handles: Vec::new(),
4170            max_queue_depth,
4171            dropped: 0,
4172            closed: false,
4173        })
4174    }
4175
4176    fn submit(&mut self, task: Box<dyn FnOnce() -> M + Send>) {
4177        if self.closed {
4178            self.dropped += 1;
4179            crate::effect_system::record_queue_drop("post_shutdown");
4180            tracing::debug!(
4181                target: crate::telemetry_schema::TARGET_EFFECT,
4182                "rejecting asupersync task submit after shutdown"
4183            );
4184            return;
4185        }
4186        // Prune completed handles so the in-flight depth used for backpressure
4187        // reflects only tasks that are still running or queued in the pool.
4188        self.handles.retain(|handle| !handle.is_done());
4189        // Backpressure: bound the number of in-flight blocking tasks, matching
4190        // the EffectQueue lane (bd-2zd0a). `0` means unbounded.
4191        if self.max_queue_depth > 0 && self.handles.len() >= self.max_queue_depth {
4192            self.dropped += 1;
4193            crate::effect_system::record_queue_drop("backpressure");
4194            emit_task_executor_backpressure_evidence(
4195                self.evidence_sink.as_ref(),
4196                "asupersync",
4197                "drop",
4198                self.handles.len(),
4199                self.max_queue_depth,
4200                self.dropped,
4201            );
4202            return;
4203        }
4204        crate::effect_system::record_queue_enqueue(self.handles.len() as u64 + 1);
4205        let sender = self.result_sender.clone();
4206        let evidence_sink = self.evidence_sink.clone();
4207        let handle = self
4208            .runtime
4209            .spawn_blocking(move || {
4210                let _ = run_task_closure(task, "asupersync", evidence_sink.as_ref(), &sender);
4211                crate::effect_system::record_queue_processed();
4212            })
4213            .expect("asupersync blocking pool must be configured");
4214        self.handles.push(handle);
4215    }
4216
4217    fn reap_finished(&mut self) {
4218        self.handles.retain(|handle| !handle.is_done());
4219    }
4220
4221    fn shutdown(&mut self) {
4222        self.closed = true;
4223        let deadline = Instant::now() + Self::SHUTDOWN_TIMEOUT;
4224        for handle in &self.handles {
4225            let remaining = deadline.saturating_duration_since(Instant::now());
4226            if remaining.is_zero() || !handle.wait_timeout(remaining) {
4227                tracing::warn!(
4228                    target: crate::telemetry_schema::TARGET_RUNTIME,
4229                    timeout_ms = Self::SHUTDOWN_TIMEOUT.as_millis() as u64,
4230                    pending_handles = self
4231                        .handles
4232                        .iter()
4233                        .filter(|pending| !pending.is_done())
4234                        .count(),
4235                    "Asupersync blocking tasks did not stop within timeout; detaching"
4236                );
4237                self.handles.clear();
4238                return;
4239            }
4240        }
4241        self.handles.clear();
4242    }
4243}
4244
4245enum TaskExecutor<M: Send + 'static> {
4246    Spawned(SpawnTaskExecutor<M>),
4247    Queued(EffectQueue<M>),
4248    #[cfg(feature = "asupersync-executor")]
4249    Asupersync(AsupersyncTaskExecutor<M>),
4250}
4251
4252impl<M: Send + 'static> TaskExecutor<M> {
4253    fn new(
4254        config: &EffectQueueConfig,
4255        result_sender: mpsc::Sender<M>,
4256        evidence_sink: Option<EvidenceSink>,
4257    ) -> io::Result<Self> {
4258        let executor = match config.backend {
4259            TaskExecutorBackend::Spawned => Self::Spawned(SpawnTaskExecutor::new(
4260                result_sender,
4261                evidence_sink.clone(),
4262                config.max_queue_depth,
4263            )),
4264            TaskExecutorBackend::EffectQueue => Self::Queued(EffectQueue::start(
4265                config.clone(),
4266                result_sender,
4267                evidence_sink.clone(),
4268            )?),
4269            #[cfg(feature = "asupersync-executor")]
4270            TaskExecutorBackend::Asupersync => Self::Asupersync(AsupersyncTaskExecutor::new(
4271                result_sender,
4272                evidence_sink.clone(),
4273                config.max_queue_depth,
4274            )?),
4275        };
4276
4277        emit_task_executor_backend_evidence(evidence_sink.as_ref(), executor.kind_name_for_logs());
4278        Ok(executor)
4279    }
4280
4281    fn submit(&mut self, spec: TaskSpec, task: Box<dyn FnOnce() -> M + Send>) {
4282        match self {
4283            Self::Spawned(executor) => executor.submit(task),
4284            Self::Queued(queue) => queue.enqueue(spec, task),
4285            #[cfg(feature = "asupersync-executor")]
4286            Self::Asupersync(executor) => executor.submit(task),
4287        }
4288    }
4289
4290    fn reap_finished(&mut self) {
4291        match self {
4292            Self::Spawned(executor) => executor.reap_finished(),
4293            #[cfg(feature = "asupersync-executor")]
4294            Self::Asupersync(executor) => executor.reap_finished(),
4295            Self::Queued(_) => {}
4296        }
4297    }
4298
4299    /// Tasks this executor accepted that have not produced their message
4300    /// yet: live worker threads for the spawned and asupersync lanes, the
4301    /// loop's unrun task map for the effect queue. Per program, unlike the
4302    /// process-global `effect_system::queue_telemetry()` counters, so one
4303    /// program's backlog never shows up in another's frame guardrail.
4304    fn in_flight(&mut self) -> usize {
4305        match self {
4306            Self::Spawned(executor) => {
4307                executor.reap_finished();
4308                executor.handles.len()
4309            }
4310            #[cfg(feature = "asupersync-executor")]
4311            Self::Asupersync(executor) => {
4312                executor.reap_finished();
4313                executor.handles.len()
4314            }
4315            Self::Queued(queue) => queue.in_flight(),
4316        }
4317    }
4318
4319    fn shutdown(&mut self) {
4320        match self {
4321            Self::Spawned(executor) => executor.shutdown(),
4322            Self::Queued(queue) => queue.shutdown(),
4323            #[cfg(feature = "asupersync-executor")]
4324            Self::Asupersync(executor) => executor.shutdown(),
4325        }
4326    }
4327
4328    #[cfg(test)]
4329    fn kind_name(&self) -> &'static str {
4330        self.kind_name_for_logs()
4331    }
4332
4333    fn kind_name_for_logs(&self) -> &'static str {
4334        match self {
4335            Self::Spawned(_) => "spawned",
4336            Self::Queued(_) => "queued",
4337            #[cfg(feature = "asupersync-executor")]
4338            Self::Asupersync(_) => "asupersync",
4339        }
4340    }
4341}
4342
4343fn emit_task_executor_backend_evidence(sink: Option<&EvidenceSink>, backend: &str) {
4344    let Some(sink) = sink else {
4345        return;
4346    };
4347    let _ = sink.write_jsonl(&format!(
4348        r#"{{"schema_version":"ftui-evidence-v1","event":"task_executor_backend","backend":"{backend}"}}"#
4349    ));
4350}
4351
4352fn emit_task_executor_completion_evidence(
4353    sink: Option<&EvidenceSink>,
4354    backend: &str,
4355    duration_us: u64,
4356) {
4357    let Some(sink) = sink else {
4358        return;
4359    };
4360    let _ = sink.write_jsonl(&format!(
4361        r#"{{"schema_version":"ftui-evidence-v1","event":"task_executor_complete","backend":"{backend}","duration_us":{duration_us}}}"#
4362    ));
4363}
4364
4365fn emit_task_executor_panic_evidence(sink: Option<&EvidenceSink>, backend: &str, panic_msg: &str) {
4366    let Some(sink) = sink else {
4367        return;
4368    };
4369    let escaped = panic_msg
4370        .replace('\\', "\\\\")
4371        .replace('"', "\\\"")
4372        .replace('\n', "\\n")
4373        .replace('\r', "\\r")
4374        .replace('\t', "\\t");
4375    let _ = sink.write_jsonl(&format!(
4376        r#"{{"schema_version":"ftui-evidence-v1","event":"task_executor_panic","backend":"{backend}","panic_msg":"{escaped}"}}"#
4377    ));
4378}
4379
4380fn emit_task_executor_backpressure_evidence(
4381    sink: Option<&EvidenceSink>,
4382    backend: &str,
4383    action: &str,
4384    queue_length: usize,
4385    max_queue_size: usize,
4386    total_rejected: u64,
4387) {
4388    let Some(sink) = sink else {
4389        return;
4390    };
4391    let _ = sink.write_jsonl(&format!(
4392        r#"{{"schema_version":"ftui-evidence-v1","event":"task_executor_backpressure","backend":"{backend}","action":"{action}","queue_length":{queue_length},"max_queue_size":{max_queue_size},"total_rejected":{total_rejected}}}"#
4393    ));
4394}
4395
4396fn panic_payload_message(payload: Box<dyn Any + Send>) -> String {
4397    if let Some(s) = payload.downcast_ref::<&str>() {
4398        (*s).to_owned()
4399    } else if let Some(s) = payload.downcast_ref::<String>() {
4400        s.clone()
4401    } else {
4402        "unknown panic payload".to_owned()
4403    }
4404}
4405
4406/// No `eprintln!` fallback without `tracing`: stderr is the terminal the UI is
4407/// drawing on (bd-g00-root-epic-ewths.33.4). The panic hook's report covers a
4408/// task panic - kept until the teardown while a session is live, see
4409/// `ftui_core::session_teardown::install_chained_panic_hook` - and an enabled
4410/// evidence sink records a `task_executor_panic` row.
4411fn log_task_executor_panic(backend: &str, panic_msg: &str) {
4412    #[cfg(feature = "tracing")]
4413    tracing::error!(
4414        target: crate::telemetry_schema::TARGET_EFFECT,
4415        executor_backend = backend,
4416        panic_msg,
4417        "task executor task panicked"
4418    );
4419    #[cfg(not(feature = "tracing"))]
4420    let _ = (backend, panic_msg);
4421}
4422
4423fn run_task_closure<M: Send + 'static>(
4424    task: Box<dyn FnOnce() -> M + Send>,
4425    backend: &str,
4426    evidence_sink: Option<&EvidenceSink>,
4427    result_sender: &mpsc::Sender<M>,
4428) -> bool {
4429    let start = Instant::now();
4430    // This is a RECOVERABLE panic boundary โ€” the program keeps running.
4431    // Suppress the terminal panic hook: without this, a panicking task
4432    // triggers best_effort_cleanup mid-run (scroll-region reset, alt-screen
4433    // leave, raw-mode exit) and the still-live UI renders onto a cooked,
4434    // echoing main screen.
4435    let caught =
4436        ftui_core::with_panic_cleanup_suppressed(|| panic::catch_unwind(AssertUnwindSafe(task)));
4437    match caught {
4438        Ok(msg) => {
4439            let duration_us = start.elapsed().as_micros() as u64;
4440            tracing::debug!(
4441                target: crate::telemetry_schema::TARGET_EFFECT,
4442                command_type = "task",
4443                executor_backend = backend,
4444                duration_us = duration_us,
4445                effect_duration_us = duration_us,
4446                "task effect completed"
4447            );
4448            emit_task_executor_completion_evidence(evidence_sink, backend, duration_us);
4449            let _ = result_sender.send(msg);
4450            true
4451        }
4452        Err(payload) => {
4453            let panic_msg = panic_payload_message(payload);
4454            log_task_executor_panic(backend, &panic_msg);
4455            emit_task_executor_panic_evidence(evidence_sink, backend, &panic_msg);
4456            false
4457        }
4458    }
4459}
4460
4461/// One task handed to an [`EffectQueue`] finished or was dropped. Saturating:
4462/// tests drive the loop with commands that never passed through `enqueue`.
4463fn release_outstanding(outstanding: &std::sync::atomic::AtomicUsize) {
4464    use std::sync::atomic::Ordering;
4465    let _ = outstanding.try_update(Ordering::AcqRel, Ordering::Acquire, |n| {
4466        Some(n.saturating_sub(1))
4467    });
4468}
4469
4470fn effect_queue_loop<M: Send + 'static>(
4471    config: EffectQueueConfig,
4472    rx: mpsc::Receiver<EffectCommand<M>>,
4473    result_sender: mpsc::Sender<M>,
4474    evidence_sink: Option<EvidenceSink>,
4475    outstanding: &std::sync::atomic::AtomicUsize,
4476) {
4477    let mut scheduler = QueueingScheduler::new(config.scheduler);
4478    let mut tasks: HashMap<u64, Box<dyn FnOnce() -> M + Send>> = HashMap::new();
4479    let mut shutdown_requested = false;
4480    let max_depth = config.max_queue_depth;
4481
4482    loop {
4483        if tasks.is_empty() {
4484            if shutdown_requested {
4485                return;
4486            }
4487            match rx.recv() {
4488                Ok(cmd) => {
4489                    if matches!(
4490                        handle_effect_command(
4491                            cmd,
4492                            &mut scheduler,
4493                            &mut tasks,
4494                            &result_sender,
4495                            evidence_sink.as_ref(),
4496                            max_depth,
4497                            outstanding,
4498                        ),
4499                        EffectLoopControl::ShutdownRequested
4500                    ) {
4501                        shutdown_requested = true;
4502                    }
4503                }
4504                Err(_) => return,
4505            }
4506        }
4507
4508        while let Ok(cmd) = rx.try_recv() {
4509            if shutdown_requested && matches!(cmd, EffectCommand::Enqueue(_, _)) {
4510                release_outstanding(outstanding);
4511                crate::effect_system::record_queue_drop("post_shutdown");
4512                continue;
4513            }
4514            if matches!(
4515                handle_effect_command(
4516                    cmd,
4517                    &mut scheduler,
4518                    &mut tasks,
4519                    &result_sender,
4520                    evidence_sink.as_ref(),
4521                    max_depth,
4522                    outstanding,
4523                ),
4524                EffectLoopControl::ShutdownRequested
4525            ) {
4526                shutdown_requested = true;
4527            }
4528        }
4529
4530        if tasks.is_empty() {
4531            if shutdown_requested {
4532                return;
4533            }
4534            continue;
4535        }
4536
4537        let Some(job) = scheduler.peek_next().cloned() else {
4538            continue;
4539        };
4540
4541        if let Some(ref sink) = evidence_sink {
4542            let evidence = scheduler.evidence();
4543            let _ = sink.write_jsonl(&evidence.to_jsonl("effect_queue_select"));
4544        }
4545
4546        let completed = scheduler.tick(job.remaining_time);
4547        for job_id in completed {
4548            if let Some(task) = tasks.remove(&job_id) {
4549                let _ = run_task_closure(task, "queued", evidence_sink.as_ref(), &result_sender);
4550                release_outstanding(outstanding);
4551                crate::effect_system::record_queue_processed();
4552            }
4553        }
4554    }
4555}
4556
4557fn handle_effect_command<M: Send + 'static>(
4558    cmd: EffectCommand<M>,
4559    scheduler: &mut QueueingScheduler,
4560    tasks: &mut HashMap<u64, Box<dyn FnOnce() -> M + Send>>,
4561    result_sender: &mpsc::Sender<M>,
4562    evidence_sink: Option<&EvidenceSink>,
4563    max_depth: usize,
4564    outstanding: &std::sync::atomic::AtomicUsize,
4565) -> EffectLoopControl {
4566    match cmd {
4567        EffectCommand::Enqueue(spec, task) => {
4568            // Backpressure (bd-2zd0a). `EffectQueue::enqueue` already bounds
4569            // the backlog at submission; this guards direct loop callers.
4570            if max_depth > 0 && tasks.len() >= max_depth {
4571                release_outstanding(outstanding);
4572                crate::effect_system::record_queue_drop("backpressure");
4573                return EffectLoopControl::Continue;
4574            }
4575            let weight_source = if spec.weight == DEFAULT_TASK_WEIGHT {
4576                WeightSource::Default
4577            } else {
4578                WeightSource::Explicit
4579            };
4580            let estimate_source = if spec.estimate_ms == DEFAULT_TASK_ESTIMATE_MS {
4581                EstimateSource::Default
4582            } else {
4583                EstimateSource::Explicit
4584            };
4585            let id = scheduler.submit_with_sources(
4586                spec.weight,
4587                spec.estimate_ms,
4588                weight_source,
4589                estimate_source,
4590                spec.name,
4591            );
4592            if let Some(id) = id {
4593                tasks.insert(id, task);
4594                crate::effect_system::record_queue_enqueue(tasks.len() as u64);
4595            } else {
4596                let stats = scheduler.stats();
4597                emit_task_executor_backpressure_evidence(
4598                    evidence_sink,
4599                    "queued",
4600                    "inline_fallback",
4601                    stats.queue_length,
4602                    scheduler.max_queue_size(),
4603                    stats.total_rejected,
4604                );
4605                let _ =
4606                    run_task_closure(task, "queued-inline-fallback", evidence_sink, result_sender);
4607                release_outstanding(outstanding);
4608            }
4609            EffectLoopControl::Continue
4610        }
4611        EffectCommand::Shutdown => EffectLoopControl::ShutdownRequested,
4612    }
4613}
4614
4615// removed: legacy ResizeDebouncer (superseded by ResizeCoalescer)
4616
4617/// Policy for remeasuring inline auto UI height.
4618///
4619/// Uses VOI (value-of-information) sampling to decide when to perform
4620/// a costly full-height measurement, with any-time valid guarantees via
4621/// the embedded e-process in `VoiSampler`.
4622#[derive(Debug, Clone)]
4623pub struct InlineAutoRemeasureConfig {
4624    /// VOI sampling configuration.
4625    pub voi: VoiConfig,
4626    /// Minimum row delta to count as a "violation".
4627    pub change_threshold_rows: u16,
4628}
4629
4630impl Default for InlineAutoRemeasureConfig {
4631    fn default() -> Self {
4632        Self {
4633            voi: VoiConfig {
4634                // Height changes are expected to be rare; bias toward fewer samples.
4635                prior_alpha: 1.0,
4636                prior_beta: 9.0,
4637                // Allow ~1s max latency to adapt to growth/shrink.
4638                max_interval_ms: 1000,
4639                // Avoid over-sampling in high-FPS loops.
4640                min_interval_ms: 100,
4641                // Disable event forcing; use time-based gating.
4642                max_interval_events: 0,
4643                min_interval_events: 0,
4644                // Treat sampling as moderately expensive.
4645                sample_cost: 0.08,
4646                ..VoiConfig::default()
4647            },
4648            change_threshold_rows: 1,
4649        }
4650    }
4651}
4652
4653#[derive(Debug)]
4654struct InlineAutoRemeasureState {
4655    config: InlineAutoRemeasureConfig,
4656    sampler: VoiSampler,
4657}
4658
4659impl InlineAutoRemeasureState {
4660    fn new(config: InlineAutoRemeasureConfig) -> Self {
4661        let sampler = VoiSampler::new(config.voi.clone());
4662        Self { config, sampler }
4663    }
4664
4665    fn reset(&mut self) {
4666        self.sampler = VoiSampler::new(self.config.voi.clone());
4667    }
4668}
4669
4670#[derive(Debug, Clone)]
4671struct ConformalEvidence {
4672    bucket_key: String,
4673    n_b: usize,
4674    alpha: f64,
4675    q_b: Option<f64>,
4676    y_hat: f64,
4677    upper_us: Option<f64>,
4678    risk: bool,
4679    status: ConformalStatus,
4680    required_rank: usize,
4681    fallback_level: u8,
4682    window_size: usize,
4683    reset_count: u64,
4684}
4685
4686impl ConformalEvidence {
4687    fn from_prediction(prediction: &ConformalPrediction) -> Self {
4688        Self {
4689            bucket_key: prediction.bucket.to_string(),
4690            n_b: prediction.sample_count,
4691            alpha: prediction.alpha,
4692            q_b: prediction.quantile,
4693            y_hat: prediction.y_hat,
4694            upper_us: prediction.upper_us,
4695            risk: prediction.risk,
4696            status: prediction.status,
4697            required_rank: prediction.required_rank,
4698            fallback_level: prediction.fallback_level,
4699            window_size: prediction.window_size,
4700            reset_count: prediction.reset_count,
4701        }
4702    }
4703}
4704
4705#[derive(Debug, Clone)]
4706struct BudgetDecisionEvidence {
4707    frame_idx: u64,
4708    decision: BudgetDecision,
4709    controller_decision: BudgetDecision,
4710    degradation_before: DegradationLevel,
4711    degradation_after: DegradationLevel,
4712    frame_time_us: f64,
4713    budget_us: f64,
4714    pid_output: f64,
4715    pid_p: f64,
4716    pid_i: f64,
4717    pid_d: f64,
4718    e_value: f64,
4719    eprocess_lambda: f64,
4720    frames_observed: u32,
4721    frames_since_change: u32,
4722    in_warmup: bool,
4723    recovery_streak: u32,
4724    total_degrades: u64,
4725    total_recoveries: u64,
4726    controller_reason: BudgetDecisionReason,
4727    load_governor: LoadGovernorSnapshot,
4728    /// Detector that made the resize coalescer's latest regime decision.
4729    resize_detector: &'static str,
4730    conformal: Option<ConformalEvidence>,
4731}
4732
4733impl BudgetDecisionEvidence {
4734    fn decision_from_levels(before: DegradationLevel, after: DegradationLevel) -> BudgetDecision {
4735        if after > before {
4736            BudgetDecision::Degrade
4737        } else if after < before {
4738            BudgetDecision::Upgrade
4739        } else {
4740            BudgetDecision::Hold
4741        }
4742    }
4743
4744    #[must_use]
4745    fn to_jsonl(&self) -> String {
4746        let conformal = self.conformal.as_ref();
4747        let bucket_key = Self::opt_str(conformal.map(|c| c.bucket_key.as_str()));
4748        let n_b = Self::opt_usize(conformal.map(|c| c.n_b));
4749        let alpha = crate::conformal_predictor::finite_json_number(conformal.map(|c| c.alpha), 17);
4750        let q_b = Self::opt_f64(conformal.and_then(|c| c.q_b));
4751        let y_hat = Self::opt_f64(conformal.map(|c| c.y_hat));
4752        let upper_us = Self::opt_f64(conformal.and_then(|c| c.upper_us));
4753        let risk = Self::opt_bool(conformal.map(|c| c.risk));
4754        let conformal_status = Self::opt_str(conformal.map(|c| c.status.as_str()));
4755        let required_rank = Self::opt_usize(conformal.map(|c| c.required_rank));
4756        let fallback_level = Self::opt_u8(conformal.map(|c| c.fallback_level));
4757        let window_size = Self::opt_usize(conformal.map(|c| c.window_size));
4758        let reset_count = Self::opt_u64(conformal.map(|c| c.reset_count));
4759        let queue_max_depth = Self::opt_usize(self.load_governor.queue_max_depth);
4760
4761        format!(
4762            r#"{{"schema_version":"ftui-evidence-v1","event":"budget_decision","frame_idx":{},"decision":"{}","decision_controller":"{}","decision_controller_reason":"{}","degradation_before":"{}","degradation_after":"{}","frame_time_us":{:.6},"budget_us":{:.6},"pid_output":{:.6},"pid_p":{:.6},"pid_i":{:.6},"pid_d":{:.6},"e_value":{:.6},"eprocess_lambda":{:.6},"frames_observed":{},"frames_since_change":{},"in_warmup":{},"recovery_streak":{},"total_degrades":{},"total_recoveries":{},"runtime_mode":"{}","runtime_mode_before":"{}","pressure_class":"{}","work_disposition":"{}","governor_reason":"{}","governor_transition":{},"strict_semantics_preserved":{},"queue_in_flight":{},"queue_max_depth":{},"queue_dropped_delta":{},"resize_coalescing_active":{},"resize_detector":"{}","recovery_intervals_observed":{},"recovery_intervals_required":{},"deferred_work_total":{},"coalesced_work_total":{},"dropped_work_total":{},"bucket_key":{},"n_b":{},"alpha":{},"q_b":{},"y_hat":{},"upper_us":{},"risk":{},"conformal_status":{},"required_rank":{},"fallback_level":{},"window_size":{},"reset_count":{}}}"#,
4763            self.frame_idx,
4764            self.decision.as_str(),
4765            self.controller_decision.as_str(),
4766            self.controller_reason.as_str(),
4767            self.degradation_before.as_str(),
4768            self.degradation_after.as_str(),
4769            self.frame_time_us,
4770            self.budget_us,
4771            self.pid_output,
4772            self.pid_p,
4773            self.pid_i,
4774            self.pid_d,
4775            self.e_value,
4776            self.eprocess_lambda,
4777            self.frames_observed,
4778            self.frames_since_change,
4779            self.in_warmup,
4780            self.recovery_streak,
4781            self.total_degrades,
4782            self.total_recoveries,
4783            self.load_governor.mode.as_str(),
4784            self.load_governor.mode_before.as_str(),
4785            self.load_governor.pressure_class.as_str(),
4786            self.load_governor.disposition.as_str(),
4787            self.load_governor.reason_code,
4788            self.load_governor.transition,
4789            self.load_governor.strict_semantics_preserved,
4790            self.load_governor.queue_in_flight,
4791            queue_max_depth,
4792            self.load_governor.queue_dropped_delta,
4793            self.load_governor.resize_coalescing_active,
4794            self.resize_detector,
4795            self.load_governor.recovery_intervals_observed,
4796            self.load_governor.recovery_intervals_required,
4797            self.load_governor.deferred_work_total,
4798            self.load_governor.coalesced_work_total,
4799            self.load_governor.dropped_work_total,
4800            bucket_key,
4801            n_b,
4802            alpha,
4803            q_b,
4804            y_hat,
4805            upper_us,
4806            risk,
4807            conformal_status,
4808            required_rank,
4809            fallback_level,
4810            window_size,
4811            reset_count
4812        )
4813    }
4814
4815    fn opt_f64(value: Option<f64>) -> String {
4816        crate::conformal_predictor::finite_json_number(value, 6)
4817    }
4818
4819    fn opt_u64(value: Option<u64>) -> String {
4820        value
4821            .map(|v| v.to_string())
4822            .unwrap_or_else(|| "null".to_string())
4823    }
4824
4825    fn opt_u8(value: Option<u8>) -> String {
4826        value
4827            .map(|v| v.to_string())
4828            .unwrap_or_else(|| "null".to_string())
4829    }
4830
4831    fn opt_usize(value: Option<usize>) -> String {
4832        value
4833            .map(|v| v.to_string())
4834            .unwrap_or_else(|| "null".to_string())
4835    }
4836
4837    fn opt_bool(value: Option<bool>) -> String {
4838        value
4839            .map(|v| v.to_string())
4840            .unwrap_or_else(|| "null".to_string())
4841    }
4842
4843    fn opt_str(value: Option<&str>) -> String {
4844        value
4845            .map(|v| {
4846                format!(
4847                    "\"{}\"",
4848                    v.replace('\\', "\\\\")
4849                        .replace('"', "\\\"")
4850                        .replace('\n', "\\n")
4851                        .replace('\r', "\\r")
4852                        .replace('\t', "\\t")
4853                )
4854            })
4855            .unwrap_or_else(|| "null".to_string())
4856    }
4857}
4858
4859#[derive(Debug, Clone)]
4860struct FairnessConfigEvidence {
4861    enabled: bool,
4862    input_priority_threshold_ms: u64,
4863    dominance_threshold: u32,
4864    fairness_threshold: f64,
4865}
4866
4867impl FairnessConfigEvidence {
4868    #[must_use]
4869    fn to_jsonl(&self) -> String {
4870        format!(
4871            r#"{{"event":"fairness_config","enabled":{},"input_priority_threshold_ms":{},"dominance_threshold":{},"fairness_threshold":{:.6}}}"#,
4872            self.enabled,
4873            self.input_priority_threshold_ms,
4874            self.dominance_threshold,
4875            self.fairness_threshold
4876        )
4877    }
4878}
4879
4880#[derive(Debug, Clone)]
4881struct FairnessDecisionEvidence {
4882    frame_idx: u64,
4883    decision: &'static str,
4884    reason: &'static str,
4885    pending_input_latency_ms: Option<u64>,
4886    jain_index: f64,
4887    resize_dominance_count: u32,
4888    dominance_threshold: u32,
4889    fairness_threshold: f64,
4890    input_priority_threshold_ms: u64,
4891}
4892
4893impl FairnessDecisionEvidence {
4894    #[must_use]
4895    fn to_jsonl(&self) -> String {
4896        let pending_latency = self
4897            .pending_input_latency_ms
4898            .map(|v| v.to_string())
4899            .unwrap_or_else(|| "null".to_string());
4900        format!(
4901            r#"{{"event":"fairness_decision","frame_idx":{},"decision":"{}","reason":"{}","pending_input_latency_ms":{},"jain_index":{:.6},"resize_dominance_count":{},"dominance_threshold":{},"fairness_threshold":{:.6},"input_priority_threshold_ms":{}}}"#,
4902            self.frame_idx,
4903            self.decision,
4904            self.reason,
4905            pending_latency,
4906            self.jain_index,
4907            self.resize_dominance_count,
4908            self.dominance_threshold,
4909            self.fairness_threshold,
4910            self.input_priority_threshold_ms
4911        )
4912    }
4913}
4914
4915#[derive(Debug, Clone)]
4916struct ShadowFrameEvidence {
4917    frame: u64,
4918    checksum: u64,
4919    lane: &'static str,
4920    requested_lane: &'static str,
4921    rollout_policy: &'static str,
4922    task_backend: &'static str,
4923    cols: u16,
4924    rows: u16,
4925    ts_ns: u128,
4926}
4927
4928impl ShadowFrameEvidence {
4929    #[must_use]
4930    fn to_jsonl(&self) -> String {
4931        format!(
4932            r#"{{"schema_version":"{}","event":"{}","frame":{},"checksum":"{:016x}","lane":"{}","requested_lane":"{}","rollout_policy":"{}","task_backend":"{}","cols":{},"rows":{},"ts_ns":{}}}"#,
4933            crate::evidence_sink::EVIDENCE_SCHEMA_VERSION,
4934            crate::telemetry_schema::EVENT_SHADOW_FRAME,
4935            self.frame,
4936            self.checksum,
4937            self.lane,
4938            self.requested_lane,
4939            self.rollout_policy,
4940            self.task_backend,
4941            self.cols,
4942            self.rows,
4943            self.ts_ns,
4944        )
4945    }
4946}
4947
4948#[derive(Debug, Clone)]
4949struct WidgetRefreshEntry {
4950    widget_id: u64,
4951    essential: bool,
4952    starved: bool,
4953    value: f32,
4954    cost_us: f32,
4955    score: f32,
4956    staleness_ms: u64,
4957}
4958
4959impl WidgetRefreshEntry {
4960    fn to_json(&self) -> String {
4961        format!(
4962            r#"{{"id":{},"cost_us":{:.3},"value":{:.4},"score":{:.4},"essential":{},"starved":{},"staleness_ms":{}}}"#,
4963            self.widget_id,
4964            self.cost_us,
4965            self.value,
4966            self.score,
4967            self.essential,
4968            self.starved,
4969            self.staleness_ms
4970        )
4971    }
4972}
4973
4974#[derive(Debug, Clone)]
4975struct WidgetRefreshPlan {
4976    frame_idx: u64,
4977    budget_us: f64,
4978    degradation: DegradationLevel,
4979    essentials_cost_us: f64,
4980    selected_cost_us: f64,
4981    selected_value: f64,
4982    signal_count: usize,
4983    selected: Vec<WidgetRefreshEntry>,
4984    skipped_count: usize,
4985    skipped_starved: usize,
4986    starved_selected: usize,
4987    over_budget: bool,
4988}
4989
4990impl WidgetRefreshPlan {
4991    fn new() -> Self {
4992        Self {
4993            frame_idx: 0,
4994            budget_us: 0.0,
4995            degradation: DegradationLevel::Full,
4996            essentials_cost_us: 0.0,
4997            selected_cost_us: 0.0,
4998            selected_value: 0.0,
4999            signal_count: 0,
5000            selected: Vec::new(),
5001            skipped_count: 0,
5002            skipped_starved: 0,
5003            starved_selected: 0,
5004            over_budget: false,
5005        }
5006    }
5007
5008    fn clear(&mut self) {
5009        self.frame_idx = 0;
5010        self.budget_us = 0.0;
5011        self.degradation = DegradationLevel::Full;
5012        self.essentials_cost_us = 0.0;
5013        self.selected_cost_us = 0.0;
5014        self.selected_value = 0.0;
5015        self.signal_count = 0;
5016        self.selected.clear();
5017        self.skipped_count = 0;
5018        self.skipped_starved = 0;
5019        self.starved_selected = 0;
5020        self.over_budget = false;
5021    }
5022
5023    fn as_budget(&self) -> WidgetBudget {
5024        if self.signal_count == 0 {
5025            return WidgetBudget::allow_all();
5026        }
5027        let ids = self.selected.iter().map(|entry| entry.widget_id).collect();
5028        WidgetBudget::allow_only(ids)
5029    }
5030
5031    fn recompute(
5032        &mut self,
5033        frame_idx: u64,
5034        budget_us: f64,
5035        degradation: DegradationLevel,
5036        signals: &[WidgetSignal],
5037        config: &WidgetRefreshConfig,
5038    ) {
5039        self.clear();
5040        self.frame_idx = frame_idx;
5041        self.budget_us = budget_us;
5042        self.degradation = degradation;
5043
5044        if !config.enabled || signals.is_empty() {
5045            return;
5046        }
5047
5048        self.signal_count = signals.len();
5049        let mut essentials_cost = 0.0f64;
5050        let mut selected_cost = 0.0f64;
5051        let mut selected_value = 0.0f64;
5052
5053        let staleness_window = config.staleness_window_ms.max(1) as f32;
5054        let mut candidates: Vec<WidgetRefreshEntry> = Vec::with_capacity(signals.len());
5055
5056        for signal in signals {
5057            let starved = config.starve_ms > 0 && signal.staleness_ms >= config.starve_ms;
5058            let staleness_score = (signal.staleness_ms as f32 / staleness_window).min(1.0);
5059            let mut value = config.weight_priority * signal.priority
5060                + config.weight_staleness * staleness_score
5061                + config.weight_focus * signal.focus_boost
5062                + config.weight_interaction * signal.interaction_boost;
5063            if starved {
5064                value += config.starve_boost;
5065            }
5066            let raw_cost = if signal.recent_cost_us > 0.0 {
5067                signal.recent_cost_us
5068            } else {
5069                signal.cost_estimate_us
5070            };
5071            let cost_us = raw_cost.max(config.min_cost_us);
5072            let score = if cost_us > 0.0 {
5073                value / cost_us
5074            } else {
5075                value
5076            };
5077
5078            let entry = WidgetRefreshEntry {
5079                widget_id: signal.widget_id,
5080                essential: signal.essential,
5081                starved,
5082                value,
5083                cost_us,
5084                score,
5085                staleness_ms: signal.staleness_ms,
5086            };
5087
5088            if degradation >= DegradationLevel::EssentialOnly && !signal.essential {
5089                self.skipped_count += 1;
5090                if starved {
5091                    self.skipped_starved = self.skipped_starved.saturating_add(1);
5092                }
5093                continue;
5094            }
5095
5096            if signal.essential {
5097                essentials_cost += cost_us as f64;
5098                selected_cost += cost_us as f64;
5099                selected_value += value as f64;
5100                if starved {
5101                    self.starved_selected = self.starved_selected.saturating_add(1);
5102                }
5103                self.selected.push(entry);
5104            } else {
5105                candidates.push(entry);
5106            }
5107        }
5108
5109        let mut remaining = budget_us - selected_cost;
5110
5111        if degradation < DegradationLevel::EssentialOnly {
5112            let nonessential_total = candidates.len();
5113            let max_drop_fraction = config.max_drop_fraction.clamp(0.0, 1.0);
5114            let enforce_drop_rate = max_drop_fraction < 1.0 && nonessential_total > 0;
5115            let min_nonessential_selected = if enforce_drop_rate {
5116                let min_fraction = (1.0 - max_drop_fraction).max(0.0);
5117                ((min_fraction * nonessential_total as f32).ceil() as usize).min(nonessential_total)
5118            } else {
5119                0
5120            };
5121
5122            candidates.sort_by(|a, b| {
5123                b.starved
5124                    .cmp(&a.starved)
5125                    .then_with(|| b.score.total_cmp(&a.score))
5126                    .then_with(|| b.value.total_cmp(&a.value))
5127                    .then_with(|| a.cost_us.total_cmp(&b.cost_us))
5128                    .then_with(|| a.widget_id.cmp(&b.widget_id))
5129            });
5130
5131            let mut forced_starved = 0usize;
5132            let mut nonessential_selected = 0usize;
5133            let mut skipped_candidates = if enforce_drop_rate {
5134                Vec::with_capacity(candidates.len())
5135            } else {
5136                Vec::new()
5137            };
5138
5139            for entry in candidates.into_iter() {
5140                if entry.starved && forced_starved >= config.max_starved_per_frame {
5141                    self.skipped_count += 1;
5142                    self.skipped_starved = self.skipped_starved.saturating_add(1);
5143                    if enforce_drop_rate {
5144                        skipped_candidates.push(entry);
5145                    }
5146                    continue;
5147                }
5148
5149                if remaining >= entry.cost_us as f64 {
5150                    remaining -= entry.cost_us as f64;
5151                    selected_cost += entry.cost_us as f64;
5152                    selected_value += entry.value as f64;
5153                    if entry.starved {
5154                        self.starved_selected = self.starved_selected.saturating_add(1);
5155                        forced_starved += 1;
5156                    }
5157                    nonessential_selected += 1;
5158                    self.selected.push(entry);
5159                } else if entry.starved
5160                    && forced_starved < config.max_starved_per_frame
5161                    && nonessential_selected == 0
5162                {
5163                    // Starvation guard: ensure at least one starved widget can refresh.
5164                    selected_cost += entry.cost_us as f64;
5165                    selected_value += entry.value as f64;
5166                    self.starved_selected = self.starved_selected.saturating_add(1);
5167                    forced_starved += 1;
5168                    nonessential_selected += 1;
5169                    self.selected.push(entry);
5170                } else {
5171                    self.skipped_count += 1;
5172                    if entry.starved {
5173                        self.skipped_starved = self.skipped_starved.saturating_add(1);
5174                    }
5175                    if enforce_drop_rate {
5176                        skipped_candidates.push(entry);
5177                    }
5178                }
5179            }
5180
5181            if enforce_drop_rate && nonessential_selected < min_nonessential_selected {
5182                for entry in skipped_candidates.into_iter() {
5183                    if nonessential_selected >= min_nonessential_selected {
5184                        break;
5185                    }
5186                    if entry.starved && forced_starved >= config.max_starved_per_frame {
5187                        continue;
5188                    }
5189                    selected_cost += entry.cost_us as f64;
5190                    selected_value += entry.value as f64;
5191                    if entry.starved {
5192                        self.starved_selected = self.starved_selected.saturating_add(1);
5193                        forced_starved += 1;
5194                        self.skipped_starved = self.skipped_starved.saturating_sub(1);
5195                    }
5196                    self.skipped_count = self.skipped_count.saturating_sub(1);
5197                    nonessential_selected += 1;
5198                    self.selected.push(entry);
5199                }
5200            }
5201        }
5202
5203        self.essentials_cost_us = essentials_cost;
5204        self.selected_cost_us = selected_cost;
5205        self.selected_value = selected_value;
5206        self.over_budget = selected_cost > budget_us;
5207    }
5208
5209    #[must_use]
5210    fn to_jsonl(&self) -> String {
5211        let mut out = String::with_capacity(256 + self.selected.len() * 96);
5212        out.push_str(r#"{"schema_version":"ftui-evidence-v1","event":"widget_refresh""#);
5213        out.push_str(&format!(
5214            r#","frame_idx":{},"budget_us":{:.3},"degradation":"{}","essentials_cost_us":{:.3},"selected_cost_us":{:.3},"selected_value":{:.3},"selected_count":{},"skipped_count":{},"starved_selected":{},"starved_skipped":{},"over_budget":{}"#,
5215            self.frame_idx,
5216            self.budget_us,
5217            self.degradation.as_str(),
5218            self.essentials_cost_us,
5219            self.selected_cost_us,
5220            self.selected_value,
5221            self.selected.len(),
5222            self.skipped_count,
5223            self.starved_selected,
5224            self.skipped_starved,
5225            self.over_budget
5226        ));
5227        out.push_str(r#","selected":["#);
5228        for (i, entry) in self.selected.iter().enumerate() {
5229            if i > 0 {
5230                out.push(',');
5231            }
5232            out.push_str(&entry.to_json());
5233        }
5234        out.push_str("]}");
5235        out
5236    }
5237}
5238
5239// =============================================================================
5240// CrosstermEventSource: BackendEventSource adapter for TerminalSession
5241// =============================================================================
5242
5243#[cfg(feature = "crossterm-compat")]
5244/// Adapter that wraps [`TerminalSession`] to implement [`BackendEventSource`].
5245///
5246/// This provides the bridge between the legacy crossterm-based terminal session
5247/// and the new backend abstraction. Once the native `ftui-tty` backend fully
5248/// replaces crossterm, this adapter will be removed.
5249pub struct CrosstermEventSource {
5250    session: TerminalSession,
5251    features: BackendFeatures,
5252}
5253
5254#[cfg(feature = "crossterm-compat")]
5255impl CrosstermEventSource {
5256    /// Create a new crossterm event source from a terminal session.
5257    pub fn new(session: TerminalSession, initial_features: BackendFeatures) -> Self {
5258        Self {
5259            session,
5260            features: initial_features,
5261        }
5262    }
5263}
5264
5265#[cfg(feature = "crossterm-compat")]
5266impl BackendEventSource for CrosstermEventSource {
5267    type Error = io::Error;
5268
5269    fn size(&self) -> Result<(u16, u16), io::Error> {
5270        self.session.size()
5271    }
5272
5273    fn set_features(&mut self, features: BackendFeatures) -> Result<(), io::Error> {
5274        if features.mouse_capture != self.features.mouse_capture {
5275            self.session.set_mouse_capture(features.mouse_capture)?;
5276        }
5277        // bracketed_paste, focus_events, and kitty_keyboard are set at session
5278        // construction and cleaned up in TerminalSession::Drop. Runtime toggling
5279        // is not supported by the crossterm backend.
5280        self.features = features;
5281        Ok(())
5282    }
5283
5284    fn poll_event(&mut self, timeout: Duration) -> Result<bool, io::Error> {
5285        self.session.poll_event(timeout)
5286    }
5287
5288    fn read_event(&mut self) -> Result<Option<Event>, io::Error> {
5289        self.session.read_event()
5290    }
5291
5292    fn supports_suspend(&self) -> bool {
5293        self.session.is_live()
5294    }
5295
5296    fn suspend(&mut self) -> Result<bool, io::Error> {
5297        self.session.suspend()
5298    }
5299
5300    fn resume(&mut self) -> Result<(), io::Error> {
5301        self.session.resume()
5302    }
5303}
5304
5305// =============================================================================
5306// HeadlessEventSource: no-op event source for headless/test programs
5307// =============================================================================
5308
5309/// A no-op event source for headless and test programs.
5310///
5311/// Returns a fixed terminal size, accepts feature changes silently, and never
5312/// produces events. This allows the test helper to construct a `Program`
5313/// without depending on crossterm or a real terminal.
5314pub struct HeadlessEventSource {
5315    width: u16,
5316    height: u16,
5317    features: BackendFeatures,
5318}
5319
5320impl HeadlessEventSource {
5321    /// Create a headless event source with the given terminal size.
5322    pub fn new(width: u16, height: u16, features: BackendFeatures) -> Self {
5323        Self {
5324            width,
5325            height,
5326            features,
5327        }
5328    }
5329}
5330
5331impl BackendEventSource for HeadlessEventSource {
5332    type Error = io::Error;
5333
5334    fn size(&self) -> Result<(u16, u16), io::Error> {
5335        Ok((self.width, self.height))
5336    }
5337
5338    fn set_features(&mut self, features: BackendFeatures) -> Result<(), io::Error> {
5339        self.features = features;
5340        Ok(())
5341    }
5342
5343    fn poll_event(&mut self, _timeout: Duration) -> Result<bool, io::Error> {
5344        Ok(false)
5345    }
5346
5347    fn read_event(&mut self) -> Result<Option<Event>, io::Error> {
5348        Ok(None)
5349    }
5350}
5351
5352impl<M: Model> Program<M, HeadlessEventSource, TerminalPresenter<Vec<u8>>> {
5353    /// Construct a headless program backed by an in-memory `TerminalPresenter<Vec<u8>>`.
5354    pub fn new_headless(model: M, config: ProgramConfig) -> io::Result<Self> {
5355        let (width, height) = config.forced_size.unwrap_or((80, 24));
5356        let features = BackendFeatures::default();
5357        let events = HeadlessEventSource::new(width, height, features);
5358        let writer = TerminalWriter::with_diff_config(
5359            Vec::new(),
5360            config.screen_mode,
5361            config.ui_anchor,
5362            TerminalCapabilities::basic(),
5363            config.diff_config.clone(),
5364        );
5365        Self::with_event_source(
5366            model,
5367            events,
5368            features,
5369            TerminalPresenter::new(writer),
5370            config,
5371        )
5372    }
5373}
5374
5375impl<M: Model, P: BackendPresenter<Error = io::Error>> Program<M, HeadlessEventSource, P> {
5376    /// Step a single headless frame through the full budget, conformal, render,
5377    /// present, and evidence pipeline.
5378    pub fn step_headless_frame(&mut self) -> io::Result<()> {
5379        self.dirty = true;
5380        self.render_frame()
5381    }
5382
5383    /// Initialize the model, execute its initial command, drain any spawned
5384    /// background tasks, and render the initial frame.
5385    pub fn init_headless(&mut self, task_timeout: Duration) -> io::Result<()> {
5386        let cmd = self.model.init();
5387        self.execute_cmd(cmd)?;
5388        self.drain_headless_tasks(task_timeout)?;
5389        if self.running {
5390            self.reconcile_subscriptions();
5391            self.process_subscription_failures(false)?;
5392            if self.running {
5393                self.render_frame()?;
5394            }
5395        }
5396        Ok(())
5397    }
5398
5399    /// Deliver a single event to the headless program and submit any resulting
5400    /// commands without waiting for background tasks to drain or rendering.
5401    pub fn enqueue_headless_event(&mut self, event: Event) -> io::Result<()> {
5402        if !self.running {
5403            return Ok(());
5404        }
5405        self.handle_event(event)
5406    }
5407
5408    /// Deliver a single event to the headless program, drain all resulting
5409    /// background tasks up to `task_timeout`, and render if dirty.
5410    pub fn step_headless_event(&mut self, event: Event, task_timeout: Duration) -> io::Result<()> {
5411        if !self.running {
5412            return Ok(());
5413        }
5414        self.handle_event(event)?;
5415        self.drain_headless_tasks(task_timeout)?;
5416        if self.running && self.dirty {
5417            self.render_frame()?;
5418        }
5419        Ok(())
5420    }
5421
5422    /// Drain all in-flight background tasks on the active task executor up to `timeout`.
5423    pub fn drain_headless_tasks(&mut self, timeout: Duration) -> io::Result<()> {
5424        let deadline = Instant::now() + timeout;
5425        loop {
5426            self.process_task_results()?;
5427            self.reap_finished_tasks();
5428            if self.task_executor.in_flight() == 0 {
5429                self.process_task_results()?;
5430                self.reap_finished_tasks();
5431                if self.task_executor.in_flight() == 0 {
5432                    break;
5433                }
5434            }
5435            if Instant::now() >= deadline {
5436                return Err(io::Error::new(
5437                    io::ErrorKind::TimedOut,
5438                    format!(
5439                        "headless task drain timed out with {} tasks still in flight on {}",
5440                        self.task_executor.in_flight(),
5441                        self.task_executor.kind_name_for_logs()
5442                    ),
5443                ));
5444            }
5445            thread::yield_now();
5446        }
5447        Ok(())
5448    }
5449
5450    /// Return the active task executor backend label (`"spawned"`, `"queued"`, or `"asupersync"`).
5451    #[must_use]
5452    pub fn task_backend_name(&self) -> &'static str {
5453        self.task_executor.kind_name_for_logs()
5454    }
5455
5456    /// Return the resolved runtime lane.
5457    #[must_use]
5458    pub fn resolved_runtime_lane(&self) -> RuntimeLane {
5459        self.resolved_lane
5460    }
5461}
5462
5463// =============================================================================
5464// Program
5465// =============================================================================
5466
5467/// The program runtime that manages the update/view loop.
5468pub struct Program<
5469    M: Model,
5470    E: BackendEventSource<Error = io::Error>,
5471    P: BackendPresenter<Error = io::Error> = TerminalPresenter<Stdout>,
5472> {
5473    /// The application model.
5474    model: M,
5475    /// Terminal output presenter.
5476    presenter: P,
5477    /// Event source (terminal input, size queries, feature toggles).
5478    events: E,
5479    /// Currently active backend feature toggles.
5480    backend_features: BackendFeatures,
5481    /// Whether the program is running.
5482    running: bool,
5483    /// Whether the model shutdown hook and runtime teardown have completed.
5484    shutdown_complete: bool,
5485    /// Current tick rate (if any).
5486    tick_rate: Option<Duration>,
5487    /// Total commands actually executed by the runtime.
5488    executed_cmd_count: usize,
5489    /// Last tick time.
5490    last_tick: Instant,
5491    /// Whether the UI needs to be redrawn.
5492    dirty: bool,
5493    /// Monotonic frame index for evidence logging.
5494    frame_idx: u64,
5495    /// Monotonic tick index for tick-strategy scheduling.
5496    tick_count: u64,
5497    /// Widget scheduling signals captured during the last render.
5498    widget_signals: Vec<WidgetSignal>,
5499    /// Widget refresh selection configuration.
5500    widget_refresh_config: WidgetRefreshConfig,
5501    /// Last computed widget refresh plan.
5502    widget_refresh_plan: WidgetRefreshPlan,
5503    /// Current terminal width.
5504    width: u16,
5505    /// Current terminal height.
5506    height: u16,
5507    /// Forced terminal size override (when set, resize events are ignored).
5508    forced_size: Option<(u16, u16)>,
5509    /// Poll timeout when no tick is scheduled.
5510    poll_timeout: Duration,
5511    /// Whether the runtime should observe process-level termination signals.
5512    intercept_signals: bool,
5513    /// Termination signal recorded for this program instance (0 = none).
5514    ///
5515    /// Interactive constructors additionally consult the process-global slot
5516    /// that the OS signal handler thread writes to (`global_signal_slot`);
5517    /// headless and simulator programs only ever see signals injected through
5518    /// [`Program::inject_termination_signal`], so parallel tests can never
5519    /// clear or observe each other's pending signal.
5520    pending_signal: Arc<std::sync::atomic::AtomicI32>,
5521    /// Whether `observed_termination_signal` also reads the process-global
5522    /// slot written by the installed OS signal handler.
5523    global_signal_slot: bool,
5524    /// Job-control stop requested for this instance (0 = none): a Ctrl-Z key
5525    /// with `ctrl_z_suspends`, or [`Program::inject_suspend_signal`]. OS stop
5526    /// signals arrive through `job_control_claim` instead.
5527    pending_suspend: Arc<std::sync::atomic::AtomicI32>,
5528    /// Whether a stop request suspends at all: job control is configured on
5529    /// and the event source can release its terminal session.
5530    suspend_enabled: bool,
5531    /// Whether a Ctrl-Z key press requests a suspend instead of reaching the model.
5532    ctrl_z_suspends: bool,
5533    /// This program's hold on the OS stop signals; interactive programs only.
5534    job_control_claim: Option<ftui_core::job_control::JobControlClaim>,
5535    /// Stops the process after the terminal is handed back. Tests replace it:
5536    /// a test process that really stopped would hang the suite.
5537    stop_process: fn(i32) -> io::Result<()>,
5538    /// Immediate drain policy for bursty input handling.
5539    immediate_drain_config: ImmediateDrainConfig,
5540    /// Runtime counters for immediate-drain behavior.
5541    immediate_drain_stats: ImmediateDrainStats,
5542    /// Frame budget configuration.
5543    budget: RenderBudget,
5544    /// Runtime load-governor state for mode and fallback evidence.
5545    load_governor: LoadGovernorState,
5546    /// Conformal predictor for frame-time risk gating.
5547    conformal_predictor: Option<ConformalPredictor>,
5548    /// Last observed frame time (microseconds), used as a baseline predictor.
5549    last_frame_time_us: Option<f64>,
5550    /// Last observed update duration (microseconds).
5551    last_update_us: Option<u64>,
5552    /// Optional frame timing sink for profiling.
5553    frame_timing: Option<FrameTimingConfig>,
5554    /// Locale context used for rendering.
5555    locale_context: LocaleContext,
5556    /// Last observed locale version.
5557    locale_version: u64,
5558    /// Resize coalescer for rapid resize events.
5559    resize_coalescer: ResizeCoalescer,
5560    /// Shared evidence sink for decision logs (optional).
5561    evidence_sink: Option<EvidenceSink>,
5562    /// Whether fairness config has been logged to evidence sink.
5563    fairness_config_logged: bool,
5564    /// Resize handling behavior.
5565    resize_behavior: ResizeBehavior,
5566    /// Input fairness guard for scheduler integration.
5567    fairness_guard: InputFairnessGuard,
5568    /// Accumulated input processing duration awaiting the cycle's resize-fairness check.
5569    pending_fairness_input_duration: Option<Duration>,
5570    /// Optional event recorder for macro capture.
5571    event_recorder: Option<EventRecorder>,
5572    /// Subscription lifecycle manager.
5573    subscriptions: SubscriptionManager<M::Message>,
5574    /// Channel for receiving messages from background tasks.
5575    #[cfg(test)]
5576    task_sender: std::sync::mpsc::Sender<M::Message>,
5577    /// Channel for receiving messages from background tasks.
5578    task_receiver: std::sync::mpsc::Receiver<M::Message>,
5579    /// Internal task execution substrate behind `Cmd::Task`.
5580    task_executor: TaskExecutor<M::Message>,
5581    /// Optional state registry for widget persistence.
5582    state_registry: Option<std::sync::Arc<StateRegistry>>,
5583    /// Persistence configuration.
5584    persistence_config: PersistenceConfig,
5585    /// Last checkpoint save time.
5586    last_checkpoint: Instant,
5587    /// Inline auto UI height remeasurement state.
5588    inline_auto_remeasure: Option<InlineAutoRemeasureState>,
5589    /// Gesture recognizer fed by `handle_event` when
5590    /// `ProgramConfig::gestures` is set.
5591    gesture_recognizer: Option<ftui_core::gesture::GestureRecognizer>,
5592    /// Event coalescer for mouse moves and scrolls when
5593    /// `ProgramConfig::event_coalescing` is enabled.
5594    event_coalescer: Option<ftui_core::event_coalescer::EventCoalescer>,
5595    /// Screen-reader policy when `ProgramConfig::accessibility` is set.
5596    a11y_policy: Option<ScreenReaderPolicy>,
5597    /// Explicit content capture policy for accessibility evidence only.
5598    a11y_evidence_text: bool,
5599    /// Accessibility tree built from the last rendered frame.
5600    a11y_tree: Option<A11yTree>,
5601    /// Reading order (node IDs, push order) of the last accessibility tree.
5602    a11y_order: Vec<u64>,
5603    /// Screen-reader announcements derived from the last frame's tree diff.
5604    a11y_announcements: Vec<ScreenReaderAnnouncement>,
5605    /// Tree and reading order collected during `render_buffer`, consumed by
5606    /// `process_a11y_frame` once the frame has been rendered.
5607    a11y_pending: Option<(A11yTree, Vec<u64>)>,
5608    /// Set by `process_a11y_frame` when the tree differed from the previous
5609    /// frame; `render_frame` then delivers [`Model::on_accessibility`].
5610    a11y_changed: bool,
5611    /// Announcements dropped by the policy cap in the last frame.
5612    a11y_dropped: usize,
5613    /// Input events recovered from bytes the startup capability probes read
5614    /// off the tty while waiting for terminal replies; delivered before the
5615    /// main loop so a key or click during startup is not lost.
5616    startup_events: Vec<Event>,
5617    /// Preserve sequence state across successive recovered byte chunks.
5618    startup_parser: ftui_core::input_parser::InputParser,
5619    /// Forward [`Event::TerminalResponse`] replies to [`Model::update`].
5620    deliver_terminal_responses: bool,
5621    /// Per-frame bump arena for temporary render-path allocations.
5622    frame_arena: FrameArena,
5623    /// Unified frame guardrails (memory/queue limits).
5624    guardrails: FrameGuardrails,
5625    /// Frame index of the last soft-tier capacity trim (`None` = never
5626    /// trimmed).
5627    ///
5628    /// Soft memory alerts fire on retained CAPACITY that only a rebuild can
5629    /// shed; trimming every alerting frame would thrash allocations when
5630    /// usage hovers near the limit, so trims are cooldown-gated
5631    /// (bd-1za0z: actuator must be able to move the sensor).
5632    last_soft_trim_frame: Option<u64>,
5633    /// Optional tick strategy for selective background screen ticking.
5634    tick_strategy: Option<Box<dyn crate::tick_strategy::TickStrategy>>,
5635    /// Last active screen observed by the tick strategy dispatch path.
5636    last_active_screen_for_strategy: Option<String>,
5637    /// Requested runtime lane from `ProgramConfig`.
5638    requested_lane: RuntimeLane,
5639    /// Effective runtime lane after feature-gated fallback resolution.
5640    resolved_lane: RuntimeLane,
5641    /// Rollout policy controlling shadow evidence recording.
5642    rollout_policy: RolloutPolicy,
5643    /// Monotonic 0-based counter of frames presented under `RolloutPolicy::Shadow`.
5644    shadow_frame_idx: u64,
5645}
5646
5647/// Canonical error message returned when a live terminal session is opened
5648/// with redirected stdin or stdout.
5649pub const NOT_A_CONSOLE_MESSAGE: &str =
5650    "stdin is not a console; run inside Windows Terminal, conhost, or use the headless simulator";
5651
5652/// Return `true` when both standard input and standard output are attached to a
5653/// terminal/console handle.
5654#[must_use]
5655pub fn console_available() -> bool {
5656    io::IsTerminal::is_terminal(&io::stdin()) && io::IsTerminal::is_terminal(&io::stdout())
5657}
5658
5659/// Validate whether a live console is available, returning
5660/// [`io::ErrorKind::Unsupported`] with [`NOT_A_CONSOLE_MESSAGE`] when `false`.
5661pub fn validate_console_available(is_console: bool) -> io::Result<()> {
5662    if is_console {
5663        Ok(())
5664    } else {
5665        Err(io::Error::new(
5666            io::ErrorKind::Unsupported,
5667            NOT_A_CONSOLE_MESSAGE,
5668        ))
5669    }
5670}
5671
5672/// Parse a positive millisecond string (such as `"1500"`) into a [`Duration`].
5673///
5674/// Rejects empty strings, zero, negative numbers, and non-numeric input.
5675#[must_use]
5676pub fn parse_exit_after_ms(raw: &str) -> Option<Duration> {
5677    let ms = raw.trim().parse::<u64>().ok()?;
5678    (ms > 0).then(|| Duration::from_millis(ms))
5679}
5680
5681/// Read an environment variable (such as `"FTUI_EXIT_AFTER_MS"`) and parse a
5682/// positive millisecond duration for deterministic smoke/test exit.
5683#[must_use]
5684pub fn exit_after_env(var_name: &str) -> Option<Duration> {
5685    let raw = std::env::var(var_name).ok()?;
5686    parse_exit_after_ms(&raw)
5687}
5688
5689#[cfg(feature = "crossterm-compat")]
5690impl<M: Model> Program<M, CrosstermEventSource, TerminalPresenter<Stdout>> {
5691    /// Create a new program with default configuration.
5692    pub fn new(model: M) -> io::Result<Self>
5693    where
5694        M::Message: Send + 'static,
5695    {
5696        Self::with_config(model, ProgramConfig::default())
5697    }
5698
5699    /// Create a new program with the specified configuration.
5700    pub fn with_config(model: M, config: ProgramConfig) -> io::Result<Self>
5701    where
5702        M::Message: Send + 'static,
5703    {
5704        let resolved_lane = config.runtime_lane.resolve();
5705        let effect_queue_config = config.resolved_effect_queue_config(resolved_lane);
5706        let mut capabilities = TerminalCapabilities::with_overrides();
5707        let mouse_capture = config.resolved_mouse_capture();
5708        let requested_features = BackendFeatures {
5709            mouse_capture,
5710            bracketed_paste: config.bracketed_paste,
5711            focus_events: config.focus_reporting,
5712            kitty_keyboard: config.kitty_keyboard,
5713        };
5714        let initial_features =
5715            sanitize_backend_features_for_capabilities(requested_features, &capabilities);
5716        let session = match TerminalSession::new(SessionOptions {
5717            alternate_screen: matches!(config.screen_mode, ScreenMode::AltScreen),
5718            mouse_capture: initial_features.mouse_capture,
5719            pixel_mouse: config.pixel_mouse,
5720            bracketed_paste: initial_features.bracketed_paste,
5721            focus_events: initial_features.focus_events,
5722            kitty_keyboard: initial_features.kitty_keyboard,
5723            intercept_signals: config.intercept_signals,
5724        }) {
5725            Ok(session) => session,
5726            Err(_) if !console_available() => {
5727                validate_console_available(false)?;
5728                unreachable!()
5729            }
5730            Err(err) => return Err(err),
5731        };
5732        let events = CrosstermEventSource::new(session, initial_features);
5733
5734        // Raw mode is active now, so the terminal can answer probes; the
5735        // writer built below must see the refined capabilities.
5736        let capability_decisions = probe_live_terminal(&mut capabilities);
5737        let scroll_region =
5738            verify_scroll_region(&capabilities, config.screen_mode, events.size().ok());
5739
5740        let mut writer = TerminalWriter::with_diff_config(
5741            io::stdout(),
5742            config.screen_mode,
5743            config.ui_anchor,
5744            capabilities,
5745            config.diff_config.clone(),
5746        )
5747        .with_capability_decisions(capability_decisions);
5748        if let Some(limit) = config.hyperlink_limit {
5749            writer.set_hyperlink_limit(limit);
5750        }
5751        writer.set_scroll_region_verified(
5752            scroll_region.verdict,
5753            scroll_region.rows,
5754            scroll_region.region_bottom,
5755        );
5756
5757        let frame_timing = config.frame_timing.clone();
5758        writer.set_timing_enabled(frame_timing.is_some());
5759
5760        config
5761            .evidence_sink
5762            .check_terminal_ui_stdout(io::IsTerminal::is_terminal(&io::stdout()))?;
5763        let evidence_sink = EvidenceSink::from_config(&config.evidence_sink)?;
5764        if let Some(ref sink) = evidence_sink {
5765            writer = writer.with_evidence_sink(sink.clone());
5766        }
5767
5768        let render_trace = crate::RenderTraceRecorder::from_config(
5769            &config.render_trace,
5770            crate::RenderTraceContext {
5771                capabilities: writer.capabilities(),
5772                diff_config: config.diff_config.clone(),
5773                resize_config: config.resize_coalescer.clone(),
5774                conformal_config: config.conformal_config.clone(),
5775            },
5776        )?;
5777        if let Some(recorder) = render_trace {
5778            writer = writer.with_render_trace(recorder);
5779        }
5780
5781        // Get terminal size for initial frame (or forced size override).
5782        let (w, h) = config
5783            .forced_size
5784            .unwrap_or_else(|| events.size().unwrap_or((80, 24)));
5785        let width = w.max(1);
5786        let height = h.max(1);
5787        writer.set_size(width, height);
5788
5789        let budget = render_budget_from_program_config(&config);
5790        let load_governor = LoadGovernorState::new(
5791            config.load_governor.clone(),
5792            effect_queue_config.max_queue_depth,
5793        );
5794        let conformal_predictor = config
5795            .conformal_config
5796            .clone()
5797            .map(ConformalPredictor::new)
5798            .transpose()
5799            .map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error))?;
5800        let locale_context = config.locale_context.clone();
5801        let locale_version = locale_context.version();
5802        let mut resize_coalescer =
5803            ResizeCoalescer::new(config.resize_coalescer.clone(), (width, height))
5804                .with_screen_mode(config.screen_mode);
5805        if let Some(ref sink) = evidence_sink {
5806            resize_coalescer = resize_coalescer.with_evidence_sink(sink.clone());
5807        }
5808        let subscriptions = SubscriptionManager::new();
5809        let (task_sender, task_receiver) = std::sync::mpsc::channel();
5810        let inline_auto_remeasure = config
5811            .inline_auto_remeasure
5812            .clone()
5813            .map(InlineAutoRemeasureState::new);
5814        let gesture_recognizer = config
5815            .gestures
5816            .clone()
5817            .map(ftui_core::gesture::GestureRecognizer::new);
5818        let event_coalescer = if config.event_coalescing {
5819            Some(ftui_core::event_coalescer::EventCoalescer::new())
5820        } else {
5821            None
5822        };
5823        let task_executor = TaskExecutor::new(
5824            &effect_queue_config,
5825            task_sender.clone(),
5826            evidence_sink.clone(),
5827        )?;
5828        let guardrails = FrameGuardrails::new(config.guardrails);
5829
5830        // Log runtime lane and rollout policy at startup (bd-2crbt)
5831        let shadow_evidence_path = if config.rollout_policy.is_shadow() {
5832            evidence_sink
5833                .as_ref()
5834                .and_then(EvidenceSink::path)
5835                .map(|p| p.display().to_string())
5836        } else {
5837            None
5838        };
5839        tracing::info!(
5840            target: crate::telemetry_schema::TARGET_RUNTIME,
5841            os = std::env::consts::OS,
5842            console = console_available(),
5843            requested_lane = config.runtime_lane.label(),
5844            resolved_lane = resolved_lane.label(),
5845            task_backend = task_executor.kind_name_for_logs(),
5846            rollout_policy = config.rollout_policy.label(),
5847            evidence_path = shadow_evidence_path.as_deref(),
5848            "runtime startup: lane={}, rollout={}",
5849            resolved_lane.label(),
5850            config.rollout_policy.label(),
5851        );
5852
5853        let suspend_enabled = config.job_control && events.supports_suspend();
5854        let job_control_claim = (suspend_enabled && config.intercept_signals)
5855            .then(ftui_core::job_control::JobControlClaim::acquire)
5856            .flatten();
5857
5858        let mut startup_parser = ftui_core::input_parser::InputParser::new();
5859        startup_parser.set_pixel_mouse(config.pixel_mouse);
5860
5861        Ok(Self {
5862            model,
5863            presenter: TerminalPresenter::new(writer),
5864            events,
5865            backend_features: initial_features,
5866            running: true,
5867            shutdown_complete: false,
5868            tick_rate: None,
5869            executed_cmd_count: 0,
5870            last_tick: Instant::now(),
5871            dirty: true,
5872            frame_idx: 0,
5873            tick_count: 0,
5874            widget_signals: Vec::new(),
5875            a11y_policy: config.accessibility,
5876            a11y_evidence_text: config.accessibility_evidence_text,
5877            a11y_tree: None,
5878            a11y_order: Vec::new(),
5879            a11y_announcements: Vec::new(),
5880            a11y_pending: None,
5881            a11y_changed: false,
5882            a11y_dropped: 0,
5883            startup_events: Vec::new(),
5884            startup_parser,
5885            deliver_terminal_responses: config.deliver_terminal_responses,
5886            widget_refresh_config: config.widget_refresh,
5887            widget_refresh_plan: WidgetRefreshPlan::new(),
5888            width,
5889            height,
5890            forced_size: config.forced_size,
5891            poll_timeout: config.poll_timeout,
5892            intercept_signals: config.intercept_signals,
5893            pending_signal: Arc::new(std::sync::atomic::AtomicI32::new(0)),
5894            global_signal_slot: true,
5895            pending_suspend: Arc::new(std::sync::atomic::AtomicI32::new(0)),
5896            suspend_enabled,
5897            ctrl_z_suspends: config.ctrl_z_suspends,
5898            job_control_claim,
5899            stop_process: ftui_core::job_control::stop_process,
5900            immediate_drain_config: config.immediate_drain,
5901            immediate_drain_stats: ImmediateDrainStats::default(),
5902            budget,
5903            load_governor,
5904            conformal_predictor,
5905            last_frame_time_us: None,
5906            last_update_us: None,
5907            frame_timing,
5908            locale_context,
5909            locale_version,
5910            resize_coalescer,
5911            evidence_sink,
5912            fairness_config_logged: false,
5913            resize_behavior: config.resize_behavior,
5914            fairness_guard: InputFairnessGuard::new(),
5915            pending_fairness_input_duration: None,
5916            event_recorder: None,
5917            subscriptions,
5918            #[cfg(test)]
5919            task_sender,
5920            task_receiver,
5921            task_executor,
5922            state_registry: config.persistence.registry.clone(),
5923            persistence_config: config.persistence,
5924            last_checkpoint: Instant::now(),
5925            inline_auto_remeasure,
5926            gesture_recognizer,
5927            event_coalescer,
5928            frame_arena: FrameArena::default(),
5929            guardrails,
5930            last_soft_trim_frame: None,
5931            tick_strategy: config
5932                .tick_strategy
5933                .map(|strategy| Box::new(strategy) as Box<dyn crate::tick_strategy::TickStrategy>),
5934            last_active_screen_for_strategy: None,
5935            requested_lane: config.runtime_lane,
5936            resolved_lane,
5937            rollout_policy: config.rollout_policy,
5938            shadow_frame_idx: 0,
5939        })
5940    }
5941}
5942
5943impl<M: Model, E: BackendEventSource<Error = io::Error>, P: BackendPresenter<Error = io::Error>>
5944    Program<M, E, P>
5945{
5946    /// Create a program with an externally-constructed event source and presenter.
5947    ///
5948    /// This is the generic entry point for alternative backends (native tty,
5949    /// WASM, headless testing). The caller is responsible for terminal
5950    /// lifecycle (raw mode, cleanup) โ€” the event source should handle that
5951    /// via its `Drop` impl or an external RAII guard.
5952    pub fn with_event_source(
5953        model: M,
5954        events: E,
5955        backend_features: BackendFeatures,
5956        presenter: P,
5957        config: ProgramConfig,
5958    ) -> io::Result<Self>
5959    where
5960        M::Message: Send + 'static,
5961    {
5962        let resolved_lane = config.runtime_lane.resolve();
5963        let effect_queue_config = config.resolved_effect_queue_config(resolved_lane);
5964        let (width, height) = config
5965            .forced_size
5966            .unwrap_or_else(|| events.size().unwrap_or((80, 24)));
5967        let width = width.max(1);
5968        let height = height.max(1);
5969
5970        let mut presenter = presenter;
5971        if let Some(limit) = config.hyperlink_limit {
5972            presenter.set_hyperlink_limit(limit);
5973        }
5974        presenter.resize(width, height);
5975
5976        let evidence_sink = EvidenceSink::from_config(&config.evidence_sink)?;
5977        if let Some(ref sink) = evidence_sink {
5978            let sink_clone = sink.clone();
5979            presenter.set_evidence_writer(Some(Arc::new(move |line| {
5980                let _ = sink_clone.write_jsonl(line);
5981            })));
5982        }
5983
5984        let frame_timing = config.frame_timing.clone();
5985        presenter.set_timing_enabled(frame_timing.is_some());
5986
5987        let budget = render_budget_from_program_config(&config);
5988        let load_governor = LoadGovernorState::new(
5989            config.load_governor.clone(),
5990            effect_queue_config.max_queue_depth,
5991        );
5992        let conformal_predictor = config
5993            .conformal_config
5994            .clone()
5995            .map(ConformalPredictor::new)
5996            .transpose()
5997            .map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error))?;
5998        let locale_context = config.locale_context.clone();
5999        let locale_version = locale_context.version();
6000        let mut resize_coalescer =
6001            ResizeCoalescer::new(config.resize_coalescer.clone(), (width, height))
6002                .with_screen_mode(config.screen_mode);
6003        if let Some(ref sink) = evidence_sink {
6004            resize_coalescer = resize_coalescer.with_evidence_sink(sink.clone());
6005        }
6006        let subscriptions = SubscriptionManager::new();
6007        let (task_sender, task_receiver) = std::sync::mpsc::channel();
6008        let inline_auto_remeasure = config
6009            .inline_auto_remeasure
6010            .clone()
6011            .map(InlineAutoRemeasureState::new);
6012        let gesture_recognizer = config
6013            .gestures
6014            .clone()
6015            .map(ftui_core::gesture::GestureRecognizer::new);
6016        let event_coalescer = if config.event_coalescing {
6017            Some(ftui_core::event_coalescer::EventCoalescer::new())
6018        } else {
6019            None
6020        };
6021        let task_executor = TaskExecutor::new(
6022            &effect_queue_config,
6023            task_sender.clone(),
6024            evidence_sink.clone(),
6025        )?;
6026
6027        let guardrails = FrameGuardrails::new(config.guardrails);
6028
6029        let shadow_evidence_path = if config.rollout_policy.is_shadow() {
6030            evidence_sink
6031                .as_ref()
6032                .and_then(EvidenceSink::path)
6033                .map(|p| p.display().to_string())
6034        } else {
6035            None
6036        };
6037        tracing::info!(
6038            target: crate::telemetry_schema::TARGET_RUNTIME,
6039            os = std::env::consts::OS,
6040            console = console_available(),
6041            requested_lane = config.runtime_lane.label(),
6042            resolved_lane = resolved_lane.label(),
6043            task_backend = task_executor.kind_name_for_logs(),
6044            rollout_policy = config.rollout_policy.label(),
6045            evidence_path = shadow_evidence_path.as_deref(),
6046            "runtime startup: lane={}, rollout={}",
6047            resolved_lane.label(),
6048            config.rollout_policy.label(),
6049        );
6050
6051        let suspend_enabled = config.job_control && events.supports_suspend();
6052        let job_control_claim = (suspend_enabled && config.intercept_signals)
6053            .then(ftui_core::job_control::JobControlClaim::acquire)
6054            .flatten();
6055
6056        let mut startup_parser = ftui_core::input_parser::InputParser::new();
6057        startup_parser.set_pixel_mouse(config.pixel_mouse);
6058
6059        Ok(Self {
6060            model,
6061            presenter,
6062            events,
6063            backend_features,
6064            running: true,
6065            shutdown_complete: false,
6066            tick_rate: None,
6067            executed_cmd_count: 0,
6068            last_tick: Instant::now(),
6069            dirty: true,
6070            frame_idx: 0,
6071            tick_count: 0,
6072            widget_signals: Vec::new(),
6073            a11y_policy: config.accessibility,
6074            a11y_evidence_text: config.accessibility_evidence_text,
6075            a11y_tree: None,
6076            a11y_order: Vec::new(),
6077            a11y_announcements: Vec::new(),
6078            a11y_pending: None,
6079            a11y_changed: false,
6080            a11y_dropped: 0,
6081            startup_events: Vec::new(),
6082            startup_parser,
6083            deliver_terminal_responses: config.deliver_terminal_responses,
6084            widget_refresh_config: config.widget_refresh,
6085            widget_refresh_plan: WidgetRefreshPlan::new(),
6086            width,
6087            height,
6088            forced_size: config.forced_size,
6089            poll_timeout: config.poll_timeout,
6090            intercept_signals: config.intercept_signals,
6091            pending_signal: Arc::new(std::sync::atomic::AtomicI32::new(0)),
6092            global_signal_slot: true,
6093            pending_suspend: Arc::new(std::sync::atomic::AtomicI32::new(0)),
6094            suspend_enabled,
6095            ctrl_z_suspends: config.ctrl_z_suspends,
6096            job_control_claim,
6097            stop_process: ftui_core::job_control::stop_process,
6098            immediate_drain_config: config.immediate_drain,
6099            immediate_drain_stats: ImmediateDrainStats::default(),
6100            budget,
6101            load_governor,
6102            conformal_predictor,
6103            last_frame_time_us: None,
6104            last_update_us: None,
6105            frame_timing,
6106            locale_context,
6107            locale_version,
6108            resize_coalescer,
6109            evidence_sink,
6110            fairness_config_logged: false,
6111            resize_behavior: config.resize_behavior,
6112            fairness_guard: InputFairnessGuard::new(),
6113            pending_fairness_input_duration: None,
6114            event_recorder: None,
6115            subscriptions,
6116            #[cfg(test)]
6117            task_sender,
6118            task_receiver,
6119            task_executor,
6120            state_registry: config.persistence.registry.clone(),
6121            persistence_config: config.persistence,
6122            last_checkpoint: Instant::now(),
6123            inline_auto_remeasure,
6124            gesture_recognizer,
6125            event_coalescer,
6126            frame_arena: FrameArena::default(),
6127            guardrails,
6128            last_soft_trim_frame: None,
6129            tick_strategy: config
6130                .tick_strategy
6131                .map(|strategy| Box::new(strategy) as Box<dyn crate::tick_strategy::TickStrategy>),
6132            last_active_screen_for_strategy: None,
6133            requested_lane: config.runtime_lane,
6134            resolved_lane,
6135            rollout_policy: config.rollout_policy,
6136            shadow_frame_idx: 0,
6137        })
6138    }
6139}
6140
6141// =============================================================================
6142// Native TTY backend constructor (feature-gated)
6143// =============================================================================
6144
6145#[cfg(any(
6146    feature = "crossterm-compat",
6147    all(feature = "native-backend", unix),
6148    test
6149))]
6150#[inline]
6151const fn sanitize_backend_features_for_capabilities(
6152    requested: BackendFeatures,
6153    capabilities: &ftui_core::terminal_capabilities::TerminalCapabilities,
6154) -> BackendFeatures {
6155    let focus_events_supported = capabilities.focus_events && !capabilities.in_any_mux();
6156    let kitty_keyboard_supported = capabilities.kitty_keyboard && !capabilities.in_any_mux();
6157
6158    BackendFeatures {
6159        mouse_capture: requested.mouse_capture && capabilities.mouse_sgr,
6160        bracketed_paste: requested.bracketed_paste && capabilities.bracketed_paste,
6161        focus_events: requested.focus_events && focus_events_supported,
6162        kitty_keyboard: requested.kitty_keyboard && kitty_keyboard_supported,
6163    }
6164}
6165
6166#[cfg(all(feature = "native-backend", unix))]
6167impl<M: Model> Program<M, ftui_tty::TtyBackend, TerminalPresenter<Stdout>> {
6168    /// Open the default backend for this build (the native TTY backend).
6169    ///
6170    /// See [`DEFAULT_BACKEND`] and [`DefaultProgram`]; on builds without
6171    /// `native-backend` (or on non-Unix targets) this resolves to the Crossterm
6172    /// backend instead, and it does not exist when no backend was compiled.
6173    pub fn open(model: M, config: ProgramConfig) -> io::Result<Self>
6174    where
6175        M::Message: Send + 'static,
6176    {
6177        Self::with_native_backend(model, config)
6178    }
6179
6180    /// Create a program backed by the native TTY backend (no Crossterm).
6181    ///
6182    /// This opens a live terminal session via `ftui-tty`, entering raw mode
6183    /// and enabling the requested features. When the program exits (or panics),
6184    /// `TtyBackend::drop()` restores the terminal to its original state.
6185    ///
6186    /// **Unix-only.** `ftui-tty` does not yet have a Windows-native backend.
6187    /// On non-Unix targets call [`Program::with_config`] (with `crossterm-compat`)
6188    /// instead โ€” calling `with_native_backend` from Windows used to silently
6189    /// fall through to the headless 0ร—0 test backend and produce a single
6190    /// init-frame-then-silence pattern that looks like a hung TUI.
6191    #[cfg(unix)]
6192    pub fn with_native_backend(model: M, config: ProgramConfig) -> io::Result<Self>
6193    where
6194        M::Message: Send + 'static,
6195    {
6196        let mut capabilities =
6197            ftui_core::terminal_capabilities::TerminalCapabilities::with_overrides();
6198        let mouse_capture = config.resolved_mouse_capture();
6199        let requested_features = BackendFeatures {
6200            mouse_capture,
6201            bracketed_paste: config.bracketed_paste,
6202            focus_events: config.focus_reporting,
6203            kitty_keyboard: config.kitty_keyboard,
6204        };
6205        let features =
6206            sanitize_backend_features_for_capabilities(requested_features, &capabilities);
6207        let options = ftui_tty::TtySessionOptions {
6208            alternate_screen: matches!(config.screen_mode, ScreenMode::AltScreen),
6209            features,
6210            pixel_mouse: config.pixel_mouse,
6211            intercept_signals: config.intercept_signals,
6212        };
6213        let backend = ftui_tty::TtyBackend::open(0, 0, options)?;
6214
6215        // The native session is live (raw mode), so the terminal can be asked
6216        // directly what it supports; see `probe_live_terminal`.
6217        let capability_decisions = probe_live_terminal(&mut capabilities);
6218        let scroll_region =
6219            verify_scroll_region(&capabilities, config.screen_mode, backend.size().ok());
6220
6221        let mut writer = TerminalWriter::with_diff_config(
6222            io::stdout(),
6223            config.screen_mode,
6224            config.ui_anchor,
6225            capabilities,
6226            config.diff_config.clone(),
6227        )
6228        .with_capability_decisions(capability_decisions);
6229        writer.set_scroll_region_verified(
6230            scroll_region.verdict,
6231            scroll_region.rows,
6232            scroll_region.region_bottom,
6233        );
6234        config
6235            .evidence_sink
6236            .check_terminal_ui_stdout(io::IsTerminal::is_terminal(&io::stdout()))?;
6237        let evidence_sink = EvidenceSink::from_config(&config.evidence_sink)?;
6238        if let Some(ref sink) = evidence_sink {
6239            writer = writer.with_evidence_sink(sink.clone());
6240        }
6241
6242        let render_trace = crate::RenderTraceRecorder::from_config(
6243            &config.render_trace,
6244            crate::RenderTraceContext {
6245                capabilities: writer.capabilities(),
6246                diff_config: config.diff_config.clone(),
6247                resize_config: config.resize_coalescer.clone(),
6248                conformal_config: config.conformal_config.clone(),
6249            },
6250        )?;
6251        if let Some(recorder) = render_trace {
6252            writer = writer.with_render_trace(recorder);
6253        }
6254
6255        Self::with_event_source(
6256            model,
6257            backend,
6258            features,
6259            TerminalPresenter::new(writer),
6260            config,
6261        )
6262    }
6263}
6264
6265impl<M: Model, E: BackendEventSource<Error = io::Error>, P: BackendPresenter<Error = io::Error>>
6266    Program<M, E, P>
6267{
6268    /// Run the main event loop.
6269    ///
6270    /// This is the main entry point. It handles:
6271    /// 1. Initialization (terminal setup, raw mode)
6272    /// 2. Event polling and message dispatch
6273    /// 3. Frame rendering
6274    /// 4. Shutdown (terminal cleanup)
6275    pub fn run(&mut self) -> io::Result<()> {
6276        if self.shutdown_complete {
6277            return Err(io::Error::new(
6278                io::ErrorKind::InvalidInput,
6279                "program lifecycle has already completed",
6280            ));
6281        }
6282
6283        let run_result = self.run_event_loop();
6284        self.complete_lifecycle(run_result)
6285    }
6286
6287    #[inline]
6288    fn observed_termination_signal(&self) -> Option<i32> {
6289        if !self.intercept_signals {
6290            return None;
6291        }
6292        match self
6293            .pending_signal
6294            .load(std::sync::atomic::Ordering::SeqCst)
6295        {
6296            0 => {}
6297            signal => return Some(signal),
6298        }
6299        if self.global_signal_slot {
6300            check_termination_signal()
6301        } else {
6302            None
6303        }
6304    }
6305
6306    /// Record a termination signal for this program instance, as if the OS
6307    /// signal handler had delivered it. The first pending signal wins until
6308    /// the run loop consumes it. Intended for harnesses and tests; interactive
6309    /// programs receive real signals through the installed handler.
6310    pub fn inject_termination_signal(&self, signal: i32) {
6311        let _ = self.pending_signal.compare_exchange(
6312            0,
6313            signal,
6314            std::sync::atomic::Ordering::SeqCst,
6315            std::sync::atomic::Ordering::SeqCst,
6316        );
6317    }
6318
6319    /// Request a job-control stop for this program instance, as if `signal`
6320    /// (SIGTSTP, SIGTTIN or SIGTTOU) had been delivered. The run loop hands the
6321    /// terminal back, stops the process and restores the terminal when it is
6322    /// continued. Ignored unless job control is enabled and the event source
6323    /// supports suspend.
6324    pub fn inject_suspend_signal(&self, signal: i32) {
6325        self.pending_suspend
6326            .store(signal, std::sync::atomic::Ordering::SeqCst);
6327    }
6328
6329    /// The pending stop request: this instance's own first (Ctrl-Z key,
6330    /// injection), then the OS signal recorded against this program's claim.
6331    fn take_suspend_request(&mut self) -> Option<i32> {
6332        if !self.suspend_enabled {
6333            return None;
6334        }
6335        match self
6336            .pending_suspend
6337            .swap(0, std::sync::atomic::Ordering::SeqCst)
6338        {
6339            0 => self
6340                .job_control_claim
6341                .as_ref()
6342                .and_then(ftui_core::job_control::JobControlClaim::take_pending),
6343            signal => Some(signal),
6344        }
6345    }
6346
6347    /// Serve a pending stop request (`docs/spec/suspend-resume.md` ยง5-6):
6348    /// release the presenter's and then the backend's terminal state, stop
6349    /// the process, and on continue re-arm the backend, re-read the size and
6350    /// force a full repaint. Coalesces: requests that arrive meanwhile are
6351    /// taken with this one's.
6352    fn service_suspend(&mut self) -> io::Result<()> {
6353        let Some(signal) = self.take_suspend_request() else {
6354            return Ok(());
6355        };
6356        // Termination outranks suspension (ยง2 invariant 3); the caller's next
6357        // termination check ends the loop.
6358        if self.observed_termination_signal().is_some() {
6359            return Ok(());
6360        }
6361        self.presenter.suspend()?;
6362        if !self.events.suspend()? {
6363            // Nothing was released, so stopping would strand a raw terminal.
6364            // The presenter did let go of its state, so repaint in full.
6365            self.presenter.resize(self.width, self.height);
6366            self.mark_dirty();
6367            return Ok(());
6368        }
6369        self.write_job_control_evidence("suspend", signal, None);
6370        let stopped = (self.stop_process)(signal);
6371
6372        // Continued, or the stop failed: take the terminal back either way.
6373        self.events.resume()?;
6374        let _ = self.take_suspend_request();
6375        let (width, height) = self
6376            .forced_size
6377            .unwrap_or_else(|| self.events.size().unwrap_or((self.width, self.height)));
6378        let (width, height) = (width.max(1), height.max(1));
6379        let size_changed = (width, height) != (self.width, self.height);
6380        if size_changed {
6381            // Resize first, so layout runs once, at the new size (ยง6j).
6382            self.resize_coalescer
6383                .record_external_apply(width, height, Instant::now());
6384            self.apply_resize(width, height, Duration::ZERO, false)?;
6385        } else {
6386            // Drops the diff baseline: the shell may have drawn anything.
6387            self.presenter.resize(width, height);
6388            self.mark_dirty();
6389        }
6390        self.write_job_control_evidence("resume", signal, Some(size_changed));
6391        if let Err(error) = stopped {
6392            tracing::warn!(
6393                target: crate::telemetry_schema::TARGET_RUNTIME,
6394                signal,
6395                %error,
6396                "job-control stop failed; resumed without stopping"
6397            );
6398        }
6399        Ok(())
6400    }
6401
6402    /// One `suspend` or `resume` evidence row (schema in
6403    /// `docs/spec/telemetry-events.md`).
6404    fn write_job_control_evidence(&self, event: &str, signal: i32, size_changed: Option<bool>) {
6405        let Some(ref sink) = self.evidence_sink else {
6406            return;
6407        };
6408        let size_changed = size_changed.map_or(String::new(), |changed| {
6409            format!(r#","size_changed":{changed}"#)
6410        });
6411        let _ = sink.write_jsonl(&format!(
6412            r#"{{"schema_version":"{}","event":"{}","signal":{},"screen_mode":"{}","cols":{},"rows":{}{}}}"#,
6413            crate::evidence_sink::EVIDENCE_SCHEMA_VERSION,
6414            event,
6415            signal,
6416            crate::resize_coalescer::screen_mode_str(self.presenter.screen_mode()),
6417            self.width,
6418            self.height,
6419            size_changed,
6420        ));
6421    }
6422
6423    /// The termination signal pending for this program instance, if any.
6424    #[must_use]
6425    pub fn pending_termination_signal(&self) -> Option<i32> {
6426        match self
6427            .pending_signal
6428            .load(std::sync::atomic::Ordering::SeqCst)
6429        {
6430            0 => None,
6431            signal => Some(signal),
6432        }
6433    }
6434
6435    /// Access widget scheduling signals captured on the last render.
6436    #[inline]
6437    pub fn last_widget_signals(&self) -> &[WidgetSignal] {
6438        &self.widget_signals
6439    }
6440
6441    /// Snapshot immediate-drain runtime counters.
6442    #[inline]
6443    pub fn immediate_drain_stats(&self) -> ImmediateDrainStats {
6444        self.immediate_drain_stats
6445    }
6446
6447    /// The inner event loop, separated for proper cleanup handling.
6448    /// Parse raw input bytes (as the tty would have delivered them) into
6449    /// events that the main loop delivers before it starts polling. Used for
6450    /// the bytes the startup capability probes read off the tty while
6451    /// waiting for terminal replies (`caps_probe::take_probe_leftover_input`).
6452    pub fn queue_startup_input(&mut self, bytes: &[u8]) {
6453        if bytes.is_empty() {
6454            return;
6455        }
6456        let events = self.startup_parser.parse(bytes);
6457        debug!(
6458            target: crate::telemetry_schema::TARGET_RUNTIME,
6459            bytes = bytes.len(),
6460            events = events.len(),
6461            "queued startup input recovered from the capability probes"
6462        );
6463        self.startup_events.extend(events);
6464    }
6465
6466    /// Deliver the queued startup events in arrival order.
6467    fn drain_startup_events(&mut self) -> io::Result<()> {
6468        // The probe-read batch is complete. Resolve an ambiguous trailing key
6469        // before handing input ownership back to the live event source; dropping
6470        // the parser here used to silently lose a lone Escape.
6471        if let Some(event) = self.startup_parser.timeout() {
6472            self.startup_events.push(event);
6473        }
6474        let events = std::mem::take(&mut self.startup_events);
6475        for event in events {
6476            if !self.running {
6477                break;
6478            }
6479            self.handle_event(event)?;
6480        }
6481        Ok(())
6482    }
6483
6484    fn run_event_loop(&mut self) -> io::Result<Option<i32>> {
6485        // Auto-load state on start
6486        if self.persistence_config.auto_load {
6487            self.load_state();
6488        }
6489
6490        // Input the constructors' probes swallowed belongs to this program.
6491        let leftover = ftui_core::caps_probe::take_probe_leftover_input();
6492        self.queue_startup_input(&leftover);
6493
6494        // Initialize
6495        let cmd = {
6496            let _span = info_span!(crate::telemetry_schema::span::PROGRAM_INIT).entered();
6497            self.model.init()
6498        };
6499        self.execute_cmd(cmd)?;
6500
6501        let mut termination_signal = self.observed_termination_signal();
6502        if self.running && termination_signal.is_none() {
6503            // Reconcile initial subscriptions
6504            self.reconcile_subscriptions();
6505            self.process_subscription_failures(false)?;
6506
6507            // Initial render
6508            if self.running {
6509                self.render_frame()?;
6510            }
6511        }
6512
6513        // Deliver input that arrived during startup before polling for more.
6514        if self.running && termination_signal.is_none() {
6515            self.drain_startup_events()?;
6516        }
6517
6518        // Optional deterministic exit hook (FTUI_EXIT_AFTER_MS).
6519        let exit_deadline = exit_after_env("FTUI_EXIT_AFTER_MS").map(|d| Instant::now() + d);
6520
6521        // Main loop
6522        let mut loop_count: u64 = 0;
6523        while self.running {
6524            termination_signal = termination_signal.or_else(|| self.observed_termination_signal());
6525            if termination_signal.is_some() {
6526                self.running = false;
6527                break;
6528            }
6529            if exit_deadline.is_some_and(|deadline| Instant::now() >= deadline) {
6530                self.running = false;
6531                break;
6532            }
6533            // A stop signal lands here within one poll interval: signal-hook
6534            // handlers only set a flag, and poll(2) is not interrupted early.
6535            self.service_suspend()?;
6536
6537            loop_count += 1;
6538            // Log heartbeat every 100 iterations to avoid flooding stderr
6539            if loop_count.is_multiple_of(100) {
6540                crate::debug_trace!("main loop heartbeat: iteration {}", loop_count);
6541            }
6542
6543            // Poll for input with tick timeout (capped by exit_deadline if active)
6544            let mut timeout = self.effective_timeout();
6545            if let Some(deadline) = exit_deadline {
6546                timeout = timeout.min(deadline.saturating_duration_since(Instant::now()));
6547            }
6548
6549            // Poll for events with timeout
6550            let poll_result = self.events.poll_event(timeout)?;
6551            termination_signal = termination_signal.or_else(|| self.observed_termination_signal());
6552            if termination_signal.is_some() {
6553                self.running = false;
6554                break;
6555            }
6556            if poll_result {
6557                self.drain_ready_events()?;
6558            }
6559            if !self.running {
6560                break;
6561            }
6562            termination_signal = termination_signal.or_else(|| self.observed_termination_signal());
6563            if termination_signal.is_some() {
6564                self.running = false;
6565                break;
6566            }
6567            // Before rendering: a Ctrl-Z from the batch just drained must not
6568            // draw a frame first.
6569            self.service_suspend()?;
6570
6571            // Process subscription messages
6572            self.process_subscription_messages()?;
6573            self.process_subscription_failures(false)?;
6574            if !self.running {
6575                break;
6576            }
6577
6578            // Process background task results
6579            self.process_task_results()?;
6580            self.reap_finished_tasks();
6581            if !self.running {
6582                break;
6583            }
6584
6585            self.process_resize_coalescer()?;
6586            if !self.running {
6587                break;
6588            }
6589            termination_signal = termination_signal.or_else(|| self.observed_termination_signal());
6590            if termination_signal.is_some() {
6591                self.running = false;
6592                break;
6593            }
6594
6595            self.poll_long_press(Instant::now())?;
6596            if !self.running {
6597                break;
6598            }
6599
6600            // Detect screen transitions from any update() calls above.
6601            // A.2: notifies the tick strategy so predictive strategies learn.
6602            // D.3: force-ticks the newly active screen for immediate refresh.
6603            self.check_screen_transition();
6604
6605            // Check for tick - deliver to model so periodic logic can run
6606            if self.should_tick() {
6607                let tick_start = Instant::now();
6608                self.tick_count = self.tick_count.wrapping_add(1);
6609                let tick_count = self.tick_count;
6610
6611                let mut used_screen_dispatch = false;
6612
6613                // Per-screen tick dispatch: if the model supports multi-screen
6614                // dispatch and a tick strategy is configured, tick individual
6615                // screens selectively instead of calling monolithic
6616                // `update(Tick)`.
6617                if let Some(strategy) = self.tick_strategy.as_mut() {
6618                    // Snapshot screen topology first so the mutable borrow of the
6619                    // dispatch adapter does not overlap strategy decisions.
6620                    let dispatch_snapshot = self.model.as_screen_tick_dispatch().map(|dispatch| {
6621                        let active = dispatch.active_screen_id();
6622                        let all_screens = dispatch.screen_ids();
6623                        (active, all_screens)
6624                    });
6625
6626                    if let Some((active, all_screens)) = dispatch_snapshot {
6627                        used_screen_dispatch = true;
6628
6629                        // Feed active-screen transitions into the strategy so
6630                        // predictive strategies can learn from real navigation.
6631                        if let Some(previous_active) =
6632                            self.last_active_screen_for_strategy.as_deref()
6633                            && previous_active != active
6634                        {
6635                            strategy.on_screen_transition(previous_active, &active);
6636                        }
6637                        self.last_active_screen_for_strategy = Some(active.clone());
6638
6639                        let all_screens_count = all_screens.len();
6640                        let mut tick_targets = Vec::with_capacity(all_screens_count.max(1));
6641                        // Active screen is always ticked.
6642                        tick_targets.push(active.clone());
6643
6644                        // Tick inactive screens according to the strategy.
6645                        for screen_id in all_screens {
6646                            if screen_id != active
6647                                && strategy.should_tick(&screen_id, tick_count, &active)
6648                                    == crate::tick_strategy::TickDecision::Tick
6649                            {
6650                                tick_targets.push(screen_id);
6651                            }
6652                        }
6653
6654                        // Compute skipped screens for tracing.
6655                        let skipped_count = all_screens_count.saturating_sub(tick_targets.len());
6656
6657                        if let Some(dispatch) = self.model.as_screen_tick_dispatch() {
6658                            for screen_id in &tick_targets {
6659                                dispatch.tick_screen(screen_id, tick_count);
6660                            }
6661                        }
6662
6663                        trace!(
6664                            target: crate::telemetry_schema::TARGET_RUNTIME,
6665                            tick = tick_count,
6666                            active = %active,
6667                            ticked = tick_targets.len(),
6668                            skipped = skipped_count,
6669                            "tick_strategy.frame"
6670                        );
6671
6672                        // Maintenance tick for the strategy.
6673                        strategy.maintenance_tick(tick_count);
6674                        self.mark_dirty();
6675                    }
6676                }
6677
6678                if used_screen_dispatch && self.running {
6679                    self.reconcile_subscriptions();
6680                }
6681
6682                // Flush any pending coalesced events on tick so they do not sit unrendered.
6683                if self.running {
6684                    self.flush_coalesced_events()?;
6685                }
6686
6687                if !used_screen_dispatch {
6688                    // Monolithic model path does not expose active-screen
6689                    // transitions, so clear dispatch-local transition state.
6690                    self.last_active_screen_for_strategy = None;
6691                    let msg = M::Message::from(Event::Tick);
6692                    let cmd = {
6693                        let _span = debug_span!(
6694                            crate::telemetry_schema::span::PROGRAM_UPDATE,
6695                            msg_type = "Tick",
6696                            duration_us = tracing::field::Empty,
6697                            cmd_type = tracing::field::Empty
6698                        )
6699                        .entered();
6700                        let start = Instant::now();
6701                        let cmd = self.model.update(msg);
6702                        tracing::Span::current()
6703                            .record("duration_us", start.elapsed().as_micros() as u64);
6704                        tracing::Span::current()
6705                            .record("cmd_type", format!("{:?}", std::mem::discriminant(&cmd)));
6706                        cmd
6707                    };
6708                    self.mark_dirty();
6709                    self.execute_cmd(cmd)?;
6710                    if self.running {
6711                        self.reconcile_subscriptions();
6712                    }
6713                }
6714
6715                self.fairness_guard.event_processed(
6716                    FairnessEventType::Tick,
6717                    tick_start.elapsed(),
6718                    Instant::now(),
6719                );
6720            }
6721
6722            // Check for periodic checkpoint save
6723            self.check_checkpoint_save();
6724
6725            // Detect locale changes outside the event loop.
6726            self.check_locale_change();
6727            termination_signal = termination_signal.or_else(|| self.observed_termination_signal());
6728            if termination_signal.is_some() {
6729                self.running = false;
6730                break;
6731            }
6732
6733            // Render if dirty and no resize is waiting in the coalescer
6734            if self.dirty && !self.resize_coalescer.has_pending() {
6735                self.render_frame()?;
6736            }
6737
6738            // Periodic grapheme pool GC
6739            if loop_count.is_multiple_of(1000) {
6740                self.presenter.gc();
6741            }
6742        }
6743
6744        // If a resize was still coalescing when the loop exited, apply it now
6745        // so the final inline frame reflects the terminal's current geometry.
6746        if termination_signal.is_none()
6747            && self.resize_coalescer.has_pending()
6748            && matches!(
6749                self.presenter.screen_mode(),
6750                ScreenMode::Inline { .. } | ScreenMode::InlineAuto { .. }
6751            )
6752            && let CoalesceAction::ApplyResize {
6753                width,
6754                height,
6755                coalesce_time,
6756                forced_by_deadline,
6757            } = self.resize_coalescer.flush_pending()
6758        {
6759            self.apply_resize(width, height, coalesce_time, forced_by_deadline)?;
6760        }
6761
6762        // A quit returned by update() ends the loop before that update's
6763        // state is drawn. In inline mode the last frame stays in the terminal
6764        // after exit, so if one is on screen and the model changed since (a
6765        // child's final line count, say), draw it once more. Not after a
6766        // termination signal, and nothing for a program that never drew.
6767        // No later frame can repair a skipped or degraded one, so the frame
6768        // budget (which may be at SkipFrame after an output storm) is reset.
6769        if termination_signal.is_none()
6770            && self.dirty
6771            && self.frame_idx > 0
6772            && matches!(
6773                self.presenter.screen_mode(),
6774                ScreenMode::Inline { .. } | ScreenMode::InlineAuto { .. }
6775            )
6776        {
6777            self.budget.set_degradation(DegradationLevel::Full);
6778            self.render_frame()?;
6779        }
6780
6781        Ok(termination_signal)
6782    }
6783
6784    /// Complete the model/runtime lifecycle after every event-loop exit path.
6785    fn complete_lifecycle(&mut self, run_result: io::Result<Option<i32>>) -> io::Result<()> {
6786        let (loop_signal, primary_error) = match run_result {
6787            Ok(signal) => (signal, None),
6788            Err(error) => (None, Some(error)),
6789        };
6790        let termination_signal = loop_signal.or_else(|| self.observed_termination_signal());
6791
6792        // The event loop is over. Lifecycle commands may run model updates,
6793        // but they must never restart normal event processing.
6794        self.running = false;
6795
6796        let mut hook_error = None;
6797        if let Some(error) = primary_error.as_ref()
6798            && let Err(error) = self.invoke_error_hook(&error.to_string(), true)
6799        {
6800            hook_error = Some(error);
6801        }
6802
6803        if let Err(error) = self.process_subscription_failures(true) {
6804            hook_error.get_or_insert(error);
6805        }
6806
6807        let shutdown_error = self.shutdown_once().err();
6808
6809        // A pending termination signal takes precedence over lifecycle-step
6810        // errors: it is what ended the loop, and callers rely on the
6811        // SignalTerminationError contract for the 128+signal process exit.
6812        if let Some(signal) = termination_signal {
6813            self.pending_signal
6814                .store(0, std::sync::atomic::Ordering::SeqCst);
6815            if self.global_signal_slot {
6816                clear_termination_signal();
6817            }
6818            let error = io::Error::new(
6819                io::ErrorKind::Interrupted,
6820                SignalTerminationError { signal },
6821            );
6822            debug_assert_eq!(signal_termination_from_error(&error), Some(signal));
6823            return Err(error);
6824        }
6825
6826        if let Some(error) = primary_error {
6827            return Err(error);
6828        }
6829
6830        if let Some(error) = hook_error {
6831            return Err(error);
6832        }
6833
6834        if let Some(error) = shutdown_error {
6835            // A failing cleanup command is still a command error. Report it
6836            // after the one-shot shutdown hook without attempting teardown a
6837            // second time.
6838            let _ = self.invoke_error_hook(&error.to_string(), true);
6839            return Err(error);
6840        }
6841
6842        Ok(())
6843    }
6844
6845    /// Run model shutdown and runtime teardown at most once.
6846    fn shutdown_once(&mut self) -> io::Result<()> {
6847        if self.shutdown_complete {
6848            return Ok(());
6849        }
6850        self.shutdown_complete = true;
6851
6852        let shutdown_cmd = {
6853            let _span = info_span!(crate::telemetry_schema::span::PROGRAM_SHUTDOWN).entered();
6854            self.model.on_shutdown()
6855        };
6856        // The shutdown sequence is error-isolated: a failing shutdown command
6857        // must not skip auto-save, strategy/executor shutdown, or signal exit
6858        // mapping. The first error is captured and surfaced after cleanup.
6859        let mut shutdown_error = self.execute_lifecycle_cmd(shutdown_cmd).err();
6860
6861        if self.persistence_config.auto_save {
6862            self.save_state();
6863        }
6864
6865        if let Some(ref mut strategy) = self.tick_strategy {
6866            strategy.shutdown();
6867        }
6868
6869        self.subscriptions.stop_all();
6870        if let Err(error) = self.process_subscription_failures(true) {
6871            shutdown_error.get_or_insert(error);
6872        }
6873
6874        self.task_executor.shutdown();
6875        self.reap_finished_tasks();
6876        if let Err(error) = self.drain_shutdown_task_results() {
6877            shutdown_error.get_or_insert(error);
6878        }
6879
6880        self.resize_coalescer.flush_summary_to_evidence_sink();
6881
6882        if let Some(ref sink) = self.evidence_sink {
6883            let (hits, misses, len, capacity, enabled) =
6884                if let Some(stats) = ftui_core::text_width::width_cache_stats() {
6885                    (
6886                        stats.hits,
6887                        stats.misses,
6888                        stats.small_size + stats.main_size,
6889                        stats.capacity,
6890                        true,
6891                    )
6892                } else {
6893                    (0, 0, 0, 0, false)
6894                };
6895            let line = format!(
6896                r#"{{"schema_version":"{}","event":"width_cache_stats","hits":{},"misses":{},"len":{},"capacity":{},"enabled":{},"thread":"main"}}"#,
6897                crate::evidence_sink::EVIDENCE_SCHEMA_VERSION,
6898                hits,
6899                misses,
6900                len,
6901                capacity,
6902                enabled,
6903            );
6904            let _ = sink.write_jsonl(&line);
6905        }
6906
6907        match shutdown_error {
6908            Some(error) => Err(error),
6909            None => Ok(()),
6910        }
6911    }
6912
6913    /// Drain ready events while bounding zero-timeout polling work.
6914    ///
6915    /// The runtime preserves low-latency draining by polling with
6916    /// `Duration::ZERO`, but switches to a bounded backoff path when a burst
6917    /// exceeds configured immediate-drain budgets.
6918    fn drain_ready_events(&mut self) -> io::Result<()> {
6919        self.immediate_drain_stats.bursts = self.immediate_drain_stats.bursts.saturating_add(1);
6920
6921        let zero_poll_limit = self
6922            .immediate_drain_config
6923            .max_zero_timeout_polls_per_burst
6924            .max(1);
6925        let max_burst_duration = self.immediate_drain_config.max_burst_duration;
6926        let backoff_timeout = self.immediate_drain_config.backoff_timeout;
6927
6928        let mut burst_start = Instant::now();
6929        let mut zero_polls_in_burst_window: u64 = 0;
6930        let mut capped_this_burst = false;
6931
6932        loop {
6933            // `read_event` may return `Ok(None)` even though the preceding
6934            // poll reported readiness: the event may be unrepresentable in
6935            // ftui's canonical event types, and on Windows console readiness
6936            // can be spurious (discarded key-release/focus/menu records), in
6937            // which case the crossterm-backed source re-polls with a zero
6938            // timeout instead of parking in a blocking read (frankentui#95).
6939            // Either way we simply fall through to the bounded zero-timeout
6940            // poll below; when nothing is pending the burst ends and the
6941            // outer loop parks in its normal timed poll โ€” no busy-spin.
6942            if let Some(event) = self.events.read_event()? {
6943                self.handle_event(event)?;
6944                if !self.running {
6945                    break;
6946                }
6947            }
6948
6949            let budget_exhausted = (zero_polls_in_burst_window as usize) >= zero_poll_limit
6950                || (zero_polls_in_burst_window > 0 && burst_start.elapsed() >= max_burst_duration);
6951
6952            if budget_exhausted {
6953                if !capped_this_burst {
6954                    capped_this_burst = true;
6955                    self.immediate_drain_stats.capped_bursts =
6956                        self.immediate_drain_stats.capped_bursts.saturating_add(1);
6957                }
6958
6959                self.immediate_drain_stats.max_zero_timeout_polls_in_burst = self
6960                    .immediate_drain_stats
6961                    .max_zero_timeout_polls_in_burst
6962                    .max(zero_polls_in_burst_window);
6963
6964                if self.subscriptions.may_have_pending_messages() {
6965                    break;
6966                }
6967
6968                std::thread::yield_now();
6969                self.immediate_drain_stats.backoff_polls =
6970                    self.immediate_drain_stats.backoff_polls.saturating_add(1);
6971                if !self.events.poll_event(backoff_timeout)? {
6972                    break;
6973                }
6974                zero_polls_in_burst_window = 0;
6975                burst_start = Instant::now();
6976                continue;
6977            }
6978
6979            self.immediate_drain_stats.zero_timeout_polls = self
6980                .immediate_drain_stats
6981                .zero_timeout_polls
6982                .saturating_add(1);
6983            zero_polls_in_burst_window = zero_polls_in_burst_window.saturating_add(1);
6984            if !self.events.poll_event(Duration::ZERO)? {
6985                break;
6986            }
6987        }
6988
6989        self.immediate_drain_stats.max_zero_timeout_polls_in_burst = self
6990            .immediate_drain_stats
6991            .max_zero_timeout_polls_in_burst
6992            .max(zero_polls_in_burst_window);
6993
6994        if self.running {
6995            self.flush_coalesced_events()?;
6996        }
6997
6998        Ok(())
6999    }
7000
7001    /// Load state from the persistence registry.
7002    fn load_state(&mut self) {
7003        if let Some(registry) = &self.state_registry {
7004            match registry.load() {
7005                Ok(count) => {
7006                    info!(
7007                        target: crate::telemetry_schema::TARGET_RUNTIME,
7008                        count,
7009                        "loaded widget state from persistence"
7010                    );
7011                }
7012                Err(e) => {
7013                    tracing::warn!(
7014                        target: crate::telemetry_schema::TARGET_RUNTIME,
7015                        error = %e,
7016                        "failed to load widget state"
7017                    );
7018                }
7019            }
7020        }
7021    }
7022
7023    /// Save state to the persistence registry.
7024    fn save_state(&mut self) {
7025        if let Some(registry) = &self.state_registry {
7026            match registry.flush() {
7027                Ok(true) => {
7028                    debug!(
7029                        target: crate::telemetry_schema::TARGET_RUNTIME,
7030                        "saved widget state to persistence"
7031                    );
7032                }
7033                Ok(false) => {
7034                    // No changes to save
7035                }
7036                Err(e) => {
7037                    tracing::warn!(
7038                        target: crate::telemetry_schema::TARGET_RUNTIME,
7039                        error = %e,
7040                        "failed to save widget state"
7041                    );
7042                }
7043            }
7044        }
7045    }
7046
7047    /// Check if it's time for a periodic checkpoint save.
7048    fn check_checkpoint_save(&mut self) {
7049        if let Some(interval) = self.persistence_config.checkpoint_interval
7050            && self.last_checkpoint.elapsed() >= interval
7051        {
7052            self.save_state();
7053            self.last_checkpoint = Instant::now();
7054        }
7055    }
7056
7057    /// Hand one recognized gesture to `Model::on_gesture` and run the
7058    /// resulting command like any update command.
7059    fn deliver_gesture(
7060        &mut self,
7061        gesture: ftui_core::semantic_event::SemanticEvent,
7062    ) -> io::Result<()> {
7063        let cmd = {
7064            let _span = debug_span!(
7065                crate::telemetry_schema::span::PROGRAM_UPDATE,
7066                msg_type = "gesture"
7067            )
7068            .entered();
7069            self.model.on_gesture(gesture)
7070        };
7071        self.mark_dirty();
7072        self.execute_cmd(cmd)?;
7073        if self.running {
7074            self.reconcile_subscriptions();
7075        }
7076        Ok(())
7077    }
7078
7079    fn handle_event(&mut self, event: Event) -> io::Result<()> {
7080        // Track event start time and type for fairness scheduling.
7081        let event_start = Instant::now();
7082        let fairness_event_type = Self::classify_event_for_fairness(&event);
7083        if fairness_event_type == FairnessEventType::Input {
7084            self.fairness_guard.input_arrived(event_start);
7085        }
7086
7087        // Record event before processing (no-op when recorder is None or idle).
7088        if let Some(recorder) = &mut self.event_recorder {
7089            recorder.record(&event);
7090        }
7091
7092        // Raw mode turns off the terminal's own ^Z, so with `ctrl_z_suspends`
7093        // the key stands in for SIGTSTP and never reaches the model.
7094        if self.ctrl_z_suspends
7095            && self.suspend_enabled
7096            && let Event::Key(key) = &event
7097            && key.kind == ftui_core::event::KeyEventKind::Press
7098            && key.code == ftui_core::event::KeyCode::Char('z')
7099            && key.modifiers == ftui_core::event::Modifiers::CTRL
7100        {
7101            self.pending_suspend.store(
7102                ftui_core::job_control::KEYBOARD_STOP_SIGNAL,
7103                std::sync::atomic::Ordering::SeqCst,
7104            );
7105            self.fairness_guard.event_processed(
7106                fairness_event_type,
7107                event_start.elapsed(),
7108                Instant::now(),
7109            );
7110            return Ok(());
7111        }
7112
7113        let event = match event {
7114            Event::Resize { width, height } => {
7115                if let Some(ref mut coalescer) = self.event_coalescer {
7116                    coalescer.clear();
7117                }
7118                debug!(
7119                    target: crate::telemetry_schema::TARGET_RESIZE,
7120                    width,
7121                    height,
7122                    behavior = ?self.resize_behavior,
7123                    "Resize event received"
7124                );
7125                if let Some((forced_width, forced_height)) = self.forced_size {
7126                    debug!(
7127                        target: crate::telemetry_schema::TARGET_RESIZE,
7128                        forced_width,
7129                        forced_height, "Resize ignored due to forced size override"
7130                    );
7131                    self.fairness_guard.event_processed(
7132                        fairness_event_type,
7133                        event_start.elapsed(),
7134                        Instant::now(),
7135                    );
7136                    return Ok(());
7137                }
7138                // Clamp to minimum 1 to prevent Buffer::new panic on zero dimensions
7139                let width = width.max(1);
7140                let height = height.max(1);
7141                self.presenter.notify_resize(width, height);
7142                match self.resize_behavior {
7143                    ResizeBehavior::Immediate => {
7144                        self.resize_coalescer
7145                            .record_external_apply(width, height, Instant::now());
7146                        let result = self.apply_resize(width, height, Duration::ZERO, false);
7147                        self.fairness_guard.event_processed(
7148                            fairness_event_type,
7149                            event_start.elapsed(),
7150                            Instant::now(),
7151                        );
7152                        return result;
7153                    }
7154                    ResizeBehavior::Throttled => {
7155                        let defer_immediate_apply =
7156                            self.fairness_guard.should_yield_resize(Instant::now());
7157                        let action = self.resize_coalescer.handle_resize_with_fairness(
7158                            width,
7159                            height,
7160                            defer_immediate_apply,
7161                        );
7162                        if let CoalesceAction::ApplyResize {
7163                            width,
7164                            height,
7165                            coalesce_time,
7166                            forced_by_deadline,
7167                        } = action
7168                        {
7169                            let result =
7170                                self.apply_resize(width, height, coalesce_time, forced_by_deadline);
7171                            self.fairness_guard.event_processed(
7172                                fairness_event_type,
7173                                event_start.elapsed(),
7174                                Instant::now(),
7175                            );
7176                            return result;
7177                        }
7178
7179                        self.fairness_guard.event_processed(
7180                            fairness_event_type,
7181                            event_start.elapsed(),
7182                            Instant::now(),
7183                        );
7184                        return Ok(());
7185                    }
7186                }
7187            }
7188            Event::TerminalResponse(ref resp) => {
7189                self.on_terminal_response(resp);
7190                if !self.deliver_terminal_responses {
7191                    self.record_fairness_event(fairness_event_type, event_start.elapsed());
7192                    return Ok(());
7193                }
7194                event
7195            }
7196            other => other,
7197        };
7198
7199        // Gesture recognition runs beside the raw event, never instead of it:
7200        // the raw event still reaches `update()` below, and any gesture the
7201        // recognizer completes is delivered to `on_gesture` afterwards.
7202        let gestures = self
7203            .gesture_recognizer
7204            .as_mut()
7205            .map(|recognizer| recognizer.process(&event, Instant::now()))
7206            .unwrap_or_default();
7207
7208        if self.event_coalescer.is_some() {
7209            let is_coalescable = match &event {
7210                Event::Mouse(m) => matches!(
7211                    m.kind,
7212                    MouseEventKind::Moved
7213                        | MouseEventKind::ScrollUp
7214                        | MouseEventKind::ScrollDown
7215                        | MouseEventKind::ScrollLeft
7216                        | MouseEventKind::ScrollRight
7217                ),
7218                _ => false,
7219            };
7220
7221            let mut to_dispatch = Vec::new();
7222            if let Some(coalescer) = self.event_coalescer.as_mut() {
7223                if !is_coalescable && coalescer.has_pending() {
7224                    to_dispatch.extend(coalescer.flush());
7225                }
7226                if let Some(evt) = coalescer.push(event) {
7227                    to_dispatch.push(evt);
7228                }
7229            }
7230
7231            for evt in to_dispatch {
7232                self.dispatch_input_event(evt)?;
7233                if !self.running {
7234                    self.record_fairness_event(fairness_event_type, event_start.elapsed());
7235                    return Ok(());
7236                }
7237            }
7238        } else {
7239            self.dispatch_input_event(event)?;
7240        }
7241
7242        if self.running {
7243            for gesture in gestures {
7244                self.deliver_gesture(gesture)?;
7245            }
7246        }
7247
7248        // Track input event processing for fairness.
7249        self.record_fairness_event(fairness_event_type, event_start.elapsed());
7250
7251        Ok(())
7252    }
7253
7254    fn on_terminal_response(&mut self, resp: &ftui_core::event::TerminalResponse) {
7255        match resp {
7256            ftui_core::event::TerminalResponse::Dcs { payload, truncated } => {
7257                debug!(
7258                    target: crate::telemetry_schema::TARGET_RUNTIME,
7259                    payload_len = payload.len(),
7260                    truncated,
7261                    "terminal DCS response received"
7262                );
7263            }
7264            ftui_core::event::TerminalResponse::Apc { payload, truncated } => {
7265                debug!(
7266                    target: crate::telemetry_schema::TARGET_RUNTIME,
7267                    payload_len = payload.len(),
7268                    truncated,
7269                    "terminal APC response received"
7270                );
7271            }
7272            ftui_core::event::TerminalResponse::CellSize { width, height } => {
7273                debug!(
7274                    target: crate::telemetry_schema::TARGET_RUNTIME,
7275                    cell_width_px = width,
7276                    cell_height_px = height,
7277                    "terminal cell-size response received"
7278                );
7279                if *width > 0 && *height > 0 {
7280                    self.startup_parser.set_cell_size_px(*width, *height);
7281                }
7282            }
7283        }
7284    }
7285
7286    fn record_fairness_event(&mut self, event_type: FairnessEventType, duration: Duration) {
7287        if event_type == FairnessEventType::Input && self.resize_behavior.uses_coalescer() {
7288            *self
7289                .pending_fairness_input_duration
7290                .get_or_insert(Duration::ZERO) += duration;
7291        } else {
7292            self.fairness_guard
7293                .event_processed(event_type, duration, Instant::now());
7294        }
7295    }
7296
7297    fn complete_pending_fairness_input(&mut self, now: Instant) {
7298        if self
7299            .event_coalescer
7300            .as_ref()
7301            .is_some_and(ftui_core::event_coalescer::EventCoalescer::has_pending)
7302        {
7303            return;
7304        }
7305        if let Some(duration) = self.pending_fairness_input_duration.take() {
7306            self.fairness_guard
7307                .event_processed(FairnessEventType::Input, duration, now);
7308        }
7309    }
7310
7311    /// Dispatch a single input event to the model's `update()` method,
7312    /// mark dirty, execute the returned command, and reconcile subscriptions.
7313    fn dispatch_input_event(&mut self, event: Event) -> io::Result<()> {
7314        if !self.running {
7315            return Ok(());
7316        }
7317        let msg = M::Message::from(event);
7318        let cmd = {
7319            let _span = debug_span!(
7320                crate::telemetry_schema::span::PROGRAM_UPDATE,
7321                msg_type = "event",
7322                duration_us = tracing::field::Empty,
7323                cmd_type = tracing::field::Empty
7324            )
7325            .entered();
7326            let start = Instant::now();
7327            let cmd = self.model.update(msg);
7328            let elapsed_us = start.elapsed().as_micros() as u64;
7329            self.last_update_us = Some(elapsed_us);
7330            tracing::Span::current().record("duration_us", elapsed_us);
7331            tracing::Span::current()
7332                .record("cmd_type", format!("{:?}", std::mem::discriminant(&cmd)));
7333            cmd
7334        };
7335        self.mark_dirty();
7336        self.execute_cmd(cmd)?;
7337        if self.running {
7338            self.reconcile_subscriptions();
7339        }
7340        Ok(())
7341    }
7342
7343    /// Flush any pending coalesced input events to the model.
7344    pub fn flush_coalesced_events(&mut self) -> io::Result<()> {
7345        let pending = match self.event_coalescer.as_mut() {
7346            Some(coalescer) if coalescer.has_pending() => coalescer.flush(),
7347            _ => return Ok(()),
7348        };
7349        let flush_start = Instant::now();
7350        for event in pending {
7351            self.dispatch_input_event(event)?;
7352            if !self.running {
7353                break;
7354            }
7355        }
7356        self.record_fairness_event(FairnessEventType::Input, flush_start.elapsed());
7357        Ok(())
7358    }
7359
7360    /// Access the event coalescer, if enabled.
7361    #[must_use]
7362    pub fn event_coalescer(&self) -> Option<&ftui_core::event_coalescer::EventCoalescer> {
7363        self.event_coalescer.as_ref()
7364    }
7365
7366    /// Classify an event for fairness tracking.
7367    fn classify_event_for_fairness(event: &Event) -> FairnessEventType {
7368        match event {
7369            Event::Key(_)
7370            | Event::Mouse(_)
7371            | Event::Paste(_)
7372            | Event::Ime(_)
7373            | Event::Focus(_)
7374            | Event::Clipboard(_)
7375            | Event::TerminalResponse(_) => FairnessEventType::Input,
7376            Event::Resize { .. } => FairnessEventType::Resize,
7377            Event::Tick => FairnessEventType::Tick,
7378        }
7379    }
7380
7381    /// Reconcile the model's declared subscriptions with running ones.
7382    fn reconcile_subscriptions(&mut self) {
7383        let _span = debug_span!(
7384            crate::telemetry_schema::span::PROGRAM_SUBSCRIPTIONS,
7385            active_count = tracing::field::Empty,
7386            started = tracing::field::Empty,
7387            stopped = tracing::field::Empty
7388        )
7389        .entered();
7390        let subs = self.model.subscriptions();
7391        let before_count = self.subscriptions.active_count();
7392        self.subscriptions.reconcile(subs);
7393        let after_count = self.subscriptions.active_count();
7394        let started = after_count.saturating_sub(before_count);
7395        let stopped = before_count.saturating_sub(after_count);
7396        crate::debug_trace!(
7397            "subscriptions reconcile: before={}, after={}, started={}, stopped={}",
7398            before_count,
7399            after_count,
7400            started,
7401            stopped
7402        );
7403        if after_count == 0 {
7404            crate::debug_trace!("subscriptions reconcile: no active subscriptions");
7405        }
7406        let current = tracing::Span::current();
7407        current.record("active_count", after_count);
7408        // started/stopped would require tracking in SubscriptionManager
7409        current.record("started", started);
7410        current.record("stopped", stopped);
7411    }
7412
7413    /// Report newly observed subscription failures through `Model::on_error`.
7414    fn process_subscription_failures(&mut self, during_lifecycle: bool) -> io::Result<()> {
7415        let mut first_error = None;
7416        for failure in self.subscriptions.drain_failures() {
7417            let error = format!("subscription {} failed: {}", failure.id, failure.error);
7418            if let Err(error) = self.invoke_error_hook(&error, during_lifecycle) {
7419                first_error.get_or_insert(error);
7420            }
7421        }
7422
7423        match first_error {
7424            Some(error) => Err(error),
7425            None => Ok(()),
7426        }
7427    }
7428
7429    /// Invoke the model error hook and execute its recovery command.
7430    fn invoke_error_hook(&mut self, error: &str, during_lifecycle: bool) -> io::Result<()> {
7431        let cmd = {
7432            let _span = info_span!(crate::telemetry_schema::span::PROGRAM_ERROR, error).entered();
7433            self.model.on_error(error)
7434        };
7435        if during_lifecycle {
7436            self.execute_lifecycle_cmd(cmd)
7437        } else {
7438            self.execute_cmd(cmd)
7439        }
7440    }
7441
7442    /// Execute a lifecycle command even after the normal loop stopped.
7443    ///
7444    /// `Cmd::Batch` and `Cmd::Sequence` use the running flag as their halt
7445    /// boundary, so temporarily reopening dispatch is required for cleanup
7446    /// batches. An explicit `Cmd::Quit` inside the lifecycle command still
7447    /// halts the remaining commands.
7448    fn execute_lifecycle_cmd(&mut self, cmd: Cmd<M::Message>) -> io::Result<()> {
7449        let was_running = std::mem::replace(&mut self.running, true);
7450        let result = self.execute_cmd(cmd);
7451        self.running = was_running && self.running;
7452        // Lifecycle hooks may run after the render loop has stopped.
7453        let flush_result = self.presenter.flush();
7454        result.and(flush_result)
7455    }
7456
7457    /// Process pending messages from subscriptions.
7458    fn process_subscription_messages(&mut self) -> io::Result<()> {
7459        let messages = self.subscriptions.drain_messages();
7460        let msg_count = messages.len();
7461        if msg_count > 0 {
7462            crate::debug_trace!("processing {} subscription message(s)", msg_count);
7463        }
7464        for msg in messages {
7465            let cmd = {
7466                let _span = debug_span!(
7467                    crate::telemetry_schema::span::PROGRAM_UPDATE,
7468                    msg_type = "subscription",
7469                    duration_us = tracing::field::Empty,
7470                    cmd_type = tracing::field::Empty
7471                )
7472                .entered();
7473                let start = Instant::now();
7474                let cmd = self.model.update(msg);
7475                let elapsed_us = start.elapsed().as_micros() as u64;
7476                self.last_update_us = Some(elapsed_us);
7477                tracing::Span::current().record("duration_us", elapsed_us);
7478                tracing::Span::current()
7479                    .record("cmd_type", format!("{:?}", std::mem::discriminant(&cmd)));
7480                cmd
7481            };
7482            self.mark_dirty();
7483            self.execute_cmd(cmd)?;
7484            if !self.running {
7485                break;
7486            }
7487        }
7488        if self.running && self.dirty {
7489            self.reconcile_subscriptions();
7490        }
7491        Ok(())
7492    }
7493
7494    /// Process results from background tasks.
7495    fn process_task_results(&mut self) -> io::Result<()> {
7496        while let Ok(msg) = self.task_receiver.try_recv() {
7497            let cmd = {
7498                let _span = debug_span!(
7499                    crate::telemetry_schema::span::PROGRAM_UPDATE,
7500                    msg_type = "task",
7501                    duration_us = tracing::field::Empty,
7502                    cmd_type = tracing::field::Empty
7503                )
7504                .entered();
7505                let start = Instant::now();
7506                let cmd = self.model.update(msg);
7507                let elapsed_us = start.elapsed().as_micros() as u64;
7508                self.last_update_us = Some(elapsed_us);
7509                tracing::Span::current().record("duration_us", elapsed_us);
7510                tracing::Span::current()
7511                    .record("cmd_type", format!("{:?}", std::mem::discriminant(&cmd)));
7512                cmd
7513            };
7514            self.mark_dirty();
7515            self.execute_cmd(cmd)?;
7516            if !self.running {
7517                break;
7518            }
7519        }
7520        if self.running && self.dirty {
7521            self.reconcile_subscriptions();
7522        }
7523        Ok(())
7524    }
7525
7526    /// Execute a command.
7527    fn execute_cmd(&mut self, cmd: Cmd<M::Message>) -> io::Result<()> {
7528        // Commands run depth-first from an explicit stack of batch iterators,
7529        // in the order the recursive version used. A model that answers a
7530        // message with `Cmd::Msg` for its next step recursed once per step:
7531        // a chain of about 10k steps overflowed the stack, and a stack
7532        // overflow aborts the process without restoring the terminal.
7533        let mut batches: Vec<std::vec::IntoIter<Cmd<M::Message>>> = Vec::new();
7534        let mut next = Some(cmd);
7535        loop {
7536            let cmd = match next.take() {
7537                Some(cmd) => cmd,
7538                None => {
7539                    // Resume the innermost batch. A batch stops after any
7540                    // command that ends the program.
7541                    let Some(rest) = batches.last_mut() else {
7542                        return Ok(());
7543                    };
7544                    if !self.running {
7545                        return Ok(());
7546                    }
7547                    match rest.next() {
7548                        Some(cmd) => cmd,
7549                        None => {
7550                            batches.pop();
7551                            continue;
7552                        }
7553                    }
7554                }
7555            };
7556            next = self.execute_one_cmd(cmd, &mut batches)?;
7557        }
7558    }
7559
7560    /// Execute `cmd` for [`Self::execute_cmd`], returning the command to run
7561    /// next (the `update` result for `Cmd::Msg`, the first command of a batch)
7562    /// and pushing the rest of a batch onto `batches`.
7563    fn execute_one_cmd(
7564        &mut self,
7565        cmd: Cmd<M::Message>,
7566        batches: &mut Vec<std::vec::IntoIter<Cmd<M::Message>>>,
7567    ) -> io::Result<Option<Cmd<M::Message>>> {
7568        self.executed_cmd_count = self.executed_cmd_count.saturating_add(1);
7569        match cmd {
7570            Cmd::None => {}
7571            Cmd::Quit => {
7572                self.running = false;
7573                self.presenter.flush()?;
7574            }
7575            Cmd::Msg(m) => {
7576                let start = Instant::now();
7577                let cmd = self.model.update(m);
7578                let elapsed_us = start.elapsed().as_micros() as u64;
7579                self.last_update_us = Some(elapsed_us);
7580                self.mark_dirty();
7581                return Ok(Some(cmd));
7582            }
7583            // Batch currently executes sequentially, like Sequence. This is
7584            // intentional until an async runtime or task scheduler is added.
7585            Cmd::Batch(cmds) | Cmd::Sequence(cmds) => {
7586                let mut rest = cmds.into_iter();
7587                let first = rest.next();
7588                batches.push(rest);
7589                return Ok(first);
7590            }
7591            Cmd::Tick(duration) => {
7592                self.tick_rate = Some(duration);
7593                self.last_tick = Instant::now();
7594            }
7595            Cmd::Log { text, mode } => {
7596                self.presenter.write_log_line_with_mode(&text, mode)?;
7597            }
7598            Cmd::Task(spec, f) => {
7599                crate::effect_system::record_command_effect("task", 0);
7600                self.task_executor.submit(spec, f);
7601            }
7602            Cmd::SaveState => {
7603                self.save_state();
7604            }
7605            Cmd::RestoreState => {
7606                self.load_state();
7607            }
7608            Cmd::SetMouseCapture(enabled) => {
7609                self.backend_features.mouse_capture = enabled;
7610                self.events.set_features(self.backend_features)?;
7611            }
7612            Cmd::SetClipboard(text) => {
7613                self.presenter.write_osc52_set(
7614                    ftui_core::osc52::ClipboardSelection::Clipboard,
7615                    text.as_bytes(),
7616                )?;
7617                if !self.dirty {
7618                    self.presenter.flush()?;
7619                }
7620            }
7621            Cmd::GetClipboard => {
7622                self.presenter
7623                    .write_osc52_query(ftui_core::osc52::ClipboardSelection::Clipboard)?;
7624                if !self.dirty {
7625                    self.presenter.flush()?;
7626                }
7627            }
7628            Cmd::SetTickStrategy(strategy) => {
7629                let new_name = strategy.name().to_owned();
7630                if let Some(mut previous) = self.tick_strategy.replace(strategy) {
7631                    let old_name = previous.name().to_owned();
7632                    previous.shutdown();
7633                    info!(
7634                        target: crate::telemetry_schema::TARGET_RUNTIME,
7635                        old = %old_name,
7636                        new = %new_name,
7637                        "tick strategy changed at runtime"
7638                    );
7639                } else {
7640                    info!(
7641                        target: crate::telemetry_schema::TARGET_RUNTIME,
7642                        new = %new_name,
7643                        "tick strategy changed at runtime"
7644                    );
7645                }
7646                self.last_active_screen_for_strategy = None;
7647            }
7648        }
7649        Ok(None)
7650    }
7651
7652    /// Detect active-screen transitions after any `update()` call and react:
7653    ///
7654    /// - **A.2** โ€” notify the tick strategy via `on_screen_transition()` so
7655    ///   predictive strategies can learn navigation patterns.
7656    /// - **D.3** โ€” force-tick the newly active screen so it renders fresh
7657    ///   content immediately, without waiting for the next tick interval.
7658    ///
7659    /// This is a no-op when no tick strategy is configured or when the model
7660    /// does not implement [`ScreenTickDispatch`].
7661    fn check_screen_transition(&mut self) {
7662        if self.tick_strategy.is_none() {
7663            return;
7664        }
7665
7666        // Snapshot the current active screen (releases &mut self.model).
7667        let current_active = match self.model.as_screen_tick_dispatch() {
7668            Some(dispatch) => dispatch.active_screen_id(),
7669            None => return,
7670        };
7671
7672        // First observation: just record, no transition event.
7673        let previous = match self.last_active_screen_for_strategy.take() {
7674            Some(prev) => prev,
7675            None => {
7676                self.last_active_screen_for_strategy = Some(current_active);
7677                return;
7678            }
7679        };
7680
7681        if previous == current_active {
7682            self.last_active_screen_for_strategy = Some(current_active);
7683            return;
7684        }
7685
7686        // A.2: Notify strategy of the transition.
7687        if let Some(strategy) = self.tick_strategy.as_mut() {
7688            strategy.on_screen_transition(&previous, &current_active);
7689        }
7690
7691        // D.3: Force-tick the newly active screen immediately.
7692        let mut force_ticked = false;
7693        if let Some(dispatch) = self.model.as_screen_tick_dispatch() {
7694            dispatch.tick_screen(&current_active, self.tick_count);
7695            force_ticked = true;
7696        }
7697        if force_ticked && self.running {
7698            self.reconcile_subscriptions();
7699        }
7700
7701        self.last_active_screen_for_strategy = Some(current_active);
7702        self.mark_dirty();
7703    }
7704
7705    fn reap_finished_tasks(&mut self) {
7706        self.task_executor.reap_finished();
7707    }
7708
7709    fn drain_shutdown_task_results(&mut self) -> io::Result<()> {
7710        while let Ok(msg) = self.task_receiver.try_recv() {
7711            let cmd = {
7712                let _span = debug_span!(
7713                    crate::telemetry_schema::span::PROGRAM_UPDATE,
7714                    msg_type = "shutdown_task",
7715                    duration_us = tracing::field::Empty,
7716                    cmd_type = tracing::field::Empty
7717                )
7718                .entered();
7719                let start = Instant::now();
7720                let cmd = self.model.update(msg);
7721                let elapsed_us = start.elapsed().as_micros() as u64;
7722                self.last_update_us = Some(elapsed_us);
7723                tracing::Span::current().record("duration_us", elapsed_us);
7724                tracing::Span::current()
7725                    .record("cmd_type", format!("{:?}", std::mem::discriminant(&cmd)));
7726                cmd
7727            };
7728            self.mark_dirty();
7729            self.execute_lifecycle_cmd(cmd)?;
7730        }
7731        Ok(())
7732    }
7733
7734    /// Render a frame with budget tracking.
7735    fn render_frame(&mut self) -> io::Result<()> {
7736        crate::debug_trace!("render_frame: {}x{}", self.width, self.height);
7737
7738        self.frame_idx = self.frame_idx.wrapping_add(1);
7739        let frame_idx = self.frame_idx;
7740        let degradation_start = self.budget.degradation();
7741
7742        // Reset budget for new frame, potentially upgrading quality
7743        self.budget.next_frame();
7744
7745        // Check frame guardrails (memory/queue limits). The frame loop itself
7746        // is synchronous, so "queue depth" is the effect backlog: tasks this
7747        // program handed to its executor that have not produced their
7748        // message yet (`TaskExecutor::in_flight`). This is the value the
7749        // queue guardrail thresholds (warn/max/emergency) were designed
7750        // against; it used to be hard-coded to 0, which made the whole queue
7751        // guardrail dead in production (bd-1za0z item 3). It is measured per
7752        // program rather than from the process-global queue counters so a
7753        // second program in the same process (or a leaked counter) cannot
7754        // make this one shed frames.
7755        // Retained capacity, not live usage: sustained growth across frames is
7756        // the leak signal. Usage-level accounting requires an allocator hook.
7757        let memory_bytes =
7758            self.presenter.estimate_memory_usage() + self.frame_arena.allocated_bytes();
7759        let queue_depth = u32::try_from(self.task_executor.in_flight()).unwrap_or(u32::MAX);
7760        let verdict = self.guardrails.check_frame(memory_bytes, queue_depth);
7761
7762        // F2 observability: export a guardrail snapshot whenever any
7763        // guardrail fires (including suspected retained-capacity growth).
7764        // This stays quiet in healthy runs
7765        // (bd-1za0z: GuardrailSnapshot::to_jsonl was production-dead).
7766        if !verdict.alerts.is_empty()
7767            && let Some(ref sink) = self.evidence_sink
7768        {
7769            let line = format!(
7770                r#"{{"schema_version":"{}","event":"guardrail_snapshot","snapshot":{}}}"#,
7771                crate::evidence_sink::EVIDENCE_SCHEMA_VERSION,
7772                self.guardrails.snapshot().to_jsonl(),
7773            );
7774            let _ = sink.write_jsonl(&line);
7775        }
7776
7777        if let Some(ref alert) = verdict.leak_alert {
7778            tracing::warn!(
7779                target: crate::telemetry_schema::TARGET_GUARDRAILS,
7780                e_value = alert.e_value,
7781                cusum = alert.cusum_upper,
7782                mean_bytes = self.guardrails.snapshot().leak_mean_bytes,
7783                "allocation leak suspected"
7784            );
7785        }
7786
7787        if verdict.should_drop_frame() {
7788            // Emergency shed: skip this frame entirely to prevent OOM.
7789            // CRUCIALLY, remediate: two of the sensor's components are
7790            // retained CAPACITY that never shrinks on its own (bumpalo keeps
7791            // its largest chunk across reset(); the grapheme pool's Vec never
7792            // shrinks). Without releasing them the verdict is permanent and
7793            // the UI freezes forever โ€” dropping frames cannot move the
7794            // sensor. Rebuilding the arena frees the retained chunk so the
7795            // next frame re-measures honestly.
7796            self.frame_arena = FrameArena::default();
7797            self.presenter.gc();
7798            self.guardrails.reset_leak_detector();
7799            tracing::warn!(
7800                target: crate::telemetry_schema::TARGET_GUARDRAILS,
7801                memory_bytes,
7802                "emergency frame drop: memory guardrail tripped; arena rebuilt"
7803            );
7804            return Ok(());
7805        }
7806
7807        if verdict.should_degrade() {
7808            // Apply guardrail-recommended degradation if it's stricter than budget's
7809            let current = self.budget.degradation();
7810            if verdict.recommended_level > current {
7811                self.budget.set_degradation(verdict.recommended_level);
7812            }
7813
7814            // Soft-tier early trim (bd-1za0z): the memory sensor measures
7815            // retained CAPACITY, so once past the soft limit nothing the
7816            // degradation actuator does can lower it again โ€” only releasing
7817            // capacity can. Trim early (same remediation as the emergency
7818            // shed, but non-fatal) instead of waiting for the emergency
7819            // tier; cooldown-gated so hovering near the limit cannot thrash
7820            // allocations.
7821            let soft_alert = verdict.alerts.iter().any(|alert| {
7822                alert.kind == GuardrailKind::Memory && alert.severity == AlertSeverity::Warning
7823            });
7824            let cooldown_elapsed = match self.last_soft_trim_frame {
7825                None => true,
7826                Some(last) => self.frame_idx.saturating_sub(last) >= SOFT_TRIM_COOLDOWN_FRAMES,
7827            };
7828            if soft_alert && cooldown_elapsed {
7829                self.frame_arena = FrameArena::default();
7830                self.presenter.gc();
7831                self.guardrails.reset_leak_detector();
7832                self.last_soft_trim_frame = Some(self.frame_idx);
7833                tracing::debug!(
7834                    target: crate::telemetry_schema::TARGET_GUARDRAILS,
7835                    memory_bytes,
7836                    "soft memory alert: arena rebuilt to release retained capacity"
7837                );
7838            }
7839        }
7840
7841        // Apply conformal risk gate before rendering (if enabled)
7842        let mut conformal_prediction = None;
7843        if let Some(predictor) = self.conformal_predictor.as_ref() {
7844            let baseline_us = self
7845                .last_frame_time_us
7846                .unwrap_or_else(|| self.budget.total().as_secs_f64() * 1_000_000.0);
7847            let diff_strategy = self
7848                .presenter
7849                .last_diff_strategy()
7850                .unwrap_or(DiffStrategy::Full);
7851            let frame_height_hint = self.presenter.render_height_hint().max(1);
7852            let key = BucketKey::from_context(
7853                self.presenter.screen_mode(),
7854                diff_strategy,
7855                self.width,
7856                frame_height_hint,
7857            );
7858            let budget_us = self.budget.total().as_secs_f64() * 1_000_000.0;
7859            let prediction = predictor.predict(key, baseline_us, budget_us);
7860            // An unavailable bound supplies no confidence-based action. Defer
7861            // explicitly to the independent measured-budget controller, which
7862            // already ran in next_frame(); do not erase its degradation or
7863            // stop collecting measurements by repeatedly degrading to SkipFrame.
7864            if !predictor.is_calibrated(&prediction) {
7865                debug!(
7866                    target: crate::telemetry_schema::TARGET_RUNTIME,
7867                    bucket = %prediction.bucket,
7868                    sample_count = prediction.sample_count,
7869                    fallback_level = prediction.fallback_level,
7870                    status = prediction.status.as_str(),
7871                    required_rank = prediction.required_rank,
7872                    action = "defer_to_budget_controller",
7873                    "conformal bound unavailable"
7874                );
7875            } else if prediction.risk && self.budget.degrade_respecting_floor() {
7876                info!(
7877                    target: crate::telemetry_schema::TARGET_RUNTIME,
7878                    bucket = %prediction.bucket,
7879                    upper_us = ?prediction.upper_us,
7880                    budget_us = prediction.budget_us,
7881                    fallback_level = prediction.fallback_level,
7882                    degradation = self.budget.degradation().as_str(),
7883                    "conformal gate triggered strategy downgrade"
7884                );
7885                debug!(
7886                    target: crate::telemetry_schema::TARGET_RUNTIME,
7887                    bucket = %prediction.bucket,
7888                    monotonic.counter.conformal_gate_triggers_total = 1_u64,
7889                    "conformal gate trigger"
7890                );
7891            }
7892            debug!(
7893                target: crate::telemetry_schema::TARGET_RUNTIME,
7894                bucket = %prediction.bucket,
7895                upper_us = ?prediction.upper_us,
7896                budget_us = prediction.budget_us,
7897                fallback = prediction.fallback_level,
7898                risk = prediction.risk,
7899                "conformal risk gate"
7900            );
7901            if predictor.is_calibrated(&prediction)
7902                && let Some(quantile) = prediction.quantile
7903            {
7904                debug!(
7905                    target: crate::telemetry_schema::TARGET_RUNTIME,
7906                    bucket = %prediction.bucket,
7907                    monotonic.histogram.conformal_prediction_interval_width_us = quantile.max(0.0),
7908                    "conformal prediction interval width"
7909                );
7910            }
7911            conformal_prediction = Some(prediction);
7912        }
7913
7914        // Early skip only when degradation has reached SkipFrame and the
7915        // config allows frame skips. Running out of time is not a reason to
7916        // skip: a late frame is rendered and presented, and the budget lowers
7917        // the quality of later frames instead (frankentui#104).
7918        if self.budget.should_skip_frame() {
7919            self.budget.record_frame_time(Duration::ZERO);
7920            let load_snapshot =
7921                self.update_load_governor_snapshot(frame_idx, 0.0, conformal_prediction.as_ref());
7922            self.emit_budget_evidence(
7923                frame_idx,
7924                degradation_start,
7925                0.0,
7926                conformal_prediction.as_ref(),
7927                &load_snapshot,
7928            );
7929            crate::debug_trace!(
7930                "frame skipped: degradation at SkipFrame (degradation={})",
7931                self.budget.degradation().as_str()
7932            );
7933            debug!(
7934                target: crate::telemetry_schema::TARGET_RUNTIME,
7935                degradation = self.budget.degradation().as_str(),
7936                "frame skipped: degradation at SkipFrame before render"
7937            );
7938            // Keep dirty=true: the UI update was never presented, so a
7939            // future frame must still pick it up.
7940            return Ok(());
7941        }
7942
7943        let auto_bounds = self.presenter.inline_auto_bounds();
7944        let needs_measure = auto_bounds.is_some() && self.presenter.auto_ui_height().is_none();
7945        let mut should_measure = needs_measure;
7946        if auto_bounds.is_some()
7947            && let Some(state) = self.inline_auto_remeasure.as_mut()
7948        {
7949            let (alpha, beta) = state.sampler.posterior_params();
7950            let decision = state.sampler.decide(Instant::now());
7951            let decision_str = if decision.should_sample {
7952                "sample"
7953            } else {
7954                "skip"
7955            };
7956            debug!(
7957                target: crate::telemetry_schema::TARGET_VOI,
7958                source = "inline_auto",
7959                widget_id = 0u64,
7960                index = 0usize,
7961                alpha = alpha,
7962                beta = beta,
7963                voi = decision.voi_gain,
7964                sample_cost = decision.cost,
7965                decision = decision_str,
7966                "voi_sample decision"
7967            );
7968            // The VOI decision is an evidence event like diff and budget
7969            // decisions: without this line the sampler's reasoning was only
7970            // visible through the in-process telemetry snapshot.
7971            if let Some(ref sink) = self.evidence_sink {
7972                let sample_line = format!(
7973                    r#"{{"schema_version":"ftui-evidence-v1","event":"{}","source":"inline_auto","widget_id":0,"index":0,"alpha":{:.6},"beta":{:.6},"voi":{:.6},"sample_cost":{:.6},"decision":"{}"}}"#,
7974                    crate::telemetry_schema::evidence::VOI_SAMPLE,
7975                    alpha,
7976                    beta,
7977                    decision.voi_gain,
7978                    decision.cost,
7979                    decision_str,
7980                );
7981                let _ = sink.write_jsonl(&sample_line);
7982                let _ = sink.write_jsonl(&decision.to_jsonl());
7983            }
7984            if decision.should_sample {
7985                should_measure = true;
7986            }
7987        } else {
7988            crate::voi_telemetry::clear_inline_auto_voi_snapshot();
7989        }
7990
7991        // --- Render phase ---
7992        let render_start = Instant::now();
7993        if let (Some((min_height, max_height)), true) = (auto_bounds, should_measure) {
7994            let measure_height = if needs_measure {
7995                self.presenter.render_height_hint().max(1)
7996            } else {
7997                max_height.max(1)
7998            };
7999            let (measure_buffer, _) = self.render_measure_buffer(measure_height);
8000            let measured_height = measure_buffer.content_height();
8001            let clamped = measured_height.clamp(min_height, max_height);
8002            let previous_height = self.presenter.auto_ui_height();
8003            self.presenter.set_auto_ui_height(clamped);
8004            if let Some(state) = self.inline_auto_remeasure.as_mut() {
8005                let threshold = state.config.change_threshold_rows;
8006                let violated = previous_height
8007                    .map(|prev| prev.abs_diff(clamped) >= threshold)
8008                    .unwrap_or(false);
8009                state.sampler.observe(violated);
8010            }
8011        }
8012        if auto_bounds.is_some()
8013            && let Some(state) = self.inline_auto_remeasure.as_ref()
8014        {
8015            let snapshot = state.sampler.snapshot(8, crate::debug_trace::elapsed_ms());
8016            crate::voi_telemetry::set_inline_auto_voi_snapshot(Some(snapshot));
8017        }
8018
8019        let frame_height = self.presenter.render_height_hint().max(1);
8020        let _frame_span = info_span!(
8021            crate::telemetry_schema::span::RENDER_FRAME,
8022            width = self.width,
8023            height = frame_height,
8024            duration_us = tracing::field::Empty
8025        )
8026        .entered();
8027        let (buffer, cursor, cursor_visible) = self.render_buffer(frame_height);
8028        self.process_a11y_frame();
8029        self.update_widget_refresh_plan(frame_idx);
8030        let render_elapsed = render_start.elapsed();
8031
8032        // Check if render phase overspent its budget
8033        let render_budget = self.budget.phase_budgets().render;
8034        if render_elapsed > render_budget {
8035            debug!(
8036                target: crate::telemetry_schema::TARGET_RUNTIME,
8037                render_ms = render_elapsed.as_millis() as u32,
8038                budget_ms = render_budget.as_millis() as u32,
8039                "render phase exceeded budget"
8040            );
8041            // With the load governor active, the controller decides degradation
8042            // from measured frame history at the next frame boundary. The
8043            // legacy path keeps its immediate threshold fallback.
8044            if self.budget.controller().is_none() && self.budget.should_degrade(render_budget) {
8045                self.budget.degrade();
8046            }
8047        }
8048
8049        // --- Present phase ---
8050        // A rendered frame is always presented, even when it ran over budget.
8051        // Dropping it would leave the terminal on an older frame, and with
8052        // steadily slow frames nothing would ever be presented again
8053        // (frankentui#104). The budget acts on later frames instead: through
8054        // the degradation level, and at SkipFrame through the skip before
8055        // render.
8056        if self.budget.remaining().is_zero() {
8057            debug!(
8058                target: crate::telemetry_schema::TARGET_RUNTIME,
8059                degradation = self.budget.degradation().as_str(),
8060                elapsed_ms = self.budget.elapsed().as_millis() as u32,
8061                "frame presented over budget"
8062            );
8063        }
8064        let shadow_checksum = if self.rollout_policy.is_shadow() && self.evidence_sink.is_some() {
8065            Some(ftui_render::buffer::buffer_checksum(&buffer))
8066        } else {
8067            None
8068        };
8069        let present_start = Instant::now();
8070        {
8071            let _present_span =
8072                debug_span!(crate::telemetry_schema::span::RENDER_PRESENT).entered();
8073            self.presenter
8074                .present_ui_owned(buffer, cursor, cursor_visible)?;
8075        }
8076        let present_elapsed = present_start.elapsed();
8077
8078        if let (Some(checksum), Some(sink)) = (shadow_checksum, self.evidence_sink.as_ref()) {
8079            let frame = self.shadow_frame_idx;
8080            self.shadow_frame_idx = self.shadow_frame_idx.saturating_add(1);
8081            let ts_ns = std::time::SystemTime::now()
8082                .duration_since(std::time::UNIX_EPOCH)
8083                .unwrap_or_default()
8084                .as_nanos();
8085            let evidence = ShadowFrameEvidence {
8086                frame,
8087                checksum,
8088                lane: self.resolved_lane.label(),
8089                requested_lane: self.requested_lane.label(),
8090                rollout_policy: self.rollout_policy.label(),
8091                task_backend: self.task_executor.kind_name_for_logs(),
8092                cols: self.width,
8093                rows: frame_height,
8094                ts_ns,
8095            };
8096            let _ = sink.write_jsonl(&evidence.to_jsonl());
8097        }
8098
8099        let present_budget = self.budget.phase_budgets().present;
8100        if present_elapsed > present_budget {
8101            debug!(
8102                target: crate::telemetry_schema::TARGET_RUNTIME,
8103                present_ms = present_elapsed.as_millis() as u32,
8104                budget_ms = present_budget.as_millis() as u32,
8105                "present phase exceeded budget"
8106            );
8107        }
8108
8109        if let Some(ref frame_timing) = self.frame_timing {
8110            let update_us = self.last_update_us.unwrap_or(0);
8111            let render_us = render_elapsed.as_micros() as u64;
8112            let present_us = present_elapsed.as_micros() as u64;
8113            let diff_us = self
8114                .presenter
8115                .take_last_present_timings()
8116                .map(|timings| timings.diff_us)
8117                .unwrap_or(0);
8118            let total_us = update_us
8119                .saturating_add(render_us)
8120                .saturating_add(present_us);
8121            let timing = FrameTiming {
8122                frame_idx,
8123                update_us,
8124                render_us,
8125                diff_us,
8126                present_us,
8127                total_us,
8128            };
8129            frame_timing.sink.record_frame(&timing);
8130        }
8131
8132        let frame_time = render_elapsed.saturating_add(present_elapsed);
8133        self.budget.record_frame_time(frame_time);
8134        let frame_time_us = frame_time.as_secs_f64() * 1_000_000.0;
8135
8136        if let (Some(predictor), Some(prediction)) = (
8137            self.conformal_predictor.as_mut(),
8138            conformal_prediction.as_ref(),
8139        ) {
8140            let diff_strategy = self
8141                .presenter
8142                .last_diff_strategy()
8143                .unwrap_or(DiffStrategy::Full);
8144            let key = BucketKey::from_context(
8145                self.presenter.screen_mode(),
8146                diff_strategy,
8147                self.width,
8148                frame_height,
8149            );
8150            predictor.observe(key, prediction.y_hat, frame_time_us);
8151        }
8152        self.last_frame_time_us = Some(frame_time_us);
8153        let load_snapshot = self.update_load_governor_snapshot(
8154            frame_idx,
8155            frame_time_us,
8156            conformal_prediction.as_ref(),
8157        );
8158        self.emit_budget_evidence(
8159            frame_idx,
8160            degradation_start,
8161            frame_time_us,
8162            conformal_prediction.as_ref(),
8163            &load_snapshot,
8164        );
8165
8166        // The frame was presented, so the UI is up to date. (A frame skipped
8167        // before render returns early above and keeps dirty set.)
8168        self.dirty = false;
8169
8170        // Deliver the accessibility hook after the dirty reset so a model
8171        // that changes state in response gets one more frame.
8172        if self.a11y_changed {
8173            self.a11y_changed = false;
8174            self.deliver_a11y_frame()?;
8175        }
8176
8177        Ok(())
8178    }
8179
8180    fn update_load_governor_snapshot(
8181        &mut self,
8182        _frame_idx: u64,
8183        frame_time_us: f64,
8184        conformal_prediction: Option<&ConformalPrediction>,
8185    ) -> LoadGovernorSnapshot {
8186        let budget_us = conformal_prediction
8187            .map(|prediction| prediction.budget_us)
8188            .unwrap_or_else(|| self.budget.total().as_secs_f64() * 1_000_000.0);
8189        let resize_stats = self.resize_coalescer.stats();
8190        self.load_governor.observe(LoadGovernorObservation {
8191            frame_time_us,
8192            budget_us,
8193            degradation: self.budget.degradation(),
8194            queue: crate::effect_system::queue_telemetry(),
8195            // Only meaningful when the coalescer actually runs: in legacy
8196            // Immediate mode `tick_at` never fires, so a single Burst entry
8197            // would otherwise pin the governor at SoftOverload forever.
8198            resize_coalescing_active: self.resize_behavior.uses_coalescer()
8199                && (resize_stats.has_pending
8200                    || !matches!(resize_stats.regime, crate::resize_coalescer::Regime::Steady)),
8201            strict_semantics_violation: false,
8202        })
8203    }
8204
8205    fn emit_budget_evidence(
8206        &self,
8207        frame_idx: u64,
8208        degradation_start: DegradationLevel,
8209        frame_time_us: f64,
8210        conformal_prediction: Option<&ConformalPrediction>,
8211        load_snapshot: &LoadGovernorSnapshot,
8212    ) {
8213        let Some(telemetry) = self.budget.telemetry() else {
8214            set_budget_snapshot(None);
8215            return;
8216        };
8217
8218        let budget_us = conformal_prediction
8219            .map(|prediction| prediction.budget_us)
8220            .unwrap_or_else(|| self.budget.total().as_secs_f64() * 1_000_000.0);
8221        let conformal = conformal_prediction.map(ConformalEvidence::from_prediction);
8222        let degradation_after = self.budget.degradation();
8223
8224        let evidence = BudgetDecisionEvidence {
8225            frame_idx,
8226            decision: BudgetDecisionEvidence::decision_from_levels(
8227                degradation_start,
8228                degradation_after,
8229            ),
8230            controller_decision: telemetry.last_decision,
8231            degradation_before: degradation_start,
8232            degradation_after,
8233            frame_time_us,
8234            budget_us,
8235            pid_output: telemetry.pid_output,
8236            pid_p: telemetry.pid_p,
8237            pid_i: telemetry.pid_i,
8238            pid_d: telemetry.pid_d,
8239            e_value: telemetry.e_value,
8240            eprocess_lambda: telemetry.eprocess_lambda,
8241            frames_observed: telemetry.frames_observed,
8242            frames_since_change: telemetry.frames_since_change,
8243            in_warmup: telemetry.in_warmup,
8244            recovery_streak: telemetry.recovery_streak,
8245            total_degrades: telemetry.total_degrades,
8246            total_recoveries: telemetry.total_recoveries,
8247            controller_reason: telemetry.decision_reason,
8248            load_governor: *load_snapshot,
8249            resize_detector: self.resize_coalescer.last_detector().as_str(),
8250            conformal,
8251        };
8252
8253        let conformal_snapshot = evidence
8254            .conformal
8255            .as_ref()
8256            .map(|snapshot| ConformalSnapshot {
8257                bucket_key: snapshot.bucket_key.clone(),
8258                sample_count: snapshot.n_b,
8259                upper_us: snapshot.upper_us,
8260                risk: snapshot.risk,
8261                status: snapshot.status,
8262                required_rank: snapshot.required_rank,
8263            });
8264        set_budget_snapshot(Some(BudgetDecisionSnapshot {
8265            frame_idx: evidence.frame_idx,
8266            decision: evidence.decision,
8267            controller_decision: evidence.controller_decision,
8268            degradation_before: evidence.degradation_before,
8269            degradation_after: evidence.degradation_after,
8270            frame_time_us: evidence.frame_time_us,
8271            budget_us: evidence.budget_us,
8272            pid_output: evidence.pid_output,
8273            e_value: evidence.e_value,
8274            frames_observed: evidence.frames_observed,
8275            frames_since_change: evidence.frames_since_change,
8276            in_warmup: evidence.in_warmup,
8277            conformal: conformal_snapshot,
8278        }));
8279
8280        if let Some(ref sink) = self.evidence_sink {
8281            let _ = sink.write_jsonl(&evidence.to_jsonl());
8282        }
8283    }
8284
8285    fn update_widget_refresh_plan(&mut self, frame_idx: u64) {
8286        if !self.widget_refresh_config.enabled {
8287            self.widget_refresh_plan.clear();
8288            return;
8289        }
8290
8291        let budget_us = self.budget.phase_budgets().render.as_secs_f64() * 1_000_000.0;
8292        let degradation = self.budget.degradation();
8293        self.widget_refresh_plan.recompute(
8294            frame_idx,
8295            budget_us,
8296            degradation,
8297            &self.widget_signals,
8298            &self.widget_refresh_config,
8299        );
8300
8301        if let Some(ref sink) = self.evidence_sink {
8302            let _ = sink.write_jsonl(&self.widget_refresh_plan.to_jsonl());
8303        }
8304    }
8305
8306    fn render_buffer(&mut self, frame_height: u16) -> (Buffer, Option<(u16, u16)>, bool) {
8307        // Reset the per-frame arena so widgets get fresh scratch space.
8308        self.frame_arena.reset();
8309
8310        // Pin the successful presentation baseline before registering this
8311        // frame's URLs. Also retire links from any abandoned render, since a
8312        // budget decision can skip presentation after model.view has run.
8313        self.presenter.begin_link_frame();
8314
8315        // Note: Frame borrows the pool and links from presenter.
8316        // We scope it so it drops before we call present_ui (which needs exclusive presenter access).
8317        let buffer = self.presenter.take_render_buffer(self.width, frame_height);
8318        let mut a11y_builder = self.a11y_policy.map(|_| A11yTreeBuilder::new());
8319        let (pool, links) = self.presenter.pool_and_links_mut();
8320        let mut frame = Frame::from_buffer(buffer, pool);
8321        frame.set_degradation(self.budget.degradation());
8322        frame.set_links(links);
8323        frame.set_widget_budget(self.widget_refresh_plan.as_budget());
8324        frame.set_arena(&self.frame_arena);
8325        frame.text_direction = self.locale_context.direction().into();
8326        if let Some(builder) = a11y_builder.as_mut() {
8327            frame.set_a11y(builder);
8328        }
8329
8330        let view_start = Instant::now();
8331        let _view_span = debug_span!(
8332            crate::telemetry_schema::span::PROGRAM_VIEW,
8333            duration_us = tracing::field::Empty,
8334            widget_count = tracing::field::Empty
8335        )
8336        .entered();
8337        self.model.view(&mut frame);
8338        self.widget_signals = frame.take_widget_signals();
8339        let remeasure_requests = frame.take_remeasure_requests();
8340        frame.finish_a11y();
8341        let a11y_order = frame.take_a11y_order();
8342        tracing::Span::current().record("duration_us", view_start.elapsed().as_micros() as u64);
8343        // widget_count would require tracking in Frame
8344
8345        let output = (frame.buffer, frame.cursor_position, frame.cursor_visible);
8346        // `frame` is not used past this point, which releases its borrow of
8347        // the builder so the tree can be built.
8348        self.a11y_pending = a11y_builder.map(|builder| (builder.build(), a11y_order));
8349        self.process_remeasure_requests(remeasure_requests);
8350        output
8351    }
8352
8353    fn process_remeasure_requests(&self, requests: Vec<ftui_render::frame::RemeasureRequest>) {
8354        for req in requests {
8355            debug!(
8356                target: crate::telemetry_schema::TARGET_VOI,
8357                source = "virtualized_list",
8358                widget_id = req.widget_id,
8359                index = req.index,
8360                alpha = req.alpha,
8361                beta = req.beta,
8362                voi = req.voi,
8363                sample_cost = req.cost,
8364                decision = "sample",
8365                "voi_sample decision"
8366            );
8367            if let Some(ref sink) = self.evidence_sink {
8368                let line = format!(
8369                    r#"{{"schema_version":"ftui-evidence-v1","event":"{}","source":"virtualized_list","widget_id":{},"index":{},"alpha":{:.6},"beta":{:.6},"voi":{:.6},"sample_cost":{:.6},"decision":"sample"}}"#,
8370                    crate::telemetry_schema::evidence::VOI_SAMPLE,
8371                    req.widget_id,
8372                    req.index,
8373                    req.alpha,
8374                    req.beta,
8375                    req.voi,
8376                    req.cost,
8377                );
8378                let _ = sink.write_jsonl(&line);
8379            }
8380        }
8381    }
8382
8383    /// Diff the accessibility tree collected by the last `render_buffer`
8384    /// against the previous frame's tree, derive screen-reader
8385    /// announcements, and export their metadata. Full text stays local unless
8386    /// explicitly included in the evidence sink; tracing never contains it.
8387    ///
8388    /// No-op unless `ProgramConfig::accessibility` is set.
8389    fn process_a11y_frame(&mut self) {
8390        let Some(policy) = self.a11y_policy else {
8391            return;
8392        };
8393        let Some((tree, order)) = self.a11y_pending.take() else {
8394            return;
8395        };
8396        let previous = self
8397            .a11y_tree
8398            .take()
8399            .unwrap_or_else(|| A11yTreeBuilder::new().build());
8400        let diff = tree.diff(&previous);
8401        let announcements = diff.screen_reader_announcements(&tree, policy);
8402
8403        if !diff.is_empty() {
8404            tracing::debug!(
8405                target: crate::telemetry_schema::TARGET_A11Y,
8406                frame_idx = self.frame_idx,
8407                nodes = tree.node_count(),
8408                added = diff.added.len(),
8409                removed = diff.removed.len(),
8410                changed = diff.changed.len(),
8411                focus_changed = diff.focus_changed.is_some(),
8412                announcements = announcements.announcements.len(),
8413                dropped = announcements.dropped_count,
8414                "a11y tree changed"
8415            );
8416            if let Some(ref sink) = self.evidence_sink {
8417                let focus = match diff.focus_changed {
8418                    Some((_, Some(id))) => id.to_string(),
8419                    Some((_, None)) | None => "null".to_string(),
8420                };
8421                let _ = sink.write_jsonl(&format!(
8422                    r#"{{"event":"a11y_tree","frame_idx":{},"nodes":{},"added":{},"removed":{},"changed":{},"focus":{},"announcements":{},"dropped":{}}}"#,
8423                    self.frame_idx,
8424                    tree.node_count(),
8425                    diff.added.len(),
8426                    diff.removed.len(),
8427                    diff.changed.len(),
8428                    focus,
8429                    announcements.announcements.len(),
8430                    announcements.dropped_count,
8431                ));
8432                for announcement in &announcements.announcements {
8433                    let node_id = announcement
8434                        .node_id
8435                        .map_or_else(|| "null".to_string(), |id| id.to_string());
8436                    let text = if self.a11y_evidence_text {
8437                        format!(
8438                            "\"{}\"",
8439                            crate::queueing_scheduler::escape_json(&announcement.text)
8440                        )
8441                    } else {
8442                        "null".to_string()
8443                    };
8444                    let _ = sink.write_jsonl(&format!(
8445                        r#"{{"event":"a11y_announcement","frame_idx":{},"node_id":{},"urgency":"{}","reason":"{:?}","text":{},"text_chars":{}}}"#,
8446                        self.frame_idx,
8447                        node_id,
8448                        announcement.urgency,
8449                        announcement.reason,
8450                        text,
8451                        announcement.text.chars().count(),
8452                    ));
8453                }
8454            }
8455        }
8456        for announcement in &announcements.announcements {
8457            tracing::info!(
8458                target: crate::telemetry_schema::TARGET_A11Y,
8459                frame_idx = self.frame_idx,
8460                node_id = announcement.node_id,
8461                urgency = %announcement.urgency,
8462                reason = ?announcement.reason,
8463                text_chars = announcement.text.chars().count(),
8464                "screen reader announcement"
8465            );
8466        }
8467
8468        self.a11y_changed = !diff.is_empty();
8469        self.a11y_dropped = announcements.dropped_count;
8470        self.a11y_announcements = announcements.announcements;
8471        self.a11y_tree = Some(tree);
8472        self.a11y_order = order;
8473    }
8474
8475    /// Hand the last frame's tree to [`Model::on_accessibility`] (called by
8476    /// `render_frame` when `process_a11y_frame` saw a change) and schedule
8477    /// one more frame so state the hook changed gets rendered.
8478    fn deliver_a11y_frame(&mut self) -> io::Result<()> {
8479        let Some(tree) = self.a11y_tree.as_ref() else {
8480            return Ok(());
8481        };
8482        let cmd = {
8483            let _span = debug_span!(
8484                crate::telemetry_schema::span::PROGRAM_UPDATE,
8485                msg_type = "accessibility"
8486            )
8487            .entered();
8488            self.model.on_accessibility(AccessibilityFrame {
8489                frame_idx: self.frame_idx,
8490                tree,
8491                order: &self.a11y_order,
8492                announcements: &self.a11y_announcements,
8493                dropped: self.a11y_dropped,
8494            })
8495        };
8496        self.mark_dirty();
8497        self.execute_cmd(cmd)?;
8498        if self.running {
8499            self.reconcile_subscriptions();
8500        }
8501        Ok(())
8502    }
8503
8504    /// The accessibility tree built from the last rendered frame, or `None`
8505    /// when [`ProgramConfig::accessibility`] is unset or nothing has been
8506    /// rendered yet.
8507    #[must_use]
8508    pub fn accessibility_tree(&self) -> Option<&A11yTree> {
8509        self.a11y_tree.as_ref()
8510    }
8511
8512    /// Reading order (node IDs in widget push order) of the last
8513    /// accessibility tree; empty when accessibility is off.
8514    #[must_use]
8515    pub fn accessibility_order(&self) -> &[u64] {
8516        &self.a11y_order
8517    }
8518
8519    /// Screen-reader announcements derived from the last frame's tree diff
8520    /// (bounded by the configured [`ScreenReaderPolicy`]); empty when the
8521    /// tree did not change in an announceable way.
8522    #[must_use]
8523    pub fn accessibility_announcements(&self) -> &[ScreenReaderAnnouncement] {
8524        &self.a11y_announcements
8525    }
8526
8527    /// Indented, one-node-per-line dump of the last accessibility tree in
8528    /// reading order (see [`A11yTree::dump_text`]); `None` when off.
8529    #[must_use]
8530    pub fn accessibility_dump(&self) -> Option<String> {
8531        self.a11y_tree
8532            .as_ref()
8533            .map(|tree| tree.dump_text(&self.a11y_order))
8534    }
8535
8536    fn emit_fairness_evidence(&mut self, decision: &FairnessDecision, dominance_count: u32) {
8537        let Some(ref sink) = self.evidence_sink else {
8538            return;
8539        };
8540
8541        let config = self.fairness_guard.config();
8542        if !self.fairness_config_logged {
8543            let config_entry = FairnessConfigEvidence {
8544                enabled: config.enabled,
8545                input_priority_threshold_ms: config.input_priority_threshold.as_millis() as u64,
8546                dominance_threshold: config.dominance_threshold,
8547                fairness_threshold: config.fairness_threshold,
8548            };
8549            let _ = sink.write_jsonl(&config_entry.to_jsonl());
8550            self.fairness_config_logged = true;
8551        }
8552
8553        let evidence = FairnessDecisionEvidence {
8554            frame_idx: self.frame_idx,
8555            decision: if decision.should_process {
8556                "allow"
8557            } else {
8558                "yield"
8559            },
8560            reason: decision.reason.as_str(),
8561            pending_input_latency_ms: decision
8562                .pending_input_latency
8563                .map(|latency| latency.as_millis() as u64),
8564            jain_index: decision.jain_index,
8565            resize_dominance_count: dominance_count,
8566            dominance_threshold: config.dominance_threshold,
8567            fairness_threshold: config.fairness_threshold,
8568            input_priority_threshold_ms: config.input_priority_threshold.as_millis() as u64,
8569        };
8570
8571        let _ = sink.write_jsonl(&evidence.to_jsonl());
8572    }
8573
8574    fn render_measure_buffer(&mut self, frame_height: u16) -> (Buffer, Option<(u16, u16)>) {
8575        // Reset the per-frame arena for measurement pass.
8576        self.frame_arena.reset();
8577
8578        let pool = self.presenter.pool_mut();
8579        let mut frame = Frame::new(self.width, frame_height, pool);
8580        frame.set_degradation(self.budget.degradation());
8581        frame.set_arena(&self.frame_arena);
8582        frame.text_direction = self.locale_context.direction().into();
8583
8584        let view_start = Instant::now();
8585        let _view_span = debug_span!(
8586            crate::telemetry_schema::span::PROGRAM_VIEW,
8587            duration_us = tracing::field::Empty,
8588            widget_count = tracing::field::Empty
8589        )
8590        .entered();
8591        self.model.view(&mut frame);
8592        tracing::Span::current().record("duration_us", view_start.elapsed().as_micros() as u64);
8593
8594        (frame.buffer, frame.cursor_position)
8595    }
8596
8597    /// Calculate the effective poll timeout.
8598    /// A stationary mouse-down becomes a long press with the passage of time
8599    /// alone, so this runs on every loop iteration โ€” and
8600    /// [`Self::effective_timeout`] wakes the loop at the deadline โ€” whether or
8601    /// not the app set a tick rate (bd-g00-root-epic-ewths.50.2).
8602    fn poll_long_press(&mut self, now: Instant) -> io::Result<()> {
8603        if let Some(gesture) = self
8604            .gesture_recognizer
8605            .as_mut()
8606            .and_then(|recognizer| recognizer.check_long_press(now))
8607        {
8608            self.deliver_gesture(gesture)?;
8609        }
8610        Ok(())
8611    }
8612
8613    fn effective_timeout(&self) -> Duration {
8614        // A full subscription batch may leave a FIFO suffix queued. Poll input
8615        // without sleeping before the next batch, while still returning through
8616        // the normal input, tick, and render work on every iteration.
8617        if self.subscriptions.may_have_pending_messages() {
8618            return Duration::ZERO;
8619        }
8620        let timeout = self.tick_or_poll_timeout();
8621        match self
8622            .gesture_recognizer
8623            .as_ref()
8624            .and_then(|recognizer| recognizer.long_press_deadline())
8625        {
8626            Some(deadline) => timeout.min(deadline.saturating_duration_since(Instant::now())),
8627            None => timeout,
8628        }
8629    }
8630
8631    fn tick_or_poll_timeout(&self) -> Duration {
8632        if let Some(tick_rate) = self.tick_rate {
8633            let elapsed = self.last_tick.elapsed();
8634            let mut timeout = tick_rate.saturating_sub(elapsed);
8635            if self.resize_behavior.uses_coalescer()
8636                && let Some(resize_timeout) = self.resize_coalescer.time_until_apply(Instant::now())
8637            {
8638                timeout = timeout.min(resize_timeout);
8639            }
8640            timeout
8641        } else {
8642            let mut timeout = self.poll_timeout;
8643            if self.resize_behavior.uses_coalescer()
8644                && let Some(resize_timeout) = self.resize_coalescer.time_until_apply(Instant::now())
8645            {
8646                timeout = timeout.min(resize_timeout);
8647            }
8648            timeout
8649        }
8650    }
8651
8652    /// Check if we should send a tick.
8653    fn should_tick(&mut self) -> bool {
8654        if let Some(tick_rate) = self.tick_rate
8655            && self.last_tick.elapsed() >= tick_rate
8656        {
8657            self.last_tick = Instant::now();
8658            return true;
8659        }
8660        false
8661    }
8662
8663    fn process_resize_coalescer(&mut self) -> io::Result<()> {
8664        if !self.resize_behavior.uses_coalescer() {
8665            self.complete_pending_fairness_input(Instant::now());
8666            return Ok(());
8667        }
8668
8669        // Check fairness: if input is starving, skip resize application this cycle.
8670        // This ensures input events are processed before resize is finalized.
8671        let now = Instant::now();
8672        let dominance_count = self.fairness_guard.resize_dominance_count();
8673        let fairness_decision = self.fairness_guard.check_fairness(now);
8674        self.emit_fairness_evidence(&fairness_decision, dominance_count);
8675        self.complete_pending_fairness_input(now);
8676        if !fairness_decision.should_process {
8677            debug!(
8678                target: crate::telemetry_schema::TARGET_RESIZE,
8679                reason = ?fairness_decision.reason,
8680                pending_latency_ms = fairness_decision.pending_input_latency.map(|d| d.as_millis() as u64),
8681                "Resize yielding to input for fairness"
8682            );
8683            // Skip resize application this cycle to allow input processing.
8684            return Ok(());
8685        }
8686
8687        let action = self.resize_coalescer.tick();
8688        let resize_snapshot =
8689            self.resize_coalescer
8690                .logs()
8691                .last()
8692                .map(|entry| ResizeDecisionSnapshot {
8693                    event_idx: entry.event_idx,
8694                    action: entry.action,
8695                    dt_ms: entry.dt_ms,
8696                    event_rate: entry.event_rate,
8697                    regime: entry.regime,
8698                    pending_size: entry.pending_size,
8699                    applied_size: entry.applied_size,
8700                    time_since_render_ms: entry.time_since_render_ms,
8701                    bocpd: self
8702                        .resize_coalescer
8703                        .bocpd()
8704                        .and_then(|detector| detector.last_evidence().cloned()),
8705                });
8706        set_resize_snapshot(resize_snapshot);
8707
8708        match action {
8709            CoalesceAction::ApplyResize {
8710                width,
8711                height,
8712                coalesce_time,
8713                forced_by_deadline,
8714            } => {
8715                let apply_start = Instant::now();
8716                let result = self.apply_resize(width, height, coalesce_time, forced_by_deadline);
8717                self.fairness_guard.event_processed(
8718                    FairnessEventType::Resize,
8719                    apply_start.elapsed(),
8720                    Instant::now(),
8721                );
8722                result
8723            }
8724            _ => Ok(()),
8725        }
8726    }
8727
8728    fn apply_resize(
8729        &mut self,
8730        width: u16,
8731        height: u16,
8732        coalesce_time: Duration,
8733        forced_by_deadline: bool,
8734    ) -> io::Result<()> {
8735        // Clamp to minimum 1 to prevent Buffer::new panic on zero dimensions
8736        let width = width.max(1);
8737        let height = height.max(1);
8738        self.width = width;
8739        self.height = height;
8740        self.presenter.resize(width, height);
8741        info!(
8742            target: crate::telemetry_schema::TARGET_RESIZE,
8743            width = width,
8744            height = height,
8745            coalesce_ms = coalesce_time.as_millis() as u64,
8746            forced = forced_by_deadline,
8747            "Resize applied"
8748        );
8749
8750        let msg = M::Message::from(Event::Resize { width, height });
8751        let start = Instant::now();
8752        let cmd = self.model.update(msg);
8753        let elapsed_us = start.elapsed().as_micros() as u64;
8754        self.last_update_us = Some(elapsed_us);
8755        self.mark_dirty();
8756        self.execute_cmd(cmd)?;
8757        if self.running && self.dirty {
8758            self.reconcile_subscriptions();
8759        }
8760        Ok(())
8761    }
8762
8763    // removed: resize placeholder rendering (continuous reflow preferred)
8764
8765    /// Get a reference to the model.
8766    pub fn model(&self) -> &M {
8767        &self.model
8768    }
8769
8770    /// Get a mutable reference to the model.
8771    pub fn model_mut(&mut self) -> &mut M {
8772        &mut self.model
8773    }
8774
8775    /// Check if the program is running.
8776    pub fn is_running(&self) -> bool {
8777        self.running
8778    }
8779
8780    /// Get the current tick rate, if one has been installed.
8781    #[must_use]
8782    pub const fn tick_rate(&self) -> Option<Duration> {
8783        self.tick_rate
8784    }
8785
8786    /// Get the number of commands actually executed by the runtime.
8787    #[must_use]
8788    pub const fn executed_cmd_count(&self) -> usize {
8789        self.executed_cmd_count
8790    }
8791
8792    /// Request a quit.
8793    pub fn quit(&mut self) {
8794        self.running = false;
8795    }
8796
8797    /// Get a reference to the state registry, if configured.
8798    pub fn state_registry(&self) -> Option<&std::sync::Arc<StateRegistry>> {
8799        self.state_registry.as_ref()
8800    }
8801
8802    /// Check if state persistence is enabled.
8803    pub fn has_persistence(&self) -> bool {
8804        self.state_registry.is_some()
8805    }
8806
8807    /// Query the current tick strategy's debug statistics.
8808    ///
8809    /// Returns key-value pairs describing the strategy's internal state
8810    /// (e.g. strategy name, divisors, confidence, transition counts).
8811    /// Returns an empty vec if no tick strategy is configured.
8812    #[must_use]
8813    pub fn tick_strategy_stats(&self) -> Vec<(String, String)> {
8814        self.tick_strategy
8815            .as_ref()
8816            .map(|s| s.debug_stats())
8817            .unwrap_or_default()
8818    }
8819
8820    /// Trigger a manual save of widget state.
8821    ///
8822    /// Returns the result of the flush operation, or `Ok(false)` if
8823    /// persistence is not configured.
8824    pub fn trigger_save(&mut self) -> StorageResult<bool> {
8825        if let Some(registry) = &self.state_registry {
8826            registry.flush()
8827        } else {
8828            Ok(false)
8829        }
8830    }
8831
8832    /// Trigger a manual load of widget state.
8833    ///
8834    /// Returns the number of entries loaded, or `Ok(0)` if persistence
8835    /// is not configured.
8836    pub fn trigger_load(&mut self) -> StorageResult<usize> {
8837        if let Some(registry) = &self.state_registry {
8838            registry.load()
8839        } else {
8840            Ok(0)
8841        }
8842    }
8843
8844    fn mark_dirty(&mut self) {
8845        self.dirty = true;
8846    }
8847
8848    fn check_locale_change(&mut self) {
8849        let version = self.locale_context.version();
8850        if version != self.locale_version {
8851            self.locale_version = version;
8852            self.mark_dirty();
8853        }
8854    }
8855
8856    /// Mark the UI as needing redraw.
8857    pub fn request_redraw(&mut self) {
8858        self.mark_dirty();
8859    }
8860
8861    /// Request a re-measure of inline auto UI height on next render.
8862    pub fn request_ui_height_remeasure(&mut self) {
8863        if self.presenter.inline_auto_bounds().is_some() {
8864            self.presenter.clear_auto_ui_height();
8865            if let Some(state) = self.inline_auto_remeasure.as_mut() {
8866                state.reset();
8867            }
8868            crate::voi_telemetry::clear_inline_auto_voi_snapshot();
8869            self.mark_dirty();
8870        }
8871    }
8872
8873    /// Start recording events into a macro.
8874    ///
8875    /// If already recording, the current recording is discarded and a new one starts.
8876    /// The current terminal size is captured as metadata.
8877    pub fn start_recording(&mut self, name: impl Into<String>) {
8878        let mut recorder = EventRecorder::new(name).with_terminal_size(self.width, self.height);
8879        recorder.start();
8880        self.event_recorder = Some(recorder);
8881    }
8882
8883    /// Stop recording and return the recorded macro, if any.
8884    ///
8885    /// Returns `None` if not currently recording.
8886    pub fn stop_recording(&mut self) -> Option<InputMacro> {
8887        self.event_recorder.take().map(EventRecorder::finish)
8888    }
8889
8890    /// Check if event recording is active.
8891    pub fn is_recording(&self) -> bool {
8892        self.event_recorder
8893            .as_ref()
8894            .is_some_and(EventRecorder::is_recording)
8895    }
8896}
8897
8898/// Builder for creating and running programs.
8899pub struct App;
8900
8901impl App {
8902    /// Create a new app builder with the given model.
8903    #[allow(clippy::new_ret_no_self)] // App is a namespace for builder methods
8904    pub fn new<M: Model>(model: M) -> AppBuilder<M> {
8905        AppBuilder {
8906            model,
8907            config: ProgramConfig::default(),
8908        }
8909    }
8910
8911    /// Create a fullscreen app.
8912    pub fn fullscreen<M: Model>(model: M) -> AppBuilder<M> {
8913        AppBuilder {
8914            model,
8915            config: ProgramConfig::fullscreen(),
8916        }
8917    }
8918
8919    /// Create an inline app with the given height.
8920    pub fn inline<M: Model>(model: M, height: u16) -> AppBuilder<M> {
8921        AppBuilder {
8922            model,
8923            config: ProgramConfig::inline(height),
8924        }
8925    }
8926
8927    /// Create an inline app with automatic UI height.
8928    pub fn inline_auto<M: Model>(model: M, min_height: u16, max_height: u16) -> AppBuilder<M> {
8929        AppBuilder {
8930            model,
8931            config: ProgramConfig::inline_auto(min_height, max_height),
8932        }
8933    }
8934
8935    /// Create a fullscreen app from a [`StringModel`](crate::string_model::StringModel).
8936    ///
8937    /// This wraps the string model in a [`StringModelAdapter`](crate::string_model::StringModelAdapter)
8938    /// so that `view_string()` output is rendered through the standard kernel pipeline.
8939    pub fn string_model<S: crate::string_model::StringModel>(
8940        model: S,
8941    ) -> AppBuilder<crate::string_model::StringModelAdapter<S>> {
8942        AppBuilder {
8943            model: crate::string_model::StringModelAdapter::new(model),
8944            config: ProgramConfig::fullscreen(),
8945        }
8946    }
8947}
8948
8949/// Builder for configuring and running programs.
8950#[must_use]
8951pub struct AppBuilder<M: Model> {
8952    model: M,
8953    config: ProgramConfig,
8954}
8955
8956impl<M: Model> AppBuilder<M> {
8957    /// Bound hyperlinks per frame and retire URLs no longer displayed.
8958    /// See [`ProgramConfig::hyperlink_limit`] for the ID lifetime contract.
8959    pub fn with_hyperlink_limit(mut self, limit: usize) -> Self {
8960        self.config.hyperlink_limit = Some(limit);
8961        self
8962    }
8963
8964    /// Set the screen mode.
8965    pub fn screen_mode(mut self, mode: ScreenMode) -> Self {
8966        self.config.screen_mode = mode;
8967        self
8968    }
8969
8970    /// Set the UI anchor.
8971    pub fn anchor(mut self, anchor: UiAnchor) -> Self {
8972        self.config.ui_anchor = anchor;
8973        self
8974    }
8975
8976    /// Force mouse capture on.
8977    pub fn with_mouse(mut self) -> Self {
8978        self.config.mouse_capture_policy = MouseCapturePolicy::On;
8979        self
8980    }
8981
8982    /// Set mouse capture policy for this app.
8983    pub fn with_mouse_capture_policy(mut self, policy: MouseCapturePolicy) -> Self {
8984        self.config.mouse_capture_policy = policy;
8985        self
8986    }
8987
8988    /// Force mouse capture enabled/disabled for this app.
8989    pub fn with_mouse_enabled(mut self, enabled: bool) -> Self {
8990        self.config.mouse_capture_policy = if enabled {
8991            MouseCapturePolicy::On
8992        } else {
8993            MouseCapturePolicy::Off
8994        };
8995        self
8996    }
8997
8998    /// Set the frame budget configuration.
8999    pub fn with_budget(mut self, budget: FrameBudgetConfig) -> Self {
9000        self.config.budget = budget;
9001        self
9002    }
9003
9004    /// Set the runtime load-governor configuration.
9005    pub fn with_load_governor(mut self, config: LoadGovernorConfig) -> Self {
9006        self.config.load_governor = config;
9007        self
9008    }
9009
9010    /// Disable the adaptive load governor for this app.
9011    pub fn without_load_governor(mut self) -> Self {
9012        self.config.load_governor = LoadGovernorConfig::disabled();
9013        self
9014    }
9015
9016    /// Set the evidence JSONL sink configuration.
9017    pub fn with_evidence_sink(mut self, config: EvidenceSinkConfig) -> Self {
9018        self.config.evidence_sink = config;
9019        self
9020    }
9021
9022    /// Set the render-trace recorder configuration.
9023    pub fn with_render_trace(mut self, config: RenderTraceConfig) -> Self {
9024        self.config.render_trace = config;
9025        self
9026    }
9027
9028    /// Set the widget refresh selection configuration.
9029    pub fn with_widget_refresh(mut self, config: WidgetRefreshConfig) -> Self {
9030        self.config.widget_refresh = config;
9031        self
9032    }
9033
9034    /// Set the effect queue scheduling configuration.
9035    pub fn with_effect_queue(mut self, config: EffectQueueConfig) -> Self {
9036        self.config.effect_queue = config;
9037        self
9038    }
9039
9040    /// Enable inline auto UI height remeasurement.
9041    pub fn with_inline_auto_remeasure(mut self, config: InlineAutoRemeasureConfig) -> Self {
9042        self.config.inline_auto_remeasure = Some(config);
9043        self
9044    }
9045
9046    /// Disable inline auto UI height remeasurement.
9047    pub fn without_inline_auto_remeasure(mut self) -> Self {
9048        self.config.inline_auto_remeasure = None;
9049        self
9050    }
9051
9052    /// Set the locale context used for rendering.
9053    pub fn with_locale_context(mut self, locale_context: LocaleContext) -> Self {
9054        self.config.locale_context = locale_context;
9055        self
9056    }
9057
9058    /// Set the base locale used for rendering.
9059    pub fn with_locale(mut self, locale: impl Into<crate::locale::Locale>) -> Self {
9060        self.config.locale_context = LocaleContext::new(locale);
9061        self
9062    }
9063
9064    /// Set the resize coalescer configuration.
9065    pub fn resize_coalescer(mut self, config: CoalescerConfig) -> Self {
9066        self.config.resize_coalescer = config;
9067        self
9068    }
9069
9070    /// Set the resize handling behavior.
9071    pub fn resize_behavior(mut self, behavior: ResizeBehavior) -> Self {
9072        self.config.resize_behavior = behavior;
9073        self
9074    }
9075
9076    /// Toggle legacy immediate-resize behavior for migration.
9077    pub fn legacy_resize(mut self, enabled: bool) -> Self {
9078        if enabled {
9079            self.config.resize_behavior = ResizeBehavior::Immediate;
9080        }
9081        self
9082    }
9083
9084    /// Set the tick strategy for selective background screen ticking.
9085    pub fn tick_strategy(mut self, strategy: crate::tick_strategy::TickStrategyKind) -> Self {
9086        self.config.tick_strategy = Some(strategy);
9087        self
9088    }
9089
9090    /// Run the application on the default backend for this build.
9091    ///
9092    /// Selects the native TTY backend on Unix when `native-backend` is
9093    /// compiled, otherwise the Crossterm backend when `crossterm-compat` is
9094    /// compiled (see [`DEFAULT_BACKEND`]). When neither backend feature was
9095    /// compiled this returns an [`io::ErrorKind::Unsupported`] error whose
9096    /// message names the feature to enable ([`NO_BACKEND_MESSAGE`]).
9097    ///
9098    /// A termination signal that ends the run exits the process with
9099    /// `128 + signal` after the terminal has been restored, matching the
9100    /// behavior of [`AppBuilder::run_native`] and [`AppBuilder::run_crossterm`].
9101    pub fn run(self) -> io::Result<()>
9102    where
9103        M::Message: Send + 'static,
9104    {
9105        self.run_default_backend()
9106    }
9107
9108    #[cfg(all(feature = "native-backend", unix))]
9109    fn run_default_backend(self) -> io::Result<()>
9110    where
9111        M::Message: Send + 'static,
9112    {
9113        self.run_native()
9114    }
9115
9116    #[cfg(all(
9117        feature = "crossterm-compat",
9118        not(all(feature = "native-backend", unix))
9119    ))]
9120    fn run_default_backend(self) -> io::Result<()>
9121    where
9122        M::Message: Send + 'static,
9123    {
9124        self.run_crossterm()
9125    }
9126
9127    #[cfg(not(any(all(feature = "native-backend", unix), feature = "crossterm-compat")))]
9128    fn run_default_backend(self) -> io::Result<()>
9129    where
9130        M::Message: Send + 'static,
9131    {
9132        let _ = (self.model, self.config);
9133        Err(io::Error::new(
9134            io::ErrorKind::Unsupported,
9135            NO_BACKEND_MESSAGE,
9136        ))
9137    }
9138
9139    /// Run the application using the Crossterm backend.
9140    #[cfg(feature = "crossterm-compat")]
9141    pub fn run_crossterm(self) -> io::Result<()>
9142    where
9143        M::Message: Send + 'static,
9144    {
9145        finish_run(Program::with_config(self.model, self.config)?)
9146    }
9147
9148    /// Run the application using the Crossterm backend.
9149    ///
9150    /// This build did not enable `crossterm-compat`; use [`AppBuilder::run`]
9151    /// for the default backend.
9152    #[cfg(not(feature = "crossterm-compat"))]
9153    pub fn run_crossterm(self) -> io::Result<()>
9154    where
9155        M::Message: Send + 'static,
9156    {
9157        let _ = (self.model, self.config);
9158        Err(io::Error::new(
9159            io::ErrorKind::Unsupported,
9160            "enable `crossterm-compat` feature to use AppBuilder::run_crossterm()",
9161        ))
9162    }
9163
9164    /// Run the application using the native TTY backend.
9165    #[cfg(all(feature = "native-backend", unix))]
9166    pub fn run_native(self) -> io::Result<()>
9167    where
9168        M::Message: Send + 'static,
9169    {
9170        finish_run(Program::with_native_backend(self.model, self.config)?)
9171    }
9172
9173    /// Run the application using the native TTY backend.
9174    ///
9175    /// On non-Unix targets the native backend is unavailable; call
9176    /// [`AppBuilder::run`] (which selects Crossterm there) instead.
9177    #[cfg(any(not(feature = "native-backend"), not(unix)))]
9178    pub fn run_native(self) -> io::Result<()>
9179    where
9180        M::Message: Send + 'static,
9181    {
9182        let _ = (self.model, self.config);
9183        // Prefer the platform-level message: a Windows user without
9184        // `native-backend` enabled would otherwise be told to enable the
9185        // feature, only to discover after rebuilding that it's still
9186        // Unix-only. Pointing them at run() up front avoids the two-step debug.
9187        #[cfg(not(unix))]
9188        let msg = "AppBuilder::run_native() is Unix-only; use AppBuilder::run() on this platform";
9189        #[cfg(all(unix, not(feature = "native-backend")))]
9190        let msg = "enable `native-backend` feature to use AppBuilder::run_native()";
9191        Err(io::Error::new(io::ErrorKind::Unsupported, msg))
9192    }
9193}
9194
9195// =============================================================================
9196// Adaptive Batch Window: Queueing Model (bd-4kq0.8.1)
9197// =============================================================================
9198//
9199// # M/G/1 Queueing Model for Event Batching
9200//
9201// ## Problem
9202//
9203// The event loop must balance two objectives:
9204// 1. **Low latency**: Process events quickly (small batch window ฯ„).
9205// 2. **Efficiency**: Batch multiple events to amortize render cost (large ฯ„).
9206//
9207// ## Model
9208//
9209// We model the event loop as an M/G/1 queue:
9210// - Events arrive at rate ฮป (Poisson process, reasonable for human input).
9211// - Service time S has mean E[S] and variance Var[S] (render + present).
9212// - Utilization ฯ = ฮปยทE[S] must be < 1 for stability.
9213//
9214// ## Pollaczekโ€“Khinchine Mean Waiting Time
9215//
9216// For M/G/1: E[W] = (ฮปยทE[Sยฒ]) / (2ยท(1 โˆ’ ฯ))
9217// where E[Sยฒ] = Var[S] + E[S]ยฒ.
9218//
9219// ## Optimal Batch Window ฯ„
9220//
9221// With batching window ฯ„, we collect ~(ฮปยทฯ„) events per batch, amortizing
9222// the per-frame render cost. The effective per-event latency is:
9223//
9224//   L(ฯ„) = ฯ„/2 + E[S]
9225//         (waiting in batch)  (service)
9226//
9227// The batch reduces arrival rate to ฮป_eff = 1/ฯ„ (one batch per window),
9228// giving utilization ฯ_eff = E[S]/ฯ„.
9229//
9230// Minimizing L(ฯ„) subject to ฯ_eff < 1:
9231//   L(ฯ„) = ฯ„/2 + E[S]
9232//   dL/dฯ„ = 1/2  (always positive, so smaller ฯ„ is always better for latency)
9233//
9234// But we need ฯ_eff < 1, so ฯ„ > E[S].
9235//
9236// The practical rule: ฯ„ = max(E[S] ยท headroom_factor, ฯ„_min)
9237// where headroom_factor provides margin (typically 1.5โ€“2.0).
9238//
9239// For high arrival rates: ฯ„ = max(E[S] ยท headroom, 1/ฮป_target)
9240// where ฮป_target is the max frame rate we want to sustain.
9241//
9242// ## Failure Modes
9243//
9244// 1. **Overload (ฯ โ‰ฅ 1)**: Queue grows unbounded. Mitigation: increase ฯ„
9245//    (degrade to lower frame rate), or drop stale events.
9246// 2. **Bursty arrivals**: Real input is bursty (typing, mouse drag). The
9247//    exponential moving average of ฮป smooths this; high burst periods
9248//    temporarily increase ฯ„.
9249// 3. **Variable service time**: Render complexity varies per frame. Using
9250//    EMA of E[S] tracks this adaptively.
9251//
9252// ## Observable Telemetry
9253//
9254// - ฮป_est: Exponential moving average of inter-arrival times.
9255// - es_est: Exponential moving average of service (render) times.
9256// - ฯ_est: ฮป_est ร— es_est (estimated utilization).
9257
9258/// Adaptive batch window controller based on M/G/1 queueing model.
9259///
9260/// Estimates arrival rate ฮป and service time `E[S]` from observations,
9261/// then computes the optimal batch window ฯ„ to maintain stability
9262/// (ฯ < 1) while minimizing latency.
9263#[derive(Debug, Clone)]
9264pub struct BatchController {
9265    /// Exponential moving average of inter-arrival time (seconds).
9266    ema_inter_arrival_s: f64,
9267    /// Exponential moving average of service time (seconds).
9268    ema_service_s: f64,
9269    /// EMA smoothing factor (0..1). Higher = more responsive.
9270    alpha: f64,
9271    /// Minimum batch window (floor).
9272    tau_min_s: f64,
9273    /// Maximum batch window (cap for responsiveness).
9274    tau_max_s: f64,
9275    /// Headroom factor: ฯ„ >= E[S] ร— headroom to keep ฯ < 1.
9276    headroom: f64,
9277    /// Last event arrival timestamp.
9278    last_arrival: Option<Instant>,
9279    /// Number of observations.
9280    observations: u64,
9281}
9282
9283impl BatchController {
9284    /// Create a new controller with sensible defaults.
9285    ///
9286    /// - `alpha`: EMA smoothing (default 0.2)
9287    /// - `tau_min`: minimum batch window (default 1ms)
9288    /// - `tau_max`: maximum batch window (default 50ms)
9289    /// - `headroom`: stability margin (default 2.0, keeps ฯ โ‰ค 0.5)
9290    pub fn new() -> Self {
9291        Self {
9292            ema_inter_arrival_s: 0.1, // assume 10 events/sec initially
9293            ema_service_s: 0.002,     // assume 2ms render initially
9294            alpha: 0.2,
9295            tau_min_s: 0.001, // 1ms floor
9296            tau_max_s: 0.050, // 50ms cap
9297            headroom: 2.0,
9298            last_arrival: None,
9299            observations: 0,
9300        }
9301    }
9302
9303    /// Record an event arrival, updating the inter-arrival estimate.
9304    pub fn observe_arrival(&mut self, now: Instant) {
9305        if let Some(last) = self.last_arrival {
9306            let dt = now.saturating_duration_since(last).as_secs_f64();
9307            if dt > 0.0 && dt < 10.0 {
9308                // Guard against stale gaps (e.g., app was suspended)
9309                self.ema_inter_arrival_s =
9310                    self.alpha * dt + (1.0 - self.alpha) * self.ema_inter_arrival_s;
9311                self.observations += 1;
9312            }
9313        }
9314        self.last_arrival = Some(now);
9315    }
9316
9317    /// Record a service (render) time observation.
9318    pub fn observe_service(&mut self, duration: Duration) {
9319        let dt = duration.as_secs_f64();
9320        if (0.0..10.0).contains(&dt) {
9321            self.ema_service_s = self.alpha * dt + (1.0 - self.alpha) * self.ema_service_s;
9322        }
9323    }
9324
9325    /// Estimated arrival rate ฮป (events/second).
9326    #[inline]
9327    pub fn lambda_est(&self) -> f64 {
9328        if self.ema_inter_arrival_s > 0.0 {
9329            1.0 / self.ema_inter_arrival_s
9330        } else {
9331            0.0
9332        }
9333    }
9334
9335    /// Estimated service time `E[S]` (seconds).
9336    #[inline]
9337    pub fn service_est_s(&self) -> f64 {
9338        self.ema_service_s
9339    }
9340
9341    /// Estimated utilization ฯ = ฮป ร— `E[S]`.
9342    #[inline]
9343    pub fn rho_est(&self) -> f64 {
9344        self.lambda_est() * self.ema_service_s
9345    }
9346
9347    /// Compute the optimal batch window ฯ„ (seconds).
9348    ///
9349    /// ฯ„ = clamp(`E[S]` ร— headroom, ฯ„_min, ฯ„_max)
9350    ///
9351    /// When ฯ approaches 1, ฯ„ increases to maintain stability.
9352    pub fn tau_s(&self) -> f64 {
9353        let base = self.ema_service_s * self.headroom;
9354        base.clamp(self.tau_min_s, self.tau_max_s)
9355    }
9356
9357    /// Compute the optimal batch window as a Duration.
9358    pub fn tau(&self) -> Duration {
9359        Duration::from_secs_f64(self.tau_s())
9360    }
9361
9362    /// Check if the system is stable (ฯ < 1).
9363    #[inline]
9364    pub fn is_stable(&self) -> bool {
9365        self.rho_est() < 1.0
9366    }
9367
9368    /// Number of observations recorded.
9369    #[inline]
9370    pub fn observations(&self) -> u64 {
9371        self.observations
9372    }
9373}
9374
9375impl Default for BatchController {
9376    fn default() -> Self {
9377        Self::new()
9378    }
9379}
9380
9381#[cfg(test)]
9382mod tests {
9383    use super::*;
9384    use ftui_core::terminal_capabilities::TerminalCapabilities;
9385    use ftui_layout::PaneDragResizeEffect;
9386    use ftui_render::buffer::Buffer;
9387    use ftui_render::cell::Cell;
9388    use ftui_render::diff_strategy::DiffStrategy;
9389    use ftui_render::frame::CostEstimateSource;
9390    use ftui_render::frame_guardrails::{MemoryBudgetConfig, QueueConfig};
9391    use serde_json::Value;
9392    use std::collections::{HashMap, VecDeque};
9393    use std::io::Write;
9394    use std::path::PathBuf;
9395    use std::sync::mpsc;
9396    use std::sync::{
9397        Arc,
9398        atomic::{AtomicUsize, Ordering},
9399    };
9400
9401    // Simple test model
9402    struct TestModel {
9403        value: i32,
9404    }
9405
9406    #[derive(Debug)]
9407    enum TestMsg {
9408        Increment,
9409        Decrement,
9410        Quit,
9411    }
9412
9413    impl From<Event> for TestMsg {
9414        fn from(_event: Event) -> Self {
9415            TestMsg::Increment
9416        }
9417    }
9418
9419    impl Model for TestModel {
9420        type Message = TestMsg;
9421
9422        fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
9423            match msg {
9424                TestMsg::Increment => {
9425                    self.value += 1;
9426                    Cmd::none()
9427                }
9428                TestMsg::Decrement => {
9429                    self.value -= 1;
9430                    Cmd::none()
9431                }
9432                TestMsg::Quit => Cmd::quit(),
9433            }
9434        }
9435
9436        fn view(&self, _frame: &mut Frame) {
9437            // No-op for tests
9438        }
9439    }
9440
9441    #[test]
9442    fn cmd_none() {
9443        let cmd: Cmd<TestMsg> = Cmd::none();
9444        assert!(matches!(cmd, Cmd::None));
9445    }
9446
9447    #[test]
9448    fn cmd_quit() {
9449        let cmd: Cmd<TestMsg> = Cmd::quit();
9450        assert!(matches!(cmd, Cmd::Quit));
9451    }
9452
9453    #[test]
9454    fn cmd_msg() {
9455        let cmd: Cmd<TestMsg> = Cmd::msg(TestMsg::Increment);
9456        assert!(matches!(cmd, Cmd::Msg(TestMsg::Increment)));
9457    }
9458
9459    #[test]
9460    fn cmd_batch_empty() {
9461        let cmd: Cmd<TestMsg> = Cmd::batch(vec![]);
9462        assert!(matches!(cmd, Cmd::None));
9463    }
9464
9465    #[test]
9466    fn cmd_batch_single() {
9467        let cmd: Cmd<TestMsg> = Cmd::batch(vec![Cmd::quit()]);
9468        assert!(matches!(cmd, Cmd::Quit));
9469    }
9470
9471    #[test]
9472    fn cmd_batch_multiple() {
9473        let cmd: Cmd<TestMsg> = Cmd::batch(vec![Cmd::none(), Cmd::quit()]);
9474        assert!(matches!(cmd, Cmd::Batch(_)));
9475    }
9476
9477    #[test]
9478    fn cmd_sequence_empty() {
9479        let cmd: Cmd<TestMsg> = Cmd::sequence(vec![]);
9480        assert!(matches!(cmd, Cmd::None));
9481    }
9482
9483    #[test]
9484    fn cmd_tick() {
9485        let cmd: Cmd<TestMsg> = Cmd::tick(Duration::from_millis(100));
9486        assert!(matches!(cmd, Cmd::Tick(_)));
9487    }
9488
9489    #[test]
9490    fn cmd_task() {
9491        let cmd: Cmd<TestMsg> = Cmd::task(|| TestMsg::Increment);
9492        assert!(matches!(cmd, Cmd::Task(..)));
9493    }
9494
9495    #[test]
9496    fn cmd_debug_format() {
9497        let cmd: Cmd<TestMsg> = Cmd::task(|| TestMsg::Increment);
9498        let debug = format!("{cmd:?}");
9499        assert_eq!(
9500            debug,
9501            "Task { spec: TaskSpec { weight: 1.0, estimate_ms: 10.0, name: None } }"
9502        );
9503    }
9504
9505    #[test]
9506    fn model_subscriptions_default_empty() {
9507        let model = TestModel { value: 0 };
9508        let subs = model.subscriptions();
9509        assert!(subs.is_empty());
9510    }
9511
9512    #[test]
9513    fn program_config_default() {
9514        let config = ProgramConfig::default();
9515        assert!(matches!(config.screen_mode, ScreenMode::Inline { .. }));
9516        assert_eq!(config.mouse_capture_policy, MouseCapturePolicy::Auto);
9517        assert!(!config.resolved_mouse_capture());
9518        assert!(config.bracketed_paste);
9519        assert_eq!(config.resize_behavior, ResizeBehavior::Throttled);
9520        assert!(config.inline_auto_remeasure.is_none());
9521        let conformal = config
9522            .conformal_config
9523            .as_ref()
9524            .expect("conformal frame-time gating is on by default");
9525        assert_eq!(conformal.min_samples, 20, "warm-up before any gating");
9526        assert!(
9527            ProgramConfig::default()
9528                .without_conformal()
9529                .conformal_config
9530                .is_none()
9531        );
9532        assert!(config.diff_config.bayesian_enabled);
9533        assert!(config.diff_config.dirty_rows_enabled);
9534        assert!(
9535            !config.resize_coalescer.enable_bocpd,
9536            "the rate heuristic is the default resize regime detector (bd-h8l3d)"
9537        );
9538        assert!(config.resize_coalescer.heuristic_fallback);
9539        assert!(!config.effect_queue.enabled);
9540        assert_eq!(config.immediate_drain.max_zero_timeout_polls_per_burst, 64);
9541        assert_eq!(
9542            config.immediate_drain.max_burst_duration,
9543            Duration::from_millis(2)
9544        );
9545        assert_eq!(
9546            config.immediate_drain.backoff_timeout,
9547            Duration::from_millis(1)
9548        );
9549        assert_eq!(
9550            config.resize_coalescer.steady_delay_ms,
9551            CoalescerConfig::default().steady_delay_ms
9552        );
9553    }
9554
9555    #[test]
9556    fn program_config_with_immediate_drain() {
9557        let custom = ImmediateDrainConfig {
9558            max_zero_timeout_polls_per_burst: 7,
9559            max_burst_duration: Duration::from_millis(9),
9560            backoff_timeout: Duration::from_millis(3),
9561        };
9562        let config = ProgramConfig::default().with_immediate_drain(custom.clone());
9563        assert_eq!(
9564            config.immediate_drain.max_zero_timeout_polls_per_burst,
9565            custom.max_zero_timeout_polls_per_burst
9566        );
9567        assert_eq!(
9568            config.immediate_drain.max_burst_duration,
9569            custom.max_burst_duration
9570        );
9571        assert_eq!(
9572            config.immediate_drain.backoff_timeout,
9573            custom.backoff_timeout
9574        );
9575    }
9576
9577    #[test]
9578    fn program_config_fullscreen() {
9579        let config = ProgramConfig::fullscreen();
9580        assert!(matches!(config.screen_mode, ScreenMode::AltScreen));
9581    }
9582
9583    #[test]
9584    fn program_config_inline() {
9585        let config = ProgramConfig::inline(10);
9586        assert!(matches!(
9587            config.screen_mode,
9588            ScreenMode::Inline { ui_height: 10 }
9589        ));
9590    }
9591
9592    #[test]
9593    fn program_config_inline_auto() {
9594        let config = ProgramConfig::inline_auto(3, 9);
9595        assert!(matches!(
9596            config.screen_mode,
9597            ScreenMode::InlineAuto {
9598                min_height: 3,
9599                max_height: 9
9600            }
9601        ));
9602        assert!(config.inline_auto_remeasure.is_some());
9603    }
9604
9605    #[test]
9606    fn program_config_with_mouse() {
9607        let config = ProgramConfig::default().with_mouse();
9608        assert_eq!(config.mouse_capture_policy, MouseCapturePolicy::On);
9609        assert!(config.resolved_mouse_capture());
9610    }
9611
9612    #[test]
9613    fn exit_after_env_parses_ms_and_rejects_garbage() {
9614        assert_eq!(
9615            parse_exit_after_ms("1500"),
9616            Some(Duration::from_millis(1500))
9617        );
9618        assert_eq!(
9619            parse_exit_after_ms("  250 \n"),
9620            Some(Duration::from_millis(250))
9621        );
9622        assert_eq!(parse_exit_after_ms("0"), None);
9623        assert_eq!(parse_exit_after_ms(""), None);
9624        assert_eq!(parse_exit_after_ms("-50"), None);
9625        assert_eq!(parse_exit_after_ms("garbage"), None);
9626        assert_eq!(parse_exit_after_ms("1500ms"), None);
9627        assert_eq!(
9628            exit_after_env("FTUI_NONEXISTENT_EXIT_AFTER_MS_TEST_VAR"),
9629            None
9630        );
9631    }
9632
9633    #[test]
9634    fn with_config_reports_not_a_console_cleanly() {
9635        assert!(validate_console_available(true).is_ok());
9636        let err = validate_console_available(false)
9637            .expect_err("non-console handle must report Unsupported");
9638        assert_eq!(err.kind(), io::ErrorKind::Unsupported);
9639        assert_eq!(err.to_string(), NOT_A_CONSOLE_MESSAGE);
9640        assert!(err.to_string().contains("not a console"));
9641        // Verify a non-terminal handle (anonymous file / pipe) is detected as false
9642        let temp = tempfile::tempfile().expect("tempfile");
9643        assert!(!io::IsTerminal::is_terminal(&temp));
9644    }
9645
9646    #[cfg(feature = "native-backend")]
9647    #[test]
9648    fn sanitize_backend_features_disables_unsupported_features() {
9649        let requested = BackendFeatures {
9650            mouse_capture: true,
9651            bracketed_paste: true,
9652            focus_events: true,
9653            kitty_keyboard: true,
9654        };
9655        let sanitized =
9656            sanitize_backend_features_for_capabilities(requested, &TerminalCapabilities::basic());
9657        assert_eq!(sanitized, BackendFeatures::default());
9658    }
9659
9660    #[cfg(feature = "native-backend")]
9661    #[test]
9662    fn sanitize_backend_features_is_conservative_in_wezterm_mux() {
9663        let requested = BackendFeatures {
9664            mouse_capture: true,
9665            bracketed_paste: true,
9666            focus_events: true,
9667            kitty_keyboard: true,
9668        };
9669        let caps = TerminalCapabilities::builder()
9670            .mouse_sgr(true)
9671            .bracketed_paste(true)
9672            .focus_events(true)
9673            .kitty_keyboard(true)
9674            .in_wezterm_mux(true)
9675            .build();
9676        let sanitized = sanitize_backend_features_for_capabilities(requested, &caps);
9677
9678        assert!(sanitized.mouse_capture);
9679        assert!(sanitized.bracketed_paste);
9680        assert!(!sanitized.focus_events);
9681        assert!(!sanitized.kitty_keyboard);
9682    }
9683
9684    #[cfg(feature = "native-backend")]
9685    #[test]
9686    fn sanitize_backend_features_is_conservative_in_tmux() {
9687        let requested = BackendFeatures {
9688            mouse_capture: true,
9689            bracketed_paste: true,
9690            focus_events: true,
9691            kitty_keyboard: true,
9692        };
9693        let caps = TerminalCapabilities::builder()
9694            .mouse_sgr(true)
9695            .bracketed_paste(true)
9696            .focus_events(true)
9697            .kitty_keyboard(true)
9698            .in_tmux(true)
9699            .build();
9700        let sanitized = sanitize_backend_features_for_capabilities(requested, &caps);
9701
9702        assert!(sanitized.mouse_capture);
9703        assert!(sanitized.bracketed_paste);
9704        assert!(!sanitized.focus_events);
9705        assert!(!sanitized.kitty_keyboard);
9706    }
9707
9708    #[test]
9709    fn program_config_mouse_policy_auto_altscreen() {
9710        let config = ProgramConfig::fullscreen();
9711        assert_eq!(config.mouse_capture_policy, MouseCapturePolicy::Auto);
9712        assert!(config.resolved_mouse_capture());
9713    }
9714
9715    #[test]
9716    fn program_config_mouse_policy_force_off() {
9717        let config = ProgramConfig::fullscreen().with_mouse_capture_policy(MouseCapturePolicy::Off);
9718        assert_eq!(config.mouse_capture_policy, MouseCapturePolicy::Off);
9719        assert!(!config.resolved_mouse_capture());
9720    }
9721
9722    #[test]
9723    fn program_config_mouse_policy_force_on_inline() {
9724        let config = ProgramConfig::inline(6).with_mouse_enabled(true);
9725        assert_eq!(config.mouse_capture_policy, MouseCapturePolicy::On);
9726        assert!(config.resolved_mouse_capture());
9727    }
9728
9729    fn pane_target(axis: SplitAxis) -> PaneResizeTarget {
9730        PaneResizeTarget {
9731            split_id: ftui_layout::PaneId::MIN,
9732            axis,
9733        }
9734    }
9735
9736    fn pane_id(raw: u64) -> ftui_layout::PaneId {
9737        ftui_layout::PaneId::new(raw).expect("test pane id must be non-zero")
9738    }
9739
9740    fn nested_pane_tree() -> ftui_layout::PaneTree {
9741        let root = pane_id(1);
9742        let left = pane_id(2);
9743        let right_split = pane_id(3);
9744        let right_top = pane_id(4);
9745        let right_bottom = pane_id(5);
9746        let snapshot = ftui_layout::PaneTreeSnapshot {
9747            schema_version: ftui_layout::PANE_TREE_SCHEMA_VERSION,
9748            root,
9749            next_id: pane_id(6),
9750            nodes: vec![
9751                ftui_layout::PaneNodeRecord::split(
9752                    root,
9753                    None,
9754                    ftui_layout::PaneSplit {
9755                        axis: SplitAxis::Horizontal,
9756                        ratio: ftui_layout::PaneSplitRatio::new(1, 1).expect("valid ratio"),
9757                        first: left,
9758                        second: right_split,
9759                    },
9760                ),
9761                ftui_layout::PaneNodeRecord::leaf(
9762                    left,
9763                    Some(root),
9764                    ftui_layout::PaneLeaf::new("left"),
9765                ),
9766                ftui_layout::PaneNodeRecord::split(
9767                    right_split,
9768                    Some(root),
9769                    ftui_layout::PaneSplit {
9770                        axis: SplitAxis::Vertical,
9771                        ratio: ftui_layout::PaneSplitRatio::new(1, 1).expect("valid ratio"),
9772                        first: right_top,
9773                        second: right_bottom,
9774                    },
9775                ),
9776                ftui_layout::PaneNodeRecord::leaf(
9777                    right_top,
9778                    Some(right_split),
9779                    ftui_layout::PaneLeaf::new("right_top"),
9780                ),
9781                ftui_layout::PaneNodeRecord::leaf(
9782                    right_bottom,
9783                    Some(right_split),
9784                    ftui_layout::PaneLeaf::new("right_bottom"),
9785                ),
9786            ],
9787            extensions: std::collections::BTreeMap::new(),
9788        };
9789        ftui_layout::PaneTree::from_snapshot(snapshot).expect("valid nested pane tree")
9790    }
9791
9792    /// First-child share (in basis points) of a split node's ratio.
9793    fn root_first_share_bps(tree: &ftui_layout::PaneTree, split: ftui_layout::PaneId) -> u32 {
9794        match &tree.node(split).expect("split node present").kind {
9795            PaneNodeKind::Split(node) => {
9796                node.ratio.numerator() * 10_000
9797                    / (node.ratio.numerator() + node.ratio.denominator())
9798            }
9799            other => panic!("expected split node, got {other:?}"),
9800        }
9801    }
9802
9803    /// A fixed, timing-independent pressure-snap profile for deterministic tests.
9804    fn fixed_neutral_pressure() -> PanePressureSnapProfile {
9805        PanePressureSnapProfile {
9806            strength_bps: 5_000,
9807            hysteresis_bps: 100,
9808        }
9809    }
9810
9811    /// Apply a terminal dispatch's geometry-bearing transition to the live tree
9812    /// using a fixed, caller-supplied pressure profile.
9813    ///
9814    /// Unlike the realistic path (which derives pressure from pointer motion and
9815    /// therefore from wall-clock `speed`), this helper always uses `pressure`, so
9816    /// repeated runs of the same scripted event sequence are byte-for-byte
9817    /// deterministic. Returns the number of operations applied.
9818    fn apply_dispatch_fixed(
9819        tree: &mut ftui_layout::PaneTree,
9820        layout: &ftui_layout::PaneLayout,
9821        dispatch: &PaneTerminalDispatch,
9822        pressure: PanePressureSnapProfile,
9823        seed: &mut u64,
9824    ) -> usize {
9825        let Some(transition) = dispatch.primary_transition.as_ref() else {
9826            return 0;
9827        };
9828        let ops = tree.operations_for_transition(transition, layout, pressure);
9829        let applied = ops.len();
9830        for op in ops {
9831            tree.apply_operation(*seed, op).expect("operation applies");
9832            *seed += 1;
9833        }
9834        applied
9835    }
9836
9837    /// Drive a full scripted horizontal splitter drag through the live
9838    /// adapter -> bridge -> tree path with a fixed pressure profile. Press at
9839    /// `down_x`, then send Drag events for every position in `drag_xs` except the
9840    /// last, which is sent as the release (Up). Pointer x must increase across
9841    /// samples (the adapter tracks magnitude via saturating deltas). Returns the
9842    /// number of operations applied.
9843    #[allow(clippy::too_many_arguments)]
9844    fn drive_horizontal_drag_fixed(
9845        adapter: &mut PaneTerminalAdapter,
9846        tree: &mut ftui_layout::PaneTree,
9847        layout: &ftui_layout::PaneLayout,
9848        target: PaneResizeTarget,
9849        down_x: u16,
9850        y: u16,
9851        drag_xs: &[u16],
9852        pressure: PanePressureSnapProfile,
9853        seed: &mut u64,
9854    ) -> usize {
9855        let down = Event::Mouse(MouseEvent::new(
9856            MouseEventKind::Down(MouseButton::Left),
9857            down_x,
9858            y,
9859        ));
9860        let mut applied = apply_dispatch_fixed(
9861            tree,
9862            layout,
9863            &adapter.translate(&down, Some(target)),
9864            pressure,
9865            seed,
9866        );
9867
9868        let last = drag_xs.len().saturating_sub(1);
9869        for (idx, &x) in drag_xs.iter().enumerate() {
9870            let kind = if idx == last {
9871                MouseEventKind::Up(MouseButton::Left)
9872            } else {
9873                MouseEventKind::Drag(MouseButton::Left)
9874            };
9875            let event = Event::Mouse(MouseEvent::new(kind, x, y));
9876            applied += apply_dispatch_fixed(
9877                tree,
9878                layout,
9879                &adapter.translate(&event, None),
9880                pressure,
9881                seed,
9882            );
9883        }
9884        applied
9885    }
9886
9887    #[test]
9888    fn pane_terminal_splitter_resolution_is_deterministic() {
9889        let tree = nested_pane_tree();
9890        let layout = tree
9891            .solve_layout(Rect::new(0, 0, 50, 20))
9892            .expect("layout should solve");
9893        let handles = pane_terminal_splitter_handles(&tree, &layout, 3);
9894        assert_eq!(handles.len(), 2);
9895
9896        // Intersection between root vertical splitter and right-side horizontal
9897        // splitter deterministically resolves to smaller split ID.
9898        let overlap = pane_terminal_resolve_splitter_target(&handles, 25, 10)
9899            .expect("overlap cell should resolve");
9900        assert_eq!(overlap.split_id, pane_id(1));
9901        assert_eq!(overlap.axis, SplitAxis::Horizontal);
9902
9903        let right_only = pane_terminal_resolve_splitter_target(&handles, 40, 10)
9904            .expect("right split should resolve");
9905        assert_eq!(right_only.split_id, pane_id(3));
9906        assert_eq!(right_only.axis, SplitAxis::Vertical);
9907    }
9908
9909    #[test]
9910    fn pane_terminal_splitter_hits_register_and_decode_target() {
9911        let tree = nested_pane_tree();
9912        let layout = tree
9913            .solve_layout(Rect::new(0, 0, 50, 20))
9914            .expect("layout should solve");
9915        let handles = pane_terminal_splitter_handles(&tree, &layout, 3);
9916
9917        let mut pool = ftui_render::grapheme_pool::GraphemePool::new();
9918        let mut frame = Frame::with_hit_grid(50, 20, &mut pool);
9919        let registered = register_pane_terminal_splitter_hits(&mut frame, &handles, 9_000);
9920        assert_eq!(registered, handles.len());
9921
9922        let root_hit = frame
9923            .hit_test(25, 2)
9924            .expect("root splitter should be hittable");
9925        assert_eq!(root_hit.1, HitRegion::Handle);
9926        let root_target = pane_terminal_target_from_hit(root_hit).expect("target from hit");
9927        assert_eq!(root_target.split_id, pane_id(1));
9928        assert_eq!(root_target.axis, SplitAxis::Horizontal);
9929
9930        let right_hit = frame
9931            .hit_test(40, 10)
9932            .expect("right splitter should be hittable");
9933        assert_eq!(right_hit.1, HitRegion::Handle);
9934        let right_target = pane_terminal_target_from_hit(right_hit).expect("target from hit");
9935        assert_eq!(right_target.split_id, pane_id(3));
9936        assert_eq!(right_target.axis, SplitAxis::Vertical);
9937    }
9938
9939    #[test]
9940    fn pane_terminal_adapter_maps_basic_drag_lifecycle() {
9941        let mut adapter =
9942            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
9943        let target = pane_target(SplitAxis::Horizontal);
9944
9945        let down = Event::Mouse(MouseEvent::new(
9946            MouseEventKind::Down(MouseButton::Left),
9947            10,
9948            4,
9949        ));
9950        let down_dispatch = adapter.translate(&down, Some(target));
9951        let down_event = down_dispatch
9952            .primary_event
9953            .as_ref()
9954            .expect("pointer down semantic event");
9955        assert_eq!(down_event.sequence, 1);
9956        assert!(matches!(
9957            down_event.kind,
9958            PaneSemanticInputEventKind::PointerDown {
9959                target: actual_target,
9960                pointer_id: 1,
9961                button: PanePointerButton::Primary,
9962                position
9963            } if actual_target == target && position == PanePointerPosition::new(10, 4)
9964        ));
9965        assert!(down_event.validate().is_ok());
9966
9967        let drag = Event::Mouse(MouseEvent::new(
9968            MouseEventKind::Drag(MouseButton::Left),
9969            14,
9970            4,
9971        ));
9972        let drag_dispatch = adapter.translate(&drag, None);
9973        let drag_event = drag_dispatch
9974            .primary_event
9975            .as_ref()
9976            .expect("pointer move semantic event");
9977        assert_eq!(drag_event.sequence, 2);
9978        assert!(matches!(
9979            drag_event.kind,
9980            PaneSemanticInputEventKind::PointerMove {
9981                target: actual_target,
9982                pointer_id: 1,
9983                position,
9984                delta_x: 4,
9985                delta_y: 0
9986            } if actual_target == target && position == PanePointerPosition::new(14, 4)
9987        ));
9988        let drag_motion = drag_dispatch
9989            .motion
9990            .expect("drag should emit motion metadata");
9991        assert_eq!(drag_motion.delta_x, 4);
9992        assert_eq!(drag_motion.delta_y, 0);
9993        assert_eq!(drag_motion.direction_changes, 0);
9994        assert!(drag_motion.speed > 0.0);
9995        assert!(drag_dispatch.pressure_snap_profile().is_some());
9996
9997        let up = Event::Mouse(MouseEvent::new(
9998            MouseEventKind::Up(MouseButton::Left),
9999            14,
10000            4,
10001        ));
10002        let up_dispatch = adapter.translate(&up, None);
10003        let up_event = up_dispatch
10004            .primary_event
10005            .as_ref()
10006            .expect("pointer up semantic event");
10007        assert_eq!(up_event.sequence, 3);
10008        assert!(matches!(
10009            up_event.kind,
10010            PaneSemanticInputEventKind::PointerUp {
10011                target: actual_target,
10012                pointer_id: 1,
10013                button: PanePointerButton::Primary,
10014                position
10015            } if actual_target == target && position == PanePointerPosition::new(14, 4)
10016        ));
10017        let up_motion = up_dispatch
10018            .motion
10019            .expect("up should emit final motion metadata");
10020        assert_eq!(up_motion.delta_x, 4);
10021        assert_eq!(up_motion.delta_y, 0);
10022        assert_eq!(up_motion.direction_changes, 0);
10023        let inertial_throw = up_dispatch
10024            .inertial_throw
10025            .expect("up should emit inertial throw metadata");
10026        assert_eq!(
10027            up_dispatch.projected_position,
10028            Some(inertial_throw.projected_pointer(PanePointerPosition::new(14, 4)))
10029        );
10030        assert_eq!(adapter.active_pointer_id(), None);
10031        assert!(matches!(adapter.machine_state(), PaneDragResizeState::Idle));
10032    }
10033
10034    #[test]
10035    fn pane_terminal_adapter_drives_live_tree_mutation() {
10036        // End-to-end proof that the terminal adapter actually mutates the live
10037        // pane tree. Raw crossterm events flow through PaneTerminalAdapter into
10038        // PaneDragResizeTransition values, the layout bridge
10039        // (PaneTree::operations_for_transition) turns each geometry-bearing
10040        // transition into PaneOperation values, and apply_operation moves the
10041        // live root split ratio. This closes the historical gap where the
10042        // adapter emitted transitions that no production path consumed.
10043        fn apply_dispatch(
10044            tree: &mut ftui_layout::PaneTree,
10045            layout: &ftui_layout::PaneLayout,
10046            dispatch: &PaneTerminalDispatch,
10047            neutral: PanePressureSnapProfile,
10048            seed: &mut u64,
10049        ) -> usize {
10050            let Some(transition) = dispatch.primary_transition.as_ref() else {
10051                return 0;
10052            };
10053            let pressure = dispatch.pressure_snap_profile().unwrap_or(neutral);
10054            let ops = tree.operations_for_transition(transition, layout, pressure);
10055            let applied = ops.len();
10056            for op in ops {
10057                tree.apply_operation(*seed, op).expect("operation applies");
10058                *seed += 1;
10059            }
10060            applied
10061        }
10062
10063        let mut tree = nested_pane_tree();
10064        // The root split's own rectangle spans the whole viewport regardless of
10065        // its ratio, so a single solve is sufficient for targeting it.
10066        let layout = tree
10067            .solve_layout(Rect::new(0, 0, 50, 20))
10068            .expect("layout should solve");
10069        let root_split = pane_id(1);
10070        let target = PaneResizeTarget {
10071            split_id: root_split,
10072            axis: SplitAxis::Horizontal,
10073        };
10074        let neutral = PanePressureSnapProfile {
10075            strength_bps: 5_000,
10076            hysteresis_bps: 100,
10077        };
10078
10079        let before_share = root_first_share_bps(&tree, root_split);
10080
10081        let mut adapter =
10082            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
10083        let mut op_seed = 7_000u64;
10084        let mut geometry_transitions = 0usize;
10085
10086        // Press on the splitter (arms the machine; no geometry yet).
10087        let down = Event::Mouse(MouseEvent::new(
10088            MouseEventKind::Down(MouseButton::Left),
10089            25,
10090            10,
10091        ));
10092        let down_dispatch = adapter.translate(&down, Some(target));
10093        geometry_transitions +=
10094            apply_dispatch(&mut tree, &layout, &down_dispatch, neutral, &mut op_seed);
10095
10096        // Drag rightward across cells, applying each transition to the tree.
10097        for x in [30u16, 36, 42] {
10098            let drag = Event::Mouse(MouseEvent::new(
10099                MouseEventKind::Drag(MouseButton::Left),
10100                x,
10101                10,
10102            ));
10103            let dispatch = adapter.translate(&drag, None);
10104            geometry_transitions +=
10105                apply_dispatch(&mut tree, &layout, &dispatch, neutral, &mut op_seed);
10106        }
10107
10108        // Release.
10109        let up = Event::Mouse(MouseEvent::new(
10110            MouseEventKind::Up(MouseButton::Left),
10111            42,
10112            10,
10113        ));
10114        let up_dispatch = adapter.translate(&up, None);
10115        geometry_transitions +=
10116            apply_dispatch(&mut tree, &layout, &up_dispatch, neutral, &mut op_seed);
10117
10118        assert!(
10119            geometry_transitions > 0,
10120            "drag lifecycle should yield at least one geometry-bearing transition"
10121        );
10122        let after_share = root_first_share_bps(&tree, root_split);
10123        assert!(
10124            after_share > before_share,
10125            "rightward splitter drag should grow the first child: after={after_share} before={before_share}"
10126        );
10127        assert!(matches!(adapter.machine_state(), PaneDragResizeState::Idle));
10128    }
10129
10130    #[test]
10131    fn pane_terminal_adapter_resize_interrupt_cancels_drag_and_preserves_tree() {
10132        // Edge interruption: a terminal resize (SIGWINCH) arrives mid-drag. With
10133        // the default config (cancel_on_resize = true) the adapter must cancel the
10134        // in-flight gesture cleanly, leave the live tree valid and unmutated by the
10135        // interrupt itself, and remain reusable for a fresh gesture afterwards.
10136        let mut tree = nested_pane_tree();
10137        let layout = tree
10138            .solve_layout(Rect::new(0, 0, 50, 20))
10139            .expect("layout should solve");
10140        let root_split = pane_id(1);
10141        let target = PaneResizeTarget {
10142            split_id: root_split,
10143            axis: SplitAxis::Horizontal,
10144        };
10145        let pressure = fixed_neutral_pressure();
10146        let mut seed = 4_100u64;
10147
10148        let initial_hash = tree.state_hash();
10149
10150        let mut adapter =
10151            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
10152
10153        // Arm + drag (without releasing) so a gesture is genuinely in flight.
10154        let _ = apply_dispatch_fixed(
10155            &mut tree,
10156            &layout,
10157            &adapter.translate(
10158                &Event::Mouse(MouseEvent::new(
10159                    MouseEventKind::Down(MouseButton::Left),
10160                    25,
10161                    10,
10162                )),
10163                Some(target),
10164            ),
10165            pressure,
10166            &mut seed,
10167        );
10168        for x in [30u16, 36] {
10169            let _ = apply_dispatch_fixed(
10170                &mut tree,
10171                &layout,
10172                &adapter.translate(
10173                    &Event::Mouse(MouseEvent::new(
10174                        MouseEventKind::Drag(MouseButton::Left),
10175                        x,
10176                        10,
10177                    )),
10178                    None,
10179                ),
10180                pressure,
10181                &mut seed,
10182            );
10183        }
10184        let mid_drag_hash = tree.state_hash();
10185        assert_ne!(
10186            mid_drag_hash, initial_hash,
10187            "drag should have mutated the tree before the interrupt"
10188        );
10189        assert!(tree.validate().is_ok());
10190        assert_eq!(adapter.active_pointer_id(), Some(1));
10191
10192        // Resize interrupt mid-drag.
10193        let resize_dispatch = adapter.translate(
10194            &Event::Resize {
10195                width: 60,
10196                height: 24,
10197            },
10198            None,
10199        );
10200        let cancel = resize_dispatch
10201            .primary_event
10202            .as_ref()
10203            .expect("resize interrupt should emit a cancel semantic event");
10204        assert!(matches!(
10205            cancel.kind,
10206            PaneSemanticInputEventKind::Cancel {
10207                target: Some(actual),
10208                reason: PaneCancelReason::Programmatic
10209            } if actual == target
10210        ));
10211        assert_eq!(
10212            resize_dispatch.log.phase,
10213            PaneTerminalLifecyclePhase::ResizeInterrupt
10214        );
10215        assert_eq!(
10216            resize_dispatch.log.outcome,
10217            PaneTerminalLogOutcome::SemanticForwarded
10218        );
10219
10220        // The cancel transition carries no geometry, so the bridge yields no ops
10221        // and the tree is left exactly as the last drag sample left it.
10222        let cancel_transition = resize_dispatch
10223            .primary_transition
10224            .as_ref()
10225            .expect("cancel transition present");
10226        let cancel_ops = tree.operations_for_transition(cancel_transition, &layout, pressure);
10227        assert!(
10228            cancel_ops.is_empty(),
10229            "cancel transition must not mutate the live tree"
10230        );
10231        assert_eq!(tree.state_hash(), mid_drag_hash);
10232        assert!(tree.validate().is_ok());
10233
10234        // Adapter is back to idle with no active pointer.
10235        assert_eq!(adapter.active_pointer_id(), None);
10236        assert!(matches!(adapter.machine_state(), PaneDragResizeState::Idle));
10237
10238        // Reusable: a fresh gesture at the new viewport mutates the tree again.
10239        let new_layout = tree
10240            .solve_layout(Rect::new(0, 0, 60, 24))
10241            .expect("layout should solve at new size");
10242        let before_reuse = tree.state_hash();
10243        let applied = drive_horizontal_drag_fixed(
10244            &mut adapter,
10245            &mut tree,
10246            &new_layout,
10247            target,
10248            30,
10249            12,
10250            &[36, 42, 48],
10251            pressure,
10252            &mut seed,
10253        );
10254        assert!(applied > 0, "fresh gesture should apply operations");
10255        assert_ne!(
10256            tree.state_hash(),
10257            before_reuse,
10258            "adapter must remain usable after a resize interrupt"
10259        );
10260        assert!(tree.validate().is_ok());
10261        assert!(matches!(adapter.machine_state(), PaneDragResizeState::Idle));
10262    }
10263
10264    #[test]
10265    fn pane_terminal_adapter_survives_resize_storm_and_is_deterministic() {
10266        // Resize-storm stability at the live-tree level. The default config
10267        // cancels in-flight gestures on resize (matching real SIGWINCH behavior),
10268        // so a storm rapidly re-grabs the splitter and re-drags across many
10269        // viewport sizes. After every step the tree must stay structurally valid
10270        // and within ratio bounds, and the whole scripted storm must be
10271        // byte-for-byte deterministic across repeated runs.
10272        fn run_storm() -> u64 {
10273            let mut adapter = PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default())
10274                .expect("valid adapter");
10275            let mut tree = nested_pane_tree();
10276            let root_split = pane_id(1);
10277            let target = PaneResizeTarget {
10278                split_id: root_split,
10279                axis: SplitAxis::Horizontal,
10280            };
10281            let pressure = fixed_neutral_pressure();
10282            let mut seed = 5_200u64;
10283
10284            // Sizes the "window manager" cycles through during the storm.
10285            let sizes: [(u16, u16); 6] =
10286                [(50, 20), (80, 24), (40, 16), (120, 40), (30, 12), (100, 30)];
10287
10288            for (idx, &(w, h)) in sizes.iter().enumerate() {
10289                let layout = tree
10290                    .solve_layout(Rect::new(0, 0, w, h))
10291                    .expect("layout should solve under storm");
10292
10293                // Re-grab near 1/5 width and drag rightward to 3/5 width (always
10294                // increasing x, comfortably mid-rail to avoid child minimums).
10295                let down_x = (w / 5).max(2);
10296                let drag_x = (3 * w / 5).max(down_x + 2);
10297                let _ = apply_dispatch_fixed(
10298                    &mut tree,
10299                    &layout,
10300                    &adapter.translate(
10301                        &Event::Mouse(MouseEvent::new(
10302                            MouseEventKind::Down(MouseButton::Left),
10303                            down_x,
10304                            h / 2,
10305                        )),
10306                        Some(target),
10307                    ),
10308                    pressure,
10309                    &mut seed,
10310                );
10311                let _ = apply_dispatch_fixed(
10312                    &mut tree,
10313                    &layout,
10314                    &adapter.translate(
10315                        &Event::Mouse(MouseEvent::new(
10316                            MouseEventKind::Drag(MouseButton::Left),
10317                            drag_x,
10318                            h / 2,
10319                        )),
10320                        None,
10321                    ),
10322                    pressure,
10323                    &mut seed,
10324                );
10325                assert!(
10326                    tree.validate().is_ok(),
10327                    "tree invalid after drag at step {idx}"
10328                );
10329                let share = root_first_share_bps(&tree, root_split);
10330                assert!(
10331                    share > 0 && share < 10_000,
10332                    "split ratio escaped bounds at step {idx}: {share}"
10333                );
10334
10335                // Storm: a resize arrives mid-gesture and cancels it cleanly.
10336                let resize = adapter.translate(
10337                    &Event::Resize {
10338                        width: w,
10339                        height: h,
10340                    },
10341                    None,
10342                );
10343                if let Some(cancel_transition) = resize.primary_transition.as_ref() {
10344                    let cancel_ops =
10345                        tree.operations_for_transition(cancel_transition, &layout, pressure);
10346                    assert!(
10347                        cancel_ops.is_empty(),
10348                        "resize cancel must not mutate the tree at step {idx}"
10349                    );
10350                }
10351                assert!(matches!(adapter.machine_state(), PaneDragResizeState::Idle));
10352                assert_eq!(adapter.active_pointer_id(), None);
10353                assert!(
10354                    tree.validate().is_ok(),
10355                    "tree invalid after resize at step {idx}"
10356                );
10357            }
10358
10359            // A final complete gesture (with a real release) settles the tree.
10360            let (w, h) = (90u16, 30u16);
10361            let layout = tree
10362                .solve_layout(Rect::new(0, 0, w, h))
10363                .expect("final layout should solve");
10364            let _ = drive_horizontal_drag_fixed(
10365                &mut adapter,
10366                &mut tree,
10367                &layout,
10368                target,
10369                (w / 5).max(2),
10370                h / 2,
10371                &[w / 2, 3 * w / 5],
10372                pressure,
10373                &mut seed,
10374            );
10375            assert!(matches!(adapter.machine_state(), PaneDragResizeState::Idle));
10376            assert!(tree.validate().is_ok());
10377
10378            tree.state_hash()
10379        }
10380
10381        let first = run_storm();
10382        let second = run_storm();
10383        assert_eq!(
10384            first, second,
10385            "resize storm with repeated re-grabs must be deterministic"
10386        );
10387    }
10388
10389    #[test]
10390    fn pane_terminal_adapter_geometry_is_capability_invariant() {
10391        // Capability variance: the terminal adapter consumes already-parsed
10392        // `Event` values and makes no terminal-capability queries, so the same
10393        // logical drag must produce identical live-tree geometry whether the host
10394        // is a dumb terminal, a modern emulator, or tmux. We assert both halves:
10395        // (1) the capability profiles genuinely differ (non-vacuous), and (2) the
10396        // resulting tree state is identical across all three. This locks the
10397        // invariant that pane resize is capability-independent and would catch any
10398        // future regression that silently couples geometry to terminal caps.
10399        fn drag_under(
10400            over: ftui_core::capability_override::CapabilityOverride,
10401        ) -> (bool, bool, bool, u64) {
10402            ftui_core::capability_override::with_capability_override(over, || {
10403                let caps = ftui_core::capability_override::current_capabilities();
10404                let mut tree = nested_pane_tree();
10405                let layout = tree
10406                    .solve_layout(Rect::new(0, 0, 50, 20))
10407                    .expect("layout should solve");
10408                let target = PaneResizeTarget {
10409                    split_id: pane_id(1),
10410                    axis: SplitAxis::Horizontal,
10411                };
10412                let pressure = fixed_neutral_pressure();
10413                let mut seed = 6_300u64;
10414                let mut adapter = PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default())
10415                    .expect("valid adapter");
10416                let applied = drive_horizontal_drag_fixed(
10417                    &mut adapter,
10418                    &mut tree,
10419                    &layout,
10420                    target,
10421                    25,
10422                    10,
10423                    &[30, 36, 42],
10424                    pressure,
10425                    &mut seed,
10426                );
10427                assert!(
10428                    applied > 0,
10429                    "drag should apply operations under every profile"
10430                );
10431                (
10432                    caps.mouse_sgr,
10433                    caps.supports_true_color(),
10434                    caps.in_tmux,
10435                    tree.state_hash(),
10436                )
10437            })
10438        }
10439
10440        let (dumb_sgr, dumb_truecolor, _dumb_tmux, dumb_hash) =
10441            drag_under(ftui_core::capability_override::CapabilityOverride::dumb());
10442        let (modern_sgr, modern_truecolor, modern_tmux, modern_hash) =
10443            drag_under(ftui_core::capability_override::CapabilityOverride::modern());
10444        let (_tmux_sgr, _tmux_truecolor, tmux_tmux, tmux_hash) =
10445            drag_under(ftui_core::capability_override::CapabilityOverride::tmux());
10446
10447        // Non-vacuous: the three profiles really do present different caps.
10448        assert!(
10449            dumb_sgr != modern_sgr || dumb_truecolor != modern_truecolor,
10450            "dumb and modern profiles must differ in capabilities"
10451        );
10452        assert!(
10453            modern_tmux != tmux_tmux,
10454            "modern and tmux profiles must differ in the in_tmux flag"
10455        );
10456
10457        // Invariant: identical geometry regardless of terminal capabilities.
10458        assert_eq!(
10459            dumb_hash, modern_hash,
10460            "geometry must not depend on terminal capabilities"
10461        );
10462        assert_eq!(
10463            modern_hash, tmux_hash,
10464            "geometry must not depend on terminal capabilities"
10465        );
10466    }
10467
10468    #[test]
10469    fn pane_terminal_adapter_dispatch_log_traces_routing_and_failures() {
10470        // Diagnostic logs must capture event routing (the lifecycle phase of each
10471        // translated event) and failure context (deterministic ignore reasons), so
10472        // operators can reconstruct what the adapter did from the dispatch log
10473        // alone. This exercises both the happy routing path and two failure paths.
10474        let mut adapter =
10475            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
10476        let target = pane_target(SplitAxis::Horizontal);
10477
10478        // Failure path 1: wrong activation button is ignored with a precise reason.
10479        let wrong_button = adapter.translate(
10480            &Event::Mouse(MouseEvent::new(
10481                MouseEventKind::Down(MouseButton::Right),
10482                5,
10483                5,
10484            )),
10485            Some(target),
10486        );
10487        assert_eq!(
10488            wrong_button.log.phase,
10489            PaneTerminalLifecyclePhase::MouseDown
10490        );
10491        assert_eq!(
10492            wrong_button.log.outcome,
10493            PaneTerminalLogOutcome::Ignored(PaneTerminalIgnoredReason::ActivationButtonRequired)
10494        );
10495        assert!(wrong_button.primary_event.is_none());
10496        assert_eq!(adapter.active_pointer_id(), None);
10497
10498        // Routing: a real gesture progresses MouseDown -> MouseDrag -> MouseUp,
10499        // each forwarded with a monotonically increasing sequence number.
10500        let down = adapter.translate(
10501            &Event::Mouse(MouseEvent::new(
10502                MouseEventKind::Down(MouseButton::Left),
10503                25,
10504                10,
10505            )),
10506            Some(target),
10507        );
10508        assert_eq!(down.log.phase, PaneTerminalLifecyclePhase::MouseDown);
10509        assert_eq!(down.log.outcome, PaneTerminalLogOutcome::SemanticForwarded);
10510        assert_eq!(down.log.target, Some(target));
10511        assert_eq!(down.log.pointer_id, Some(1));
10512        let down_seq = down.log.sequence.expect("down sequence");
10513
10514        let drag = adapter.translate(
10515            &Event::Mouse(MouseEvent::new(
10516                MouseEventKind::Drag(MouseButton::Left),
10517                31,
10518                10,
10519            )),
10520            None,
10521        );
10522        assert_eq!(drag.log.phase, PaneTerminalLifecyclePhase::MouseDrag);
10523        assert_eq!(drag.log.outcome, PaneTerminalLogOutcome::SemanticForwarded);
10524        let drag_seq = drag.log.sequence.expect("drag sequence");
10525        assert!(drag_seq > down_seq, "sequence numbers must be monotonic");
10526
10527        let up = adapter.translate(
10528            &Event::Mouse(MouseEvent::new(
10529                MouseEventKind::Up(MouseButton::Left),
10530                31,
10531                10,
10532            )),
10533            None,
10534        );
10535        assert_eq!(up.log.phase, PaneTerminalLifecyclePhase::MouseUp);
10536        assert_eq!(up.log.outcome, PaneTerminalLogOutcome::SemanticForwarded);
10537        assert!(up.log.sequence.expect("up sequence") > drag_seq);
10538
10539        // Failure path 2: a resize with no active gesture is a clean no-op with a
10540        // precise reason rather than a spurious cancel.
10541        let idle_resize = adapter.translate(
10542            &Event::Resize {
10543                width: 80,
10544                height: 24,
10545            },
10546            None,
10547        );
10548        assert_eq!(
10549            idle_resize.log.phase,
10550            PaneTerminalLifecyclePhase::ResizeInterrupt
10551        );
10552        assert_eq!(
10553            idle_resize.log.outcome,
10554            PaneTerminalLogOutcome::Ignored(PaneTerminalIgnoredReason::ResizeNoop)
10555        );
10556        assert!(idle_resize.primary_event.is_none());
10557    }
10558
10559    #[test]
10560    fn pane_terminal_adapter_resize_preserves_gesture_when_cancel_disabled() {
10561        // Edge interruption, opposite branch: with cancel_on_resize disabled a
10562        // resize event is a deterministic no-op that leaves the active gesture
10563        // intact, so the drag can continue to completion afterwards.
10564        let config = PaneTerminalAdapterConfig {
10565            cancel_on_resize: false,
10566            ..PaneTerminalAdapterConfig::default()
10567        };
10568        let mut adapter = PaneTerminalAdapter::new(config).expect("valid adapter");
10569        let mut tree = nested_pane_tree();
10570        let layout = tree
10571            .solve_layout(Rect::new(0, 0, 50, 20))
10572            .expect("layout should solve");
10573        let root_split = pane_id(1);
10574        let target = PaneResizeTarget {
10575            split_id: root_split,
10576            axis: SplitAxis::Horizontal,
10577        };
10578        let pressure = fixed_neutral_pressure();
10579        let mut seed = 7_700u64;
10580
10581        // Arm + first drag sample.
10582        let _ = apply_dispatch_fixed(
10583            &mut tree,
10584            &layout,
10585            &adapter.translate(
10586                &Event::Mouse(MouseEvent::new(
10587                    MouseEventKind::Down(MouseButton::Left),
10588                    20,
10589                    10,
10590                )),
10591                Some(target),
10592            ),
10593            pressure,
10594            &mut seed,
10595        );
10596        let _ = apply_dispatch_fixed(
10597            &mut tree,
10598            &layout,
10599            &adapter.translate(
10600                &Event::Mouse(MouseEvent::new(
10601                    MouseEventKind::Drag(MouseButton::Left),
10602                    26,
10603                    10,
10604                )),
10605                None,
10606            ),
10607            pressure,
10608            &mut seed,
10609        );
10610        assert_eq!(adapter.active_pointer_id(), Some(1));
10611
10612        // Resize arrives mid-drag: ignored as a no-op, gesture survives.
10613        let resize = adapter.translate(
10614            &Event::Resize {
10615                width: 50,
10616                height: 20,
10617            },
10618            None,
10619        );
10620        assert!(resize.primary_event.is_none());
10621        assert!(resize.primary_transition.is_none());
10622        assert_eq!(
10623            resize.log.outcome,
10624            PaneTerminalLogOutcome::Ignored(PaneTerminalIgnoredReason::ResizeNoop)
10625        );
10626        assert_eq!(
10627            adapter.active_pointer_id(),
10628            Some(1),
10629            "gesture must survive the resize when cancel_on_resize is disabled"
10630        );
10631
10632        // The drag continues and a release commits cleanly.
10633        let before_finish = tree.state_hash();
10634        for x in [32u16, 38] {
10635            let _ = apply_dispatch_fixed(
10636                &mut tree,
10637                &layout,
10638                &adapter.translate(
10639                    &Event::Mouse(MouseEvent::new(
10640                        MouseEventKind::Drag(MouseButton::Left),
10641                        x,
10642                        10,
10643                    )),
10644                    None,
10645                ),
10646                pressure,
10647                &mut seed,
10648            );
10649        }
10650        let _ = apply_dispatch_fixed(
10651            &mut tree,
10652            &layout,
10653            &adapter.translate(
10654                &Event::Mouse(MouseEvent::new(
10655                    MouseEventKind::Up(MouseButton::Left),
10656                    38,
10657                    10,
10658                )),
10659                None,
10660            ),
10661            pressure,
10662            &mut seed,
10663        );
10664        assert_ne!(
10665            tree.state_hash(),
10666            before_finish,
10667            "the surviving gesture should keep mutating the tree"
10668        );
10669        assert!(matches!(adapter.machine_state(), PaneDragResizeState::Idle));
10670        assert!(tree.validate().is_ok());
10671    }
10672
10673    #[test]
10674    fn pane_terminal_adapter_focus_loss_emits_cancel() {
10675        let mut adapter =
10676            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
10677        let target = pane_target(SplitAxis::Vertical);
10678
10679        let down = Event::Mouse(MouseEvent::new(
10680            MouseEventKind::Down(MouseButton::Left),
10681            3,
10682            9,
10683        ));
10684        let _ = adapter.translate(&down, Some(target));
10685        assert_eq!(adapter.active_pointer_id(), Some(1));
10686
10687        let cancel_dispatch = adapter.translate(&Event::Focus(false), None);
10688        let cancel_event = cancel_dispatch
10689            .primary_event
10690            .as_ref()
10691            .expect("focus-loss cancel event");
10692        assert!(matches!(
10693            cancel_event.kind,
10694            PaneSemanticInputEventKind::Cancel {
10695                target: Some(actual_target),
10696                reason: PaneCancelReason::FocusLost
10697            } if actual_target == target
10698        ));
10699        assert_eq!(adapter.active_pointer_id(), None);
10700        assert!(matches!(adapter.machine_state(), PaneDragResizeState::Idle));
10701    }
10702
10703    #[test]
10704    fn pane_terminal_adapter_recovers_missing_mouse_up() {
10705        let mut adapter =
10706            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
10707        let first_target = pane_target(SplitAxis::Horizontal);
10708        let second_target = pane_target(SplitAxis::Vertical);
10709
10710        let first_down = Event::Mouse(MouseEvent::new(
10711            MouseEventKind::Down(MouseButton::Left),
10712            5,
10713            5,
10714        ));
10715        let _ = adapter.translate(&first_down, Some(first_target));
10716
10717        let second_down = Event::Mouse(MouseEvent::new(
10718            MouseEventKind::Down(MouseButton::Left),
10719            8,
10720            11,
10721        ));
10722        let dispatch = adapter.translate(&second_down, Some(second_target));
10723        let recovery = dispatch
10724            .recovery_event
10725            .as_ref()
10726            .expect("recovery cancel expected");
10727        assert!(matches!(
10728            recovery.kind,
10729            PaneSemanticInputEventKind::Cancel {
10730                target: Some(actual_target),
10731                reason: PaneCancelReason::PointerCancel
10732            } if actual_target == first_target
10733        ));
10734        let primary = dispatch
10735            .primary_event
10736            .as_ref()
10737            .expect("second pointer down expected");
10738        assert!(matches!(
10739            primary.kind,
10740            PaneSemanticInputEventKind::PointerDown {
10741                target: actual_target,
10742                pointer_id: 1,
10743                button: PanePointerButton::Primary,
10744                position
10745            } if actual_target == second_target && position == PanePointerPosition::new(8, 11)
10746        ));
10747        assert_eq!(recovery.sequence, 2);
10748        assert_eq!(primary.sequence, 3);
10749        assert!(matches!(
10750            dispatch.log.outcome,
10751            PaneTerminalLogOutcome::SemanticForwardedAfterRecovery
10752        ));
10753        assert_eq!(dispatch.log.recovery_cancel_sequence, Some(2));
10754    }
10755
10756    #[test]
10757    fn pane_terminal_adapter_modifier_parity() {
10758        let mut adapter =
10759            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
10760        let target = pane_target(SplitAxis::Horizontal);
10761
10762        let mouse = MouseEvent::new(MouseEventKind::Down(MouseButton::Left), 1, 2)
10763            .with_modifiers(Modifiers::SHIFT | Modifiers::ALT | Modifiers::CTRL | Modifiers::SUPER);
10764        let dispatch = adapter.translate(&Event::Mouse(mouse), Some(target));
10765        let event = dispatch.primary_event.expect("semantic event");
10766        assert!(event.modifiers.shift);
10767        assert!(event.modifiers.alt);
10768        assert!(event.modifiers.ctrl);
10769        assert!(event.modifiers.meta);
10770    }
10771
10772    #[test]
10773    fn pane_terminal_adapter_keyboard_resize_mapping() {
10774        let mut adapter =
10775            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
10776        let target = pane_target(SplitAxis::Horizontal);
10777
10778        let key = KeyEvent::new(KeyCode::Right);
10779        let dispatch = adapter.translate(&Event::Key(key), Some(target));
10780        let event = dispatch.primary_event.expect("keyboard resize event");
10781        assert!(matches!(
10782            event.kind,
10783            PaneSemanticInputEventKind::KeyboardResize {
10784                target: actual_target,
10785                direction: PaneResizeDirection::Increase,
10786                units: 1
10787            } if actual_target == target
10788        ));
10789
10790        let shifted = KeyEvent::new(KeyCode::Right).with_modifiers(Modifiers::SHIFT);
10791        let shifted_dispatch = adapter.translate(&Event::Key(shifted), Some(target));
10792        let shifted_event = shifted_dispatch
10793            .primary_event
10794            .expect("shifted resize event");
10795        assert!(matches!(
10796            shifted_event.kind,
10797            PaneSemanticInputEventKind::KeyboardResize {
10798                direction: PaneResizeDirection::Increase,
10799                units: 5,
10800                ..
10801            }
10802        ));
10803        assert!(shifted_event.modifiers.shift);
10804    }
10805
10806    #[test]
10807    fn pane_terminal_adapter_keyboard_resize_requires_focus() {
10808        let mut adapter =
10809            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
10810        let target = pane_target(SplitAxis::Horizontal);
10811
10812        let _ = adapter.translate(&Event::Focus(false), None);
10813        assert!(!adapter.window_focused());
10814
10815        let unfocused = adapter.translate(&Event::Key(KeyEvent::new(KeyCode::Right)), Some(target));
10816        assert!(unfocused.primary_event.is_none());
10817        assert!(matches!(
10818            unfocused.log.outcome,
10819            PaneTerminalLogOutcome::Ignored(PaneTerminalIgnoredReason::WindowNotFocused)
10820        ));
10821
10822        let _ = adapter.translate(&Event::Focus(true), None);
10823        assert!(adapter.window_focused());
10824
10825        let focused = adapter.translate(&Event::Key(KeyEvent::new(KeyCode::Right)), Some(target));
10826        assert!(focused.primary_event.is_some());
10827    }
10828
10829    #[test]
10830    fn pane_terminal_adapter_drag_updates_are_coalesced() {
10831        let mut adapter = PaneTerminalAdapter::new(PaneTerminalAdapterConfig {
10832            drag_update_coalesce_distance: 2,
10833            ..PaneTerminalAdapterConfig::default()
10834        })
10835        .expect("valid adapter");
10836        let target = pane_target(SplitAxis::Horizontal);
10837
10838        let down = Event::Mouse(MouseEvent::new(
10839            MouseEventKind::Down(MouseButton::Left),
10840            10,
10841            4,
10842        ));
10843        let _ = adapter.translate(&down, Some(target));
10844
10845        let drag_start = Event::Mouse(MouseEvent::new(
10846            MouseEventKind::Drag(MouseButton::Left),
10847            14,
10848            4,
10849        ));
10850        let started = adapter.translate(&drag_start, None);
10851        assert!(started.primary_event.is_some());
10852        assert!(matches!(
10853            adapter.machine_state(),
10854            PaneDragResizeState::Dragging { .. }
10855        ));
10856
10857        let coalesced = Event::Mouse(MouseEvent::new(
10858            MouseEventKind::Drag(MouseButton::Left),
10859            15,
10860            4,
10861        ));
10862        let coalesced_dispatch = adapter.translate(&coalesced, None);
10863        assert!(coalesced_dispatch.primary_event.is_none());
10864        assert!(matches!(
10865            coalesced_dispatch.log.outcome,
10866            PaneTerminalLogOutcome::Ignored(PaneTerminalIgnoredReason::DragCoalesced)
10867        ));
10868
10869        let forwarded = Event::Mouse(MouseEvent::new(
10870            MouseEventKind::Drag(MouseButton::Left),
10871            16,
10872            4,
10873        ));
10874        let forwarded_dispatch = adapter.translate(&forwarded, None);
10875        let forwarded_event = forwarded_dispatch
10876            .primary_event
10877            .as_ref()
10878            .expect("coalesced movement should flush once threshold reached");
10879        assert!(matches!(
10880            forwarded_event.kind,
10881            PaneSemanticInputEventKind::PointerMove {
10882                delta_x: 2,
10883                delta_y: 0,
10884                ..
10885            }
10886        ));
10887    }
10888
10889    #[test]
10890    fn pane_terminal_adapter_motion_tracks_direction_changes() {
10891        let mut adapter =
10892            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
10893        let target = pane_target(SplitAxis::Horizontal);
10894
10895        let down = Event::Mouse(MouseEvent::new(
10896            MouseEventKind::Down(MouseButton::Left),
10897            10,
10898            4,
10899        ));
10900        let _ = adapter.translate(&down, Some(target));
10901
10902        let drag_forward = Event::Mouse(MouseEvent::new(
10903            MouseEventKind::Drag(MouseButton::Left),
10904            14,
10905            4,
10906        ));
10907        let forward_dispatch = adapter.translate(&drag_forward, None);
10908        let forward_motion = forward_dispatch
10909            .motion
10910            .expect("forward drag should emit motion metadata");
10911        assert_eq!(forward_motion.direction_changes, 0);
10912
10913        let drag_reverse = Event::Mouse(MouseEvent::new(
10914            MouseEventKind::Drag(MouseButton::Left),
10915            12,
10916            4,
10917        ));
10918        let reverse_dispatch = adapter.translate(&drag_reverse, None);
10919        let reverse_motion = reverse_dispatch
10920            .motion
10921            .expect("reverse drag should emit motion metadata");
10922        assert_eq!(reverse_motion.direction_changes, 1);
10923
10924        let up = Event::Mouse(MouseEvent::new(
10925            MouseEventKind::Up(MouseButton::Left),
10926            12,
10927            4,
10928        ));
10929        let up_dispatch = adapter.translate(&up, None);
10930        let up_motion = up_dispatch
10931            .motion
10932            .expect("release should include cumulative motion metadata");
10933        assert_eq!(up_motion.direction_changes, 1);
10934    }
10935
10936    #[test]
10937    fn pane_terminal_adapter_drag_and_moved_share_motion_bookkeeping() {
10938        // `Drag` and `Moved` forward identical `PointerMove` semantics through
10939        // the same `apply_pointer_motion` path; only the lifecycle phase differs.
10940        // Driving the identical motion sequence through each arm must therefore
10941        // produce identical motion metadata at every step (the extraction's
10942        // equivalence guarantee).
10943        let run = |moved: bool| {
10944            let mut adapter = PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default())
10945                .expect("valid adapter");
10946            let target = pane_target(SplitAxis::Horizontal);
10947            let down = Event::Mouse(MouseEvent::new(
10948                MouseEventKind::Down(MouseButton::Left),
10949                10,
10950                4,
10951            ));
10952            let _ = adapter.translate(&down, Some(target));
10953            let mut motions = Vec::new();
10954            for (x, y) in [(14u16, 4u16), (12, 4), (16, 4)] {
10955                let kind = if moved {
10956                    MouseEventKind::Moved
10957                } else {
10958                    MouseEventKind::Drag(MouseButton::Left)
10959                };
10960                let dispatch = adapter.translate(&Event::Mouse(MouseEvent::new(kind, x, y)), None);
10961                assert!(dispatch.primary_event.is_some());
10962                motions.push(dispatch.motion.expect("motion metadata present"));
10963            }
10964            motions
10965        };
10966
10967        // `speed` divides by the wall-clock time since the press, so the two
10968        // runs agree on it only when they happen to take equally long (they
10969        // did not under DSR load: 666 vs 4000). The bookkeeping both arms
10970        // share is clock-independent: compare that, and require a speed.
10971        let bookkeeping = |motions: &[PaneMotionVector]| {
10972            motions
10973                .iter()
10974                .map(|motion| (motion.delta_x, motion.delta_y, motion.direction_changes))
10975                .collect::<Vec<_>>()
10976        };
10977        let via_drag = run(false);
10978        let via_moved = run(true);
10979        assert_eq!(bookkeeping(&via_drag), bookkeeping(&via_moved));
10980        assert!(
10981            via_drag
10982                .iter()
10983                .chain(&via_moved)
10984                .all(|motion| motion.speed > 0.0)
10985        );
10986        // Sanity: the reverse step (14->12) registered a direction change in both.
10987        assert_eq!(via_drag[1].direction_changes, 1);
10988    }
10989
10990    #[test]
10991    fn pane_terminal_adapter_translate_with_handles_resolves_target() {
10992        let tree = nested_pane_tree();
10993        let layout = tree
10994            .solve_layout(Rect::new(0, 0, 50, 20))
10995            .expect("layout should solve");
10996        let handles =
10997            pane_terminal_splitter_handles(&tree, &layout, PANE_TERMINAL_DEFAULT_HIT_THICKNESS);
10998        let mut adapter =
10999            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
11000
11001        let down = Event::Mouse(MouseEvent::new(
11002            MouseEventKind::Down(MouseButton::Left),
11003            25,
11004            10,
11005        ));
11006        let dispatch = adapter.translate_with_handles(&down, &handles);
11007        let event = dispatch
11008            .primary_event
11009            .as_ref()
11010            .expect("pointer down should be routed from handles");
11011        assert!(matches!(
11012            event.kind,
11013            PaneSemanticInputEventKind::PointerDown {
11014                target:
11015                    PaneResizeTarget {
11016                        split_id,
11017                        axis: SplitAxis::Horizontal
11018                    },
11019                ..
11020            } if split_id == pane_id(1)
11021        ));
11022    }
11023
11024    #[test]
11025    fn model_update() {
11026        let mut model = TestModel { value: 0 };
11027        model.update(TestMsg::Increment);
11028        assert_eq!(model.value, 1);
11029        model.update(TestMsg::Decrement);
11030        assert_eq!(model.value, 0);
11031        assert!(matches!(model.update(TestMsg::Quit), Cmd::Quit));
11032    }
11033
11034    #[test]
11035    fn model_init_default() {
11036        let mut model = TestModel { value: 0 };
11037        let cmd = model.init();
11038        assert!(matches!(cmd, Cmd::None));
11039    }
11040
11041    // Resize coalescer behavior is covered by resize_coalescer.rs tests.
11042
11043    // =========================================================================
11044    // DETERMINISM TESTS - Program loop determinism (bd-2nu8.10.1)
11045    // =========================================================================
11046
11047    #[test]
11048    fn cmd_sequence_executes_in_order() {
11049        // Verify that Cmd::Sequence executes commands in declared order
11050        use crate::simulator::ProgramSimulator;
11051
11052        struct SeqModel {
11053            trace: Vec<i32>,
11054        }
11055
11056        #[derive(Debug)]
11057        enum SeqMsg {
11058            Append(i32),
11059            TriggerSequence,
11060        }
11061
11062        impl From<Event> for SeqMsg {
11063            fn from(_: Event) -> Self {
11064                SeqMsg::Append(0)
11065            }
11066        }
11067
11068        impl Model for SeqModel {
11069            type Message = SeqMsg;
11070
11071            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
11072                match msg {
11073                    SeqMsg::Append(n) => {
11074                        self.trace.push(n);
11075                        Cmd::none()
11076                    }
11077                    SeqMsg::TriggerSequence => Cmd::sequence(vec![
11078                        Cmd::msg(SeqMsg::Append(1)),
11079                        Cmd::msg(SeqMsg::Append(2)),
11080                        Cmd::msg(SeqMsg::Append(3)),
11081                    ]),
11082                }
11083            }
11084
11085            fn view(&self, _frame: &mut Frame) {}
11086        }
11087
11088        let mut sim = ProgramSimulator::new(SeqModel { trace: vec![] });
11089        sim.init();
11090        sim.send(SeqMsg::TriggerSequence);
11091
11092        assert_eq!(sim.model().trace, vec![1, 2, 3]);
11093    }
11094
11095    #[test]
11096    fn cmd_batch_executes_all_in_order_today() {
11097        // Cmd::Batch runs every command, and today in order like Sequence, as
11098        // the README's command table states. Concurrent batches would change
11099        // both this test and that row.
11100        use crate::simulator::ProgramSimulator;
11101
11102        struct BatchModel {
11103            values: Vec<i32>,
11104        }
11105
11106        #[derive(Debug)]
11107        enum BatchMsg {
11108            Add(i32),
11109            TriggerBatch,
11110        }
11111
11112        impl From<Event> for BatchMsg {
11113            fn from(_: Event) -> Self {
11114                BatchMsg::Add(0)
11115            }
11116        }
11117
11118        impl Model for BatchModel {
11119            type Message = BatchMsg;
11120
11121            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
11122                match msg {
11123                    BatchMsg::Add(n) => {
11124                        self.values.push(n);
11125                        Cmd::none()
11126                    }
11127                    BatchMsg::TriggerBatch => Cmd::batch(vec![
11128                        Cmd::msg(BatchMsg::Add(10)),
11129                        Cmd::msg(BatchMsg::Add(20)),
11130                        Cmd::msg(BatchMsg::Add(30)),
11131                    ]),
11132                }
11133            }
11134
11135            fn view(&self, _frame: &mut Frame) {}
11136        }
11137
11138        let mut sim = ProgramSimulator::new(BatchModel { values: vec![] });
11139        sim.init();
11140        sim.send(BatchMsg::TriggerBatch);
11141
11142        assert_eq!(sim.model().values, [10, 20, 30]);
11143    }
11144
11145    #[test]
11146    fn cmd_sequence_stops_on_quit() {
11147        // Verify that Cmd::Sequence stops processing after Quit
11148        use crate::simulator::ProgramSimulator;
11149
11150        struct SeqQuitModel {
11151            trace: Vec<i32>,
11152        }
11153
11154        #[derive(Debug)]
11155        enum SeqQuitMsg {
11156            Append(i32),
11157            TriggerSequenceWithQuit,
11158        }
11159
11160        impl From<Event> for SeqQuitMsg {
11161            fn from(_: Event) -> Self {
11162                SeqQuitMsg::Append(0)
11163            }
11164        }
11165
11166        impl Model for SeqQuitModel {
11167            type Message = SeqQuitMsg;
11168
11169            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
11170                match msg {
11171                    SeqQuitMsg::Append(n) => {
11172                        self.trace.push(n);
11173                        Cmd::none()
11174                    }
11175                    SeqQuitMsg::TriggerSequenceWithQuit => Cmd::sequence(vec![
11176                        Cmd::msg(SeqQuitMsg::Append(1)),
11177                        Cmd::quit(),
11178                        Cmd::msg(SeqQuitMsg::Append(2)), // Should not execute
11179                    ]),
11180                }
11181            }
11182
11183            fn view(&self, _frame: &mut Frame) {}
11184        }
11185
11186        let mut sim = ProgramSimulator::new(SeqQuitModel { trace: vec![] });
11187        sim.init();
11188        sim.send(SeqQuitMsg::TriggerSequenceWithQuit);
11189
11190        assert_eq!(sim.model().trace, vec![1]);
11191        assert!(!sim.is_running());
11192    }
11193
11194    #[test]
11195    fn identical_input_produces_identical_state() {
11196        // Verify deterministic state transitions
11197        use crate::simulator::ProgramSimulator;
11198
11199        fn run_scenario() -> Vec<i32> {
11200            struct DetModel {
11201                values: Vec<i32>,
11202            }
11203
11204            #[derive(Debug, Clone)]
11205            enum DetMsg {
11206                Add(i32),
11207                Double,
11208            }
11209
11210            impl From<Event> for DetMsg {
11211                fn from(_: Event) -> Self {
11212                    DetMsg::Add(1)
11213                }
11214            }
11215
11216            impl Model for DetModel {
11217                type Message = DetMsg;
11218
11219                fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
11220                    match msg {
11221                        DetMsg::Add(n) => {
11222                            self.values.push(n);
11223                            Cmd::none()
11224                        }
11225                        DetMsg::Double => {
11226                            if let Some(&last) = self.values.last() {
11227                                self.values.push(last * 2);
11228                            }
11229                            Cmd::none()
11230                        }
11231                    }
11232                }
11233
11234                fn view(&self, _frame: &mut Frame) {}
11235            }
11236
11237            let mut sim = ProgramSimulator::new(DetModel { values: vec![] });
11238            sim.init();
11239            sim.send(DetMsg::Add(5));
11240            sim.send(DetMsg::Double);
11241            sim.send(DetMsg::Add(3));
11242            sim.send(DetMsg::Double);
11243
11244            sim.model().values.clone()
11245        }
11246
11247        // Run the same scenario multiple times
11248        let run1 = run_scenario();
11249        let run2 = run_scenario();
11250        let run3 = run_scenario();
11251
11252        assert_eq!(run1, run2);
11253        assert_eq!(run2, run3);
11254        assert_eq!(run1, vec![5, 10, 3, 6]);
11255    }
11256
11257    #[test]
11258    fn identical_state_produces_identical_render() {
11259        // Verify consistent render outputs for identical inputs
11260        use crate::simulator::ProgramSimulator;
11261
11262        struct RenderModel {
11263            counter: i32,
11264        }
11265
11266        #[derive(Debug)]
11267        enum RenderMsg {
11268            Set(i32),
11269        }
11270
11271        impl From<Event> for RenderMsg {
11272            fn from(_: Event) -> Self {
11273                RenderMsg::Set(0)
11274            }
11275        }
11276
11277        impl Model for RenderModel {
11278            type Message = RenderMsg;
11279
11280            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
11281                match msg {
11282                    RenderMsg::Set(n) => {
11283                        self.counter = n;
11284                        Cmd::none()
11285                    }
11286                }
11287            }
11288
11289            fn view(&self, frame: &mut Frame) {
11290                let text = format!("Value: {}", self.counter);
11291                for (i, c) in text.chars().enumerate() {
11292                    if (i as u16) < frame.width() {
11293                        use ftui_render::cell::Cell;
11294                        frame.buffer.set_raw(i as u16, 0, Cell::from_char(c));
11295                    }
11296                }
11297            }
11298        }
11299
11300        // Create two simulators with the same state
11301        let mut sim1 = ProgramSimulator::new(RenderModel { counter: 42 });
11302        let mut sim2 = ProgramSimulator::new(RenderModel { counter: 42 });
11303
11304        let buf1 = sim1.capture_frame(80, 24);
11305        let buf2 = sim2.capture_frame(80, 24);
11306
11307        // Compare buffer contents
11308        for y in 0..24 {
11309            for x in 0..80 {
11310                let cell1 = buf1.get(x, y).unwrap();
11311                let cell2 = buf2.get(x, y).unwrap();
11312                assert_eq!(
11313                    cell1.content.as_char(),
11314                    cell2.content.as_char(),
11315                    "Mismatch at ({}, {})",
11316                    x,
11317                    y
11318                );
11319            }
11320        }
11321    }
11322
11323    // Resize coalescer timing invariants are covered in resize_coalescer.rs tests.
11324
11325    #[test]
11326    fn cmd_log_creates_log_command() {
11327        let cmd: Cmd<TestMsg> = Cmd::log("test message");
11328        assert!(
11329            matches!(cmd, Cmd::Log { text, mode: SanitizeMode::Strip } if text == "test message")
11330        );
11331    }
11332
11333    #[test]
11334    fn cmd_log_from_string() {
11335        let msg = String::from("dynamic message");
11336        let cmd: Cmd<TestMsg> = Cmd::log(msg);
11337        assert!(
11338            matches!(cmd, Cmd::Log { text, mode: SanitizeMode::Strip } if text == "dynamic message")
11339        );
11340    }
11341
11342    #[test]
11343    fn cmd_log_markers_keep_the_explicit_policy() {
11344        for (marker, expected) in [
11345            (Text::sanitized("hello"), SanitizeMode::Strip),
11346            (Text::sgr_only("\x1b[31mhello"), SanitizeMode::SgrOnly),
11347            (Text::trusted("\x1b[2Jhello"), SanitizeMode::Raw),
11348        ] {
11349            let expected_text = marker.as_str().to_owned();
11350            let cmd: Cmd<TestMsg> = Cmd::log_text(marker);
11351            assert_eq!(cmd.type_name(), "Log");
11352            assert!(
11353                matches!(cmd, Cmd::Log { text, mode } if text == expected_text && mode == expected)
11354            );
11355        }
11356    }
11357
11358    #[test]
11359    fn program_simulator_logs_jsonl_with_seed_and_run_id() {
11360        // Ensure ProgramSimulator captures JSONL log lines with run_id/seed.
11361        use crate::simulator::ProgramSimulator;
11362
11363        struct LogModel {
11364            run_id: &'static str,
11365            seed: u64,
11366        }
11367
11368        #[derive(Debug)]
11369        enum LogMsg {
11370            Emit,
11371        }
11372
11373        impl From<Event> for LogMsg {
11374            fn from(_: Event) -> Self {
11375                LogMsg::Emit
11376            }
11377        }
11378
11379        impl Model for LogModel {
11380            type Message = LogMsg;
11381
11382            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
11383                let line = format!(
11384                    r#"{{"event":"test","run_id":"{}","seed":{}}}"#,
11385                    self.run_id, self.seed
11386                );
11387                Cmd::log(line)
11388            }
11389
11390            fn view(&self, _frame: &mut Frame) {}
11391        }
11392
11393        let mut sim = ProgramSimulator::new(LogModel {
11394            run_id: "test-run-001",
11395            seed: 4242,
11396        });
11397        sim.init();
11398        sim.send(LogMsg::Emit);
11399
11400        let logs = sim.logs();
11401        assert_eq!(logs.len(), 1);
11402        assert!(logs[0].contains(r#""run_id":"test-run-001""#));
11403        assert!(logs[0].contains(r#""seed":4242"#));
11404    }
11405
11406    #[test]
11407    fn cmd_sequence_single_unwraps() {
11408        let cmd: Cmd<TestMsg> = Cmd::sequence(vec![Cmd::quit()]);
11409        // Single element sequence should unwrap to the inner command
11410        assert!(matches!(cmd, Cmd::Quit));
11411    }
11412
11413    #[test]
11414    fn cmd_sequence_multiple() {
11415        let cmd: Cmd<TestMsg> = Cmd::sequence(vec![Cmd::none(), Cmd::quit()]);
11416        assert!(matches!(cmd, Cmd::Sequence(_)));
11417    }
11418
11419    #[test]
11420    fn cmd_default_is_none() {
11421        let cmd: Cmd<TestMsg> = Cmd::default();
11422        assert!(matches!(cmd, Cmd::None));
11423    }
11424
11425    #[test]
11426    fn cmd_debug_all_variants() {
11427        // Test Debug impl for all variants
11428        let none: Cmd<TestMsg> = Cmd::none();
11429        assert_eq!(format!("{none:?}"), "None");
11430
11431        let quit: Cmd<TestMsg> = Cmd::quit();
11432        assert_eq!(format!("{quit:?}"), "Quit");
11433
11434        let msg: Cmd<TestMsg> = Cmd::msg(TestMsg::Increment);
11435        assert!(format!("{msg:?}").starts_with("Msg("));
11436
11437        let batch: Cmd<TestMsg> = Cmd::batch(vec![Cmd::none(), Cmd::none()]);
11438        assert!(format!("{batch:?}").starts_with("Batch("));
11439
11440        let seq: Cmd<TestMsg> = Cmd::sequence(vec![Cmd::none(), Cmd::none()]);
11441        assert!(format!("{seq:?}").starts_with("Sequence("));
11442
11443        let tick: Cmd<TestMsg> = Cmd::tick(Duration::from_secs(1));
11444        assert!(format!("{tick:?}").starts_with("Tick("));
11445
11446        let log: Cmd<TestMsg> = Cmd::log("test");
11447        assert!(format!("{log:?}").starts_with("Log("));
11448    }
11449
11450    #[test]
11451    fn program_config_with_budget() {
11452        let budget = FrameBudgetConfig {
11453            total: Duration::from_millis(50),
11454            ..Default::default()
11455        };
11456        let config = ProgramConfig::default().with_budget(budget);
11457        assert_eq!(config.budget.total, Duration::from_millis(50));
11458    }
11459
11460    #[test]
11461    fn load_governor_default_is_enabled() {
11462        let config = LoadGovernorConfig::default();
11463        assert!(config.enabled);
11464        assert_eq!(
11465            config.budget_controller.degradation_floor,
11466            DegradationLevel::SimpleBorders
11467        );
11468    }
11469
11470    #[test]
11471    fn program_config_load_governor_builders() {
11472        let governor = LoadGovernorConfig::disabled().with_enabled(true);
11473        let config = ProgramConfig::default().with_load_governor(governor);
11474        assert!(config.load_governor.enabled);
11475
11476        let config = config.without_load_governor();
11477        assert!(!config.load_governor.enabled);
11478    }
11479
11480    fn governor_observation(
11481        frame_time_ms: f64,
11482        in_flight: u64,
11483        dropped: u64,
11484        degradation: DegradationLevel,
11485        resize_coalescing_active: bool,
11486        strict_semantics_violation: bool,
11487    ) -> LoadGovernorObservation {
11488        LoadGovernorObservation {
11489            frame_time_us: frame_time_ms * 1_000.0,
11490            budget_us: 16_000.0,
11491            degradation,
11492            queue: crate::effect_system::QueueTelemetry {
11493                // Invariant: in_flight = enqueued - processed (drops are
11494                // rejected before ever being counted as enqueued).
11495                enqueued: in_flight,
11496                processed: 0,
11497                dropped,
11498                high_water: in_flight,
11499                in_flight,
11500            },
11501            resize_coalescing_active,
11502            strict_semantics_violation,
11503        }
11504    }
11505
11506    fn test_load_governor(max_queue_depth: usize, recovery_intervals: u8) -> LoadGovernorState {
11507        let policy = LoadGovernorPolicy {
11508            recovery_intervals,
11509            ..Default::default()
11510        };
11511        LoadGovernorState::new(
11512            LoadGovernorConfig::enabled().with_policy(policy),
11513            max_queue_depth,
11514        )
11515    }
11516
11517    #[test]
11518    fn load_governor_policy_defaults_match_runtime_contract() {
11519        let policy = LoadGovernorPolicy::default().normalized();
11520
11521        assert_eq!(policy.stressed_queue_watermark, 0.5);
11522        assert_eq!(policy.degraded_queue_watermark, 0.8);
11523        assert_eq!(policy.recovery_queue_watermark, 0.25);
11524        assert_eq!(policy.recovery_intervals, 3);
11525        assert_eq!(policy.budget_overrun_soft_ratio, 1.0);
11526    }
11527
11528    #[test]
11529    fn load_governor_classifies_queue_watermarks_and_recovery() {
11530        let mut governor = test_load_governor(100, 2);
11531
11532        let steady = governor.observe(governor_observation(
11533            8.0,
11534            0,
11535            0,
11536            DegradationLevel::Full,
11537            false,
11538            false,
11539        ));
11540        assert_eq!(steady.mode, RuntimeLoadMode::Healthy);
11541        assert_eq!(steady.pressure_class, RuntimePressureClass::SteadyState);
11542        assert_eq!(steady.disposition, RuntimeWorkDisposition::AdmitAll);
11543
11544        let stressed = governor.observe(governor_observation(
11545            8.0,
11546            50,
11547            0,
11548            DegradationLevel::Full,
11549            false,
11550            false,
11551        ));
11552        assert_eq!(stressed.mode, RuntimeLoadMode::Stressed);
11553        assert_eq!(stressed.pressure_class, RuntimePressureClass::SoftOverload);
11554        assert_eq!(
11555            stressed.disposition,
11556            RuntimeWorkDisposition::CoalesceVisibleDeferBackground
11557        );
11558        assert_eq!(stressed.reason_code, "queue_stressed_watermark");
11559
11560        let degraded = governor.observe(governor_observation(
11561            8.0,
11562            80,
11563            0,
11564            DegradationLevel::Full,
11565            false,
11566            false,
11567        ));
11568        assert_eq!(degraded.mode, RuntimeLoadMode::Degraded);
11569        assert_eq!(degraded.pressure_class, RuntimePressureClass::HardOverload);
11570        assert_eq!(
11571            degraded.disposition,
11572            RuntimeWorkDisposition::DeferBackgroundDropBestEffort
11573        );
11574        assert_eq!(degraded.reason_code, "queue_degraded_watermark");
11575
11576        let recovery_pending = governor.observe(governor_observation(
11577            8.0,
11578            10,
11579            0,
11580            DegradationLevel::Full,
11581            false,
11582            false,
11583        ));
11584        assert_eq!(recovery_pending.mode, RuntimeLoadMode::Degraded);
11585        assert_eq!(recovery_pending.reason_code, "recovery_hysteresis_pending");
11586        assert_eq!(recovery_pending.recovery_intervals_observed, 1);
11587
11588        let recovered = governor.observe(governor_observation(
11589            8.0,
11590            10,
11591            0,
11592            DegradationLevel::Full,
11593            false,
11594            false,
11595        ));
11596        assert_eq!(recovered.mode, RuntimeLoadMode::Recovered);
11597        assert_eq!(recovered.reason_code, "recovery_hysteresis_satisfied");
11598        assert_eq!(
11599            recovered.disposition,
11600            RuntimeWorkDisposition::ReadmitAfterHysteresis
11601        );
11602
11603        let healthy = governor.observe(governor_observation(
11604            8.0,
11605            10,
11606            0,
11607            DegradationLevel::Full,
11608            false,
11609            false,
11610        ));
11611        assert_eq!(healthy.mode, RuntimeLoadMode::Healthy);
11612        assert_eq!(healthy.reason_code, "recovered_interval_closed");
11613    }
11614
11615    #[test]
11616    fn load_governor_uses_uncapped_budget_pressure_fallback() {
11617        let mut governor = test_load_governor(0, 2);
11618
11619        let stressed = governor.observe(governor_observation(
11620            20.0,
11621            0,
11622            0,
11623            DegradationLevel::Full,
11624            false,
11625            false,
11626        ));
11627        assert_eq!(stressed.mode, RuntimeLoadMode::Stressed);
11628        assert_eq!(stressed.reason_code, "frame_budget_overrun");
11629        assert_eq!(stressed.queue_max_depth, None);
11630
11631        let degraded = governor.observe(governor_observation(
11632            8.0,
11633            0,
11634            0,
11635            DegradationLevel::SimpleBorders,
11636            false,
11637            false,
11638        ));
11639        assert_eq!(degraded.mode, RuntimeLoadMode::Degraded);
11640        assert_eq!(degraded.reason_code, "budget_degradation_active");
11641    }
11642
11643    #[test]
11644    fn load_governor_strict_semantics_failure_is_terminal() {
11645        let mut governor = test_load_governor(100, 2);
11646
11647        let unsafe_snapshot = governor.observe(governor_observation(
11648            8.0,
11649            0,
11650            0,
11651            DegradationLevel::Full,
11652            false,
11653            true,
11654        ));
11655
11656        assert_eq!(unsafe_snapshot.mode, RuntimeLoadMode::Unsafe);
11657        assert_eq!(unsafe_snapshot.pressure_class, RuntimePressureClass::Unsafe);
11658        assert_eq!(
11659            unsafe_snapshot.disposition,
11660            RuntimeWorkDisposition::FailFastStrictGuarantee
11661        );
11662        assert!(!unsafe_snapshot.strict_semantics_preserved);
11663        assert_eq!(unsafe_snapshot.reason_code, "strict_semantics_violation");
11664    }
11665
11666    #[test]
11667    fn load_governor_unsafe_latches_through_later_pressure() {
11668        let mut governor = test_load_governor(100, 2);
11669
11670        // Enter Unsafe via a strict-semantics violation.
11671        let entered = governor.observe(governor_observation(
11672            8.0,
11673            0,
11674            0,
11675            DegradationLevel::Full,
11676            false,
11677            true,
11678        ));
11679        assert_eq!(entered.mode, RuntimeLoadMode::Unsafe);
11680
11681        // A later hard-overload interval (queue ratio >= degraded watermark) with
11682        // NO fresh violation must not downgrade the terminal Unsafe state.
11683        let hard = governor.observe(governor_observation(
11684            8.0,
11685            90,
11686            0,
11687            DegradationLevel::SimpleBorders,
11688            false,
11689            false,
11690        ));
11691        assert_eq!(hard.mode, RuntimeLoadMode::Unsafe);
11692        assert_eq!(
11693            hard.disposition,
11694            RuntimeWorkDisposition::FailFastStrictGuarantee
11695        );
11696        assert!(!hard.strict_semantics_preserved);
11697        assert_eq!(hard.reason_code, "strict_semantics_violation");
11698
11699        // A soft-overload interval (would otherwise classify as Stressed) must
11700        // also keep Unsafe latched rather than escaping downward.
11701        let soft = governor.observe(governor_observation(
11702            8.0,
11703            60,
11704            0,
11705            DegradationLevel::Full,
11706            true,
11707            false,
11708        ));
11709        assert_eq!(soft.mode, RuntimeLoadMode::Unsafe);
11710
11711        // And a fully steady interval never recovers out of Unsafe.
11712        let steady = governor.observe(governor_observation(
11713            8.0,
11714            0,
11715            0,
11716            DegradationLevel::Full,
11717            false,
11718            false,
11719        ));
11720        assert_eq!(steady.mode, RuntimeLoadMode::Unsafe);
11721        assert!(!steady.strict_semantics_preserved);
11722    }
11723
11724    #[test]
11725    fn load_governor_hysteresis_prevents_single_sample_recovery() {
11726        let mut governor = test_load_governor(100, 3);
11727
11728        governor.observe(governor_observation(
11729            8.0,
11730            90,
11731            0,
11732            DegradationLevel::Full,
11733            false,
11734            false,
11735        ));
11736
11737        for expected in 1..=2 {
11738            let snapshot = governor.observe(governor_observation(
11739                8.0,
11740                0,
11741                0,
11742                DegradationLevel::Full,
11743                false,
11744                false,
11745            ));
11746            assert_eq!(snapshot.mode, RuntimeLoadMode::Degraded);
11747            assert_eq!(snapshot.recovery_intervals_observed, expected);
11748            assert_eq!(snapshot.reason_code, "recovery_hysteresis_pending");
11749        }
11750
11751        let recovered = governor.observe(governor_observation(
11752            8.0,
11753            0,
11754            0,
11755            DegradationLevel::Full,
11756            false,
11757            false,
11758        ));
11759        assert_eq!(recovered.mode, RuntimeLoadMode::Recovered);
11760    }
11761
11762    #[test]
11763    fn load_governor_stress_e2e_evidence_shows_degraded_and_recovery() {
11764        let mut governor = test_load_governor(50, 2);
11765        let scenario = [
11766            governor_observation(8.0, 0, 0, DegradationLevel::Full, false, false),
11767            governor_observation(18.0, 25, 0, DegradationLevel::Full, true, false),
11768            governor_observation(22.0, 45, 1, DegradationLevel::SimpleBorders, true, false),
11769            governor_observation(8.0, 5, 1, DegradationLevel::Full, false, false),
11770            governor_observation(8.0, 5, 1, DegradationLevel::Full, false, false),
11771            governor_observation(8.0, 5, 1, DegradationLevel::Full, false, false),
11772        ];
11773
11774        let mut modes = Vec::new();
11775        for observation in scenario {
11776            let snapshot = governor.observe(observation);
11777            modes.push(snapshot.mode);
11778            println!(
11779                "{{\"test\":\"load_governor_stress_e2e\",\"mode\":\"{}\",\"pressure_class\":\"{}\",\"work_disposition\":\"{}\",\"reason\":\"{}\",\"transition\":{},\"deferred\":{},\"coalesced\":{},\"dropped\":{}}}",
11780                snapshot.mode.as_str(),
11781                snapshot.pressure_class.as_str(),
11782                snapshot.disposition.as_str(),
11783                snapshot.reason_code,
11784                snapshot.transition,
11785                snapshot.deferred_work_total,
11786                snapshot.coalesced_work_total,
11787                snapshot.dropped_work_total
11788            );
11789        }
11790
11791        assert!(modes.contains(&RuntimeLoadMode::Stressed));
11792        assert!(modes.contains(&RuntimeLoadMode::Degraded));
11793        assert!(modes.contains(&RuntimeLoadMode::Recovered));
11794        assert_eq!(modes.last(), Some(&RuntimeLoadMode::Healthy));
11795    }
11796
11797    #[test]
11798    fn headless_program_default_load_governor_attaches_controller() {
11799        let program =
11800            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
11801        assert!(program.budget.controller().is_some());
11802    }
11803
11804    #[test]
11805    fn headless_program_load_governor_target_tracks_frame_budget() {
11806        let config = ProgramConfig::default().with_budget(FrameBudgetConfig {
11807            total: Duration::from_millis(50),
11808            ..Default::default()
11809        });
11810        let program = headless_program_with_config(TestModel { value: 0 }, config);
11811        assert_eq!(
11812            program.budget.controller().unwrap().config().target,
11813            Duration::from_millis(50)
11814        );
11815    }
11816
11817    #[test]
11818    fn headless_program_without_load_governor_uses_legacy_budget() {
11819        let program = headless_program_with_config(
11820            TestModel { value: 0 },
11821            ProgramConfig::default().without_load_governor(),
11822        );
11823        assert!(program.budget.controller().is_none());
11824    }
11825
11826    #[test]
11827    fn app_builder_without_load_governor_sets_config() {
11828        let builder = App::new(TestModel { value: 0 }).without_load_governor();
11829        assert!(!builder.config.load_governor.enabled);
11830    }
11831
11832    #[test]
11833    fn program_config_with_conformal() {
11834        let config = ProgramConfig::default().with_conformal_config(ConformalConfig {
11835            alpha: 0.2,
11836            ..Default::default()
11837        });
11838        assert!(config.conformal_config.is_some());
11839        assert!((config.conformal_config.as_ref().unwrap().alpha - 0.2).abs() < 1e-6);
11840    }
11841
11842    #[test]
11843    fn program_rejects_invalid_conformal_configuration() {
11844        let features = BackendFeatures::default();
11845        let events = HeadlessEventSource::new(80, 24, features);
11846        let writer = TerminalWriter::new(
11847            Vec::<u8>::new(),
11848            ScreenMode::AltScreen,
11849            UiAnchor::Bottom,
11850            TerminalCapabilities::default(),
11851        );
11852        let result = Program::with_event_source(
11853            TestModel { value: 0 },
11854            events,
11855            features,
11856            TerminalPresenter::new(writer),
11857            ProgramConfig::default()
11858                .with_signal_interception(false)
11859                .with_conformal_config(ConformalConfig {
11860                    alpha: f64::NAN,
11861                    ..Default::default()
11862                }),
11863        );
11864        let error = result.err().expect("invalid configuration must fail");
11865        assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
11866        assert!(error.to_string().contains("alpha"));
11867    }
11868
11869    #[test]
11870    fn program_config_forced_size_clamps_minimums() {
11871        let config = ProgramConfig::default().with_forced_size(0, 0);
11872        assert_eq!(config.forced_size, Some((1, 1)));
11873
11874        let cleared = config.without_forced_size();
11875        assert!(cleared.forced_size.is_none());
11876    }
11877
11878    #[test]
11879    fn effect_queue_config_defaults_are_safe() {
11880        let config = EffectQueueConfig::default();
11881        assert!(!config.enabled);
11882        assert_eq!(config.backend, TaskExecutorBackend::Spawned);
11883        assert!(config.scheduler.smith_enabled);
11884        assert!(!config.scheduler.preemptive);
11885        assert_eq!(config.scheduler.aging_factor, 0.0);
11886        assert_eq!(config.scheduler.wait_starve_ms, 0.0);
11887    }
11888
11889    #[test]
11890    fn handle_effect_command_enqueues_or_executes_inline() {
11891        let (result_tx, result_rx) = mpsc::channel::<u32>();
11892        let mut scheduler = QueueingScheduler::new(EffectQueueConfig::default().scheduler);
11893        let mut tasks: HashMap<u64, Box<dyn FnOnce() -> u32 + Send>> = HashMap::new();
11894
11895        let ran = Arc::new(AtomicUsize::new(0));
11896        let ran_task = ran.clone();
11897        let cmd = EffectCommand::Enqueue(
11898            TaskSpec::default(),
11899            Box::new(move || {
11900                ran_task.fetch_add(1, Ordering::SeqCst);
11901                7
11902            }),
11903        );
11904
11905        let outstanding = AtomicUsize::new(1);
11906        let shutdown = handle_effect_command(
11907            cmd,
11908            &mut scheduler,
11909            &mut tasks,
11910            &result_tx,
11911            None,
11912            0,
11913            &outstanding,
11914        );
11915        assert_eq!(shutdown, EffectLoopControl::Continue);
11916        assert_eq!(
11917            outstanding.load(Ordering::SeqCst),
11918            1,
11919            "accepted, not finished"
11920        );
11921        assert_eq!(ran.load(Ordering::SeqCst), 0);
11922        assert_eq!(tasks.len(), 1);
11923        assert!(result_rx.try_recv().is_err());
11924
11925        let mut full_scheduler = QueueingScheduler::new(SchedulerConfig {
11926            max_queue_size: 0,
11927            ..Default::default()
11928        });
11929        let mut full_tasks: HashMap<u64, Box<dyn FnOnce() -> u32 + Send>> = HashMap::new();
11930        let ran_full = Arc::new(AtomicUsize::new(0));
11931        let ran_full_task = ran_full.clone();
11932        let cmd_full = EffectCommand::Enqueue(
11933            TaskSpec::default(),
11934            Box::new(move || {
11935                ran_full_task.fetch_add(1, Ordering::SeqCst);
11936                42
11937            }),
11938        );
11939
11940        let full_outstanding = AtomicUsize::new(1);
11941        let shutdown_full = handle_effect_command(
11942            cmd_full,
11943            &mut full_scheduler,
11944            &mut full_tasks,
11945            &result_tx,
11946            None,
11947            0,
11948            &full_outstanding,
11949        );
11950        assert_eq!(shutdown_full, EffectLoopControl::Continue);
11951        assert!(full_tasks.is_empty());
11952        assert_eq!(ran_full.load(Ordering::SeqCst), 1);
11953        assert_eq!(
11954            full_outstanding.load(Ordering::SeqCst),
11955            0,
11956            "the inline fallback ran the task, so it is no longer outstanding"
11957        );
11958        assert_eq!(
11959            result_rx.recv_timeout(Duration::from_millis(200)).unwrap(),
11960            42
11961        );
11962
11963        let shutdown = handle_effect_command(
11964            EffectCommand::Shutdown,
11965            &mut full_scheduler,
11966            &mut full_tasks,
11967            &result_tx,
11968            None,
11969            0,
11970            &full_outstanding,
11971        );
11972        assert_eq!(shutdown, EffectLoopControl::ShutdownRequested);
11973    }
11974
11975    #[test]
11976    fn handle_effect_command_inline_fallback_writes_backpressure_evidence() {
11977        let evidence_path = temp_evidence_path("task_executor_backpressure");
11978        let sink_config = EvidenceSinkConfig::enabled_file(&evidence_path);
11979        let sink = EvidenceSink::from_config(&sink_config)
11980            .expect("evidence sink config")
11981            .expect("evidence sink enabled");
11982        let (result_tx, result_rx) = mpsc::channel::<u32>();
11983        let mut scheduler = QueueingScheduler::new(SchedulerConfig {
11984            max_queue_size: 0,
11985            ..Default::default()
11986        });
11987        let mut tasks: HashMap<u64, Box<dyn FnOnce() -> u32 + Send>> = HashMap::new();
11988
11989        let shutdown = handle_effect_command(
11990            EffectCommand::Enqueue(TaskSpec::default(), Box::new(|| 7)),
11991            &mut scheduler,
11992            &mut tasks,
11993            &result_tx,
11994            Some(&sink),
11995            0,
11996            &AtomicUsize::new(1),
11997        );
11998
11999        assert_eq!(shutdown, EffectLoopControl::Continue);
12000        assert!(tasks.is_empty());
12001        assert_eq!(
12002            result_rx.recv_timeout(Duration::from_millis(200)).unwrap(),
12003            7
12004        );
12005
12006        let backpressure_line = read_evidence_event(&evidence_path, "task_executor_backpressure");
12007        assert_eq!(backpressure_line["backend"], "queued");
12008        assert_eq!(backpressure_line["action"], "inline_fallback");
12009        assert_eq!(backpressure_line["max_queue_size"], 0);
12010        assert_eq!(backpressure_line["total_rejected"], 1);
12011
12012        let completion_line = read_evidence_event(&evidence_path, "task_executor_complete");
12013        assert_eq!(completion_line["backend"], "queued-inline-fallback");
12014        assert!(completion_line["duration_us"].is_number());
12015    }
12016
12017    #[test]
12018    fn effect_queue_loop_executes_tasks_and_shutdowns() {
12019        let (cmd_tx, cmd_rx) = mpsc::channel::<EffectCommand<u32>>();
12020        let (result_tx, result_rx) = mpsc::channel::<u32>();
12021        let config = EffectQueueConfig {
12022            enabled: true,
12023            backend: TaskExecutorBackend::EffectQueue,
12024            scheduler: SchedulerConfig {
12025                preemptive: false,
12026                ..Default::default()
12027            },
12028            explicit_backend: true,
12029            ..Default::default()
12030        };
12031
12032        let handle = std::thread::spawn(move || {
12033            effect_queue_loop(
12034                config,
12035                cmd_rx,
12036                result_tx,
12037                None,
12038                &std::sync::atomic::AtomicUsize::new(0),
12039            );
12040        });
12041
12042        cmd_tx
12043            .send(EffectCommand::Enqueue(TaskSpec::default(), Box::new(|| 10)))
12044            .unwrap();
12045        cmd_tx
12046            .send(EffectCommand::Enqueue(
12047                TaskSpec::new(2.0, 5.0).with_name("second"),
12048                Box::new(|| 20),
12049            ))
12050            .unwrap();
12051
12052        let mut results = vec![
12053            result_rx.recv_timeout(Duration::from_millis(500)).unwrap(),
12054            result_rx.recv_timeout(Duration::from_millis(500)).unwrap(),
12055        ];
12056        results.sort_unstable();
12057        assert_eq!(results, vec![10, 20]);
12058
12059        cmd_tx.send(EffectCommand::Shutdown).unwrap();
12060        let _ = handle.join();
12061    }
12062
12063    #[test]
12064    fn effect_queue_loop_drains_queued_tasks_after_shutdown_request() {
12065        let (cmd_tx, cmd_rx) = mpsc::channel::<EffectCommand<u32>>();
12066        let (result_tx, result_rx) = mpsc::channel::<u32>();
12067        let config = EffectQueueConfig {
12068            enabled: true,
12069            backend: TaskExecutorBackend::EffectQueue,
12070            scheduler: SchedulerConfig {
12071                preemptive: false,
12072                ..Default::default()
12073            },
12074            explicit_backend: true,
12075            ..Default::default()
12076        };
12077
12078        let handle = std::thread::spawn(move || {
12079            effect_queue_loop(
12080                config,
12081                cmd_rx,
12082                result_tx,
12083                None,
12084                &std::sync::atomic::AtomicUsize::new(0),
12085            );
12086        });
12087
12088        cmd_tx
12089            .send(EffectCommand::Enqueue(
12090                TaskSpec::default().with_name("slow"),
12091                Box::new(|| {
12092                    std::thread::sleep(Duration::from_millis(20));
12093                    10
12094                }),
12095            ))
12096            .unwrap();
12097        cmd_tx
12098            .send(EffectCommand::Enqueue(
12099                TaskSpec::new(2.0, 5.0).with_name("fast"),
12100                Box::new(|| 20),
12101            ))
12102            .unwrap();
12103        cmd_tx.send(EffectCommand::Shutdown).unwrap();
12104
12105        let mut results = vec![
12106            result_rx.recv_timeout(Duration::from_millis(500)).unwrap(),
12107            result_rx.recv_timeout(Duration::from_millis(500)).unwrap(),
12108        ];
12109        results.sort_unstable();
12110        assert_eq!(results, vec![10, 20]);
12111
12112        handle
12113            .join()
12114            .expect("effect queue thread joins after draining");
12115    }
12116
12117    #[test]
12118    fn effect_queue_loop_survives_panicking_task_and_runs_later_work() {
12119        let (cmd_tx, cmd_rx) = mpsc::channel::<EffectCommand<u32>>();
12120        let (result_tx, result_rx) = mpsc::channel::<u32>();
12121        let config = EffectQueueConfig {
12122            enabled: true,
12123            backend: TaskExecutorBackend::EffectQueue,
12124            scheduler: SchedulerConfig {
12125                preemptive: false,
12126                ..Default::default()
12127            },
12128            explicit_backend: true,
12129            ..Default::default()
12130        };
12131
12132        let handle = std::thread::spawn(move || {
12133            effect_queue_loop(
12134                config,
12135                cmd_rx,
12136                result_tx,
12137                None,
12138                &std::sync::atomic::AtomicUsize::new(0),
12139            );
12140        });
12141
12142        cmd_tx
12143            .send(EffectCommand::Enqueue(
12144                TaskSpec::new(3.0, 1.0).with_name("panic"),
12145                Box::new(|| panic!("queued panic")),
12146            ))
12147            .unwrap();
12148        cmd_tx
12149            .send(EffectCommand::Enqueue(
12150                TaskSpec::new(1.0, 5.0).with_name("after"),
12151                Box::new(|| 99),
12152            ))
12153            .unwrap();
12154
12155        assert_eq!(
12156            result_rx.recv_timeout(Duration::from_millis(500)).unwrap(),
12157            99
12158        );
12159
12160        cmd_tx.send(EffectCommand::Shutdown).unwrap();
12161        handle
12162            .join()
12163            .expect("effect queue thread survives task panic");
12164    }
12165
12166    #[test]
12167    fn effect_queue_loop_rejects_tasks_submitted_after_shutdown_request() {
12168        let (cmd_tx, cmd_rx) = mpsc::channel::<EffectCommand<u32>>();
12169        let (result_tx, result_rx) = mpsc::channel::<u32>();
12170        let config = EffectQueueConfig {
12171            enabled: true,
12172            backend: TaskExecutorBackend::EffectQueue,
12173            scheduler: SchedulerConfig {
12174                preemptive: false,
12175                ..Default::default()
12176            },
12177            explicit_backend: true,
12178            ..Default::default()
12179        };
12180
12181        let handle = std::thread::spawn(move || {
12182            effect_queue_loop(
12183                config,
12184                cmd_rx,
12185                result_tx,
12186                None,
12187                &std::sync::atomic::AtomicUsize::new(0),
12188            );
12189        });
12190
12191        cmd_tx
12192            .send(EffectCommand::Enqueue(
12193                TaskSpec::default().with_name("slow"),
12194                Box::new(|| {
12195                    std::thread::sleep(Duration::from_millis(20));
12196                    10
12197                }),
12198            ))
12199            .unwrap();
12200        cmd_tx.send(EffectCommand::Shutdown).unwrap();
12201        cmd_tx
12202            .send(EffectCommand::Enqueue(
12203                TaskSpec::new(1.0, 1.0).with_name("late"),
12204                Box::new(|| 99),
12205            ))
12206            .unwrap();
12207
12208        assert_eq!(
12209            result_rx.recv_timeout(Duration::from_millis(500)).unwrap(),
12210            10
12211        );
12212        assert!(
12213            result_rx.recv_timeout(Duration::from_millis(100)).is_err(),
12214            "post-shutdown enqueue should not execute"
12215        );
12216
12217        handle
12218            .join()
12219            .expect("effect queue thread joins after rejecting post-shutdown work");
12220    }
12221
12222    #[test]
12223    fn effect_queue_enqueue_after_shutdown_records_drop() {
12224        let (tx, rx) = mpsc::channel::<EffectCommand<u32>>();
12225        drop(rx);
12226
12227        let queue = EffectQueue {
12228            sender: tx,
12229            handle: None,
12230            closed: true,
12231            outstanding: Arc::new(AtomicUsize::new(0)),
12232            max_depth: 0,
12233        };
12234        let runs = Arc::new(AtomicUsize::new(0));
12235        let before = crate::effect_system::effects_queue_dropped();
12236
12237        queue.enqueue(
12238            TaskSpec::default(),
12239            Box::new({
12240                let runs = Arc::clone(&runs);
12241                move || {
12242                    runs.fetch_add(1, Ordering::SeqCst);
12243                    7
12244                }
12245            }),
12246        );
12247
12248        let after = crate::effect_system::effects_queue_dropped();
12249        assert_eq!(runs.load(Ordering::SeqCst), 0);
12250        assert!(
12251            after > before,
12252            "enqueue after shutdown should increment dropped counter"
12253        );
12254    }
12255
12256    /// `.50.1`: while one long task holds the single worker, submissions past
12257    /// `max_queue_depth` are refused at `enqueue` instead of piling up in the
12258    /// channel; exactly `max_queue_depth` tasks run and the count drains.
12259    #[test]
12260    fn effect_queue_bounds_the_backlog_at_submission() {
12261        const MAX: usize = 4;
12262        let (result_tx, result_rx) = mpsc::channel::<u32>();
12263        let mut queue = EffectQueue::start(
12264            EffectQueueConfig::default()
12265                .with_enabled(true)
12266                .with_max_queue_depth(MAX),
12267            result_tx,
12268            None,
12269        )
12270        .expect("start effect queue");
12271        let (release_tx, release_rx) = mpsc::channel::<()>();
12272        let release_rx = Arc::new(std::sync::Mutex::new(release_rx));
12273        {
12274            let release_rx = Arc::clone(&release_rx);
12275            queue.enqueue(
12276                TaskSpec::default(),
12277                Box::new(move || {
12278                    let _ = release_rx.lock().expect("release lock").recv();
12279                    0
12280                }),
12281            );
12282        }
12283        for i in 1..(10 * MAX as u32) {
12284            queue.enqueue(TaskSpec::default(), Box::new(move || i));
12285            assert!(
12286                queue.in_flight() <= MAX,
12287                "backlog {} > {MAX}",
12288                queue.in_flight()
12289            );
12290        }
12291        assert_eq!(
12292            queue.in_flight(),
12293            MAX,
12294            "the bound is reached, not undershot"
12295        );
12296
12297        release_tx.send(()).expect("release the blocking task");
12298        let mut ran = Vec::new();
12299        while ran.len() < MAX {
12300            ran.push(
12301                result_rx
12302                    .recv_timeout(Duration::from_secs(5))
12303                    .expect("admitted task result"),
12304            );
12305        }
12306        assert!(
12307            result_rx.recv_timeout(Duration::from_millis(200)).is_err(),
12308            "a refused task ran: {ran:?}"
12309        );
12310        let deadline = Instant::now() + Duration::from_secs(5);
12311        while queue.in_flight() > 0 && Instant::now() < deadline {
12312            thread::sleep(Duration::from_millis(1));
12313        }
12314        assert_eq!(queue.in_flight(), 0, "outstanding count drains");
12315        queue.shutdown();
12316    }
12317
12318    #[test]
12319    fn effect_queue_enqueue_with_closed_channel_records_drop() {
12320        let (tx, rx) = mpsc::channel::<EffectCommand<u32>>();
12321        drop(rx);
12322
12323        let queue = EffectQueue {
12324            sender: tx,
12325            handle: None,
12326            closed: false,
12327            outstanding: Arc::new(AtomicUsize::new(0)),
12328            max_depth: 0,
12329        };
12330        let runs = Arc::new(AtomicUsize::new(0));
12331        let before = crate::effect_system::effects_queue_dropped();
12332
12333        queue.enqueue(
12334            TaskSpec::default(),
12335            Box::new({
12336                let runs = Arc::clone(&runs);
12337                move || {
12338                    runs.fetch_add(1, Ordering::SeqCst);
12339                    9
12340                }
12341            }),
12342        );
12343
12344        let after = crate::effect_system::effects_queue_dropped();
12345        assert_eq!(runs.load(Ordering::SeqCst), 0);
12346        assert!(
12347            after > before,
12348            "enqueue into a closed queue channel should increment dropped counter"
12349        );
12350    }
12351
12352    // =========================================================================
12353    // Backpressure tests (bd-2zd0a)
12354    // =========================================================================
12355
12356    #[test]
12357    fn backpressure_drops_tasks_beyond_max_depth() {
12358        let (result_tx, _result_rx) = mpsc::channel::<u32>();
12359        let mut scheduler = QueueingScheduler::new(SchedulerConfig::default());
12360        let mut tasks: HashMap<u64, Box<dyn FnOnce() -> u32 + Send>> = HashMap::new();
12361        let in_flight_before = crate::effect_system::queue_telemetry().in_flight;
12362
12363        // Enqueue 2 tasks with max_depth=2 โ€” should succeed
12364        let r1 = handle_effect_command(
12365            EffectCommand::Enqueue(TaskSpec::default(), Box::new(|| 1)),
12366            &mut scheduler,
12367            &mut tasks,
12368            &result_tx,
12369            None,
12370            2,
12371            &AtomicUsize::new(0),
12372        );
12373        assert_eq!(r1, EffectLoopControl::Continue);
12374        assert_eq!(tasks.len(), 1);
12375
12376        let r2 = handle_effect_command(
12377            EffectCommand::Enqueue(TaskSpec::default(), Box::new(|| 2)),
12378            &mut scheduler,
12379            &mut tasks,
12380            &result_tx,
12381            None,
12382            2,
12383            &AtomicUsize::new(0),
12384        );
12385        assert_eq!(r2, EffectLoopControl::Continue);
12386        assert_eq!(tasks.len(), 2);
12387
12388        // 3rd task should be dropped (depth=2 >= max_depth=2)
12389        let dropped_before = crate::effect_system::effects_queue_dropped();
12390        let r3 = handle_effect_command(
12391            EffectCommand::Enqueue(TaskSpec::default(), Box::new(|| 3)),
12392            &mut scheduler,
12393            &mut tasks,
12394            &result_tx,
12395            None,
12396            2,
12397            &AtomicUsize::new(0),
12398        );
12399        assert_eq!(r3, EffectLoopControl::Continue);
12400        assert_eq!(
12401            tasks.len(),
12402            2,
12403            "task should have been dropped, not enqueued"
12404        );
12405        assert!(
12406            crate::effect_system::effects_queue_dropped() > dropped_before,
12407            "dropped counter should increment"
12408        );
12409        release_unrun_queued_tasks(in_flight_before);
12410    }
12411
12412    #[test]
12413    fn backpressure_zero_depth_means_unbounded() {
12414        let (result_tx, _result_rx) = mpsc::channel::<u32>();
12415        let mut scheduler = QueueingScheduler::new(SchedulerConfig::default());
12416        let mut tasks: HashMap<u64, Box<dyn FnOnce() -> u32 + Send>> = HashMap::new();
12417
12418        // With max_depth=0, can enqueue many tasks
12419        let in_flight_before = crate::effect_system::queue_telemetry().in_flight;
12420        for i in 0..20 {
12421            let r = handle_effect_command(
12422                EffectCommand::Enqueue(TaskSpec::default(), Box::new(move || i)),
12423                &mut scheduler,
12424                &mut tasks,
12425                &result_tx,
12426                None,
12427                0,
12428                &AtomicUsize::new(0),
12429            );
12430            assert_eq!(r, EffectLoopControl::Continue);
12431        }
12432        // All should be enqueued (some may have been inlined by scheduler, but none dropped)
12433        release_unrun_queued_tasks(in_flight_before);
12434    }
12435
12436    /// The enqueue counters are process-global and `in_flight` feeds the
12437    /// frame guardrail of every `Program` in this process. A unit test that
12438    /// queues tasks into a bare task map never runs them, so it must hand the
12439    /// accounting back or later headless render tests see a phantom backlog
12440    /// and drop their frames.
12441    fn release_unrun_queued_tasks(in_flight_before: u64) {
12442        let leaked = crate::effect_system::queue_telemetry()
12443            .in_flight
12444            .saturating_sub(in_flight_before);
12445        for _ in 0..leaked {
12446            crate::effect_system::record_queue_processed();
12447        }
12448    }
12449
12450    #[test]
12451    fn inline_auto_remeasure_reset_clears_decision() {
12452        let mut state = InlineAutoRemeasureState::new(InlineAutoRemeasureConfig::default());
12453        state.sampler.decide(Instant::now());
12454        assert!(state.sampler.last_decision().is_some());
12455
12456        state.reset();
12457        assert!(state.sampler.last_decision().is_none());
12458    }
12459
12460    #[test]
12461    fn budget_decision_jsonl_contains_required_fields() {
12462        let evidence = BudgetDecisionEvidence {
12463            frame_idx: 7,
12464            decision: BudgetDecision::Degrade,
12465            controller_decision: BudgetDecision::Hold,
12466            degradation_before: DegradationLevel::Full,
12467            degradation_after: DegradationLevel::NoStyling,
12468            frame_time_us: 12_345.678,
12469            budget_us: 16_000.0,
12470            pid_output: 1.25,
12471            pid_p: 0.5,
12472            pid_i: 0.25,
12473            pid_d: 0.5,
12474            e_value: 2.0,
12475            eprocess_lambda: 0.65,
12476            frames_observed: 42,
12477            frames_since_change: 3,
12478            in_warmup: false,
12479            recovery_streak: 5,
12480            total_degrades: 2,
12481            total_recoveries: 1,
12482            controller_reason: BudgetDecisionReason::OverloadEvidencePassed,
12483            resize_detector: "bocpd",
12484            load_governor: LoadGovernorSnapshot {
12485                mode: RuntimeLoadMode::Degraded,
12486                mode_before: RuntimeLoadMode::Stressed,
12487                pressure_class: RuntimePressureClass::HardOverload,
12488                disposition: RuntimeWorkDisposition::DeferBackgroundDropBestEffort,
12489                reason_code: "budget_degradation_active",
12490                transition: true,
12491                strict_semantics_preserved: true,
12492                queue_in_flight: 8,
12493                queue_max_depth: Some(10),
12494                queue_dropped_delta: 0,
12495                resize_coalescing_active: false,
12496                recovery_intervals_observed: 0,
12497                recovery_intervals_required: 3,
12498                deferred_work_total: 2,
12499                coalesced_work_total: 1,
12500                dropped_work_total: 0,
12501            },
12502            conformal: Some(ConformalEvidence {
12503                bucket_key: "inline:dirty:10".to_string(),
12504                n_b: 32,
12505                alpha: 0.05,
12506                q_b: Some(1000.0),
12507                y_hat: 12_000.0,
12508                upper_us: Some(13_000.0),
12509                risk: true,
12510                status: ConformalStatus::Calibrated,
12511                required_rank: 32,
12512                fallback_level: 1,
12513                window_size: 256,
12514                reset_count: 2,
12515            }),
12516        };
12517
12518        let jsonl = evidence.to_jsonl();
12519        assert!(jsonl.contains("\"event\":\"budget_decision\""));
12520        assert!(jsonl.contains("\"decision\":\"degrade\""));
12521        assert!(jsonl.contains("\"decision_controller\":\"stay\""));
12522        assert!(jsonl.contains("\"decision_controller_reason\":\"overload_evidence_passed\""));
12523        assert!(jsonl.contains("\"degradation_before\":\"Full\""));
12524        assert!(jsonl.contains("\"degradation_after\":\"NoStyling\""));
12525        assert!(jsonl.contains("\"frame_time_us\":12345.678000"));
12526        assert!(jsonl.contains("\"budget_us\":16000.000000"));
12527        assert!(jsonl.contains("\"pid_output\":1.250000"));
12528        assert!(jsonl.contains("\"e_value\":2.000000"));
12529        assert!(jsonl.contains("\"eprocess_lambda\":0.650000"));
12530        assert!(jsonl.contains("\"recovery_streak\":5"));
12531        assert!(jsonl.contains("\"total_degrades\":2"));
12532        assert!(jsonl.contains("\"total_recoveries\":1"));
12533        assert!(jsonl.contains("\"runtime_mode\":\"degraded\""));
12534        assert!(jsonl.contains("\"runtime_mode_before\":\"stressed\""));
12535        assert!(jsonl.contains("\"pressure_class\":\"hard_overload\""));
12536        assert!(jsonl.contains("\"work_disposition\":\"defer_background_drop_best_effort\""));
12537        assert!(jsonl.contains("\"governor_reason\":\"budget_degradation_active\""));
12538        assert!(jsonl.contains("\"governor_transition\":true"));
12539        assert!(jsonl.contains("\"strict_semantics_preserved\":true"));
12540        assert!(jsonl.contains("\"queue_in_flight\":8"));
12541        assert!(jsonl.contains("\"queue_max_depth\":10"));
12542        assert!(jsonl.contains("\"resize_detector\":\"bocpd\""));
12543        assert!(jsonl.contains("\"deferred_work_total\":2"));
12544        assert!(jsonl.contains("\"bucket_key\":\"inline:dirty:10\""));
12545        assert!(jsonl.contains("\"n_b\":32"));
12546        assert!(jsonl.contains("\"alpha\":0.050000"));
12547        assert!(jsonl.contains("\"q_b\":1000.000000"));
12548        assert!(jsonl.contains("\"y_hat\":12000.000000"));
12549        assert!(jsonl.contains("\"upper_us\":13000.000000"));
12550        assert!(jsonl.contains("\"risk\":true"));
12551        assert!(jsonl.contains("\"fallback_level\":1"));
12552        assert!(jsonl.contains("\"window_size\":256"));
12553        assert!(jsonl.contains("\"reset_count\":2"));
12554    }
12555
12556    fn make_signal(
12557        widget_id: u64,
12558        essential: bool,
12559        priority: f32,
12560        staleness_ms: u64,
12561        cost_us: f32,
12562    ) -> WidgetSignal {
12563        WidgetSignal {
12564            widget_id,
12565            essential,
12566            priority,
12567            staleness_ms,
12568            focus_boost: 0.0,
12569            interaction_boost: 0.0,
12570            area_cells: 1,
12571            cost_estimate_us: cost_us,
12572            recent_cost_us: 0.0,
12573            estimate_source: CostEstimateSource::FixedDefault,
12574        }
12575    }
12576
12577    fn signal_value_cost(signal: &WidgetSignal, config: &WidgetRefreshConfig) -> (f32, f32, bool) {
12578        let starved = config.starve_ms > 0 && signal.staleness_ms >= config.starve_ms;
12579        let staleness_window = config.staleness_window_ms.max(1) as f32;
12580        let staleness_score = (signal.staleness_ms as f32 / staleness_window).min(1.0);
12581        let mut value = config.weight_priority * signal.priority
12582            + config.weight_staleness * staleness_score
12583            + config.weight_focus * signal.focus_boost
12584            + config.weight_interaction * signal.interaction_boost;
12585        if starved {
12586            value += config.starve_boost;
12587        }
12588        let raw_cost = if signal.recent_cost_us > 0.0 {
12589            signal.recent_cost_us
12590        } else {
12591            signal.cost_estimate_us
12592        };
12593        let cost_us = raw_cost.max(config.min_cost_us);
12594        (value, cost_us, starved)
12595    }
12596
12597    fn fifo_select(
12598        signals: &[WidgetSignal],
12599        budget_us: f64,
12600        config: &WidgetRefreshConfig,
12601    ) -> (Vec<u64>, f64, usize) {
12602        let mut selected = Vec::new();
12603        let mut total_value = 0.0f64;
12604        let mut starved_selected = 0usize;
12605        let mut remaining = budget_us;
12606
12607        for signal in signals {
12608            if !signal.essential {
12609                continue;
12610            }
12611            let (value, cost_us, starved) = signal_value_cost(signal, config);
12612            remaining -= cost_us as f64;
12613            total_value += value as f64;
12614            if starved {
12615                starved_selected = starved_selected.saturating_add(1);
12616            }
12617            selected.push(signal.widget_id);
12618        }
12619        for signal in signals {
12620            if signal.essential {
12621                continue;
12622            }
12623            let (value, cost_us, starved) = signal_value_cost(signal, config);
12624            if remaining >= cost_us as f64 {
12625                remaining -= cost_us as f64;
12626                total_value += value as f64;
12627                if starved {
12628                    starved_selected = starved_selected.saturating_add(1);
12629                }
12630                selected.push(signal.widget_id);
12631            }
12632        }
12633
12634        (selected, total_value, starved_selected)
12635    }
12636
12637    fn rotate_signals(signals: &[WidgetSignal], offset: usize) -> Vec<WidgetSignal> {
12638        if signals.is_empty() {
12639            return Vec::new();
12640        }
12641        let mut rotated = Vec::with_capacity(signals.len());
12642        for idx in 0..signals.len() {
12643            rotated.push(signals[(idx + offset) % signals.len()].clone());
12644        }
12645        rotated
12646    }
12647
12648    #[test]
12649    fn widget_refresh_selects_essentials_first() {
12650        let signals = vec![
12651            make_signal(1, true, 0.6, 0, 5.0),
12652            make_signal(2, false, 0.9, 0, 4.0),
12653        ];
12654        let mut plan = WidgetRefreshPlan::new();
12655        let config = WidgetRefreshConfig::default();
12656        plan.recompute(1, 6.0, DegradationLevel::Full, &signals, &config);
12657        let selected: Vec<u64> = plan.selected.iter().map(|e| e.widget_id).collect();
12658        assert_eq!(selected, vec![1]);
12659        assert!(!plan.over_budget);
12660    }
12661
12662    #[test]
12663    fn widget_refresh_degradation_essential_only_skips_nonessential() {
12664        let signals = vec![
12665            make_signal(1, true, 0.5, 0, 2.0),
12666            make_signal(2, false, 1.0, 0, 1.0),
12667        ];
12668        let mut plan = WidgetRefreshPlan::new();
12669        let config = WidgetRefreshConfig::default();
12670        plan.recompute(3, 10.0, DegradationLevel::EssentialOnly, &signals, &config);
12671        let selected: Vec<u64> = plan.selected.iter().map(|e| e.widget_id).collect();
12672        assert_eq!(selected, vec![1]);
12673        assert_eq!(plan.skipped_count, 1);
12674    }
12675
12676    #[test]
12677    fn widget_refresh_starvation_guard_forces_one_starved() {
12678        let signals = vec![make_signal(7, false, 0.1, 10_000, 8.0)];
12679        let mut plan = WidgetRefreshPlan::new();
12680        let config = WidgetRefreshConfig {
12681            starve_ms: 1_000,
12682            max_starved_per_frame: 1,
12683            ..Default::default()
12684        };
12685        plan.recompute(5, 0.0, DegradationLevel::Full, &signals, &config);
12686        assert_eq!(plan.selected.len(), 1);
12687        assert!(plan.selected[0].starved);
12688        assert!(plan.over_budget);
12689    }
12690
12691    #[test]
12692    fn widget_refresh_budget_blocks_when_no_selection() {
12693        let signals = vec![make_signal(42, false, 0.2, 0, 10.0)];
12694        let mut plan = WidgetRefreshPlan::new();
12695        let config = WidgetRefreshConfig {
12696            starve_ms: 0,
12697            max_starved_per_frame: 0,
12698            ..Default::default()
12699        };
12700        plan.recompute(8, 0.0, DegradationLevel::Full, &signals, &config);
12701        let budget = plan.as_budget();
12702        assert!(!budget.allows(42, false));
12703    }
12704
12705    #[test]
12706    fn widget_refresh_max_drop_fraction_forces_minimum_refresh() {
12707        let signals = vec![
12708            make_signal(1, false, 0.4, 0, 10.0),
12709            make_signal(2, false, 0.4, 0, 10.0),
12710            make_signal(3, false, 0.4, 0, 10.0),
12711            make_signal(4, false, 0.4, 0, 10.0),
12712        ];
12713        let mut plan = WidgetRefreshPlan::new();
12714        let config = WidgetRefreshConfig {
12715            starve_ms: 0,
12716            max_starved_per_frame: 0,
12717            max_drop_fraction: 0.5,
12718            ..Default::default()
12719        };
12720        plan.recompute(12, 0.0, DegradationLevel::Full, &signals, &config);
12721        let selected: Vec<u64> = plan.selected.iter().map(|e| e.widget_id).collect();
12722        assert_eq!(selected, vec![1, 2]);
12723    }
12724
12725    #[test]
12726    fn widget_refresh_greedy_beats_fifo_and_round_robin() {
12727        let signals = vec![
12728            make_signal(1, false, 0.1, 0, 6.0),
12729            make_signal(2, false, 0.2, 0, 6.0),
12730            make_signal(3, false, 1.0, 0, 4.0),
12731            make_signal(4, false, 0.9, 0, 3.0),
12732            make_signal(5, false, 0.8, 0, 3.0),
12733            make_signal(6, false, 0.1, 4_000, 2.0),
12734        ];
12735        let budget_us = 10.0;
12736        let config = WidgetRefreshConfig::default();
12737
12738        let mut plan = WidgetRefreshPlan::new();
12739        plan.recompute(21, budget_us, DegradationLevel::Full, &signals, &config);
12740        let greedy_value = plan.selected_value;
12741        let greedy_selected: Vec<u64> = plan.selected.iter().map(|e| e.widget_id).collect();
12742
12743        let (fifo_selected, fifo_value, _fifo_starved) = fifo_select(&signals, budget_us, &config);
12744        let rotated = rotate_signals(&signals, 2);
12745        let (rr_selected, rr_value, _rr_starved) = fifo_select(&rotated, budget_us, &config);
12746
12747        assert!(
12748            greedy_value > fifo_value,
12749            "greedy_value={greedy_value:.3} <= fifo_value={fifo_value:.3}; greedy={:?}, fifo={:?}",
12750            greedy_selected,
12751            fifo_selected
12752        );
12753        assert!(
12754            greedy_value > rr_value,
12755            "greedy_value={greedy_value:.3} <= rr_value={rr_value:.3}; greedy={:?}, rr={:?}",
12756            greedy_selected,
12757            rr_selected
12758        );
12759        assert!(
12760            plan.starved_selected > 0,
12761            "greedy did not select starved widget; greedy={:?}",
12762            greedy_selected
12763        );
12764    }
12765
12766    #[test]
12767    fn widget_refresh_jsonl_contains_required_fields() {
12768        let signals = vec![make_signal(7, true, 0.2, 0, 2.0)];
12769        let mut plan = WidgetRefreshPlan::new();
12770        let config = WidgetRefreshConfig::default();
12771        plan.recompute(9, 4.0, DegradationLevel::Full, &signals, &config);
12772        let jsonl = plan.to_jsonl();
12773        assert!(jsonl.contains("\"event\":\"widget_refresh\""));
12774        assert!(jsonl.contains("\"frame_idx\":9"));
12775        assert!(jsonl.contains("\"selected_count\":1"));
12776        assert!(jsonl.contains("\"id\":7"));
12777    }
12778
12779    #[test]
12780    fn program_config_with_resize_coalescer() {
12781        let config = ProgramConfig::default().with_resize_coalescer(CoalescerConfig {
12782            steady_delay_ms: 8,
12783            burst_delay_ms: 20,
12784            hard_deadline_ms: 80,
12785            burst_enter_rate: 12.0,
12786            burst_exit_rate: 6.0,
12787            cooldown_frames: 2,
12788            rate_window_size: 6,
12789            enable_logging: true,
12790            enable_bocpd: false,
12791            heuristic_fallback: true,
12792            bocpd_config: None,
12793        });
12794        assert_eq!(config.resize_coalescer.steady_delay_ms, 8);
12795        assert!(config.resize_coalescer.enable_logging);
12796    }
12797
12798    #[test]
12799    fn program_config_with_resize_behavior() {
12800        let config = ProgramConfig::default().with_resize_behavior(ResizeBehavior::Immediate);
12801        assert_eq!(config.resize_behavior, ResizeBehavior::Immediate);
12802    }
12803
12804    #[test]
12805    fn program_config_with_legacy_resize_enabled() {
12806        let config = ProgramConfig::default().with_legacy_resize(true);
12807        assert_eq!(config.resize_behavior, ResizeBehavior::Immediate);
12808    }
12809
12810    #[test]
12811    fn program_config_with_legacy_resize_disabled_keeps_default() {
12812        let config = ProgramConfig::default().with_legacy_resize(false);
12813        assert_eq!(config.resize_behavior, ResizeBehavior::Throttled);
12814    }
12815
12816    fn diff_strategy_trace(bayesian_enabled: bool) -> Vec<DiffStrategy> {
12817        let config = RuntimeDiffConfig::default().with_bayesian_enabled(bayesian_enabled);
12818        let mut writer = TerminalWriter::with_diff_config(
12819            Vec::<u8>::new(),
12820            ScreenMode::AltScreen,
12821            UiAnchor::Bottom,
12822            TerminalCapabilities::basic(),
12823            config,
12824        );
12825        writer.set_size(8, 4);
12826
12827        let mut buffer = Buffer::new(8, 4);
12828        let mut trace = Vec::new();
12829
12830        writer.present_ui(&buffer, None, false).unwrap();
12831        trace.push(
12832            writer
12833                .last_diff_strategy()
12834                .unwrap_or(DiffStrategy::FullRedraw),
12835        );
12836
12837        buffer.set_raw(0, 0, Cell::from_char('A'));
12838        writer.present_ui(&buffer, None, false).unwrap();
12839        trace.push(
12840            writer
12841                .last_diff_strategy()
12842                .unwrap_or(DiffStrategy::FullRedraw),
12843        );
12844
12845        buffer.set_raw(1, 1, Cell::from_char('B'));
12846        writer.present_ui(&buffer, None, false).unwrap();
12847        trace.push(
12848            writer
12849                .last_diff_strategy()
12850                .unwrap_or(DiffStrategy::FullRedraw),
12851        );
12852
12853        trace
12854    }
12855
12856    fn coalescer_checksum(enable_bocpd: bool) -> String {
12857        let mut config = CoalescerConfig::default().with_logging(true);
12858        config = if enable_bocpd {
12859            config.with_bocpd()
12860        } else {
12861            config.without_bocpd()
12862        };
12863
12864        let base = Instant::now();
12865        let mut coalescer = ResizeCoalescer::new(config, (80, 24)).with_last_render(base);
12866
12867        let events = [
12868            (0_u64, (82_u16, 24_u16)),
12869            (10, (83, 25)),
12870            (20, (84, 26)),
12871            (35, (90, 28)),
12872            (55, (92, 30)),
12873        ];
12874
12875        let mut idx = 0usize;
12876        for t_ms in (0_u64..=160).step_by(8) {
12877            let now = base + Duration::from_millis(t_ms);
12878            while idx < events.len() && events[idx].0 == t_ms {
12879                let (w, h) = events[idx].1;
12880                coalescer.handle_resize_at(w, h, now);
12881                idx += 1;
12882            }
12883            coalescer.tick_at(now);
12884        }
12885
12886        coalescer.decision_checksum_hex()
12887    }
12888
12889    fn conformal_trace(enabled: bool) -> Vec<(Option<f64>, bool)> {
12890        if !enabled {
12891            return Vec::new();
12892        }
12893
12894        let mut predictor =
12895            ConformalPredictor::new(ConformalConfig::default()).expect("valid config");
12896        let key = BucketKey::from_context(ScreenMode::AltScreen, DiffStrategy::Full, 80, 24);
12897        let mut trace = Vec::new();
12898
12899        for i in 0..30 {
12900            let y_hat = 16_000.0 + (i as f64) * 15.0;
12901            let observed = y_hat + (i % 7) as f64 * 120.0;
12902            predictor.observe(key, y_hat, observed);
12903            let prediction = predictor.predict(key, y_hat, 20_000.0);
12904            trace.push((prediction.upper_us, prediction.risk));
12905        }
12906
12907        trace
12908    }
12909
12910    #[test]
12911    fn policy_toggle_matrix_determinism() {
12912        for &bayesian in &[false, true] {
12913            for &bocpd in &[false, true] {
12914                for &conformal in &[false, true] {
12915                    let diff_a = diff_strategy_trace(bayesian);
12916                    let diff_b = diff_strategy_trace(bayesian);
12917                    assert_eq!(diff_a, diff_b, "diff strategy not deterministic");
12918
12919                    let checksum_a = coalescer_checksum(bocpd);
12920                    let checksum_b = coalescer_checksum(bocpd);
12921                    assert_eq!(checksum_a, checksum_b, "coalescer checksum mismatch");
12922
12923                    let conf_a = conformal_trace(conformal);
12924                    let conf_b = conformal_trace(conformal);
12925                    assert_eq!(conf_a, conf_b, "conformal predictor not deterministic");
12926
12927                    if conformal {
12928                        assert!(!conf_a.is_empty(), "conformal trace should be populated");
12929                    } else {
12930                        assert!(conf_a.is_empty(), "conformal trace should be empty");
12931                    }
12932                }
12933            }
12934        }
12935    }
12936
12937    #[test]
12938    fn resize_behavior_uses_coalescer_flag() {
12939        assert!(ResizeBehavior::Throttled.uses_coalescer());
12940        assert!(!ResizeBehavior::Immediate.uses_coalescer());
12941    }
12942
12943    #[test]
12944    fn nested_cmd_msg_executes_recursively() {
12945        // Verify that Cmd::Msg triggers recursive update
12946        use crate::simulator::ProgramSimulator;
12947
12948        struct NestedModel {
12949            depth: usize,
12950        }
12951
12952        #[derive(Debug)]
12953        enum NestedMsg {
12954            Nest(usize),
12955        }
12956
12957        impl From<Event> for NestedMsg {
12958            fn from(_: Event) -> Self {
12959                NestedMsg::Nest(0)
12960            }
12961        }
12962
12963        impl Model for NestedModel {
12964            type Message = NestedMsg;
12965
12966            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
12967                match msg {
12968                    NestedMsg::Nest(n) => {
12969                        self.depth += 1;
12970                        if n > 0 {
12971                            Cmd::msg(NestedMsg::Nest(n - 1))
12972                        } else {
12973                            Cmd::none()
12974                        }
12975                    }
12976                }
12977            }
12978
12979            fn view(&self, _frame: &mut Frame) {}
12980        }
12981
12982        let mut sim = ProgramSimulator::new(NestedModel { depth: 0 });
12983        sim.init();
12984        sim.send(NestedMsg::Nest(3));
12985
12986        // Should have recursed 4 times (3, 2, 1, 0)
12987        assert_eq!(sim.model().depth, 4);
12988    }
12989
12990    #[test]
12991    fn task_executes_synchronously_in_simulator() {
12992        // In simulator, tasks execute synchronously
12993        use crate::simulator::ProgramSimulator;
12994
12995        struct TaskModel {
12996            completed: bool,
12997        }
12998
12999        #[derive(Debug)]
13000        enum TaskMsg {
13001            Complete,
13002            SpawnTask,
13003        }
13004
13005        impl From<Event> for TaskMsg {
13006            fn from(_: Event) -> Self {
13007                TaskMsg::Complete
13008            }
13009        }
13010
13011        impl Model for TaskModel {
13012            type Message = TaskMsg;
13013
13014            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
13015                match msg {
13016                    TaskMsg::Complete => {
13017                        self.completed = true;
13018                        Cmd::none()
13019                    }
13020                    TaskMsg::SpawnTask => Cmd::task(|| TaskMsg::Complete),
13021                }
13022            }
13023
13024            fn view(&self, _frame: &mut Frame) {}
13025        }
13026
13027        let mut sim = ProgramSimulator::new(TaskModel { completed: false });
13028        sim.init();
13029        sim.send(TaskMsg::SpawnTask);
13030
13031        // Task should have completed synchronously
13032        assert!(sim.model().completed);
13033    }
13034
13035    #[test]
13036    fn multiple_updates_accumulate_correctly() {
13037        // Verify state accumulates correctly across multiple updates
13038        use crate::simulator::ProgramSimulator;
13039
13040        struct AccumModel {
13041            sum: i32,
13042        }
13043
13044        #[derive(Debug)]
13045        enum AccumMsg {
13046            Add(i32),
13047            Multiply(i32),
13048        }
13049
13050        impl From<Event> for AccumMsg {
13051            fn from(_: Event) -> Self {
13052                AccumMsg::Add(1)
13053            }
13054        }
13055
13056        impl Model for AccumModel {
13057            type Message = AccumMsg;
13058
13059            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
13060                match msg {
13061                    AccumMsg::Add(n) => {
13062                        self.sum += n;
13063                        Cmd::none()
13064                    }
13065                    AccumMsg::Multiply(n) => {
13066                        self.sum *= n;
13067                        Cmd::none()
13068                    }
13069                }
13070            }
13071
13072            fn view(&self, _frame: &mut Frame) {}
13073        }
13074
13075        let mut sim = ProgramSimulator::new(AccumModel { sum: 0 });
13076        sim.init();
13077
13078        // (0 + 5) * 2 + 3 = 13
13079        sim.send(AccumMsg::Add(5));
13080        sim.send(AccumMsg::Multiply(2));
13081        sim.send(AccumMsg::Add(3));
13082
13083        assert_eq!(sim.model().sum, 13);
13084    }
13085
13086    #[test]
13087    fn init_command_executes_before_first_update() {
13088        // Verify init() command executes before any update
13089        use crate::simulator::ProgramSimulator;
13090
13091        struct InitModel {
13092            initialized: bool,
13093            updates: usize,
13094        }
13095
13096        #[derive(Debug)]
13097        enum InitMsg {
13098            Update,
13099            MarkInit,
13100        }
13101
13102        impl From<Event> for InitMsg {
13103            fn from(_: Event) -> Self {
13104                InitMsg::Update
13105            }
13106        }
13107
13108        impl Model for InitModel {
13109            type Message = InitMsg;
13110
13111            fn init(&mut self) -> Cmd<Self::Message> {
13112                Cmd::msg(InitMsg::MarkInit)
13113            }
13114
13115            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
13116                match msg {
13117                    InitMsg::MarkInit => {
13118                        self.initialized = true;
13119                        Cmd::none()
13120                    }
13121                    InitMsg::Update => {
13122                        self.updates += 1;
13123                        Cmd::none()
13124                    }
13125                }
13126            }
13127
13128            fn view(&self, _frame: &mut Frame) {}
13129        }
13130
13131        let mut sim = ProgramSimulator::new(InitModel {
13132            initialized: false,
13133            updates: 0,
13134        });
13135        sim.init();
13136
13137        assert!(sim.model().initialized);
13138        sim.send(InitMsg::Update);
13139        assert_eq!(sim.model().updates, 1);
13140    }
13141
13142    // =========================================================================
13143    // INLINE MODE FRAME SIZING TESTS (bd-20vg)
13144    // =========================================================================
13145
13146    #[test]
13147    fn ui_height_returns_correct_value_inline_mode() {
13148        // Verify TerminalWriter.ui_height() returns ui_height in inline mode
13149        use crate::terminal_writer::{ScreenMode, TerminalWriter, UiAnchor};
13150        use ftui_core::terminal_capabilities::TerminalCapabilities;
13151
13152        let output = Vec::new();
13153        let writer = TerminalWriter::new(
13154            output,
13155            ScreenMode::Inline { ui_height: 10 },
13156            UiAnchor::Bottom,
13157            TerminalCapabilities::basic(),
13158        );
13159        assert_eq!(writer.ui_height(), 10);
13160    }
13161
13162    #[test]
13163    fn ui_height_returns_term_height_altscreen_mode() {
13164        // Verify TerminalWriter.ui_height() returns full terminal height in alt-screen mode
13165        use crate::terminal_writer::{ScreenMode, TerminalWriter, UiAnchor};
13166        use ftui_core::terminal_capabilities::TerminalCapabilities;
13167
13168        let output = Vec::new();
13169        let mut writer = TerminalWriter::new(
13170            output,
13171            ScreenMode::AltScreen,
13172            UiAnchor::Bottom,
13173            TerminalCapabilities::basic(),
13174        );
13175        writer.set_size(80, 24);
13176        assert_eq!(writer.ui_height(), 24);
13177    }
13178
13179    #[test]
13180    fn inline_mode_frame_uses_ui_height_not_terminal_height() {
13181        // Verify that in inline mode, the model receives a frame with ui_height,
13182        // not the full terminal height. This is the core fix for bd-20vg.
13183        use crate::simulator::ProgramSimulator;
13184        use std::cell::Cell as StdCell;
13185
13186        thread_local! {
13187            static CAPTURED_HEIGHT: StdCell<u16> = const { StdCell::new(0) };
13188        }
13189
13190        struct FrameSizeTracker;
13191
13192        #[derive(Debug)]
13193        enum SizeMsg {
13194            Check,
13195        }
13196
13197        impl From<Event> for SizeMsg {
13198            fn from(_: Event) -> Self {
13199                SizeMsg::Check
13200            }
13201        }
13202
13203        impl Model for FrameSizeTracker {
13204            type Message = SizeMsg;
13205
13206            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
13207                Cmd::none()
13208            }
13209
13210            fn view(&self, frame: &mut Frame) {
13211                // Capture the frame height we receive
13212                CAPTURED_HEIGHT.with(|h| h.set(frame.height()));
13213            }
13214        }
13215
13216        // Use simulator to verify frame dimension handling
13217        let mut sim = ProgramSimulator::new(FrameSizeTracker);
13218        sim.init();
13219
13220        // Capture with specific dimensions (simulates inline mode ui_height=10)
13221        let buf = sim.capture_frame(80, 10);
13222        assert_eq!(buf.height(), 10);
13223        assert_eq!(buf.width(), 80);
13224
13225        // Verify the frame has the correct dimensions
13226        // In inline mode with ui_height=10, the frame should be 10 rows tall,
13227        // NOT the full terminal height (e.g., 24).
13228    }
13229
13230    #[test]
13231    fn managed_hyperlinks_survive_changed_targets_abandoned_frames_and_resizes() {
13232        use ftui_render::cell::{Cell, CellAttrs, StyleFlags};
13233
13234        struct LinkModel {
13235            targets: [String; 2],
13236        }
13237
13238        impl Model for LinkModel {
13239            type Message = Event;
13240
13241            fn update(&mut self, _event: Event) -> Cmd<Event> {
13242                Cmd::none()
13243            }
13244
13245            fn view(&self, frame: &mut Frame) {
13246                for (x, (label, target)) in ['L', 'R'].iter().zip(&self.targets).enumerate() {
13247                    let id = frame.register_link(target);
13248                    frame.buffer.set_raw(
13249                        x as u16,
13250                        0,
13251                        Cell::from_char(*label).with_attrs(CellAttrs::new(StyleFlags::empty(), id)),
13252                    );
13253                }
13254            }
13255        }
13256
13257        for limit in [0, 1, 2] {
13258            let model = LinkModel {
13259                targets: Default::default(),
13260            };
13261            // Use the public constructor and App configuration, rather than
13262            // the test helper that assembles Program fields directly.
13263            let builder = App::new(model).with_hyperlink_limit(limit);
13264            let config = builder
13265                .config
13266                .with_forced_size(2, 1)
13267                .with_signal_interception(false)
13268                .without_load_governor()
13269                .without_conformal()
13270                .with_budget(FrameBudgetConfig::with_total(Duration::from_secs(5)));
13271            let mut caps = TerminalCapabilities::basic();
13272            caps.osc8_hyperlinks = true;
13273            let writer =
13274                TerminalWriter::new(Vec::new(), ScreenMode::AltScreen, UiAnchor::Bottom, caps);
13275            let events = HeadlessEventSource::new(2, 1, BackendFeatures::default());
13276            let mut program = Program::with_event_source(
13277                builder.model,
13278                events,
13279                BackendFeatures::default(),
13280                TerminalPresenter::new(writer),
13281                config,
13282            )
13283            .expect("construct actual program");
13284            let mut expected_links = Vec::new();
13285            for index in 0..256 {
13286                if index % 3 == 0 {
13287                    program.model.targets = [
13288                        format!("https://abandoned.test/{index}/left"),
13289                        format!("https://abandoned.test/{index}/right"),
13290                    ];
13291                    // A render that never reaches present must not consume
13292                    // admission or unpin the last successful frame next time.
13293                    let _abandoned = program.render_buffer(1);
13294                }
13295                if index % 64 == 0 {
13296                    program
13297                        .apply_resize(2 + (index / 64) % 2, 1, Duration::ZERO, false)
13298                        .expect("resize between link frames");
13299                }
13300                program.model.targets = [
13301                    format!("https://shown.test/{index}/left"),
13302                    format!("https://shown.test/{index}/right"),
13303                ];
13304                expected_links.extend(program.model.targets.iter().take(limit).cloned());
13305                program
13306                    .render_frame()
13307                    .expect("render and present changed URLs");
13308                assert!(program.presenter.writer.links().len() <= 2 * limit);
13309                assert!(program.presenter.writer.links().slot_count() <= 2 * limit);
13310            }
13311            let output = String::from_utf8(program.presenter.into_inner().unwrap()).unwrap();
13312            let actual_links: Vec<_> = output
13313                .split("\x1b]8;;")
13314                .skip(1)
13315                .filter_map(|part| part.split_once('\x07'))
13316                .map(|(url, _)| url)
13317                .filter(|url| !url.is_empty())
13318                .collect();
13319            assert_eq!(actual_links, expected_links, "per-frame limit {limit}");
13320            assert!(!output.contains("abandoned.test"));
13321            assert!(output.contains('L') && output.contains('R'));
13322        }
13323    }
13324
13325    #[test]
13326    fn inline_mode_program_frames_clamp_to_terminal_height_through_resizes() {
13327        use std::cell::RefCell;
13328
13329        #[derive(Default)]
13330        struct FrameSizeTracker {
13331            frame_sizes: RefCell<Vec<(u16, u16)>>,
13332        }
13333
13334        impl Model for FrameSizeTracker {
13335            type Message = Event;
13336
13337            fn update(&mut self, _event: Self::Message) -> Cmd<Self::Message> {
13338                Cmd::none()
13339            }
13340
13341            fn view(&self, frame: &mut Frame) {
13342                self.frame_sizes
13343                    .borrow_mut()
13344                    .push((frame.width(), frame.height()));
13345            }
13346        }
13347
13348        // Exercise Program's actual sizing path without supplying a model
13349        // frame size. The headless backend does not establish PTY behavior.
13350        let mut program = headless_program_with_config(
13351            FrameSizeTracker::default(),
13352            ProgramConfig {
13353                screen_mode: ScreenMode::Inline { ui_height: 64 },
13354                ..ProgramConfig::default()
13355            },
13356        );
13357        program.render_frame().expect("render initial inline frame");
13358        assert_eq!(program.model().frame_sizes.borrow().as_slice(), &[(80, 24)]);
13359        assert_eq!(program.presenter.ui_height(), 64);
13360
13361        for (width, height, expected_height) in [
13362            (40, 3, 3),
13363            (96, 18, 18),
13364            (120, 90, 64),
13365            (90, 70, 64),
13366            (80, 24, 24),
13367            (0, 0, 1),
13368        ] {
13369            program
13370                .apply_resize(width, height, Duration::ZERO, false)
13371                .expect("apply inline terminal resize");
13372            program.render_frame().expect("render resized inline frame");
13373            assert_eq!(
13374                program.model().frame_sizes.borrow().last(),
13375                Some(&(width.max(1), expected_height)),
13376                "terminal resize to {width}x{height}"
13377            );
13378            assert_eq!(
13379                program.presenter.ui_height(),
13380                64,
13381                "resizing must retain the configured inline height"
13382            );
13383        }
13384        assert_eq!(
13385            program.model().frame_sizes.borrow().as_slice(),
13386            &[
13387                (80, 24),
13388                (40, 3),
13389                (96, 18),
13390                (120, 64),
13391                (90, 64),
13392                (80, 24),
13393                (1, 1)
13394            ]
13395        );
13396    }
13397
13398    #[test]
13399    fn altscreen_frame_uses_full_terminal_height() {
13400        // Regression test: in alt-screen mode, frame should use full terminal height.
13401        use crate::terminal_writer::{ScreenMode, TerminalWriter, UiAnchor};
13402        use ftui_core::terminal_capabilities::TerminalCapabilities;
13403
13404        let output = Vec::new();
13405        let mut writer = TerminalWriter::new(
13406            output,
13407            ScreenMode::AltScreen,
13408            UiAnchor::Bottom,
13409            TerminalCapabilities::basic(),
13410        );
13411        writer.set_size(80, 40);
13412
13413        // In alt-screen, ui_height equals terminal height
13414        assert_eq!(writer.ui_height(), 40);
13415    }
13416
13417    #[test]
13418    fn ui_height_clamped_to_terminal_height() {
13419        // Verify ui_height doesn't exceed terminal height
13420        // (This is handled in present_inline, but ui_height() returns the configured value)
13421        use crate::terminal_writer::{ScreenMode, TerminalWriter, UiAnchor};
13422        use ftui_core::terminal_capabilities::TerminalCapabilities;
13423
13424        let output = Vec::new();
13425        let mut writer = TerminalWriter::new(
13426            output,
13427            ScreenMode::Inline { ui_height: 100 },
13428            UiAnchor::Bottom,
13429            TerminalCapabilities::basic(),
13430        );
13431        writer.set_size(80, 10);
13432
13433        // ui_height() retains the configured value. render_height_hint() and
13434        // present_inline clamp the model frame and visible region separately.
13435        assert_eq!(writer.ui_height(), 100);
13436    }
13437
13438    // =========================================================================
13439    // TICK DELIVERY TESTS (bd-3ufh)
13440    // =========================================================================
13441
13442    #[test]
13443    fn tick_event_delivered_to_model_update() {
13444        // Verify that Event::Tick is delivered to model.update()
13445        // This is the core fix: ticks now flow through the update pipeline.
13446        use crate::simulator::ProgramSimulator;
13447
13448        struct TickTracker {
13449            tick_count: usize,
13450        }
13451
13452        #[derive(Debug)]
13453        enum TickMsg {
13454            Tick,
13455            Other,
13456        }
13457
13458        impl From<Event> for TickMsg {
13459            fn from(event: Event) -> Self {
13460                match event {
13461                    Event::Tick => TickMsg::Tick,
13462                    _ => TickMsg::Other,
13463                }
13464            }
13465        }
13466
13467        impl Model for TickTracker {
13468            type Message = TickMsg;
13469
13470            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
13471                match msg {
13472                    TickMsg::Tick => {
13473                        self.tick_count += 1;
13474                        Cmd::none()
13475                    }
13476                    TickMsg::Other => Cmd::none(),
13477                }
13478            }
13479
13480            fn view(&self, _frame: &mut Frame) {}
13481        }
13482
13483        let mut sim = ProgramSimulator::new(TickTracker { tick_count: 0 });
13484        sim.init();
13485
13486        // Manually inject tick event to simulate what the runtime does
13487        sim.inject_event(Event::Tick);
13488        assert_eq!(sim.model().tick_count, 1);
13489
13490        sim.inject_event(Event::Tick);
13491        sim.inject_event(Event::Tick);
13492        assert_eq!(sim.model().tick_count, 3);
13493    }
13494
13495    #[test]
13496    fn tick_command_sets_tick_rate() {
13497        // Verify Cmd::tick() sets the tick rate in the simulator
13498        use crate::simulator::{CmdRecord, ProgramSimulator};
13499
13500        struct TickModel;
13501
13502        #[derive(Debug)]
13503        enum Msg {
13504            SetTick,
13505            Noop,
13506        }
13507
13508        impl From<Event> for Msg {
13509            fn from(_: Event) -> Self {
13510                Msg::Noop
13511            }
13512        }
13513
13514        impl Model for TickModel {
13515            type Message = Msg;
13516
13517            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
13518                match msg {
13519                    Msg::SetTick => Cmd::tick(Duration::from_millis(100)),
13520                    Msg::Noop => Cmd::none(),
13521                }
13522            }
13523
13524            fn view(&self, _frame: &mut Frame) {}
13525        }
13526
13527        let mut sim = ProgramSimulator::new(TickModel);
13528        sim.init();
13529        sim.send(Msg::SetTick);
13530
13531        // Check that tick was recorded
13532        let commands = sim.command_log();
13533        assert!(
13534            commands
13535                .iter()
13536                .any(|c| matches!(c, CmdRecord::Tick(d) if *d == Duration::from_millis(100)))
13537        );
13538    }
13539
13540    #[test]
13541    fn tick_can_trigger_further_commands() {
13542        // Verify that tick handling can return commands that are executed
13543        use crate::simulator::ProgramSimulator;
13544
13545        struct ChainModel {
13546            stage: usize,
13547        }
13548
13549        #[derive(Debug)]
13550        enum ChainMsg {
13551            Tick,
13552            Advance,
13553            Noop,
13554        }
13555
13556        impl From<Event> for ChainMsg {
13557            fn from(event: Event) -> Self {
13558                match event {
13559                    Event::Tick => ChainMsg::Tick,
13560                    _ => ChainMsg::Noop,
13561                }
13562            }
13563        }
13564
13565        impl Model for ChainModel {
13566            type Message = ChainMsg;
13567
13568            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
13569                match msg {
13570                    ChainMsg::Tick => {
13571                        self.stage += 1;
13572                        // Return another message to be processed
13573                        Cmd::msg(ChainMsg::Advance)
13574                    }
13575                    ChainMsg::Advance => {
13576                        self.stage += 10;
13577                        Cmd::none()
13578                    }
13579                    ChainMsg::Noop => Cmd::none(),
13580                }
13581            }
13582
13583            fn view(&self, _frame: &mut Frame) {}
13584        }
13585
13586        let mut sim = ProgramSimulator::new(ChainModel { stage: 0 });
13587        sim.init();
13588        sim.inject_event(Event::Tick);
13589
13590        // Tick increments by 1, then Advance increments by 10
13591        assert_eq!(sim.model().stage, 11);
13592    }
13593
13594    #[test]
13595    fn tick_disabled_with_zero_duration() {
13596        // Verify that Duration::ZERO disables ticks (no busy loop)
13597        use crate::simulator::ProgramSimulator;
13598
13599        struct ZeroTickModel {
13600            disabled: bool,
13601        }
13602
13603        #[derive(Debug)]
13604        enum ZeroMsg {
13605            DisableTick,
13606            Noop,
13607        }
13608
13609        impl From<Event> for ZeroMsg {
13610            fn from(_: Event) -> Self {
13611                ZeroMsg::Noop
13612            }
13613        }
13614
13615        impl Model for ZeroTickModel {
13616            type Message = ZeroMsg;
13617
13618            fn init(&mut self) -> Cmd<Self::Message> {
13619                // Start with a tick enabled
13620                Cmd::tick(Duration::from_millis(100))
13621            }
13622
13623            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
13624                match msg {
13625                    ZeroMsg::DisableTick => {
13626                        self.disabled = true;
13627                        // Setting tick to ZERO should effectively disable
13628                        Cmd::tick(Duration::ZERO)
13629                    }
13630                    ZeroMsg::Noop => Cmd::none(),
13631                }
13632            }
13633
13634            fn view(&self, _frame: &mut Frame) {}
13635        }
13636
13637        let mut sim = ProgramSimulator::new(ZeroTickModel { disabled: false });
13638        sim.init();
13639
13640        // Verify initial tick rate is set
13641        assert!(sim.tick_rate().is_some());
13642        assert_eq!(sim.tick_rate(), Some(Duration::from_millis(100)));
13643
13644        // Disable ticks
13645        sim.send(ZeroMsg::DisableTick);
13646        assert!(sim.model().disabled);
13647
13648        // Note: The simulator still records the ZERO tick, but the runtime's
13649        // should_tick() handles ZERO duration appropriately
13650        assert_eq!(sim.tick_rate(), Some(Duration::ZERO));
13651    }
13652
13653    #[test]
13654    fn tick_event_distinguishable_from_other_events() {
13655        // Verify Event::Tick can be distinguished in pattern matching
13656        let tick = Event::Tick;
13657        let key = Event::Key(ftui_core::event::KeyEvent::new(
13658            ftui_core::event::KeyCode::Char('a'),
13659        ));
13660
13661        assert!(matches!(tick, Event::Tick));
13662        assert!(!matches!(key, Event::Tick));
13663    }
13664
13665    #[test]
13666    fn tick_event_clone_and_eq() {
13667        // Verify Event::Tick implements Clone and Eq correctly
13668        let tick1 = Event::Tick;
13669        let tick2 = tick1.clone();
13670        assert_eq!(tick1, tick2);
13671    }
13672
13673    #[test]
13674    fn model_receives_tick_and_input_events() {
13675        // Verify model can handle both tick and input events correctly
13676        use crate::simulator::ProgramSimulator;
13677
13678        struct MixedModel {
13679            ticks: usize,
13680            keys: usize,
13681        }
13682
13683        #[derive(Debug)]
13684        enum MixedMsg {
13685            Tick,
13686            Key,
13687        }
13688
13689        impl From<Event> for MixedMsg {
13690            fn from(event: Event) -> Self {
13691                match event {
13692                    Event::Tick => MixedMsg::Tick,
13693                    _ => MixedMsg::Key,
13694                }
13695            }
13696        }
13697
13698        impl Model for MixedModel {
13699            type Message = MixedMsg;
13700
13701            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
13702                match msg {
13703                    MixedMsg::Tick => {
13704                        self.ticks += 1;
13705                        Cmd::none()
13706                    }
13707                    MixedMsg::Key => {
13708                        self.keys += 1;
13709                        Cmd::none()
13710                    }
13711                }
13712            }
13713
13714            fn view(&self, _frame: &mut Frame) {}
13715        }
13716
13717        let mut sim = ProgramSimulator::new(MixedModel { ticks: 0, keys: 0 });
13718        sim.init();
13719
13720        // Interleave tick and input events
13721        sim.inject_event(Event::Tick);
13722        sim.inject_event(Event::Key(ftui_core::event::KeyEvent::new(
13723            ftui_core::event::KeyCode::Char('a'),
13724        )));
13725        sim.inject_event(Event::Tick);
13726        sim.inject_event(Event::Key(ftui_core::event::KeyEvent::new(
13727            ftui_core::event::KeyCode::Char('b'),
13728        )));
13729        sim.inject_event(Event::Tick);
13730
13731        assert_eq!(sim.model().ticks, 3);
13732        assert_eq!(sim.model().keys, 2);
13733    }
13734
13735    // =========================================================================
13736    // HEADLESS PROGRAM TESTS (bd-1av4o.2)
13737    // =========================================================================
13738
13739    fn headless_program_with_resolved_config<M: Model>(
13740        model: M,
13741        config: ProgramConfig,
13742    ) -> Program<M, HeadlessEventSource, TerminalPresenter<Vec<u8>>>
13743    where
13744        M::Message: Send + 'static,
13745    {
13746        let resolved_lane = config.runtime_lane.resolve();
13747        let effect_queue_config = config.resolved_effect_queue_config(resolved_lane);
13748        let capabilities = TerminalCapabilities::basic();
13749        let mut writer = TerminalWriter::with_diff_config(
13750            Vec::new(),
13751            config.screen_mode,
13752            config.ui_anchor,
13753            capabilities,
13754            config.diff_config.clone(),
13755        );
13756        if let Some(limit) = config.hyperlink_limit {
13757            writer.set_hyperlink_limit(limit);
13758        }
13759        let frame_timing = config.frame_timing.clone();
13760        writer.set_timing_enabled(frame_timing.is_some());
13761
13762        let (width, height) = config.forced_size.unwrap_or((80, 24));
13763        let width = width.max(1);
13764        let height = height.max(1);
13765        writer.set_size(width, height);
13766
13767        let mouse_capture = config.resolved_mouse_capture();
13768        let initial_features = BackendFeatures {
13769            mouse_capture,
13770            bracketed_paste: config.bracketed_paste,
13771            focus_events: config.focus_reporting,
13772            kitty_keyboard: config.kitty_keyboard,
13773        };
13774        let events = HeadlessEventSource::new(width, height, initial_features);
13775        let evidence_sink = EvidenceSink::from_config(&config.evidence_sink)
13776            .expect("headless evidence sink config");
13777
13778        let budget = render_budget_from_program_config(&config);
13779        let load_governor = LoadGovernorState::new(
13780            config.load_governor.clone(),
13781            effect_queue_config.max_queue_depth,
13782        );
13783        let conformal_predictor = config
13784            .conformal_config
13785            .clone()
13786            .map(ConformalPredictor::new)
13787            .transpose()
13788            .expect("valid headless conformal config");
13789        let locale_context = config.locale_context.clone();
13790        let locale_version = locale_context.version();
13791        let mut resize_coalescer =
13792            ResizeCoalescer::new(config.resize_coalescer.clone(), (width, height));
13793        if let Some(ref sink) = evidence_sink {
13794            resize_coalescer = resize_coalescer.with_evidence_sink(sink.clone());
13795        }
13796        let subscriptions = SubscriptionManager::new();
13797        let (task_sender, task_receiver) = std::sync::mpsc::channel();
13798        let inline_auto_remeasure = config
13799            .inline_auto_remeasure
13800            .clone()
13801            .map(InlineAutoRemeasureState::new);
13802        let gesture_recognizer = config
13803            .gestures
13804            .clone()
13805            .map(ftui_core::gesture::GestureRecognizer::new);
13806        let event_coalescer = if config.event_coalescing {
13807            Some(ftui_core::event_coalescer::EventCoalescer::new())
13808        } else {
13809            None
13810        };
13811        let guardrails = FrameGuardrails::new(config.guardrails);
13812        let task_executor = TaskExecutor::new(
13813            &effect_queue_config,
13814            task_sender.clone(),
13815            evidence_sink.clone(),
13816        )
13817        .expect("task executor");
13818
13819        let mut startup_parser = ftui_core::input_parser::InputParser::new();
13820        startup_parser.set_pixel_mouse(config.pixel_mouse);
13821
13822        Program {
13823            model,
13824            presenter: TerminalPresenter::new(writer),
13825            events,
13826            backend_features: initial_features,
13827            running: true,
13828            shutdown_complete: false,
13829            tick_rate: None,
13830            executed_cmd_count: 0,
13831            last_tick: Instant::now(),
13832            dirty: true,
13833            frame_idx: 0,
13834            tick_count: 0,
13835            widget_signals: Vec::new(),
13836            a11y_policy: config.accessibility,
13837            a11y_evidence_text: config.accessibility_evidence_text,
13838            a11y_tree: None,
13839            a11y_order: Vec::new(),
13840            a11y_announcements: Vec::new(),
13841            a11y_pending: None,
13842            a11y_changed: false,
13843            a11y_dropped: 0,
13844            startup_events: Vec::new(),
13845            startup_parser,
13846            deliver_terminal_responses: config.deliver_terminal_responses,
13847            widget_refresh_config: config.widget_refresh,
13848            widget_refresh_plan: WidgetRefreshPlan::new(),
13849            width,
13850            height,
13851            forced_size: config.forced_size,
13852            poll_timeout: config.poll_timeout,
13853            intercept_signals: config.intercept_signals,
13854            pending_signal: Arc::new(std::sync::atomic::AtomicI32::new(0)),
13855            // Headless test programs never install an OS signal handler, so
13856            // they must not read (or clear) the process-global slot: that is
13857            // exactly the cross-test race that used to hang this binary.
13858            global_signal_slot: false,
13859            // Headless: no terminal to release and no OS handler, so stop
13860            // requests are ignored; tests that need the sequence build a
13861            // program over an event source that supports suspend.
13862            pending_suspend: Arc::new(std::sync::atomic::AtomicI32::new(0)),
13863            suspend_enabled: false,
13864            ctrl_z_suspends: config.ctrl_z_suspends,
13865            job_control_claim: None,
13866            stop_process: ftui_core::job_control::stop_process,
13867            immediate_drain_config: config.immediate_drain,
13868            immediate_drain_stats: ImmediateDrainStats::default(),
13869            budget,
13870            load_governor,
13871            conformal_predictor,
13872            last_frame_time_us: None,
13873            last_update_us: None,
13874            frame_timing,
13875            locale_context,
13876            locale_version,
13877            resize_coalescer,
13878            evidence_sink,
13879            fairness_config_logged: false,
13880            resize_behavior: config.resize_behavior,
13881            fairness_guard: InputFairnessGuard::new(),
13882            pending_fairness_input_duration: None,
13883            event_recorder: None,
13884            subscriptions,
13885            #[cfg(test)]
13886            task_sender,
13887            task_receiver,
13888            task_executor,
13889            state_registry: config.persistence.registry.clone(),
13890            persistence_config: config.persistence,
13891            last_checkpoint: Instant::now(),
13892            inline_auto_remeasure,
13893            gesture_recognizer,
13894            event_coalescer,
13895            frame_arena: FrameArena::default(),
13896            guardrails,
13897            last_soft_trim_frame: None,
13898            tick_strategy: config
13899                .tick_strategy
13900                .map(|strategy| Box::new(strategy) as Box<dyn crate::tick_strategy::TickStrategy>),
13901            last_active_screen_for_strategy: None,
13902            requested_lane: config.runtime_lane,
13903            resolved_lane,
13904            rollout_policy: config.rollout_policy,
13905            shadow_frame_idx: 0,
13906        }
13907    }
13908
13909    fn headless_program_with_config<M: Model>(
13910        model: M,
13911        config: ProgramConfig,
13912    ) -> Program<M, HeadlessEventSource, TerminalPresenter<Vec<u8>>>
13913    where
13914        M::Message: Send + 'static,
13915    {
13916        // Headless unit tests should not observe process-global shutdown state
13917        // unless they explicitly opt into signal interception.
13918        headless_program_with_resolved_config(model, config.with_signal_interception(false))
13919    }
13920
13921    fn headless_signal_program_with_config<M: Model>(
13922        model: M,
13923        config: ProgramConfig,
13924    ) -> Program<M, HeadlessEventSource, TerminalPresenter<Vec<u8>>>
13925    where
13926        M::Message: Send + 'static,
13927    {
13928        headless_program_with_resolved_config(model, config)
13929    }
13930
13931    fn temp_evidence_path(label: &str) -> PathBuf {
13932        // Retain evidence even if the test panics, with a fresh directory per run.
13933        let dir = tempfile::Builder::new()
13934            .prefix(&format!("ftui-program-{label}-"))
13935            .disable_cleanup(true)
13936            .tempdir()
13937            .expect("create retained evidence directory");
13938        dir.path().join("evidence.jsonl")
13939    }
13940
13941    fn read_evidence_event(path: &PathBuf, event: &str) -> Value {
13942        let jsonl = std::fs::read_to_string(path).expect("read evidence jsonl");
13943        let needle = format!("\"event\":\"{event}\"");
13944        let missing_msg = format!("missing {event} line");
13945        let line = jsonl
13946            .lines()
13947            .find(|line| line.contains(&needle))
13948            .expect(&missing_msg);
13949        serde_json::from_str(line).expect("valid evidence json")
13950    }
13951
13952    #[test]
13953    fn startup_emits_capability_decision_per_capability() {
13954        use ftui_core::caps_probe::{CapabilityDecision, ProbeOutcome, ProbeableCapability};
13955
13956        let evidence_path = temp_evidence_path("startup_emits_capability_decision");
13957        let sink = EvidenceSink::from_config(
13958            &crate::evidence_sink::EvidenceSinkConfig::enabled_file(&evidence_path),
13959        )
13960        .expect("sink config")
13961        .expect("sink enabled");
13962
13963        let decisions: Vec<CapabilityDecision> = ProbeableCapability::ALL
13964            .iter()
13965            .map(|&cap| {
13966                CapabilityDecision::build(cap, false, ProbeOutcome::Confirmed, None, false, true)
13967            })
13968            .collect();
13969
13970        assert_eq!(decisions.len(), ProbeableCapability::ALL.len());
13971
13972        let writer = TerminalWriter::new(
13973            Vec::new(),
13974            ScreenMode::Inline { ui_height: 5 },
13975            UiAnchor::Bottom,
13976            TerminalCapabilities::basic(),
13977        )
13978        .with_evidence_sink(sink)
13979        .with_capability_decisions(decisions);
13980        drop(writer);
13981
13982        let contents = std::fs::read_to_string(&evidence_path).expect("evidence file written");
13983        let cap_lines: Vec<&str> = contents
13984            .lines()
13985            .filter(|l| l.contains(r#""event":"capability_decision""#))
13986            .collect();
13987        assert_eq!(
13988            cap_lines.len(),
13989            ProbeableCapability::ALL.len(),
13990            "expected {} capability_decision lines, got {}",
13991            ProbeableCapability::ALL.len(),
13992            cap_lines.len()
13993        );
13994        for cap in ProbeableCapability::ALL {
13995            let cap_str = cap.as_str();
13996            assert!(
13997                cap_lines
13998                    .iter()
13999                    .any(|l| l.contains(&format!(r#""capability":"{cap_str}""#))),
14000                "missing capability_decision line for {cap_str}"
14001            );
14002        }
14003    }
14004
14005    #[test]
14006    fn headless_apply_resize_updates_model_and_dimensions() {
14007        struct ResizeModel {
14008            last_size: Option<(u16, u16)>,
14009        }
14010
14011        #[derive(Debug)]
14012        enum ResizeMsg {
14013            Resize(u16, u16),
14014            Other,
14015        }
14016
14017        impl From<Event> for ResizeMsg {
14018            fn from(event: Event) -> Self {
14019                match event {
14020                    Event::Resize { width, height } => ResizeMsg::Resize(width, height),
14021                    _ => ResizeMsg::Other,
14022                }
14023            }
14024        }
14025
14026        impl Model for ResizeModel {
14027            type Message = ResizeMsg;
14028
14029            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
14030                if let ResizeMsg::Resize(w, h) = msg {
14031                    self.last_size = Some((w, h));
14032                }
14033                Cmd::none()
14034            }
14035
14036            fn view(&self, _frame: &mut Frame) {}
14037        }
14038
14039        let mut program =
14040            headless_program_with_config(ResizeModel { last_size: None }, ProgramConfig::default());
14041        program.dirty = false;
14042
14043        program
14044            .apply_resize(0, 0, Duration::ZERO, false)
14045            .expect("resize");
14046
14047        assert_eq!(program.width, 1);
14048        assert_eq!(program.height, 1);
14049        assert_eq!(program.model().last_size, Some((1, 1)));
14050        assert!(program.dirty);
14051    }
14052
14053    #[test]
14054    fn headless_apply_resize_reconciles_subscriptions() {
14055        use crate::subscription::{StopSignal, SubId, Subscription, SubscriptionSender};
14056
14057        struct ResizeSubModel {
14058            subscribed: bool,
14059        }
14060
14061        #[derive(Debug)]
14062        enum ResizeSubMsg {
14063            Resize,
14064            Other,
14065        }
14066
14067        impl From<Event> for ResizeSubMsg {
14068            fn from(event: Event) -> Self {
14069                match event {
14070                    Event::Resize { .. } => Self::Resize,
14071                    _ => Self::Other,
14072                }
14073            }
14074        }
14075
14076        impl Model for ResizeSubModel {
14077            type Message = ResizeSubMsg;
14078
14079            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
14080                if matches!(msg, ResizeSubMsg::Resize) {
14081                    self.subscribed = true;
14082                }
14083                Cmd::none()
14084            }
14085
14086            fn view(&self, _frame: &mut Frame) {}
14087
14088            fn subscriptions(&self) -> Vec<Box<dyn Subscription<Self::Message>>> {
14089                if self.subscribed {
14090                    vec![Box::new(ResizeSubscription)]
14091                } else {
14092                    vec![]
14093                }
14094            }
14095        }
14096
14097        struct ResizeSubscription;
14098
14099        impl Subscription<ResizeSubMsg> for ResizeSubscription {
14100            fn id(&self) -> SubId {
14101                1
14102            }
14103
14104            fn run(&self, _sender: SubscriptionSender<ResizeSubMsg>, _stop: StopSignal) {}
14105        }
14106
14107        let mut program = headless_program_with_config(
14108            ResizeSubModel { subscribed: false },
14109            ProgramConfig::default(),
14110        );
14111
14112        assert_eq!(program.subscriptions.active_count(), 0);
14113        program
14114            .apply_resize(120, 40, Duration::ZERO, false)
14115            .expect("resize");
14116
14117        assert!(program.model().subscribed);
14118        assert_eq!(program.subscriptions.active_count(), 1);
14119    }
14120
14121    #[test]
14122    fn headless_execute_cmd_log_writes_output() {
14123        let mut program =
14124            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
14125        program.execute_cmd(Cmd::log("hello world")).expect("log");
14126
14127        let bytes = program.presenter.into_inner().expect("writer output");
14128        let output = String::from_utf8_lossy(&bytes);
14129        assert!(output.contains("hello world"));
14130    }
14131
14132    #[test]
14133    fn headless_process_task_results_updates_model() {
14134        struct TaskModel {
14135            updates: usize,
14136        }
14137
14138        #[derive(Debug)]
14139        enum TaskMsg {
14140            Done,
14141        }
14142
14143        impl From<Event> for TaskMsg {
14144            fn from(_: Event) -> Self {
14145                TaskMsg::Done
14146            }
14147        }
14148
14149        impl Model for TaskModel {
14150            type Message = TaskMsg;
14151
14152            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
14153                self.updates += 1;
14154                Cmd::none()
14155            }
14156
14157            fn view(&self, _frame: &mut Frame) {}
14158        }
14159
14160        let mut program =
14161            headless_program_with_config(TaskModel { updates: 0 }, ProgramConfig::default());
14162        program.dirty = false;
14163        program.task_sender.send(TaskMsg::Done).unwrap();
14164
14165        program
14166            .process_task_results()
14167            .expect("process task results");
14168        assert_eq!(program.model().updates, 1);
14169        assert!(program.dirty);
14170    }
14171
14172    #[test]
14173    fn run_invokes_on_shutdown_after_quit() {
14174        use std::sync::{
14175            Arc,
14176            atomic::{AtomicUsize, Ordering},
14177        };
14178
14179        struct ShutdownModel {
14180            shutdowns: Arc<AtomicUsize>,
14181        }
14182
14183        #[derive(Debug, Clone, Copy)]
14184        enum ShutdownMsg {
14185            Quit,
14186            ShutdownRan,
14187        }
14188
14189        impl From<Event> for ShutdownMsg {
14190            fn from(_: Event) -> Self {
14191                ShutdownMsg::Quit
14192            }
14193        }
14194
14195        impl Model for ShutdownModel {
14196            type Message = ShutdownMsg;
14197
14198            fn init(&mut self) -> Cmd<Self::Message> {
14199                Cmd::quit()
14200            }
14201
14202            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
14203                match msg {
14204                    ShutdownMsg::Quit => Cmd::quit(),
14205                    ShutdownMsg::ShutdownRan => {
14206                        self.shutdowns.fetch_add(1, Ordering::SeqCst);
14207                        Cmd::none()
14208                    }
14209                }
14210            }
14211
14212            fn view(&self, _frame: &mut Frame) {}
14213
14214            fn on_shutdown(&mut self) -> Cmd<Self::Message> {
14215                Cmd::msg(ShutdownMsg::ShutdownRan)
14216            }
14217        }
14218
14219        let shutdowns = Arc::new(AtomicUsize::new(0));
14220        let mut program = headless_program_with_config(
14221            ShutdownModel {
14222                shutdowns: Arc::clone(&shutdowns),
14223            },
14224            ProgramConfig::default(),
14225        );
14226
14227        program.run().expect("program run");
14228
14229        assert_eq!(shutdowns.load(Ordering::SeqCst), 1);
14230    }
14231
14232    /// G48 `.47.6`: the frame left in an inline terminal after a quit from
14233    /// a subscription message shows the state that update produced, not the
14234    /// one before โ€” even when the frame budget has degraded to SkipFrame.
14235    /// (A quit from a tick is drawn in the same loop iteration anyway.)
14236    #[test]
14237    fn inline_quit_from_subscription_draws_the_final_state_once() {
14238        use crate::subscription::{StopSignal, SubId, Subscription, SubscriptionSender};
14239        use std::sync::{
14240            Arc,
14241            atomic::{AtomicUsize, Ordering},
14242        };
14243
14244        /// Emits three messages back to back, then stops.
14245        struct Burst;
14246
14247        impl Subscription<CountMsg> for Burst {
14248            fn id(&self) -> SubId {
14249                0xB0_0057
14250            }
14251
14252            fn run(&self, sender: SubscriptionSender<CountMsg>, _stop: StopSignal) {
14253                for _ in 0..3 {
14254                    let _ = sender.send(CountMsg::Line);
14255                }
14256            }
14257        }
14258
14259        struct CountingModel {
14260            count: usize,
14261            last_drawn: Arc<AtomicUsize>,
14262        }
14263
14264        #[derive(Debug, Clone, Copy)]
14265        enum CountMsg {
14266            Line,
14267            Other,
14268        }
14269
14270        impl From<Event> for CountMsg {
14271            fn from(_: Event) -> Self {
14272                CountMsg::Other
14273            }
14274        }
14275
14276        impl Model for CountingModel {
14277            type Message = CountMsg;
14278
14279            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
14280                if matches!(msg, CountMsg::Line) {
14281                    self.count += 1;
14282                    if self.count == 3 {
14283                        return Cmd::quit();
14284                    }
14285                }
14286                Cmd::none()
14287            }
14288
14289            fn view(&self, _frame: &mut Frame) {
14290                self.last_drawn.store(self.count, Ordering::SeqCst);
14291            }
14292
14293            fn subscriptions(&self) -> Vec<Box<dyn Subscription<Self::Message>>> {
14294                vec![Box::new(Burst)]
14295            }
14296        }
14297
14298        for (mode, skip_frames, expected) in [
14299            (ScreenMode::Inline { ui_height: 4 }, false, Some(3)),
14300            (ScreenMode::Inline { ui_height: 4 }, true, Some(3)),
14301            // Alt-screen output is torn down on exit: no extra frame.
14302            (ScreenMode::AltScreen, false, None),
14303        ] {
14304            let last_drawn = Arc::new(AtomicUsize::new(usize::MAX));
14305            let config = ProgramConfig {
14306                screen_mode: mode,
14307                ..ProgramConfig::default()
14308            };
14309            let mut program = headless_program_with_config(
14310                CountingModel {
14311                    count: 0,
14312                    last_drawn: Arc::clone(&last_drawn),
14313                },
14314                config,
14315            );
14316            if skip_frames {
14317                program.budget.set_degradation(DegradationLevel::SkipFrame);
14318            }
14319            program.run().expect("program run");
14320            let drawn = last_drawn.load(Ordering::SeqCst);
14321            match expected {
14322                Some(count) => assert_eq!(drawn, count, "{mode:?} skip={skip_frames}"),
14323                None => assert_ne!(drawn, 3, "{mode:?}: no frame after quit"),
14324            }
14325        }
14326    }
14327
14328    #[test]
14329    fn inline_quit_from_init_draws_nothing() {
14330        use std::sync::{
14331            Arc,
14332            atomic::{AtomicUsize, Ordering},
14333        };
14334
14335        struct QuitAtInit {
14336            draws: Arc<AtomicUsize>,
14337        }
14338
14339        impl Model for QuitAtInit {
14340            type Message = Event;
14341
14342            fn init(&mut self) -> Cmd<Self::Message> {
14343                Cmd::quit()
14344            }
14345
14346            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
14347                Cmd::none()
14348            }
14349
14350            fn view(&self, _frame: &mut Frame) {
14351                self.draws.fetch_add(1, Ordering::SeqCst);
14352            }
14353        }
14354
14355        let draws = Arc::new(AtomicUsize::new(0));
14356        let mut program = headless_program_with_config(
14357            QuitAtInit {
14358                draws: Arc::clone(&draws),
14359            },
14360            ProgramConfig::default(),
14361        );
14362        program.run().expect("program run");
14363        assert_eq!(draws.load(Ordering::SeqCst), 0);
14364    }
14365
14366    #[test]
14367    fn run_processes_shutdown_task_results_before_exit() {
14368        use std::sync::{
14369            Arc,
14370            atomic::{AtomicUsize, Ordering},
14371        };
14372
14373        struct ShutdownTaskModel {
14374            shutdowns: Arc<AtomicUsize>,
14375        }
14376
14377        #[derive(Debug, Clone, Copy)]
14378        enum ShutdownTaskMsg {
14379            Quit,
14380            ShutdownRan,
14381        }
14382
14383        impl From<Event> for ShutdownTaskMsg {
14384            fn from(_: Event) -> Self {
14385                ShutdownTaskMsg::Quit
14386            }
14387        }
14388
14389        impl Model for ShutdownTaskModel {
14390            type Message = ShutdownTaskMsg;
14391
14392            fn init(&mut self) -> Cmd<Self::Message> {
14393                Cmd::quit()
14394            }
14395
14396            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
14397                match msg {
14398                    ShutdownTaskMsg::Quit => Cmd::quit(),
14399                    ShutdownTaskMsg::ShutdownRan => {
14400                        self.shutdowns.fetch_add(1, Ordering::SeqCst);
14401                        Cmd::none()
14402                    }
14403                }
14404            }
14405
14406            fn view(&self, _frame: &mut Frame) {}
14407
14408            fn on_shutdown(&mut self) -> Cmd<Self::Message> {
14409                Cmd::task(|| ShutdownTaskMsg::ShutdownRan)
14410            }
14411        }
14412
14413        let shutdowns = Arc::new(AtomicUsize::new(0));
14414        let mut program = headless_program_with_config(
14415            ShutdownTaskModel {
14416                shutdowns: Arc::clone(&shutdowns),
14417            },
14418            ProgramConfig::default(),
14419        );
14420
14421        program.run().expect("program run");
14422
14423        assert_eq!(shutdowns.load(Ordering::SeqCst), 1);
14424    }
14425
14426    #[test]
14427    fn run_processes_shutdown_task_results_with_effect_queue_backend() {
14428        use std::sync::{
14429            Arc,
14430            atomic::{AtomicUsize, Ordering},
14431        };
14432
14433        struct ShutdownTaskModel {
14434            shutdowns: Arc<AtomicUsize>,
14435        }
14436
14437        #[derive(Debug, Clone, Copy)]
14438        enum ShutdownTaskMsg {
14439            Quit,
14440            ShutdownRan,
14441        }
14442
14443        impl From<Event> for ShutdownTaskMsg {
14444            fn from(_: Event) -> Self {
14445                ShutdownTaskMsg::Quit
14446            }
14447        }
14448
14449        impl Model for ShutdownTaskModel {
14450            type Message = ShutdownTaskMsg;
14451
14452            fn init(&mut self) -> Cmd<Self::Message> {
14453                Cmd::quit()
14454            }
14455
14456            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
14457                match msg {
14458                    ShutdownTaskMsg::Quit => Cmd::quit(),
14459                    ShutdownTaskMsg::ShutdownRan => {
14460                        self.shutdowns.fetch_add(1, Ordering::SeqCst);
14461                        Cmd::none()
14462                    }
14463                }
14464            }
14465
14466            fn view(&self, _frame: &mut Frame) {}
14467
14468            fn on_shutdown(&mut self) -> Cmd<Self::Message> {
14469                Cmd::task(|| ShutdownTaskMsg::ShutdownRan)
14470            }
14471        }
14472
14473        let shutdowns = Arc::new(AtomicUsize::new(0));
14474        let mut program = headless_program_with_config(
14475            ShutdownTaskModel {
14476                shutdowns: Arc::clone(&shutdowns),
14477            },
14478            ProgramConfig::default().with_effect_queue(
14479                EffectQueueConfig::default().with_backend(TaskExecutorBackend::EffectQueue),
14480            ),
14481        );
14482
14483        program.run().expect("program run");
14484
14485        assert_eq!(shutdowns.load(Ordering::SeqCst), 1);
14486    }
14487
14488    #[test]
14489    fn shutdown_task_results_do_not_spawn_follow_up_tasks_after_executor_shutdown() {
14490        use std::sync::{
14491            Arc,
14492            atomic::{AtomicUsize, Ordering},
14493        };
14494
14495        struct ShutdownTaskModel {
14496            shutdowns: Arc<AtomicUsize>,
14497            follow_up_runs: Arc<AtomicUsize>,
14498        }
14499
14500        #[derive(Debug, Clone, Copy)]
14501        enum ShutdownTaskMsg {
14502            Quit,
14503            ShutdownRan,
14504            FollowUp,
14505        }
14506
14507        impl From<Event> for ShutdownTaskMsg {
14508            fn from(_: Event) -> Self {
14509                ShutdownTaskMsg::Quit
14510            }
14511        }
14512
14513        impl Model for ShutdownTaskModel {
14514            type Message = ShutdownTaskMsg;
14515
14516            fn init(&mut self) -> Cmd<Self::Message> {
14517                Cmd::quit()
14518            }
14519
14520            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
14521                match msg {
14522                    ShutdownTaskMsg::Quit => Cmd::quit(),
14523                    ShutdownTaskMsg::ShutdownRan => {
14524                        self.shutdowns.fetch_add(1, Ordering::SeqCst);
14525                        let follow_up_runs = Arc::clone(&self.follow_up_runs);
14526                        Cmd::task(move || {
14527                            follow_up_runs.fetch_add(1, Ordering::SeqCst);
14528                            ShutdownTaskMsg::FollowUp
14529                        })
14530                    }
14531                    ShutdownTaskMsg::FollowUp => {
14532                        self.follow_up_runs.fetch_add(1, Ordering::SeqCst);
14533                        Cmd::none()
14534                    }
14535                }
14536            }
14537
14538            fn view(&self, _frame: &mut Frame) {}
14539
14540            fn on_shutdown(&mut self) -> Cmd<Self::Message> {
14541                Cmd::task(|| ShutdownTaskMsg::ShutdownRan)
14542            }
14543        }
14544
14545        let shutdowns = Arc::new(AtomicUsize::new(0));
14546        let follow_up_runs = Arc::new(AtomicUsize::new(0));
14547        let mut program = headless_program_with_config(
14548            ShutdownTaskModel {
14549                shutdowns: Arc::clone(&shutdowns),
14550                follow_up_runs: Arc::clone(&follow_up_runs),
14551            },
14552            ProgramConfig::default(),
14553        );
14554
14555        program.run().expect("program run");
14556
14557        assert_eq!(shutdowns.load(Ordering::SeqCst), 1);
14558        assert_eq!(follow_up_runs.load(Ordering::SeqCst), 0);
14559    }
14560
14561    #[test]
14562    fn run_quit_from_init_skips_initial_render_and_subscription_start() {
14563        use crate::subscription::{StopSignal, SubId, Subscription, SubscriptionSender};
14564
14565        struct InitQuitModel {
14566            render_calls: Arc<AtomicUsize>,
14567            subscription_starts: Arc<AtomicUsize>,
14568        }
14569
14570        #[derive(Debug, Clone, Copy)]
14571        enum InitQuitMsg {
14572            Noop,
14573        }
14574
14575        impl From<Event> for InitQuitMsg {
14576            fn from(_: Event) -> Self {
14577                Self::Noop
14578            }
14579        }
14580
14581        impl Model for InitQuitModel {
14582            type Message = InitQuitMsg;
14583
14584            fn init(&mut self) -> Cmd<Self::Message> {
14585                Cmd::quit()
14586            }
14587
14588            fn update(&mut self, _: Self::Message) -> Cmd<Self::Message> {
14589                Cmd::none()
14590            }
14591
14592            fn view(&self, _frame: &mut Frame) {
14593                self.render_calls.fetch_add(1, Ordering::SeqCst);
14594            }
14595
14596            fn subscriptions(&self) -> Vec<Box<dyn Subscription<Self::Message>>> {
14597                vec![Box::new(InitQuitSubscription {
14598                    starts: Arc::clone(&self.subscription_starts),
14599                })]
14600            }
14601        }
14602
14603        struct InitQuitSubscription {
14604            starts: Arc<AtomicUsize>,
14605        }
14606
14607        impl Subscription<InitQuitMsg> for InitQuitSubscription {
14608            fn id(&self) -> SubId {
14609                1
14610            }
14611
14612            fn run(&self, _sender: SubscriptionSender<InitQuitMsg>, stop: StopSignal) {
14613                self.starts.fetch_add(1, Ordering::SeqCst);
14614                let _ = stop.wait_timeout(Duration::from_millis(10));
14615            }
14616        }
14617
14618        let render_calls = Arc::new(AtomicUsize::new(0));
14619        let subscription_starts = Arc::new(AtomicUsize::new(0));
14620        let mut program = headless_program_with_config(
14621            InitQuitModel {
14622                render_calls: Arc::clone(&render_calls),
14623                subscription_starts: Arc::clone(&subscription_starts),
14624            },
14625            ProgramConfig::default(),
14626        );
14627
14628        program.run().expect("program run");
14629
14630        assert_eq!(render_calls.load(Ordering::SeqCst), 0);
14631        assert_eq!(subscription_starts.load(Ordering::SeqCst), 0);
14632    }
14633
14634    #[test]
14635    fn run_invokes_on_shutdown_before_returning_signal_error() {
14636        use std::sync::{
14637            Arc,
14638            atomic::{AtomicUsize, Ordering},
14639        };
14640
14641        struct ShutdownModel {
14642            shutdowns: Arc<AtomicUsize>,
14643        }
14644
14645        #[derive(Debug, Clone, Copy)]
14646        enum ShutdownMsg {
14647            Noop,
14648            ShutdownRan,
14649        }
14650
14651        impl From<Event> for ShutdownMsg {
14652            fn from(_: Event) -> Self {
14653                ShutdownMsg::Noop
14654            }
14655        }
14656
14657        impl Model for ShutdownModel {
14658            type Message = ShutdownMsg;
14659
14660            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
14661                match msg {
14662                    ShutdownMsg::Noop => Cmd::none(),
14663                    ShutdownMsg::ShutdownRan => {
14664                        self.shutdowns.fetch_add(1, Ordering::SeqCst);
14665                        Cmd::none()
14666                    }
14667                }
14668            }
14669
14670            fn view(&self, _frame: &mut Frame) {}
14671
14672            fn on_shutdown(&mut self) -> Cmd<Self::Message> {
14673                Cmd::msg(ShutdownMsg::ShutdownRan)
14674            }
14675        }
14676
14677        let shutdowns = Arc::new(AtomicUsize::new(0));
14678        let mut program = headless_signal_program_with_config(
14679            ShutdownModel {
14680                shutdowns: Arc::clone(&shutdowns),
14681            },
14682            ProgramConfig::default().with_signal_interception(true),
14683        );
14684
14685        program.inject_termination_signal(2);
14686        let err = program.run().expect_err("signal should stop runtime");
14687
14688        assert_eq!(shutdowns.load(Ordering::SeqCst), 1);
14689        assert_eq!(signal_termination_from_error(&err), Some(2));
14690        assert_eq!(program.pending_termination_signal(), None);
14691    }
14692
14693    /// Regression test for the cross-test signal race: two headless programs
14694    /// running concurrently, each with its own injected signal, must both
14695    /// terminate with their own signal. Before the per-program slot existed,
14696    /// any other test constructing or finishing a headless program cleared
14697    /// the process-global slot and left the loop waiting forever.
14698    #[test]
14699    fn two_concurrent_headless_programs_with_independent_pending_signals_both_terminate() {
14700        fn run_with_signal(signal: i32) -> Option<i32> {
14701            let mut program = headless_signal_program_with_config(
14702                TestModel { value: 0 },
14703                ProgramConfig::default().with_signal_interception(true),
14704            );
14705            program.inject_termination_signal(signal);
14706            let err = program.run().expect_err("signal should stop runtime");
14707            assert_eq!(program.pending_termination_signal(), None);
14708            signal_termination_from_error(&err)
14709        }
14710
14711        let sigint = std::thread::spawn(|| run_with_signal(2));
14712        let sigterm = std::thread::spawn(|| run_with_signal(15));
14713        // A third program without a pending signal must not observe either.
14714        let clean = std::thread::spawn(|| {
14715            let program = headless_signal_program_with_config(
14716                TestModel { value: 0 },
14717                ProgramConfig::default().with_signal_interception(true),
14718            );
14719            program.observed_termination_signal()
14720        });
14721
14722        assert_eq!(sigint.join().expect("sigint thread"), Some(2));
14723        assert_eq!(sigterm.join().expect("sigterm thread"), Some(15));
14724        assert_eq!(clean.join().expect("clean thread"), None);
14725    }
14726
14727    /// `DEFAULT_BACKEND` must agree with the cfg predicates that select the
14728    /// `AppBuilder::run` dispatch, so consumers can trust it to describe what
14729    /// `run()` will do in their build.
14730    #[test]
14731    fn default_backend_constant_matches_cfg() {
14732        let expected = if cfg!(all(feature = "native-backend", unix)) {
14733            "native"
14734        } else if cfg!(feature = "crossterm-compat") {
14735            "crossterm"
14736        } else {
14737            "none"
14738        };
14739        assert_eq!(DEFAULT_BACKEND, expected);
14740        assert!(NO_BACKEND_MESSAGE.contains("native-backend"));
14741        assert!(NO_BACKEND_MESSAGE.contains("crossterm-compat"));
14742    }
14743
14744    /// Without a compiled backend, `run()` must fail up front with an error
14745    /// that names the features to enable instead of pretending to run.
14746    #[cfg(not(any(all(feature = "native-backend", unix), feature = "crossterm-compat")))]
14747    #[test]
14748    fn run_without_backend_reports_missing_features() {
14749        let err = App::new(TestModel { value: 0 })
14750            .run()
14751            .expect_err("no backend compiled");
14752        assert_eq!(err.kind(), io::ErrorKind::Unsupported);
14753        assert_eq!(err.to_string(), NO_BACKEND_MESSAGE);
14754        let err = App::new(TestModel { value: 0 })
14755            .run_crossterm()
14756            .expect_err("crossterm not compiled");
14757        assert_eq!(err.kind(), io::ErrorKind::Unsupported);
14758        assert!(err.to_string().contains("crossterm-compat"));
14759    }
14760
14761    #[test]
14762    fn inject_termination_signal_first_signal_wins() {
14763        let program = headless_signal_program_with_config(
14764            TestModel { value: 0 },
14765            ProgramConfig::default().with_signal_interception(true),
14766        );
14767        assert_eq!(program.pending_termination_signal(), None);
14768        program.inject_termination_signal(15);
14769        program.inject_termination_signal(2);
14770        assert_eq!(program.pending_termination_signal(), Some(15));
14771        assert_eq!(program.observed_termination_signal(), Some(15));
14772
14773        // Interception disabled: the slot is still recorded but not observed.
14774        let quiet = headless_signal_program_with_config(
14775            TestModel { value: 0 },
14776            ProgramConfig::default().with_signal_interception(false),
14777        );
14778        quiet.inject_termination_signal(2);
14779        assert_eq!(quiet.pending_termination_signal(), Some(2));
14780        assert_eq!(quiet.observed_termination_signal(), None);
14781    }
14782
14783    #[test]
14784    fn run_pending_signal_skips_initial_render_and_subscription_start() {
14785        use crate::subscription::{StopSignal, SubId, Subscription, SubscriptionSender};
14786
14787        struct SignalStopModel {
14788            render_calls: Arc<AtomicUsize>,
14789            subscription_starts: Arc<AtomicUsize>,
14790        }
14791
14792        #[derive(Debug, Clone, Copy)]
14793        enum SignalStopMsg {
14794            Noop,
14795        }
14796
14797        impl From<Event> for SignalStopMsg {
14798            fn from(_: Event) -> Self {
14799                Self::Noop
14800            }
14801        }
14802
14803        impl Model for SignalStopModel {
14804            type Message = SignalStopMsg;
14805
14806            fn update(&mut self, _: Self::Message) -> Cmd<Self::Message> {
14807                Cmd::none()
14808            }
14809
14810            fn view(&self, _frame: &mut Frame) {
14811                self.render_calls.fetch_add(1, Ordering::SeqCst);
14812            }
14813
14814            fn subscriptions(&self) -> Vec<Box<dyn Subscription<Self::Message>>> {
14815                vec![Box::new(SignalStopSubscription {
14816                    starts: Arc::clone(&self.subscription_starts),
14817                })]
14818            }
14819        }
14820
14821        struct SignalStopSubscription {
14822            starts: Arc<AtomicUsize>,
14823        }
14824
14825        impl Subscription<SignalStopMsg> for SignalStopSubscription {
14826            fn id(&self) -> SubId {
14827                11
14828            }
14829
14830            fn run(&self, _sender: SubscriptionSender<SignalStopMsg>, stop: StopSignal) {
14831                self.starts.fetch_add(1, Ordering::SeqCst);
14832                let _ = stop.wait_timeout(Duration::from_millis(10));
14833            }
14834        }
14835
14836        let render_calls = Arc::new(AtomicUsize::new(0));
14837        let subscription_starts = Arc::new(AtomicUsize::new(0));
14838        let mut program = headless_signal_program_with_config(
14839            SignalStopModel {
14840                render_calls: Arc::clone(&render_calls),
14841                subscription_starts: Arc::clone(&subscription_starts),
14842            },
14843            ProgramConfig::default().with_signal_interception(true),
14844        );
14845
14846        program.inject_termination_signal(15);
14847        let err = program.run().expect_err("signal should stop runtime");
14848
14849        assert_eq!(signal_termination_from_error(&err), Some(15));
14850        assert_eq!(render_calls.load(Ordering::SeqCst), 0);
14851        assert_eq!(subscription_starts.load(Ordering::SeqCst), 0);
14852        assert_eq!(program.pending_termination_signal(), None);
14853    }
14854
14855    #[test]
14856    fn headless_should_tick_and_timeout_behaviors() {
14857        let mut program =
14858            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
14859        program.tick_rate = Some(Duration::from_millis(5));
14860        program.last_tick = Instant::now() - Duration::from_millis(10);
14861
14862        assert!(program.should_tick());
14863        assert!(!program.should_tick());
14864        // The rate persists: Cmd::tick sets a recurring tick, not a one-shot
14865        // timer (README command table), so the next interval fires again.
14866        program.last_tick = Instant::now() - Duration::from_millis(10);
14867        assert!(program.should_tick());
14868
14869        let timeout = program.effective_timeout();
14870        assert!(timeout <= Duration::from_millis(5));
14871
14872        program.tick_rate = None;
14873        program.poll_timeout = Duration::from_millis(33);
14874        assert_eq!(program.effective_timeout(), Duration::from_millis(33));
14875    }
14876
14877    #[test]
14878    fn headless_effective_timeout_respects_resize_coalescer() {
14879        let mut config = ProgramConfig::default().with_resize_behavior(ResizeBehavior::Throttled);
14880        config.resize_coalescer.steady_delay_ms = 0;
14881        config.resize_coalescer.burst_delay_ms = 0;
14882
14883        let mut program = headless_program_with_config(TestModel { value: 0 }, config);
14884        program.tick_rate = Some(Duration::from_millis(50));
14885
14886        program.resize_coalescer.handle_resize(120, 40);
14887        assert!(program.resize_coalescer.has_pending());
14888
14889        let timeout = program.effective_timeout();
14890        assert_eq!(timeout, Duration::ZERO);
14891    }
14892
14893    #[test]
14894    fn headless_ui_height_remeasure_clears_auto_height() {
14895        let mut config = ProgramConfig::inline_auto(2, 6);
14896        config.inline_auto_remeasure = Some(InlineAutoRemeasureConfig::default());
14897
14898        let mut program = headless_program_with_config(TestModel { value: 0 }, config);
14899        program.dirty = false;
14900        program.presenter.set_auto_ui_height(5);
14901
14902        assert_eq!(program.presenter.auto_ui_height(), Some(5));
14903        program.request_ui_height_remeasure();
14904
14905        assert_eq!(program.presenter.auto_ui_height(), None);
14906        assert!(program.dirty);
14907    }
14908
14909    #[test]
14910    fn headless_recording_lifecycle_and_locale_change() {
14911        let mut program =
14912            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
14913        program.dirty = false;
14914
14915        program.start_recording("demo");
14916        assert!(program.is_recording());
14917        let recorded = program.stop_recording();
14918        assert!(recorded.is_some());
14919        assert!(!program.is_recording());
14920
14921        let prev_dirty = program.dirty;
14922        program.locale_context.set_locale("fr");
14923        program.check_locale_change();
14924        assert!(program.dirty || prev_dirty);
14925    }
14926
14927    #[test]
14928    fn frame_text_direction_follows_locale_context() {
14929        use std::cell::RefCell;
14930        use std::rc::Rc;
14931
14932        struct DirectionModel {
14933            directions: Rc<RefCell<Vec<ftui_render::TextDirection>>>,
14934        }
14935
14936        #[derive(Debug)]
14937        enum DirectionMsg {
14938            Noop,
14939        }
14940
14941        impl From<Event> for DirectionMsg {
14942            fn from(_: Event) -> Self {
14943                DirectionMsg::Noop
14944            }
14945        }
14946
14947        impl Model for DirectionModel {
14948            type Message = DirectionMsg;
14949
14950            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
14951                Cmd::none()
14952            }
14953
14954            fn view(&self, frame: &mut Frame) {
14955                self.directions.borrow_mut().push(frame.text_direction);
14956            }
14957        }
14958
14959        let directions = Rc::new(RefCell::new(Vec::new()));
14960        let model = DirectionModel {
14961            directions: Rc::clone(&directions),
14962        };
14963        let config = ProgramConfig::default()
14964            .with_locale("ar")
14965            .with_budget(FrameBudgetConfig::strict(Duration::from_secs(60)));
14966        let mut program = headless_program_with_config(model, config);
14967
14968        program.render_frame().expect("render initial frame");
14969        assert_eq!(program.frame_idx, 1);
14970        assert_eq!(
14971            directions.borrow().as_slice(),
14972            &[ftui_render::TextDirection::Rtl]
14973        );
14974        assert!(!program.dirty);
14975
14976        program.locale_context.set_locale("en");
14977        program.check_locale_change();
14978        assert!(
14979            program.dirty,
14980            "check_locale_change must trigger redraw on locale switch"
14981        );
14982
14983        program
14984            .render_frame()
14985            .expect("render frame after locale change");
14986        assert_eq!(program.frame_idx, 2);
14987        assert_eq!(
14988            directions.borrow().as_slice(),
14989            &[
14990                ftui_render::TextDirection::Rtl,
14991                ftui_render::TextDirection::Ltr,
14992            ]
14993        );
14994    }
14995
14996    #[test]
14997    fn headless_render_frame_marks_clean_and_sets_diff() {
14998        struct RenderModel;
14999
15000        #[derive(Debug)]
15001        enum RenderMsg {
15002            Noop,
15003        }
15004
15005        impl From<Event> for RenderMsg {
15006            fn from(_: Event) -> Self {
15007                RenderMsg::Noop
15008            }
15009        }
15010
15011        impl Model for RenderModel {
15012            type Message = RenderMsg;
15013
15014            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
15015                Cmd::none()
15016            }
15017
15018            fn view(&self, frame: &mut Frame) {
15019                frame.buffer.set_raw(0, 0, Cell::from_char('X'));
15020            }
15021        }
15022
15023        let mut program = headless_program_with_config(
15024            RenderModel,
15025            ProgramConfig::default()
15026                .with_budget(FrameBudgetConfig::strict(Duration::from_secs(60))),
15027        );
15028        program.render_frame().expect("render frame");
15029
15030        assert!(!program.dirty);
15031        assert!(program.presenter.last_diff_strategy().is_some());
15032        assert_eq!(program.frame_idx, 1);
15033    }
15034
15035    // frankentui#104: a frame that ran over its budget is still presented,
15036    // an explicit SkipFrame still skips, and `FrameBudgetConfig::strict` never
15037    // skips. These use only API that predates the fix, so they also run on the
15038    // commit before the fix, where the defect makes them fail (the SkipFrame pin
15039    // passes there too).
15040
15041    /// A model whose view takes `cost` and counts its draws.
15042    struct SlowViewModel {
15043        cost: Duration,
15044        draws: Arc<AtomicUsize>,
15045    }
15046
15047    #[derive(Debug)]
15048    enum SlowViewMsg {
15049        Noop,
15050    }
15051
15052    impl From<Event> for SlowViewMsg {
15053        fn from(_: Event) -> Self {
15054            SlowViewMsg::Noop
15055        }
15056    }
15057
15058    impl Model for SlowViewModel {
15059        type Message = SlowViewMsg;
15060
15061        fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
15062            Cmd::none()
15063        }
15064
15065        fn view(&self, frame: &mut Frame) {
15066            std::thread::sleep(self.cost);
15067            frame.buffer.set_raw(0, 0, Cell::from_char('X'));
15068            self.draws.fetch_add(1, Ordering::SeqCst);
15069        }
15070    }
15071
15072    fn slow_view_program(
15073        cost: Duration,
15074        config: ProgramConfig,
15075    ) -> (
15076        Program<SlowViewModel, HeadlessEventSource, TerminalPresenter<Vec<u8>>>,
15077        Arc<AtomicUsize>,
15078    ) {
15079        let draws = Arc::new(AtomicUsize::new(0));
15080        let model = SlowViewModel {
15081            cost,
15082            draws: Arc::clone(&draws),
15083        };
15084        let mut program = headless_program_with_config(model, config);
15085        program.dirty = true;
15086        (program, draws)
15087    }
15088
15089    #[test]
15090    fn over_budget_rendered_frame_is_presented() {
15091        // 1 ms budget, 5 ms view: every frame runs over budget after render.
15092        for governor in [true, false] {
15093            let mut config = ProgramConfig::default()
15094                .with_budget(FrameBudgetConfig::with_total(Duration::from_millis(1)));
15095            if !governor {
15096                config = config.without_load_governor();
15097            }
15098            let (mut program, draws) = slow_view_program(Duration::from_millis(5), config);
15099            program.render_frame().expect("render over-budget frame");
15100
15101            assert_eq!(
15102                draws.load(Ordering::SeqCst),
15103                1,
15104                "the frame was rendered (governor={governor})"
15105            );
15106            assert!(
15107                program.budget.remaining().is_zero(),
15108                "precondition: the frame ran over its budget (governor={governor})"
15109            );
15110            assert!(
15111                !program.dirty,
15112                "an over-budget frame that rendered must be presented (governor={governor})"
15113            );
15114            assert!(
15115                program.presenter.last_diff_strategy().is_some(),
15116                "the presenter must have run (governor={governor})"
15117            );
15118        }
15119    }
15120
15121    #[test]
15122    fn explicit_skip_frame_still_skips_before_render() {
15123        // Legacy budget, so no controller decision can move the level; the
15124        // level was just set, so the upgrade cooldown holds it for this frame.
15125        let (mut program, draws) = slow_view_program(
15126            Duration::ZERO,
15127            ProgramConfig::default().without_load_governor(),
15128        );
15129        program.budget.set_degradation(DegradationLevel::SkipFrame);
15130        program.render_frame().expect("render at SkipFrame");
15131
15132        assert_eq!(
15133            draws.load(Ordering::SeqCst),
15134            0,
15135            "SkipFrame with frame skips allowed must skip before render"
15136        );
15137        assert!(
15138            program.dirty,
15139            "a skipped frame keeps the update pending for a later frame"
15140        );
15141        assert!(program.presenter.last_diff_strategy().is_none());
15142    }
15143
15144    #[test]
15145    fn strict_budget_never_skips_a_frame() {
15146        // strict(): frame skips disallowed. Even at SkipFrame and over budget,
15147        // the frame is rendered and presented, as its documentation says.
15148        let (mut program, draws) = slow_view_program(
15149            Duration::from_millis(5),
15150            ProgramConfig::default()
15151                .without_load_governor()
15152                .with_budget(FrameBudgetConfig::strict(Duration::from_millis(1))),
15153        );
15154        program.budget.set_degradation(DegradationLevel::SkipFrame);
15155        program.render_frame().expect("render strict frame");
15156
15157        assert_eq!(
15158            draws.load(Ordering::SeqCst),
15159            1,
15160            "strict() must not skip before render"
15161        );
15162        assert!(
15163            program.budget.remaining().is_zero(),
15164            "precondition: the frame ran over its budget"
15165        );
15166        assert!(!program.dirty, "strict() must present the rendered frame");
15167        assert!(program.presenter.last_diff_strategy().is_some());
15168    }
15169
15170    /// CONTRACT (bd-1za0z F2): when a guardrail alert fires during
15171    /// render_frame, a `guardrail_snapshot` evidence row is exported through
15172    /// the configured sink โ€” GuardrailSnapshot::to_jsonl is live production
15173    /// observability, not dead code.
15174    #[test]
15175    fn headless_render_frame_emits_guardrail_snapshot_evidence_on_alert() {
15176        struct AlertModel;
15177
15178        #[derive(Debug)]
15179        enum AlertMsg {
15180            Noop,
15181        }
15182
15183        impl From<Event> for AlertMsg {
15184            fn from(_: Event) -> Self {
15185                AlertMsg::Noop
15186            }
15187        }
15188
15189        impl Model for AlertModel {
15190            type Message = AlertMsg;
15191
15192            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
15193                Cmd::none()
15194            }
15195
15196            fn view(&self, frame: &mut Frame) {
15197                frame.buffer.set_raw(0, 0, Cell::from_char('X'));
15198            }
15199        }
15200
15201        let evidence_path = temp_evidence_path("guardrail_snapshot");
15202        let config = ProgramConfig {
15203            guardrails: GuardrailsConfig {
15204                // Soft limit of one byte: the very first frame alerts, so
15205                // no memory pressure needs to be manufactured.
15206                memory: MemoryBudgetConfig {
15207                    soft_limit_bytes: 1,
15208                    ..MemoryBudgetConfig::default()
15209                },
15210                queue: QueueConfig::default(),
15211                ..Default::default()
15212            },
15213            evidence_sink: EvidenceSinkConfig::enabled_file(&evidence_path),
15214            ..Default::default()
15215        };
15216
15217        let mut program = headless_program_with_config(AlertModel, config);
15218        program.dirty = true;
15219        program.render_frame().expect("render frame with alert");
15220
15221        let contents =
15222            std::fs::read_to_string(&evidence_path).expect("guardrail evidence file written");
15223        assert!(
15224            contents.contains(r#""event":"guardrail_snapshot""#),
15225            "alerting frame must export a guardrail_snapshot row; got: {contents}"
15226        );
15227        assert!(
15228            contents.contains(r#""mem_soft_violations":"#),
15229            "snapshot row must carry the violation counters"
15230        );
15231    }
15232
15233    #[test]
15234    fn headless_render_frame_emits_guardrail_snapshot_on_leak_alert() {
15235        let evidence_path = temp_evidence_path("allocation_leak_retained");
15236        let config = ProgramConfig {
15237            evidence_sink: EvidenceSinkConfig::enabled_file(&evidence_path),
15238            ..Default::default()
15239        };
15240        let mut program = headless_program_with_config(TestModel { value: 0 }, config);
15241        for _ in 0..200 {
15242            program.render_frame().expect("stationary render");
15243            assert!(!program.guardrails.snapshot().leak_alert);
15244        }
15245
15246        // Exercise the real retained-capacity sensor, not an injected verdict.
15247        let before = program.frame_arena.allocated_bytes();
15248        program
15249            .frame_arena
15250            .alloc_slice(&vec![0u8; before + 64 * 1024]);
15251        assert!(program.frame_arena.allocated_bytes() > before);
15252        program.render_frame().expect("render with capacity growth");
15253        let contents = std::fs::read_to_string(&evidence_path).expect("retained leak evidence");
15254        let snapshots: Vec<Value> = contents
15255            .lines()
15256            .map(|line| serde_json::from_str::<Value>(line).expect("valid evidence JSON"))
15257            .filter(|row| row["event"] == "guardrail_snapshot")
15258            .collect();
15259        assert_eq!(snapshots.len(), 1, "only the capacity jump should alert");
15260        let snapshot = &snapshots[0]["snapshot"];
15261        assert_eq!(snapshot["leak_alert"], true);
15262        assert!(snapshot["leak_cusum_upper"].as_f64().unwrap() > 8.0);
15263        assert!(snapshot["leak_e_value"].as_f64().unwrap().is_finite());
15264        assert!(snapshot["leak_mean_bytes"].as_f64().unwrap() > 0.0);
15265        assert_eq!(snapshot["mem_soft_violations"], 0);
15266        // Keep the evidence file for inspection (AGENTS.md Rule 1).
15267    }
15268
15269    #[test]
15270    fn headless_emergency_shed_resets_leak_baseline() {
15271        let config = ProgramConfig {
15272            guardrails: GuardrailsConfig {
15273                memory: MemoryBudgetConfig {
15274                    soft_limit_bytes: 1,
15275                    hard_limit_bytes: 1,
15276                    emergency_limit_bytes: 1,
15277                },
15278                ..Default::default()
15279            },
15280            ..Default::default()
15281        };
15282        let mut program = headless_program_with_config(TestModel { value: 0 }, config);
15283        program.frame_arena.alloc_slice(&[0u8; 1024]);
15284        program.render_frame().expect("emergency shed");
15285        let snapshot = program.guardrails.snapshot();
15286        assert_eq!(snapshot.memory_emergency_violations, 1);
15287        assert_eq!(snapshot.frames_checked, 1);
15288        assert_eq!(snapshot.leak_mean_bytes, 0.0);
15289        assert!(!snapshot.leak_alert);
15290    }
15291
15292    /// The inline-auto VOI sampler's decision is exported through the evidence
15293    /// sink (`voi_decision`), not only through the in-process telemetry
15294    /// snapshot, so operators can grep why a remeasure did or did not happen.
15295    #[test]
15296    fn headless_inline_auto_exports_voi_decision_evidence() {
15297        struct TallModel;
15298
15299        #[derive(Debug)]
15300        enum TallMsg {
15301            Noop,
15302        }
15303
15304        impl From<Event> for TallMsg {
15305            fn from(_: Event) -> Self {
15306                TallMsg::Noop
15307            }
15308        }
15309
15310        impl Model for TallModel {
15311            type Message = TallMsg;
15312
15313            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
15314                Cmd::none()
15315            }
15316
15317            fn view(&self, frame: &mut Frame) {
15318                frame.buffer.set_raw(0, 0, Cell::from_char('V'));
15319            }
15320        }
15321
15322        let evidence_path = temp_evidence_path("voi_decision");
15323        let config = ProgramConfig::inline_auto(1, 6)
15324            .with_evidence_sink(EvidenceSinkConfig::enabled_file(&evidence_path));
15325        assert!(config.inline_auto_remeasure.is_some());
15326
15327        let mut program = headless_program_with_config(TallModel, config);
15328        for _ in 0..3 {
15329            program.dirty = true;
15330            program.render_frame().expect("render inline-auto frame");
15331        }
15332
15333        let contents = std::fs::read_to_string(&evidence_path).expect("evidence file written");
15334        assert!(
15335            contents.contains(r#""event":"voi_decision""#),
15336            "inline-auto frames must export the VOI decision; got: {contents}"
15337        );
15338        assert!(
15339            contents.contains(r#""should_sample":"#) && contents.contains(r#""voi_gain":"#),
15340            "voi_decision row must carry the sampler reasoning"
15341        );
15342    }
15343
15344    #[test]
15345    fn voi_sample_written_for_inline_auto() {
15346        headless_inline_auto_exports_voi_decision_evidence();
15347    }
15348
15349    #[test]
15350    fn inline_auto_remeasure_emits_voi_sample_evidence() {
15351        struct TallModel;
15352
15353        #[derive(Debug)]
15354        enum TallMsg {
15355            Noop,
15356        }
15357
15358        impl From<Event> for TallMsg {
15359            fn from(_: Event) -> Self {
15360                TallMsg::Noop
15361            }
15362        }
15363
15364        impl Model for TallModel {
15365            type Message = TallMsg;
15366
15367            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
15368                Cmd::none()
15369            }
15370
15371            fn view(&self, frame: &mut Frame) {
15372                frame.buffer.set_raw(0, 0, Cell::from_char('V'));
15373            }
15374        }
15375
15376        let evidence_path = temp_evidence_path("voi_sample_inline_auto");
15377        let config = ProgramConfig::inline_auto(1, 6)
15378            .with_evidence_sink(EvidenceSinkConfig::enabled_file(&evidence_path));
15379
15380        let mut program = headless_program_with_config(TallModel, config);
15381        program.dirty = true;
15382        program.render_frame().expect("render inline-auto frame");
15383
15384        let contents = std::fs::read_to_string(&evidence_path).expect("evidence file written");
15385        let voi_sample_line = contents
15386            .lines()
15387            .find(|line| line.contains(r#""event":"voi_sample""#))
15388            .expect("voi_sample line emitted for inline_auto");
15389        let parsed: serde_json::Value =
15390            serde_json::from_str(voi_sample_line).expect("valid voi_sample json");
15391        assert_eq!(parsed["source"].as_str(), Some("inline_auto"));
15392        assert!(parsed["alpha"].is_number());
15393        assert!(parsed["beta"].is_number());
15394        assert!(parsed["voi"].is_number());
15395        assert!(parsed["sample_cost"].is_number());
15396        assert!(matches!(
15397            parsed["decision"].as_str(),
15398            Some("sample" | "skip")
15399        ));
15400    }
15401
15402    #[test]
15403    fn virtualized_list_remeasure_request_emits_voi_sample_evidence() {
15404        struct RemeasureModel;
15405
15406        #[derive(Debug)]
15407        enum RemeasureMsg {}
15408
15409        impl From<Event> for RemeasureMsg {
15410            fn from(_: Event) -> Self {
15411                unreachable!()
15412            }
15413        }
15414
15415        impl Model for RemeasureModel {
15416            type Message = RemeasureMsg;
15417
15418            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
15419                Cmd::none()
15420            }
15421
15422            fn view(&self, frame: &mut Frame) {
15423                frame.buffer.set_raw(0, 0, Cell::from_char('L'));
15424                frame.push_remeasure_request(ftui_render::frame::RemeasureRequest {
15425                    widget_id: 42,
15426                    index: 3,
15427                    voi: 0.027_778,
15428                    cost: 0.01,
15429                    alpha: 1.0,
15430                    beta: 1.0,
15431                });
15432            }
15433        }
15434
15435        let evidence_path = temp_evidence_path("voi_sample_virtualized_list");
15436        let config = ProgramConfig::default()
15437            .with_evidence_sink(EvidenceSinkConfig::enabled_file(&evidence_path));
15438
15439        let mut program = headless_program_with_config(RemeasureModel, config);
15440        program.dirty = true;
15441        program.render_frame().expect("render frame");
15442
15443        let contents = std::fs::read_to_string(&evidence_path).expect("evidence file written");
15444        let voi_sample_line = contents
15445            .lines()
15446            .find(|line| line.contains(r#""event":"voi_sample""#))
15447            .expect("voi_sample line emitted for virtualized_list");
15448        let parsed: serde_json::Value =
15449            serde_json::from_str(voi_sample_line).expect("valid voi_sample json");
15450        assert_eq!(parsed["source"].as_str(), Some("virtualized_list"));
15451        assert_eq!(parsed["widget_id"].as_u64(), Some(42));
15452        assert_eq!(parsed["index"].as_u64(), Some(3));
15453        assert!((parsed["alpha"].as_f64().unwrap() - 1.0).abs() < 1e-6);
15454        assert!((parsed["beta"].as_f64().unwrap() - 1.0).abs() < 1e-6);
15455        assert!(parsed["voi"].as_f64().unwrap() > 0.02);
15456        assert!((parsed["sample_cost"].as_f64().unwrap() - 0.01).abs() < 1e-6);
15457        assert_eq!(parsed["decision"].as_str(), Some("sample"));
15458    }
15459
15460    #[test]
15461    fn voi_sample_line_is_valid_json_with_registered_fields() {
15462        virtualized_list_remeasure_request_emits_voi_sample_evidence();
15463        inline_auto_remeasure_emits_voi_sample_evidence();
15464    }
15465
15466    #[test]
15467    fn voi_sample_not_written_without_auto_bounds() {
15468        struct NoAutoModel;
15469
15470        #[derive(Debug)]
15471        enum NoAutoMsg {}
15472
15473        impl From<Event> for NoAutoMsg {
15474            fn from(_: Event) -> Self {
15475                unreachable!()
15476            }
15477        }
15478
15479        impl Model for NoAutoModel {
15480            type Message = NoAutoMsg;
15481
15482            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
15483                Cmd::none()
15484            }
15485
15486            fn view(&self, frame: &mut Frame) {
15487                frame.buffer.set_raw(0, 0, Cell::from_char('N'));
15488            }
15489        }
15490
15491        let evidence_path = temp_evidence_path("voi_no_auto");
15492        let config = ProgramConfig::default()
15493            .with_evidence_sink(EvidenceSinkConfig::enabled_file(&evidence_path));
15494        assert!(config.inline_auto_remeasure.is_none());
15495
15496        let mut program = headless_program_with_config(NoAutoModel, config);
15497        for _ in 0..3 {
15498            program.dirty = true;
15499            program.render_frame().expect("render frame");
15500        }
15501
15502        let contents = std::fs::read_to_string(&evidence_path).unwrap_or_default();
15503        assert!(
15504            !contents.contains(r#""event":"voi_decision""#)
15505                && !contents.contains(r#""event":"voi_sample""#),
15506            "programs without auto bounds must not emit VOI events; got: {contents}"
15507        );
15508    }
15509
15510    #[test]
15511    fn evidence_lines_all_carry_schema_version() {
15512        use crate::telemetry_schema::ALL_EVIDENCE_EVENTS;
15513
15514        let evidence_path = temp_evidence_path("all_evidence_schema_version");
15515        let config = ProgramConfig::inline_auto(1, 6)
15516            .with_evidence_sink(EvidenceSinkConfig::enabled_file(&evidence_path));
15517
15518        struct EvidenceModel;
15519        #[derive(Debug)]
15520        enum EvMsg {}
15521        impl From<Event> for EvMsg {
15522            fn from(_: Event) -> Self {
15523                unreachable!()
15524            }
15525        }
15526        impl Model for EvidenceModel {
15527            type Message = EvMsg;
15528            fn update(&mut self, _: Self::Message) -> Cmd<Self::Message> {
15529                Cmd::none()
15530            }
15531            fn view(&self, frame: &mut Frame) {
15532                frame.buffer.set_raw(0, 0, Cell::from_char('E'));
15533            }
15534        }
15535
15536        let mut program = headless_program_with_config(EvidenceModel, config);
15537        program.dirty = true;
15538        program.render_frame().expect("render frame");
15539
15540        let contents = std::fs::read_to_string(&evidence_path).expect("evidence file written");
15541        for line in contents.lines() {
15542            let line = line.trim();
15543            if line.is_empty() {
15544                continue;
15545            }
15546            let val: serde_json::Value = serde_json::from_str(line).expect("valid jsonl line");
15547            assert_eq!(
15548                val["schema_version"].as_str(),
15549                Some("ftui-evidence-v1"),
15550                "each evidence line must carry schema_version ftui-evidence-v1: {line}"
15551            );
15552            let event = val["event"].as_str().expect("event string");
15553            assert!(
15554                ALL_EVIDENCE_EVENTS.contains(&event),
15555                "event {event} must be in ALL_EVIDENCE_EVENTS"
15556            );
15557        }
15558    }
15559
15560    /// Bytes the startup probes swallowed (a click and a key sent while the
15561    /// terminal was being probed) are parsed and delivered to the model in
15562    /// order before the main loop; draining twice delivers nothing more.
15563    #[test]
15564    fn startup_input_recovered_from_probes_reaches_the_model() {
15565        use ftui_core::event::{KeyCode, MouseEventKind};
15566
15567        #[derive(Default)]
15568        struct RecorderModel {
15569            seen: Vec<String>,
15570            keys: Vec<KeyEvent>,
15571        }
15572
15573        #[derive(Debug)]
15574        enum RecMsg {
15575            Event(Event),
15576        }
15577
15578        impl From<Event> for RecMsg {
15579            fn from(event: Event) -> Self {
15580                RecMsg::Event(event)
15581            }
15582        }
15583
15584        impl Model for RecorderModel {
15585            type Message = RecMsg;
15586
15587            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
15588                match msg {
15589                    RecMsg::Event(Event::Mouse(mouse)) => {
15590                        self.seen
15591                            .push(format!("mouse:{:?}@{},{}", mouse.kind, mouse.x, mouse.y));
15592                    }
15593                    RecMsg::Event(Event::Key(key)) => {
15594                        self.seen.push(format!("key:{:?}", key.code));
15595                        self.keys.push(key);
15596                    }
15597                    RecMsg::Event(_) => {}
15598                }
15599                Cmd::none()
15600            }
15601
15602            fn view(&self, frame: &mut Frame) {
15603                frame.buffer.set_raw(0, 0, Cell::from_char('R'));
15604            }
15605        }
15606
15607        let mut program =
15608            headless_program_with_config(RecorderModel::default(), ProgramConfig::default());
15609        // SGR mouse press + release at column 2 row 1, then a typed `q`.
15610        program.queue_startup_input(b"\x1b[<0;2;1M\x1b[<0;2;1mq");
15611        assert_eq!(program.startup_events.len(), 3);
15612        program
15613            .drain_startup_events()
15614            .expect("deliver startup events");
15615        assert!(program.startup_events.is_empty());
15616        let seen = program.model().seen.clone();
15617        assert_eq!(seen.len(), 3, "{seen:?}");
15618        assert!(
15619            seen[0].starts_with(&format!(
15620                "mouse:{:?}",
15621                MouseEventKind::Down(ftui_core::event::MouseButton::Left)
15622            )) && seen[0].ends_with("@1,0"),
15623            "{seen:?}"
15624        );
15625        assert!(seen[1].starts_with("mouse:Up"), "{seen:?}");
15626        assert_eq!(seen[2], format!("key:{:?}", KeyCode::Char('q')));
15627
15628        program.drain_startup_events().expect("nothing left");
15629        assert_eq!(program.model().seen.len(), 3);
15630        program.queue_startup_input(b"");
15631        assert!(program.startup_events.is_empty());
15632
15633        // A probe can consume the final lone Escape before timing out. The
15634        // startup handoff must deliver that key, even with no subsequent input.
15635        program.queue_startup_input(b"\x1b[<0;2;1M\x1b");
15636        program
15637            .drain_startup_events()
15638            .expect("deliver trailing ESC");
15639        assert_eq!(program.model().seen.len(), 5);
15640        assert_eq!(program.model().seen[4], "key:Escape");
15641        program.drain_startup_events().expect("no duplicate ESC");
15642        assert_eq!(program.model().seen.len(), 5);
15643
15644        // Recovery may arrive in chunks. A pending prefix is not a key until
15645        // the batch is drained, so arrows and Alt+UTF-8 keep their identity.
15646        program.queue_startup_input(b"\x1b");
15647        program.queue_startup_input(b"[C\x1b\xc3");
15648        program.queue_startup_input(b"\xa9");
15649        program.drain_startup_events().expect("fragmented recovery");
15650        assert_eq!(&program.model().seen[5..], &["key:Right", "key:Char('รฉ')"]);
15651        assert_eq!(
15652            program.model().keys.last(),
15653            Some(
15654                &KeyEvent::new(KeyCode::Char('รฉ')).with_modifiers(ftui_core::event::Modifiers::ALT)
15655            )
15656        );
15657    }
15658
15659    /// With `ProgramConfig::accessibility` set, every rendered frame builds
15660    /// an accessibility tree from the nodes the view pushes, diffs it against
15661    /// the previous frame and exports the resulting announcements as
15662    /// evidence rows; without it nothing is collected.
15663    #[test]
15664    fn headless_accessibility_builds_tree_and_exports_announcements() {
15665        use ftui_a11y::node::{A11yNodeInfo, A11yRole, A11yState, LiveRegion};
15666        use ftui_a11y::tree::AnnouncementReason;
15667        use ftui_core::geometry::Rect;
15668
15669        struct A11yModel {
15670            frames: std::cell::Cell<u32>,
15671            hook_calls: u32,
15672            last_dump: String,
15673        }
15674
15675        #[derive(Debug)]
15676        enum A11yMsg {
15677            Noop,
15678        }
15679
15680        impl From<Event> for A11yMsg {
15681            fn from(_: Event) -> Self {
15682                A11yMsg::Noop
15683            }
15684        }
15685
15686        impl Model for A11yModel {
15687            type Message = A11yMsg;
15688
15689            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
15690                Cmd::none()
15691            }
15692
15693            fn on_accessibility(&mut self, a11y: AccessibilityFrame<'_>) -> Cmd<Self::Message> {
15694                self.hook_calls += 1;
15695                self.last_dump = a11y.dump();
15696                Cmd::none()
15697            }
15698
15699            fn view(&self, frame: &mut Frame) {
15700                let n = self.frames.get();
15701                self.frames.set(n + 1);
15702                frame.buffer.set_raw(0, 0, Cell::from_char('A'));
15703                frame.push_a11y(
15704                    A11yNodeInfo::new(1, A11yRole::Button, Rect::new(0, 0, 10, 1))
15705                        .with_name("OK")
15706                        .with_state(A11yState {
15707                            focused: true,
15708                            ..A11yState::default()
15709                        }),
15710                );
15711                if let Some(builder) = frame.a11y.as_deref_mut() {
15712                    builder.set_focused(Some(1));
15713                }
15714                // The second frame adds a polite live region.
15715                if n >= 1 {
15716                    frame.push_a11y(
15717                        A11yNodeInfo::new(2, A11yRole::Label, Rect::new(0, 1, 10, 1))
15718                            .with_name("Saved")
15719                            .with_live_region(LiveRegion::Polite),
15720                    );
15721                }
15722            }
15723        }
15724
15725        // Off by default: nothing is collected even though the view pushes.
15726        let mut off = headless_program_with_config(
15727            A11yModel {
15728                frames: std::cell::Cell::new(0),
15729                hook_calls: 0,
15730                last_dump: String::new(),
15731            },
15732            ProgramConfig::default(),
15733        );
15734        off.dirty = true;
15735        off.render_frame().expect("render without accessibility");
15736        assert!(off.accessibility_tree().is_none());
15737        assert!(off.accessibility_order().is_empty());
15738        assert!(off.accessibility_announcements().is_empty());
15739        assert!(off.accessibility_dump().is_none());
15740        assert_eq!(off.model.hook_calls, 0);
15741
15742        let evidence_path = temp_evidence_path("a11y");
15743        let config = ProgramConfig::default()
15744            .with_accessibility(ScreenReaderPolicy::default())
15745            .with_budget(FrameBudgetConfig::with_total(Duration::from_secs(5)))
15746            .with_evidence_sink(EvidenceSinkConfig::enabled_file(&evidence_path));
15747        let mut program = headless_program_with_config(
15748            A11yModel {
15749                frames: std::cell::Cell::new(0),
15750                hook_calls: 0,
15751                last_dump: String::new(),
15752            },
15753            config,
15754        );
15755
15756        program.dirty = true;
15757        program.render_frame().expect("render first a11y frame");
15758        let tree = program
15759            .accessibility_tree()
15760            .expect("tree after first frame");
15761        assert_eq!(tree.node_count(), 1);
15762        assert_eq!(tree.focused_id(), Some(1));
15763        assert_eq!(program.accessibility_order(), &[1]);
15764        let first: Vec<AnnouncementReason> = program
15765            .accessibility_announcements()
15766            .iter()
15767            .map(|a| a.reason)
15768            .collect();
15769        assert!(
15770            first.contains(&AnnouncementReason::FocusChanged),
15771            "first frame must announce the focused button; got {first:?}"
15772        );
15773
15774        program.dirty = true;
15775        program.render_frame().expect("render second a11y frame");
15776        let tree = program
15777            .accessibility_tree()
15778            .expect("tree after second frame");
15779        assert_eq!(tree.node_count(), 2);
15780        assert_eq!(program.accessibility_order(), &[1, 2]);
15781        let second: Vec<(AnnouncementReason, String)> = program
15782            .accessibility_announcements()
15783            .iter()
15784            .map(|a| (a.reason, a.text.clone()))
15785            .collect();
15786        assert!(
15787            second.iter().any(
15788                |(reason, text)| *reason == AnnouncementReason::LiveRegionAdded
15789                    && text.contains("Saved")
15790            ),
15791            "second frame must announce the new live region; got {second:?}"
15792        );
15793        let dump = program.accessibility_dump().expect("dump when enabled");
15794        assert!(
15795            dump.contains("OK") && dump.contains("Saved"),
15796            "dump: {dump}"
15797        );
15798
15799        // A frame with no tree change produces no announcements.
15800        program.dirty = true;
15801        program.render_frame().expect("render third a11y frame");
15802        assert!(program.accessibility_announcements().is_empty());
15803        // The hook fired for the two changing frames only, saw the dump, and
15804        // requested one more frame each time.
15805        assert_eq!(program.model.hook_calls, 2);
15806        assert!(program.model.last_dump.contains("Saved"));
15807        assert!(
15808            !program.dirty,
15809            "an unchanged frame must not request a redraw"
15810        );
15811
15812        let contents = std::fs::read_to_string(&evidence_path).expect("evidence file written");
15813        assert!(
15814            contents.contains(r#""event":"a11y_tree""#),
15815            "tree changes must be exported; got: {contents}"
15816        );
15817        assert!(
15818            contents.contains(r#""event":"a11y_announcement""#)
15819                && contents.contains(r#""reason":"LiveRegionAdded""#)
15820                && contents.contains(r#""urgency":"polite""#),
15821            "announcements must be exported with reason and urgency; got: {contents}"
15822        );
15823        assert_eq!(
15824            contents.matches(r#""event":"a11y_tree""#).count(),
15825            2,
15826            "only the two changing frames export a11y_tree rows; got: {contents}"
15827        );
15828        assert!(
15829            !contents.contains("Saved"),
15830            "ordinary evidence must not contain accessibility content"
15831        );
15832    }
15833
15834    #[test]
15835    fn accessibility_tree_is_built_when_enabled() {
15836        use ftui_a11y::node::{A11yNodeInfo, A11yRole, A11yState};
15837        use ftui_core::geometry::Rect;
15838
15839        struct SimpleA11yModel;
15840        impl Model for SimpleA11yModel {
15841            type Message = Event;
15842            fn update(&mut self, _: Event) -> Cmd<Event> {
15843                Cmd::none()
15844            }
15845            fn view(&self, frame: &mut Frame) {
15846                frame.push_a11y(
15847                    A11yNodeInfo::new(10, A11yRole::Button, Rect::new(0, 0, 8, 1))
15848                        .with_name("Submit")
15849                        .with_state(A11yState {
15850                            focused: true,
15851                            ..A11yState::default()
15852                        }),
15853                );
15854            }
15855        }
15856
15857        let config = ProgramConfig::default().with_accessibility(ScreenReaderPolicy::default());
15858        let mut program = headless_program_with_config(SimpleA11yModel, config);
15859        program.dirty = true;
15860        program.render_frame().expect("render enabled a11y frame");
15861        let tree = program
15862            .accessibility_tree()
15863            .expect("tree built when enabled");
15864        assert_eq!(tree.node_count(), 1);
15865        assert_eq!(tree.focused_id(), Some(10));
15866    }
15867
15868    #[test]
15869    fn accessibility_tree_is_none_when_disabled() {
15870        use ftui_a11y::node::{A11yNodeInfo, A11yRole};
15871        use ftui_core::geometry::Rect;
15872
15873        struct SimpleA11yModel;
15874        impl Model for SimpleA11yModel {
15875            type Message = Event;
15876            fn update(&mut self, _: Event) -> Cmd<Event> {
15877                Cmd::none()
15878            }
15879            fn view(&self, frame: &mut Frame) {
15880                frame.push_a11y(
15881                    A11yNodeInfo::new(10, A11yRole::Button, Rect::new(0, 0, 8, 1))
15882                        .with_name("Submit"),
15883                );
15884            }
15885        }
15886
15887        let mut program = headless_program_with_config(SimpleA11yModel, ProgramConfig::default());
15888        program.dirty = true;
15889        program.render_frame().expect("render disabled a11y frame");
15890        assert!(program.accessibility_tree().is_none());
15891        assert!(program.accessibility_announcements().is_empty());
15892    }
15893
15894    #[test]
15895    fn focus_move_between_two_inputs_emits_one_announcement() {
15896        use ftui_a11y::node::{A11yNodeInfo, A11yRole, A11yState};
15897        use ftui_a11y::tree::AnnouncementReason;
15898        use ftui_core::geometry::Rect;
15899
15900        struct TwoInputModel {
15901            focused_idx: usize,
15902        }
15903        impl Model for TwoInputModel {
15904            type Message = Event;
15905            fn update(&mut self, _: Event) -> Cmd<Event> {
15906                Cmd::none()
15907            }
15908            fn view(&self, frame: &mut Frame) {
15909                for (i, label) in ["First", "Second"].into_iter().enumerate() {
15910                    frame.push_a11y(
15911                        A11yNodeInfo::new(
15912                            (i + 1) as u64,
15913                            A11yRole::TextInput,
15914                            Rect::new(0, i as u16, 12, 1),
15915                        )
15916                        .with_name(label)
15917                        .with_state(A11yState {
15918                            focused: self.focused_idx == i,
15919                            ..A11yState::default()
15920                        }),
15921                    );
15922                }
15923            }
15924        }
15925
15926        let config = ProgramConfig::default().with_accessibility(ScreenReaderPolicy::default());
15927        let mut program = headless_program_with_config(TwoInputModel { focused_idx: 0 }, config);
15928        program.dirty = true;
15929        program.render_frame().expect("render initial focus");
15930        assert_eq!(program.accessibility_tree().unwrap().focused_id(), Some(1));
15931
15932        program.model.focused_idx = 1;
15933        program.dirty = true;
15934        program.render_frame().expect("render moved focus");
15935        assert_eq!(program.accessibility_tree().unwrap().focused_id(), Some(2));
15936        let focus_announcements: Vec<_> = program
15937            .accessibility_announcements()
15938            .iter()
15939            .filter(|a| a.reason == AnnouncementReason::FocusChanged)
15940            .collect();
15941        assert_eq!(focus_announcements.len(), 1);
15942        assert_eq!(focus_announcements[0].node_id, Some(2));
15943        assert!(focus_announcements[0].text.contains("Second"));
15944    }
15945
15946    #[test]
15947    fn progress_value_change_emits_polite_live_region_announcement() {
15948        use ftui_a11y::node::{A11yNodeInfo, A11yRole, A11yState, LiveRegion};
15949        use ftui_a11y::tree::AnnouncementReason;
15950        use ftui_core::geometry::Rect;
15951
15952        struct ProgressModel {
15953            pct: u8,
15954        }
15955        impl Model for ProgressModel {
15956            type Message = Event;
15957            fn update(&mut self, _: Event) -> Cmd<Event> {
15958                Cmd::none()
15959            }
15960            fn view(&self, frame: &mut Frame) {
15961                frame.push_a11y(
15962                    A11yNodeInfo::new(1, A11yRole::ProgressBar, Rect::new(0, 0, 20, 1))
15963                        .with_name("Upload")
15964                        .with_state(A11yState {
15965                            value_now: Some(f64::from(self.pct) / 100.0),
15966                            value_min: Some(0.0),
15967                            value_max: Some(1.0),
15968                            value_text: Some(format!("{}%", self.pct)),
15969                            ..A11yState::default()
15970                        })
15971                        .with_live_region(LiveRegion::Polite),
15972                );
15973            }
15974        }
15975
15976        let config = ProgramConfig::default().with_accessibility(ScreenReaderPolicy::default());
15977        let mut program = headless_program_with_config(ProgressModel { pct: 20 }, config);
15978        program.dirty = true;
15979        program.render_frame().expect("render initial progress");
15980
15981        program.model.pct = 65;
15982        program.dirty = true;
15983        program.render_frame().expect("render updated progress");
15984        let announcements = program.accessibility_announcements();
15985        assert!(
15986            announcements.iter().any(|a| {
15987                a.reason == AnnouncementReason::LiveContentChanged
15988                    && a.urgency == LiveRegion::Polite
15989                    && a.text.contains("65%")
15990            }),
15991            "expected polite LiveContentChanged announcement for 65%; got {announcements:?}"
15992        );
15993    }
15994
15995    #[test]
15996    fn unchanged_frame_emits_no_announcement() {
15997        use ftui_a11y::node::{A11yNodeInfo, A11yRole, A11yState};
15998        use ftui_core::geometry::Rect;
15999
16000        struct StaticModel;
16001        impl Model for StaticModel {
16002            type Message = Event;
16003            fn update(&mut self, _: Event) -> Cmd<Event> {
16004                Cmd::none()
16005            }
16006            fn view(&self, frame: &mut Frame) {
16007                frame.push_a11y(
16008                    A11yNodeInfo::new(1, A11yRole::Button, Rect::new(0, 0, 10, 1))
16009                        .with_name("Save")
16010                        .with_state(A11yState {
16011                            focused: true,
16012                            ..A11yState::default()
16013                        }),
16014                );
16015            }
16016        }
16017
16018        let config = ProgramConfig::default().with_accessibility(ScreenReaderPolicy::default());
16019        let mut program = headless_program_with_config(StaticModel, config);
16020        program.dirty = true;
16021        program.render_frame().expect("first frame");
16022        assert!(!program.accessibility_announcements().is_empty());
16023
16024        program.dirty = true;
16025        program.render_frame().expect("unchanged second frame");
16026        assert!(program.accessibility_announcements().is_empty());
16027    }
16028
16029    #[test]
16030    fn on_accessibility_tree_hook_receives_arc() {
16031        use ftui_a11y::node::{A11yNodeInfo, A11yRole};
16032        use ftui_a11y::tree::A11yTree;
16033        use ftui_core::geometry::Rect;
16034        use std::sync::Arc;
16035
16036        #[derive(Default)]
16037        struct HookModel {
16038            shared: Option<Arc<A11yTree>>,
16039        }
16040        impl Model for HookModel {
16041            type Message = Event;
16042            fn update(&mut self, _: Event) -> Cmd<Event> {
16043                Cmd::none()
16044            }
16045            fn view(&self, frame: &mut Frame) {
16046                frame.push_a11y(
16047                    A11yNodeInfo::new(7, A11yRole::Group, Rect::new(0, 0, 20, 4))
16048                        .with_name("Panel"),
16049                );
16050            }
16051            fn on_accessibility(&mut self, a11y: AccessibilityFrame<'_>) -> Cmd<Event> {
16052                self.shared = Some(Arc::new(a11y.tree.clone()));
16053                Cmd::none()
16054            }
16055        }
16056
16057        let config = ProgramConfig::default().with_accessibility(ScreenReaderPolicy::default());
16058        let mut program = headless_program_with_config(HookModel::default(), config);
16059        program.dirty = true;
16060        program.render_frame().expect("render frame with hook");
16061        let arc_tree = program.model.shared.as_ref().expect("hook received tree");
16062        assert_eq!(arc_tree.node_count(), 1);
16063        assert_eq!(arc_tree.node(7).unwrap().name.as_deref(), Some("Panel"));
16064    }
16065
16066    #[test]
16067    fn a11y_announcement_line_is_valid_json_with_registered_fields() {
16068        use ftui_a11y::node::{A11yNodeInfo, A11yRole, A11yState};
16069        use ftui_core::geometry::Rect;
16070
16071        struct JsonModel;
16072        impl Model for JsonModel {
16073            type Message = Event;
16074            fn update(&mut self, _: Event) -> Cmd<Event> {
16075                Cmd::none()
16076            }
16077            fn view(&self, frame: &mut Frame) {
16078                frame.push_a11y(
16079                    A11yNodeInfo::new(42, A11yRole::TextInput, Rect::new(0, 0, 16, 1))
16080                        .with_name("Email")
16081                        .with_state(A11yState {
16082                            focused: true,
16083                            ..A11yState::default()
16084                        }),
16085                );
16086            }
16087        }
16088
16089        let path = temp_evidence_path("a11y_json_fields");
16090        let config = ProgramConfig::default()
16091            .with_accessibility(ScreenReaderPolicy::default())
16092            .with_evidence_sink(EvidenceSinkConfig::enabled_file(&path));
16093        let mut program = headless_program_with_config(JsonModel, config);
16094        program.dirty = true;
16095        program.render_frame().expect("render json model");
16096
16097        let contents = std::fs::read_to_string(&path).expect("read evidence file");
16098        let announcement_rows: Vec<serde_json::Value> = contents
16099            .lines()
16100            .filter(|line| !line.trim().is_empty())
16101            .map(|line| serde_json::from_str(line).expect("valid JSON line"))
16102            .filter(|row: &serde_json::Value| row["event"] == "a11y_announcement")
16103            .collect();
16104        assert!(
16105            !announcement_rows.is_empty(),
16106            "expected a11y_announcement rows"
16107        );
16108        for row in &announcement_rows {
16109            assert!(row.get("frame_idx").is_some());
16110            assert!(row.get("node_id").is_some());
16111            assert!(row.get("urgency").is_some());
16112            assert!(row.get("reason").is_some());
16113            assert!(row.get("text").is_some());
16114            assert!(row.get("text_chars").is_some());
16115        }
16116    }
16117
16118    const A11Y_PRIVACY_CANARY: &str = "A11Y_SECRET_450512_\"รฉ\\\nๆ—ฅ";
16119    // Screen-reader text already normalizes whitespace before delivery.
16120    const A11Y_NORMALIZED_CANARY: &str = "A11Y_SECRET_450512_\"รฉ\\ ๆ—ฅ";
16121
16122    fn exercise_a11y_privacy(config: ProgramConfig) -> (Vec<String>, usize) {
16123        use ftui_a11y::node::{A11yNodeInfo, A11yRole, A11yState, LiveRegion};
16124        use ftui_core::geometry::Rect;
16125
16126        #[derive(Default)]
16127        struct ContentModel {
16128            received: Vec<String>,
16129            dropped: usize,
16130        }
16131
16132        impl Model for ContentModel {
16133            type Message = Event;
16134
16135            fn update(&mut self, _: Event) -> Cmd<Event> {
16136                Cmd::none()
16137            }
16138
16139            fn view(&self, frame: &mut Frame) {
16140                frame.buffer.set_raw(0, 0, Cell::from_char('A'));
16141                for (index, (role, source)) in [
16142                    (A11yRole::TextInput, "input"),
16143                    (A11yRole::TextInput, "textarea"),
16144                    (A11yRole::Label, "label"),
16145                    (A11yRole::Dialog, "modal"),
16146                    (A11yRole::Label, "live-region"),
16147                ]
16148                .into_iter()
16149                .enumerate()
16150                {
16151                    frame.push_a11y(
16152                        A11yNodeInfo::new(
16153                            index as u64 + 1,
16154                            role,
16155                            Rect::new(0, index as u16, 20, 1),
16156                        )
16157                        .with_name(format!("{source}: {A11Y_PRIVACY_CANARY}"))
16158                        .with_state(A11yState {
16159                            focused: index == 0,
16160                            ..A11yState::default()
16161                        })
16162                        .with_live_region(LiveRegion::Polite),
16163                    );
16164                }
16165            }
16166
16167            fn on_accessibility(&mut self, frame: AccessibilityFrame<'_>) -> Cmd<Event> {
16168                self.received
16169                    .extend(frame.announcements.iter().map(|a| a.text.clone()));
16170                self.dropped += frame.dropped;
16171                Cmd::none()
16172            }
16173        }
16174
16175        let mut program = headless_program_with_config(ContentModel::default(), config);
16176        program.render_frame().expect("render private a11y content");
16177        let received = program.model.received.clone();
16178        let dropped = program.model.dropped;
16179        program.render_frame().expect("render unchanged a11y tree");
16180        assert_eq!(
16181            program.model.received, received,
16182            "no duplicate announcements"
16183        );
16184        (received, dropped)
16185    }
16186
16187    #[derive(Clone, Default)]
16188    struct A11yTraceCapture(std::sync::Arc<std::sync::Mutex<String>>);
16189
16190    impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for A11yTraceCapture {
16191        fn on_event(
16192            &self,
16193            event: &tracing::Event<'_>,
16194            _: tracing_subscriber::layer::Context<'_, S>,
16195        ) {
16196            struct Fields<'a>(&'a mut String);
16197            impl tracing::field::Visit for Fields<'_> {
16198                fn record_debug(
16199                    &mut self,
16200                    field: &tracing::field::Field,
16201                    value: &dyn std::fmt::Debug,
16202                ) {
16203                    use std::fmt::Write as _;
16204                    write!(self.0, "{}={value:?};", field.name()).expect("write capture");
16205                }
16206            }
16207            let mut output = self.0.lock().expect("capture lock");
16208            output.push_str(event.metadata().target());
16209            event.record(&mut Fields(&mut output));
16210            output.push('\n');
16211        }
16212    }
16213
16214    #[test]
16215    fn headless_a11y_privacy_preserves_local_content_and_explicit_capture() {
16216        use tracing_subscriber::prelude::*;
16217
16218        for enabled in [false, true] {
16219            for include_text in [false, true] {
16220                for max_announcements in [2, 8] {
16221                    let path = temp_evidence_path("a11y_privacy");
16222                    let capture = A11yTraceCapture::default();
16223                    let subscriber = tracing_subscriber::registry().with(capture.clone());
16224                    let mut config = ProgramConfig::default()
16225                        .with_accessibility_evidence_text(include_text)
16226                        .with_evidence_sink(EvidenceSinkConfig::enabled_file(&path));
16227                    if enabled {
16228                        config = config.with_accessibility(ScreenReaderPolicy {
16229                            max_announcements,
16230                            ..ScreenReaderPolicy::default()
16231                        });
16232                    }
16233                    let (local, dropped) = tracing::subscriber::with_default(subscriber, || {
16234                        exercise_a11y_privacy(config)
16235                    });
16236                    let trace = capture.0.lock().expect("capture lock").clone();
16237                    assert!(
16238                        !trace.contains("A11Y_SECRET_450512"),
16239                        "content entered tracing"
16240                    );
16241                    let contents = std::fs::read_to_string(&path).expect("read evidence");
16242                    let rows: Vec<serde_json::Value> = contents
16243                        .lines()
16244                        .map(|line| serde_json::from_str(line).expect("valid JSONL"))
16245                        .filter(|row: &serde_json::Value| row["event"] == "a11y_announcement")
16246                        .collect();
16247                    assert_eq!(rows.len(), local.len());
16248                    if enabled {
16249                        assert!(!local.is_empty(), "local accessibility received nothing");
16250                        assert!(local.len() <= max_announcements);
16251                        assert!(
16252                            local
16253                                .iter()
16254                                .all(|text| text.contains(A11Y_NORMALIZED_CANARY))
16255                        );
16256                        assert!(trace.contains("screen reader announcement"));
16257                        assert_eq!(dropped > 0, max_announcements == 2);
16258                        for (row, text) in rows.iter().zip(&local) {
16259                            assert_eq!(row["text_chars"], text.chars().count());
16260                            if include_text {
16261                                assert_eq!(row["text"], *text, "explicit content round trip");
16262                            } else {
16263                                assert!(row["text"].is_null());
16264                            }
16265                        }
16266                    } else {
16267                        assert!(local.is_empty());
16268                        assert_eq!(dropped, 0);
16269                        assert!(!trace.contains("screen reader announcement"));
16270                    }
16271                    if !include_text {
16272                        assert!(!contents.contains("A11Y_SECRET_450512"));
16273                    }
16274                }
16275            }
16276        }
16277    }
16278
16279    #[cfg(target_os = "linux")]
16280    #[test]
16281    fn headless_a11y_privacy_preserves_callback_when_evidence_write_fails() {
16282        use tracing_subscriber::prelude::*;
16283
16284        let capture = A11yTraceCapture::default();
16285        let subscriber = tracing_subscriber::registry().with(capture.clone());
16286        let config = ProgramConfig::default()
16287            .with_accessibility(ScreenReaderPolicy::default())
16288            .with_evidence_sink(EvidenceSinkConfig::enabled_file("/dev/full"));
16289        let (local, _) =
16290            tracing::subscriber::with_default(subscriber, || exercise_a11y_privacy(config));
16291        assert!(!local.is_empty());
16292        assert!(
16293            local
16294                .iter()
16295                .all(|text| text.contains(A11Y_NORMALIZED_CANARY))
16296        );
16297        let trace = capture.0.lock().expect("capture lock");
16298        assert!(trace.contains("screen reader announcement"));
16299        assert!(!trace.contains("A11Y_SECRET_450512"));
16300    }
16301
16302    #[cfg(feature = "telemetry")]
16303    #[test]
16304    fn headless_a11y_privacy_through_real_otlp_http_exporter() {
16305        use std::io::{Read as _, Write as _};
16306        use std::net::TcpListener;
16307        use std::sync::Arc;
16308        use std::sync::atomic::{AtomicBool, Ordering};
16309        use tracing_subscriber::prelude::*;
16310
16311        let listener = TcpListener::bind("127.0.0.1:0").expect("bind local collector");
16312        listener.set_nonblocking(true).expect("bounded accept");
16313        let endpoint = format!("http://{}/v1/traces", listener.local_addr().unwrap());
16314        let stop = Arc::new(AtomicBool::new(false));
16315        let collector_stop = stop.clone();
16316        let collector = std::thread::spawn(move || {
16317            let start = std::time::Instant::now();
16318            let mut payloads = Vec::new();
16319            while !collector_stop.load(Ordering::Acquire)
16320                && start.elapsed() < std::time::Duration::from_secs(30)
16321            {
16322                let (mut stream, _) = match listener.accept() {
16323                    Ok(connection) => connection,
16324                    Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
16325                        std::thread::sleep(std::time::Duration::from_millis(5));
16326                        continue;
16327                    }
16328                    Err(error) => panic!("collector accept failed: {error}"),
16329                };
16330                // On BSD/Darwin the accepted socket inherits O_NONBLOCK from
16331                // the listener (Linux does not), and SO_RCVTIMEO is ignored on
16332                // a non-blocking socket. Without this the read timeout below
16333                // is a no-op and `read_exact` fails with EAGAIN whenever
16334                // `accept` wins the race against the client's first bytes -
16335                // which it does under load. `read_exact` cannot be resumed
16336                // after WouldBlock, so the socket has to be blocking rather
16337                // than the read retried.
16338                stream
16339                    .set_nonblocking(false)
16340                    .expect("blocking reads, so the timeout below applies");
16341                stream
16342                    .set_read_timeout(Some(std::time::Duration::from_secs(3)))
16343                    .expect("bounded request read");
16344                let mut request = Vec::new();
16345                let (header_end, content_len) = loop {
16346                    let mut byte = [0];
16347                    stream.read_exact(&mut byte).expect("read HTTP headers");
16348                    request.push(byte[0]);
16349                    assert!(request.len() <= 32_768, "bounded HTTP headers");
16350                    if request.ends_with(b"\r\n\r\n") {
16351                        let headers = std::str::from_utf8(&request).expect("HTTP header text");
16352                        assert!(headers.starts_with("POST /v1/traces "));
16353                        let length: usize = headers
16354                            .lines()
16355                            .filter_map(|line| line.split_once(':'))
16356                            .find(|(name, _)| name.eq_ignore_ascii_case("content-length"))
16357                            .expect("OTLP request content length")
16358                            .1
16359                            .trim()
16360                            .parse()
16361                            .expect("numeric content length");
16362                        assert!(length <= 2 * 1024 * 1024, "bounded request body");
16363                        break (request.len(), length);
16364                    }
16365                };
16366                request.resize(header_end + content_len, 0);
16367                stream
16368                    .read_exact(&mut request[header_end..])
16369                    .expect("read actual OTLP protobuf");
16370                payloads.push(request[header_end..].to_vec());
16371                stream
16372                    .write_all(b"HTTP/1.1 200 OK\r\nContent-Type: application/x-protobuf\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
16373                    .expect("acknowledge export");
16374            }
16375            payloads
16376        });
16377
16378        let mut telemetry = crate::telemetry::TelemetryConfig::from_env_with(|key| match key {
16379            "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT" => Some(endpoint.clone()),
16380            "OTEL_TRACES_EXPORTER" => Some("otlp".into()),
16381            _ => None,
16382        });
16383        telemetry.processor = crate::telemetry::SpanProcessorKind::Simple;
16384        telemetry.headers.push((
16385            "User-Agent".into(),
16386            "frankentui-test (+https://github.com/Dicklesworthstone/frankentui)".into(),
16387        ));
16388        let (layer, provider) = telemetry.build_layer().expect("real OTLP exporter");
16389        let subscriber = tracing_subscriber::registry().with(layer);
16390        let evidence_path = temp_evidence_path("a11y_otlp_private");
16391        let (local, _) = tracing::subscriber::with_default(subscriber, || {
16392            let _span = tracing::info_span!("a11y_privacy_live_export").entered();
16393            exercise_a11y_privacy(
16394                ProgramConfig::default()
16395                    .with_accessibility(ScreenReaderPolicy::default())
16396                    .with_accessibility_evidence_text(true)
16397                    .with_evidence_sink(EvidenceSinkConfig::enabled_file(&evidence_path)),
16398            )
16399        });
16400        provider.force_flush().expect("flush actual export");
16401        provider.shutdown().expect("shutdown exporter");
16402        stop.store(true, Ordering::Release);
16403        let payloads = collector.join().expect("local collector finished");
16404        assert!(
16405            !local.is_empty(),
16406            "accessibility callback must receive text"
16407        );
16408        assert!(
16409            local
16410                .iter()
16411                .all(|text| text.contains(A11Y_NORMALIZED_CANARY))
16412        );
16413        assert!(!payloads.is_empty(), "zero exports is not a privacy pass");
16414        let exported = payloads.concat();
16415        let exported_text = String::from_utf8_lossy(&exported);
16416        assert!(exported_text.contains("screen reader announcement"));
16417        assert!(!exported_text.contains("A11Y_SECRET_450512"));
16418        let evidence = std::fs::read_to_string(evidence_path).expect("explicit local evidence");
16419        assert!(evidence.contains("A11Y_SECRET_450512"));
16420    }
16421
16422    /// Conformal gating is on by default, so its warm-up must be harmless:
16423    /// until `min_samples` residuals exist the prediction rests on the
16424    /// `q_default` prior, which (10 ms on top of a 16 ms baseline against a
16425    /// 16 ms budget by default; made deliberately huge here) reports `risk`,
16426    /// yet an uncalibrated verdict must never lower the degradation level.
16427    /// The evidence rows must still show that risky, uncalibrated verdict so
16428    /// the warm-up is observable.
16429    #[test]
16430    fn headless_default_config_never_degrades_during_conformal_warmup() {
16431        use ftui_render::budget::DegradationLevel;
16432
16433        struct WarmModel;
16434
16435        #[derive(Debug)]
16436        enum WarmMsg {
16437            Noop,
16438        }
16439
16440        impl From<Event> for WarmMsg {
16441            fn from(_: Event) -> Self {
16442                WarmMsg::Noop
16443            }
16444        }
16445
16446        impl Model for WarmModel {
16447            type Message = WarmMsg;
16448
16449            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
16450                Cmd::none()
16451            }
16452
16453            fn view(&self, frame: &mut Frame) {
16454                frame.buffer.set_raw(0, 0, Cell::from_char('W'));
16455            }
16456        }
16457
16458        let evidence_path = temp_evidence_path("conformal_warmup");
16459        let defaults = ProgramConfig::default()
16460            .conformal_config
16461            .expect("conformal on by default");
16462        let min_samples = defaults.min_samples;
16463        // Load-independent setup: a 5 s frame budget keeps the PID path from
16464        // degrading when the test host is busy, while a 10 s `q_default`
16465        // prior makes every uncalibrated conformal verdict risky, so the only
16466        // thing that could degrade here is the warm-up gate letting the
16467        // prior through.
16468        let config = ProgramConfig::default()
16469            .with_budget(FrameBudgetConfig {
16470                total: Duration::from_secs(5),
16471                ..FrameBudgetConfig::default()
16472            })
16473            .with_conformal_config(ConformalConfig {
16474                q_default: 10_000_000.0,
16475                ..defaults
16476            })
16477            .with_evidence_sink(EvidenceSinkConfig::enabled_file(&evidence_path));
16478        let mut program = headless_program_with_config(WarmModel, config);
16479        assert!(program.conformal_predictor.is_some());
16480
16481        for frame in 0..min_samples + 5 {
16482            program.dirty = true;
16483            program.render_frame().expect("render frame");
16484            assert_eq!(
16485                program.budget.degradation(),
16486                DegradationLevel::Full,
16487                "frame {frame}: an uncalibrated or fast frame must not degrade"
16488            );
16489        }
16490
16491        let contents = std::fs::read_to_string(&evidence_path).expect("evidence written");
16492        let rows: Vec<&str> = contents
16493            .lines()
16494            .filter(|l| l.contains(r#""event":"budget_decision""#))
16495            .collect();
16496        assert!(
16497            rows.len() >= min_samples,
16498            "one budget_decision row per frame: {contents}"
16499        );
16500        assert!(
16501            rows.iter()
16502                .any(|r| r.contains(r#""risk":true"#) && r.contains(r#""n_b":0"#)),
16503            "the cold-start prior must be visible as an uncalibrated risky verdict: {contents}"
16504        );
16505        assert!(
16506            rows.iter()
16507                .all(|r| r.contains(r#""degradation_after":"Full""#)),
16508            "no row may record a degradation: {contents}"
16509        );
16510    }
16511
16512    #[test]
16513    fn headless_unattainable_conformal_rank_keeps_rendering_and_measuring() {
16514        use ftui_render::budget::DegradationLevel;
16515        let path = temp_evidence_path("conformal_unattainable_rank");
16516        let config = ProgramConfig::default()
16517            .with_budget(FrameBudgetConfig::with_total(Duration::from_secs(5)))
16518            .with_conformal_config(ConformalConfig {
16519                alpha: 0.01,
16520                min_samples: 20,
16521                window_size: 128,
16522                q_default: 10_000_000.0,
16523            })
16524            .with_evidence_sink(EvidenceSinkConfig::enabled_file(&path));
16525        let mut program = headless_program_with_config(TestModel { value: 0 }, config);
16526        for _ in 0..105 {
16527            program.dirty = true;
16528            program
16529                .render_frame()
16530                .expect("render while calibration grows");
16531            assert_eq!(program.budget.degradation(), DegradationLevel::Full);
16532            assert!(
16533                !program.dirty,
16534                "unavailable rank must not strand rendering at SkipFrame"
16535            );
16536        }
16537        let contents = std::fs::read_to_string(path).expect("actual runtime evidence");
16538        let rows: Vec<serde_json::Value> = contents
16539            .lines()
16540            .map(|line| serde_json::from_str(line).expect("valid evidence JSON"))
16541            .filter(|row: &serde_json::Value| row["event"] == "budget_decision")
16542            .collect();
16543        let unavailable: Vec<_> = rows
16544            .iter()
16545            .filter(|row| row["conformal_status"] == "unattainable_rank")
16546            .collect();
16547        assert!(
16548            !unavailable.is_empty(),
16549            "must observe the post-warmup missing rank"
16550        );
16551        for row in unavailable {
16552            assert!(row["upper_us"].is_null());
16553            assert!(row["q_b"].is_null());
16554            assert_eq!(row["risk"], true);
16555            assert_eq!(row["degradation_after"], "Full");
16556        }
16557        assert!(
16558            rows.iter()
16559                .any(|row| row["conformal_status"] == "calibrated" && row["upper_us"].is_number()),
16560            "continued measurements must eventually yield an available bound"
16561        );
16562    }
16563
16564    #[test]
16565    fn headless_unavailable_conformal_bound_preserves_controller_degradation() {
16566        use ftui_render::budget::DegradationLevel;
16567        let config = ProgramConfig::default()
16568            .with_budget(FrameBudgetConfig::with_total(Duration::from_secs(5)))
16569            .with_conformal_config(ConformalConfig {
16570                alpha: 0.01,
16571                min_samples: 1,
16572                ..Default::default()
16573            });
16574        let mut program = headless_program_with_config(TestModel { value: 0 }, config);
16575        // Controlled observations exercise the actual budget controller and
16576        // runtime gate. These durations are not live performance measurements.
16577        for _ in 0..15 {
16578            program.budget.record_frame_time(Duration::from_secs(200));
16579            program.dirty = true;
16580            program
16581                .render_frame()
16582                .expect("real runtime/controller path");
16583        }
16584        assert_eq!(
16585            program.budget.degradation(),
16586            DegradationLevel::SimpleBorders
16587        );
16588        let predictor = program.conformal_predictor.as_ref().unwrap();
16589        let prediction = predictor.predict(
16590            BucketKey::from_context(ScreenMode::AltScreen, DiffStrategy::Full, 80, 24),
16591            0.0,
16592            5_000_000.0,
16593        );
16594        assert_eq!(prediction.upper_us, None);
16595        assert!(!predictor.is_calibrated(&prediction));
16596    }
16597
16598    #[test]
16599    fn headless_calibrated_conformal_risk_gate_respects_degradation_floor() {
16600        use ftui_render::budget::DegradationLevel;
16601        let config = ProgramConfig::default()
16602            .with_budget(FrameBudgetConfig::with_total(Duration::from_secs(5)))
16603            .with_conformal_config(ConformalConfig {
16604                alpha: 0.2,
16605                min_samples: 5,
16606                window_size: 32,
16607                q_default: 10_000_000.0,
16608            });
16609        let mut program = headless_program_with_config(TestModel { value: 0 }, config);
16610        let key = BucketKey::from_context(ScreenMode::AltScreen, DiffStrategy::Full, 80, 24);
16611        if let Some(predictor) = program.conformal_predictor.as_mut() {
16612            for _ in 0..10 {
16613                predictor.observe(key, 5_000_000.0, 20_000_000.0);
16614            }
16615        }
16616        // Calibrated conformal predictor now predicts risk (upper_us > budget_us),
16617        // while fast 1ms frame times keep the PID controller from degrading on its own.
16618        // Repeated risky renders must clamp at the default floor (SimpleBorders)
16619        // rather than bypassing the floor all the way to SkipFrame.
16620        for _ in 0..5 {
16621            program.budget.record_frame_time(Duration::from_millis(1));
16622            program.dirty = true;
16623            program.render_frame().expect("calibrated conformal gate");
16624        }
16625        assert_eq!(
16626            program.budget.degradation(),
16627            DegradationLevel::SimpleBorders,
16628            "calibrated conformal risk gate must honor the controller degradation_floor"
16629        );
16630    }
16631
16632    #[test]
16633    fn without_conformal_opts_out() {
16634        let evidence_path = temp_evidence_path("without_conformal_opt_out");
16635        let config = ProgramConfig::default()
16636            .without_conformal()
16637            .with_evidence_sink(EvidenceSinkConfig::enabled_file(&evidence_path));
16638        assert!(config.conformal_config.is_none());
16639
16640        let mut program = headless_program_with_config(TestModel { value: 0 }, config);
16641        assert!(
16642            program.conformal_predictor.is_none(),
16643            "without_conformal() must leave conformal_predictor as None"
16644        );
16645        program
16646            .step_headless_frame()
16647            .expect("render without conformal");
16648
16649        let contents = std::fs::read_to_string(&evidence_path).expect("evidence written");
16650        let row: serde_json::Value = contents
16651            .lines()
16652            .map(|l| serde_json::from_str(l).expect("valid JSON"))
16653            .find(|r: &serde_json::Value| r["event"] == "budget_decision")
16654            .expect("budget_decision row");
16655        assert!(row["conformal_status"].is_null());
16656        assert!(row["fallback_level"].is_null());
16657        assert!(row["upper_us"].is_null());
16658    }
16659
16660    #[test]
16661    fn headless_program_warms_up_then_degrades_then_recovers() {
16662        use ftui_render::budget::DegradationLevel;
16663
16664        let evidence_path = temp_evidence_path("conformal_warmup_degrade_recover");
16665        let defaults = ProgramConfig::default()
16666            .conformal_config
16667            .expect("conformal on by default");
16668        let min_samples = defaults.min_samples;
16669        assert_eq!(min_samples, 20);
16670
16671        // Use the default alpha (0.05) and min_samples (20) with a window_size
16672        // of 24 so that after warm-up and a single slow residual spike, 24 fast
16673        // frames evict the spike from the calibration window and allow recovery.
16674        let window_size = 24;
16675        let budget_total = Duration::from_secs(5);
16676        let config = ProgramConfig::default()
16677            .with_budget(FrameBudgetConfig::with_total(budget_total))
16678            .with_conformal_config(ConformalConfig {
16679                alpha: defaults.alpha,
16680                min_samples,
16681                window_size,
16682                q_default: 10_000_000.0,
16683            })
16684            .with_evidence_sink(EvidenceSinkConfig::enabled_file(&evidence_path));
16685        let mut program = headless_program_with_config(TestModel { value: 0 }, config);
16686
16687        // Phase 1: Warm-up (frames 1..=min_samples, where pre-render n_b = 0..19).
16688        // On the last warm-up frame (frame 20, pre-render n_b = 19), we inject a
16689        // single slow residual into the bucket after render (or via baseline_us)
16690        // so that as soon as warm-up completes (frame 21, pre-render n_b = 20),
16691        // the 95% conformal quantile exceeds the 5s budget while the PID/e-process
16692        // controller itself remains at Hold.
16693        for frame in 1..=min_samples {
16694            program.step_headless_frame().expect("warmup frame");
16695            assert_eq!(
16696                program.budget.degradation(),
16697                DegradationLevel::Full,
16698                "frame {frame}: must never degrade during warm-up (n_b < {min_samples})"
16699            );
16700        }
16701
16702        // Inject a single slow observation into the active bucket (replace the
16703        // 20th sample with a 20s residual against the 5s budget) while keeping
16704        // the budget controller's own frame-time history fast.
16705        let active_key = BucketKey::from_context(
16706            program.presenter.screen_mode(),
16707            program
16708                .presenter
16709                .last_diff_strategy()
16710                .unwrap_or(DiffStrategy::Full),
16711            program.width,
16712            program.presenter.render_height_hint().max(1),
16713        );
16714        if let Some(predictor) = program.conformal_predictor.as_mut() {
16715            predictor.observe(active_key, 100.0, 20_000_000.0);
16716        }
16717
16718        // Phase 2: Post-warmup calibrated conformal risk gate triggers degradation
16719        // on the very next frame (n_b >= min_samples, fallback_level == 0,
16720        // status == "calibrated", risk == true).
16721        program
16722            .step_headless_frame()
16723            .expect("first calibrated risky frame");
16724        assert_eq!(
16725            program.budget.degradation(),
16726            DegradationLevel::SimpleBorders,
16727            "calibrated conformal risk gate must degrade Full -> SimpleBorders"
16728        );
16729
16730        // Phase 3: Recovery. Run fast frames until the slow residual ages out of
16731        // the sliding window (window_size = 24) and the budget controller's
16732        // underload e-process upgrades SimpleBorders -> Full.
16733        let mut recovered_at = None;
16734        for step in 0..80 {
16735            program.budget.record_frame_time(Duration::from_micros(50));
16736            program.step_headless_frame().expect("recovery frame");
16737            if program.budget.degradation() == DegradationLevel::Full {
16738                recovered_at = Some(step);
16739                break;
16740            }
16741        }
16742        assert!(
16743            recovered_at.is_some(),
16744            "program must recover to DegradationLevel::Full once fast frames evict the spike and pass the upgrade gate"
16745        );
16746
16747        // Verify the JSONL evidence trail records all three phases.
16748        let contents = std::fs::read_to_string(&evidence_path).expect("evidence file");
16749        let rows: Vec<serde_json::Value> = contents
16750            .lines()
16751            .map(|l| serde_json::from_str(l).expect("valid JSON"))
16752            .filter(|r: &serde_json::Value| r["event"] == "budget_decision")
16753            .collect();
16754        assert!(rows.len() > min_samples + window_size);
16755
16756        // All warm-up rows (first min_samples frames) have status == "warmup",
16757        // fallback_level == 3, and degradation_after == "Full".
16758        for (idx, row) in rows.iter().take(min_samples).enumerate() {
16759            assert_eq!(row["conformal_status"], "warmup", "warmup row {idx}: {row}");
16760            assert_eq!(row["fallback_level"], 3, "warmup row {idx}: {row}");
16761            assert_eq!(row["degradation_after"], "Full", "warmup row {idx}: {row}");
16762        }
16763
16764        // The first post-warmup frame is calibrated at fallback_level == 0 and degrades.
16765        let degrade_row = &rows[min_samples];
16766        assert_eq!(degrade_row["conformal_status"], "calibrated");
16767        assert_eq!(degrade_row["fallback_level"], 0);
16768        assert_eq!(degrade_row["risk"], true);
16769        assert_eq!(degrade_row["decision"], "degrade");
16770        assert_eq!(degrade_row["decision_controller"], "stay");
16771        assert_eq!(degrade_row["degradation_before"], "Full");
16772        assert_eq!(degrade_row["degradation_after"], "SimpleBorders");
16773
16774        // A later calibrated row upgrades back to Full once risk clears.
16775        assert!(
16776            rows.iter().skip(min_samples + 1).any(|r| {
16777                r["conformal_status"] == "calibrated"
16778                    && r["fallback_level"] == 0
16779                    && r["risk"] == false
16780                    && r["decision"] == "upgrade"
16781                    && r["degradation_after"] == "Full"
16782            }),
16783            "evidence must record calibrated upgrade back to Full"
16784        );
16785    }
16786
16787    #[test]
16788    fn simulator_has_no_conformal_predictor() {
16789        use crate::simulator::ProgramSimulator;
16790        use ftui_render::budget::DegradationLevel;
16791
16792        struct DegradationCheckModel {
16793            observed: Arc<std::sync::Mutex<Vec<DegradationLevel>>>,
16794        }
16795
16796        impl Model for DegradationCheckModel {
16797            type Message = TestMsg;
16798
16799            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
16800                Cmd::none()
16801            }
16802
16803            fn view(&self, frame: &mut Frame) {
16804                self.observed.lock().unwrap().push(frame.buffer.degradation);
16805                frame.buffer.set_raw(0, 0, Cell::from_char('S'));
16806            }
16807        }
16808
16809        let observed = Arc::new(std::sync::Mutex::new(Vec::new()));
16810        let mut sim = ProgramSimulator::new(DegradationCheckModel {
16811            observed: Arc::clone(&observed),
16812        });
16813        sim.init();
16814        for _ in 0..40 {
16815            sim.capture_frame(80, 24);
16816        }
16817        let levels = observed.lock().unwrap();
16818        assert_eq!(levels.len(), 40);
16819        assert!(
16820            levels.iter().all(|&lvl| lvl == DegradationLevel::Full),
16821            "ProgramSimulator must stay strictly deterministic at DegradationLevel::Full with no conformal gating"
16822        );
16823    }
16824
16825    /// With `ProgramConfig::gestures` set, raw mouse events still reach
16826    /// `update()` and every recognized gesture reaches `Model::on_gesture`;
16827    /// without it nothing is recognized.
16828    /// `.50.2`: a long press reaches `on_gesture` without any tick rate, and
16829    /// the loop's poll timeout wakes it at the long-press deadline.
16830    #[test]
16831    fn long_press_fires_without_a_tick_rate() {
16832        use ftui_core::event::{Modifiers, MouseButton, MouseEvent, MouseEventKind};
16833        use ftui_core::gesture::GestureConfig;
16834        use ftui_core::semantic_event::SemanticEvent;
16835        use std::sync::{Arc, Mutex};
16836
16837        struct PressModel {
16838            gestures: Arc<Mutex<Vec<SemanticEvent>>>,
16839        }
16840
16841        impl Model for PressModel {
16842            type Message = Event;
16843
16844            fn update(&mut self, _msg: Event) -> Cmd<Event> {
16845                Cmd::none()
16846            }
16847
16848            fn view(&self, _frame: &mut Frame) {}
16849
16850            fn on_gesture(&mut self, gesture: SemanticEvent) -> Cmd<Event> {
16851                self.gestures.lock().unwrap().push(gesture);
16852                Cmd::none()
16853            }
16854        }
16855
16856        let log = Arc::new(Mutex::new(Vec::new()));
16857        let threshold = GestureConfig::default().long_press_threshold;
16858        let config = ProgramConfig {
16859            poll_timeout: Duration::from_secs(10),
16860            ..ProgramConfig::default().with_gestures(GestureConfig::default())
16861        };
16862        let mut program = headless_program_with_config(
16863            PressModel {
16864                gestures: Arc::clone(&log),
16865            },
16866            config,
16867        );
16868        assert!(program.tick_rate.is_none());
16869        assert_eq!(program.effective_timeout(), Duration::from_secs(10));
16870
16871        program
16872            .handle_event(Event::Mouse(MouseEvent {
16873                kind: MouseEventKind::Down(MouseButton::Left),
16874                x: 3,
16875                y: 3,
16876                pixel: None,
16877                modifiers: Modifiers::NONE,
16878            }))
16879            .unwrap();
16880        // The idle loop now sleeps no longer than the long-press deadline.
16881        assert!(program.effective_timeout() <= threshold);
16882
16883        let pressed_at = Instant::now();
16884        program.poll_long_press(pressed_at).unwrap();
16885        assert!(log.lock().unwrap().is_empty(), "not before the threshold");
16886        program
16887            .poll_long_press(pressed_at + threshold + Duration::from_millis(100))
16888            .unwrap();
16889        assert!(
16890            matches!(
16891                log.lock().unwrap().as_slice(),
16892                [SemanticEvent::LongPress { .. }]
16893            ),
16894            "{:?}",
16895            log.lock().unwrap()
16896        );
16897        // Fired once: no further deadline, so the idle timeout is restored.
16898        assert_eq!(program.effective_timeout(), Duration::from_secs(10));
16899    }
16900
16901    #[test]
16902    fn headless_program_delivers_recognized_gestures_to_on_gesture() {
16903        use ftui_core::event::{Modifiers, MouseButton, MouseEvent, MouseEventKind};
16904        use ftui_core::gesture::GestureConfig;
16905        use ftui_core::semantic_event::SemanticEvent;
16906        use std::sync::{Arc, Mutex};
16907
16908        struct GestureModel {
16909            raw: usize,
16910            gestures: Arc<Mutex<Vec<SemanticEvent>>>,
16911        }
16912
16913        #[derive(Debug)]
16914        enum GMsg {
16915            Raw,
16916        }
16917
16918        impl From<Event> for GMsg {
16919            fn from(_: Event) -> Self {
16920                GMsg::Raw
16921            }
16922        }
16923
16924        impl Model for GestureModel {
16925            type Message = GMsg;
16926
16927            fn update(&mut self, _msg: GMsg) -> Cmd<GMsg> {
16928                self.raw += 1;
16929                Cmd::none()
16930            }
16931
16932            fn view(&self, _frame: &mut Frame) {}
16933
16934            fn on_gesture(&mut self, gesture: SemanticEvent) -> Cmd<GMsg> {
16935                self.gestures.lock().unwrap().push(gesture);
16936                Cmd::none()
16937            }
16938        }
16939
16940        let mouse = |kind: MouseEventKind, x: u16, y: u16| {
16941            Event::Mouse(MouseEvent {
16942                kind,
16943                x,
16944                y,
16945                pixel: None,
16946                modifiers: Modifiers::NONE,
16947            })
16948        };
16949
16950        let log = Arc::new(Mutex::new(Vec::new()));
16951        let config = ProgramConfig::default().with_gestures(GestureConfig::default());
16952        let mut program = headless_program_with_config(
16953            GestureModel {
16954                raw: 0,
16955                gestures: Arc::clone(&log),
16956            },
16957            config,
16958        );
16959        // Click: down and up at the same cell.
16960        program
16961            .handle_event(mouse(MouseEventKind::Down(MouseButton::Left), 4, 2))
16962            .unwrap();
16963        program
16964            .handle_event(mouse(MouseEventKind::Up(MouseButton::Left), 4, 2))
16965            .unwrap();
16966        // Drag: down, move past the 3-cell dead zone, up.
16967        program
16968            .handle_event(mouse(MouseEventKind::Down(MouseButton::Left), 10, 5))
16969            .unwrap();
16970        program
16971            .handle_event(mouse(MouseEventKind::Drag(MouseButton::Left), 16, 5))
16972            .unwrap();
16973        program
16974            .handle_event(mouse(MouseEventKind::Up(MouseButton::Left), 16, 5))
16975            .unwrap();
16976        assert_eq!(program.model.raw, 5, "raw events keep flowing to update()");
16977
16978        let gestures = log.lock().unwrap();
16979        assert!(
16980            matches!(
16981                gestures.first(),
16982                Some(SemanticEvent::Click { pos, button: MouseButton::Left })
16983                    if pos.x == 4 && pos.y == 2
16984            ),
16985            "first gesture is the click: {gestures:?}"
16986        );
16987        assert!(
16988            gestures
16989                .iter()
16990                .any(|g| matches!(g, SemanticEvent::DragStart { .. })),
16991            "drag start recognized: {gestures:?}"
16992        );
16993        assert!(
16994            gestures
16995                .iter()
16996                .any(|g| matches!(g, SemanticEvent::DragEnd { .. })),
16997            "drag end recognized: {gestures:?}"
16998        );
16999        drop(gestures);
17000
17001        // Without the config nothing is recognized and update() is unaffected.
17002        let quiet = Arc::new(Mutex::new(Vec::new()));
17003        let mut program = headless_program_with_config(
17004            GestureModel {
17005                raw: 0,
17006                gestures: Arc::clone(&quiet),
17007            },
17008            ProgramConfig::default(),
17009        );
17010        program
17011            .handle_event(mouse(MouseEventKind::Down(MouseButton::Left), 1, 1))
17012            .unwrap();
17013        program
17014            .handle_event(mouse(MouseEventKind::Up(MouseButton::Left), 1, 1))
17015            .unwrap();
17016        assert!(quiet.lock().unwrap().is_empty());
17017        assert_eq!(program.model.raw, 2);
17018    }
17019
17020    #[test]
17021    fn headless_program_event_coalescing_disabled_by_default() {
17022        use ftui_core::event::{Modifiers, MouseEvent, MouseEventKind};
17023
17024        #[derive(Default)]
17025        struct CoalesceTestModel {
17026            events: Vec<Event>,
17027        }
17028
17029        impl Model for CoalesceTestModel {
17030            type Message = Event;
17031            fn update(&mut self, msg: Event) -> Cmd<Event> {
17032                self.events.push(msg);
17033                Cmd::none()
17034            }
17035            fn view(&self, _frame: &mut Frame) {}
17036        }
17037
17038        let mut program =
17039            headless_program_with_config(CoalesceTestModel::default(), ProgramConfig::default());
17040        assert!(program.event_coalescer().is_none());
17041
17042        for i in 0..5 {
17043            program
17044                .handle_event(Event::Mouse(MouseEvent {
17045                    kind: MouseEventKind::Moved,
17046                    x: i,
17047                    y: i,
17048                    pixel: None,
17049                    modifiers: Modifiers::NONE,
17050                }))
17051                .unwrap();
17052        }
17053        assert_eq!(program.model.events.len(), 5);
17054    }
17055
17056    #[test]
17057    fn headless_program_event_coalesces_mouse_moves_and_flushes_latest() {
17058        use ftui_core::event::{KeyCode, KeyEvent, Modifiers, MouseEvent, MouseEventKind};
17059
17060        #[derive(Default)]
17061        struct CoalesceTestModel {
17062            events: Vec<Event>,
17063        }
17064
17065        impl Model for CoalesceTestModel {
17066            type Message = Event;
17067            fn update(&mut self, msg: Event) -> Cmd<Event> {
17068                self.events.push(msg);
17069                Cmd::none()
17070            }
17071            fn view(&self, _frame: &mut Frame) {}
17072        }
17073
17074        let config = ProgramConfig::default().with_event_coalescing(true);
17075        let mut program = headless_program_with_config(CoalesceTestModel::default(), config);
17076        assert!(program.event_coalescer().is_some());
17077
17078        // Push 3 mouse move events.
17079        for i in 1..=3 {
17080            program
17081                .handle_event(Event::Mouse(MouseEvent {
17082                    kind: MouseEventKind::Moved,
17083                    x: i,
17084                    y: i * 2,
17085                    pixel: None,
17086                    modifiers: Modifiers::NONE,
17087                }))
17088                .unwrap();
17089        }
17090
17091        // None should have reached the model yet.
17092        assert_eq!(program.model.events.len(), 0);
17093        assert!(program.event_coalescer().unwrap().has_pending());
17094
17095        // A non-coalescable event (Key) arrives: flushes pending move, then delivers key.
17096        let key_evt = Event::Key(KeyEvent::new(KeyCode::Enter));
17097        program.handle_event(key_evt.clone()).unwrap();
17098
17099        assert_eq!(program.model.events.len(), 2);
17100        match &program.model.events[0] {
17101            Event::Mouse(m) => {
17102                assert_eq!(m.kind, MouseEventKind::Moved);
17103                assert_eq!(m.x, 3);
17104                assert_eq!(m.y, 6);
17105            }
17106            other => panic!("expected Mouse move, got {other:?}"),
17107        }
17108        assert_eq!(program.model.events[1], key_evt);
17109        assert!(!program.event_coalescer().unwrap().has_pending());
17110    }
17111
17112    #[test]
17113    fn headless_program_event_coalesces_scrolls_in_same_direction() {
17114        use ftui_core::event::{Modifiers, MouseEvent, MouseEventKind};
17115
17116        #[derive(Default)]
17117        struct CoalesceTestModel {
17118            events: Vec<Event>,
17119        }
17120
17121        impl Model for CoalesceTestModel {
17122            type Message = Event;
17123            fn update(&mut self, msg: Event) -> Cmd<Event> {
17124                self.events.push(msg);
17125                Cmd::none()
17126            }
17127            fn view(&self, _frame: &mut Frame) {}
17128        }
17129
17130        let config = ProgramConfig::default().with_event_coalescing(true);
17131        let mut program = headless_program_with_config(CoalesceTestModel::default(), config);
17132
17133        for _ in 0..4 {
17134            program
17135                .handle_event(Event::Mouse(MouseEvent {
17136                    kind: MouseEventKind::ScrollUp,
17137                    x: 10,
17138                    y: 20,
17139                    pixel: None,
17140                    modifiers: Modifiers::NONE,
17141                }))
17142                .unwrap();
17143        }
17144
17145        assert_eq!(program.model.events.len(), 0);
17146        assert!(program.event_coalescer().unwrap().has_pending());
17147
17148        // Four notches in, four notches out - which is the point of the fix:
17149        // collapsing the run made the application scroll a quarter as far as
17150        // the user asked (`bd-minjt`).
17151        //
17152        // Note what the assertion below therefore says about cost. The model
17153        // is updated four times, once per notch, because `MouseEventKind` has
17154        // no notch count and a model is entitled to see each notch. Batching
17155        // scroll defers those updates to flush time; it does not merge them.
17156        // Only mouse-move coalescing removes updates.
17157        program.flush_coalesced_events().unwrap();
17158        assert_eq!(program.model.events.len(), 4);
17159        for event in &program.model.events {
17160            match event {
17161                Event::Mouse(m) => {
17162                    assert_eq!(m.kind, MouseEventKind::ScrollUp);
17163                    assert_eq!(m.x, 10);
17164                    assert_eq!(m.y, 20);
17165                }
17166                other => panic!("expected ScrollUp, got {other:?}"),
17167            }
17168        }
17169    }
17170
17171    #[test]
17172    fn headless_program_event_coalescing_scroll_direction_change_flushes_old() {
17173        use ftui_core::event::{Modifiers, MouseEvent, MouseEventKind};
17174
17175        #[derive(Default)]
17176        struct CoalesceTestModel {
17177            events: Vec<Event>,
17178        }
17179
17180        impl Model for CoalesceTestModel {
17181            type Message = Event;
17182            fn update(&mut self, msg: Event) -> Cmd<Event> {
17183                self.events.push(msg);
17184                Cmd::none()
17185            }
17186            fn view(&self, _frame: &mut Frame) {}
17187        }
17188
17189        let config = ProgramConfig::default().with_event_coalescing(true);
17190        let mut program = headless_program_with_config(CoalesceTestModel::default(), config);
17191
17192        program
17193            .handle_event(Event::Mouse(MouseEvent {
17194                kind: MouseEventKind::ScrollUp,
17195                x: 5,
17196                y: 5,
17197                pixel: None,
17198                modifiers: Modifiers::NONE,
17199            }))
17200            .unwrap();
17201        assert_eq!(program.model.events.len(), 0);
17202
17203        // Direction change closes the ScrollUp run and opens a ScrollDown one.
17204        // Neither is dispatched yet: a closed run keeps its notch count, which
17205        // does not fit in the single event `push` can hand back, so it waits
17206        // for the flush that ends the batch.
17207        program
17208            .handle_event(Event::Mouse(MouseEvent {
17209                kind: MouseEventKind::ScrollDown,
17210                x: 6,
17211                y: 6,
17212                pixel: None,
17213                modifiers: Modifiers::NONE,
17214            }))
17215            .unwrap();
17216        assert_eq!(program.model.events.len(), 0);
17217
17218        // Both runs arrive in input order.
17219        program.flush_coalesced_events().unwrap();
17220        let kinds: Vec<MouseEventKind> = program
17221            .model
17222            .events
17223            .iter()
17224            .map(|e| match e {
17225                Event::Mouse(m) => m.kind,
17226                other => panic!("expected mouse event, got {other:?}"),
17227            })
17228            .collect();
17229        assert_eq!(
17230            kinds,
17231            vec![MouseEventKind::ScrollUp, MouseEventKind::ScrollDown]
17232        );
17233    }
17234
17235    #[test]
17236    fn headless_program_event_coalescing_flushed_on_tick() {
17237        use ftui_core::event::{Modifiers, MouseEvent, MouseEventKind};
17238
17239        #[derive(Default)]
17240        struct CoalesceTestModel {
17241            events: Vec<Event>,
17242        }
17243
17244        impl Model for CoalesceTestModel {
17245            type Message = Event;
17246            fn update(&mut self, msg: Event) -> Cmd<Event> {
17247                self.events.push(msg);
17248                Cmd::none()
17249            }
17250            fn view(&self, _frame: &mut Frame) {}
17251        }
17252
17253        let config = ProgramConfig::default().with_event_coalescing(true);
17254        let mut program = headless_program_with_config(CoalesceTestModel::default(), config);
17255
17256        program
17257            .handle_event(Event::Mouse(MouseEvent {
17258                kind: MouseEventKind::Moved,
17259                x: 42,
17260                y: 24,
17261                pixel: None,
17262                modifiers: Modifiers::NONE,
17263            }))
17264            .unwrap();
17265        assert_eq!(program.model.events.len(), 0);
17266
17267        program.handle_event(Event::Tick).unwrap();
17268        assert_eq!(program.model.events.len(), 2);
17269        match &program.model.events[0] {
17270            Event::Mouse(m) => {
17271                assert_eq!(m.kind, MouseEventKind::Moved);
17272                assert_eq!(m.x, 42);
17273                assert_eq!(m.y, 24);
17274            }
17275            other => panic!("expected Moved before Tick, got {other:?}"),
17276        }
17277        assert_eq!(program.model.events[1], Event::Tick);
17278    }
17279
17280    #[test]
17281    fn headless_program_event_coalescing_cleared_on_resize() {
17282        use ftui_core::event::{Modifiers, MouseEvent, MouseEventKind};
17283
17284        #[derive(Default)]
17285        struct CoalesceTestModel {
17286            events: Vec<Event>,
17287        }
17288
17289        impl Model for CoalesceTestModel {
17290            type Message = Event;
17291            fn update(&mut self, msg: Event) -> Cmd<Event> {
17292                self.events.push(msg);
17293                Cmd::none()
17294            }
17295            fn view(&self, _frame: &mut Frame) {}
17296        }
17297
17298        let config = ProgramConfig::default().with_event_coalescing(true);
17299        let mut program = headless_program_with_config(CoalesceTestModel::default(), config);
17300
17301        program
17302            .handle_event(Event::Mouse(MouseEvent {
17303                kind: MouseEventKind::Moved,
17304                x: 10,
17305                y: 10,
17306                pixel: None,
17307                modifiers: Modifiers::NONE,
17308            }))
17309            .unwrap();
17310        assert!(program.event_coalescer().unwrap().has_pending());
17311
17312        program
17313            .handle_event(Event::Resize {
17314                width: 100,
17315                height: 50,
17316            })
17317            .unwrap();
17318        assert!(!program.event_coalescer().unwrap().has_pending());
17319
17320        program.flush_coalesced_events().unwrap();
17321        // Mouse move was cleared, and resize is handled internally by the runtime.
17322        assert_eq!(program.model.events.len(), 0);
17323
17324        // Subsequent input arrives normally without the stale mouse position.
17325        program
17326            .handle_event(Event::Key(KeyEvent::new(KeyCode::Char('a'))))
17327            .unwrap();
17328        assert_eq!(program.model.events.len(), 1);
17329        assert_eq!(
17330            program.model.events[0],
17331            Event::Key(KeyEvent::new(KeyCode::Char('a')))
17332        );
17333    }
17334
17335    #[test]
17336    fn headless_program_terminal_response_intercepted_unless_opted_in() {
17337        use ftui_core::event::TerminalResponse;
17338
17339        #[derive(Default)]
17340        struct RespTestModel {
17341            events: Vec<Event>,
17342        }
17343
17344        impl Model for RespTestModel {
17345            type Message = Event;
17346            fn update(&mut self, msg: Event) -> Cmd<Event> {
17347                self.events.push(msg);
17348                Cmd::none()
17349            }
17350            fn view(&self, _frame: &mut Frame) {}
17351        }
17352
17353        let dcs = Event::TerminalResponse(TerminalResponse::Dcs {
17354            payload: b"1$r0m".to_vec(),
17355            truncated: false,
17356        });
17357        let cell_size = Event::TerminalResponse(TerminalResponse::CellSize {
17358            width: 10,
17359            height: 20,
17360        });
17361
17362        // Default: intercepted inside Program without reaching Model::update.
17363        let mut program =
17364            headless_program_with_config(RespTestModel::default(), ProgramConfig::default());
17365        program.handle_event(dcs.clone()).unwrap();
17366        program.handle_event(cell_size.clone()).unwrap();
17367        assert!(program.model.events.is_empty());
17368        assert_eq!(program.startup_parser.cell_size_px(), Some((10, 20)));
17369
17370        // Opt-in: forwarded to Model::update.
17371        let mut opted_in = headless_program_with_config(
17372            RespTestModel::default(),
17373            ProgramConfig::default().with_deliver_terminal_responses(true),
17374        );
17375        opted_in.handle_event(dcs.clone()).unwrap();
17376        opted_in.handle_event(cell_size.clone()).unwrap();
17377        assert_eq!(opted_in.model.events, vec![dcs, cell_size]);
17378        assert_eq!(opted_in.startup_parser.cell_size_px(), Some((10, 20)));
17379    }
17380
17381    /// CONTRACT (bd-1za0z item 3): the queue guardrail sees the live effect
17382    /// backlog (`TaskExecutor::in_flight`), not a hard-coded zero. With a
17383    /// warn depth of one and four tasks in flight, the very first frame must
17384    /// raise a queue alert and export a snapshot carrying that depth.
17385    #[test]
17386    fn headless_render_frame_feeds_live_effect_backlog_to_queue_guardrail() {
17387        struct QueueModel;
17388
17389        #[derive(Debug)]
17390        enum QueueMsg {
17391            Noop,
17392        }
17393
17394        impl From<Event> for QueueMsg {
17395            fn from(_: Event) -> Self {
17396                QueueMsg::Noop
17397            }
17398        }
17399
17400        impl Model for QueueModel {
17401            type Message = QueueMsg;
17402
17403            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
17404                Cmd::none()
17405            }
17406
17407            fn view(&self, frame: &mut Frame) {
17408                frame.buffer.set_raw(0, 0, Cell::from_char('Q'));
17409            }
17410        }
17411
17412        let evidence_path = temp_evidence_path("guardrail_queue_depth");
17413        let config = ProgramConfig {
17414            guardrails: GuardrailsConfig {
17415                memory: MemoryBudgetConfig::default(),
17416                queue: QueueConfig {
17417                    warn_depth: 1,
17418                    ..QueueConfig::default()
17419                },
17420                ..Default::default()
17421            },
17422            evidence_sink: EvidenceSinkConfig::enabled_file(&evidence_path),
17423            ..Default::default()
17424        };
17425
17426        // Hand four real effects to this program's executor (the default
17427        // spawned lane) that are still running when the frame renders: the
17428        // guardrail must count them as the backlog. Drain them afterwards so
17429        // the test leaves no worker threads behind.
17430        const IN_FLIGHT: usize = 4;
17431        let mut program = headless_program_with_config(QueueModel, config);
17432        let release = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
17433        for _ in 0..IN_FLIGHT {
17434            let release = std::sync::Arc::clone(&release);
17435            program
17436                .execute_cmd(Cmd::task(move || {
17437                    while !release.load(std::sync::atomic::Ordering::Acquire) {
17438                        std::thread::sleep(Duration::from_millis(1));
17439                    }
17440                    QueueMsg::Noop
17441                }))
17442                .expect("submit in-flight task");
17443        }
17444        assert_eq!(program.task_executor.in_flight(), IN_FLIGHT);
17445        program.dirty = true;
17446        let rendered = program.render_frame();
17447        release.store(true, std::sync::atomic::Ordering::Release);
17448        let deadline = Instant::now() + Duration::from_secs(5);
17449        while program.task_executor.in_flight() > 0 && Instant::now() <= deadline {
17450            program
17451                .process_task_results()
17452                .expect("process task results");
17453            std::thread::sleep(Duration::from_millis(1));
17454        }
17455        assert_eq!(program.task_executor.in_flight(), 0, "tasks must drain");
17456        rendered.expect("render frame with queue alert");
17457
17458        let contents =
17459            std::fs::read_to_string(&evidence_path).expect("guardrail evidence file written");
17460        assert!(
17461            contents.contains(r#""event":"guardrail_snapshot""#),
17462            "queue backlog above warn_depth must export a guardrail_snapshot row; got: {contents}"
17463        );
17464        let depth = contents
17465            .split(r#""queue_depth":"#)
17466            .nth(1)
17467            .and_then(|rest| rest.split(|c: char| !c.is_ascii_digit()).next())
17468            .and_then(|digits| digits.parse::<u64>().ok())
17469            .expect("snapshot row carries queue_depth");
17470        assert!(
17471            depth >= IN_FLIGHT as u64,
17472            "guardrail must observe the live backlog (>= {IN_FLIGHT}), saw {depth}: {contents}"
17473        );
17474    }
17475
17476    #[test]
17477    fn guardrails_receive_live_queue_depth() {
17478        headless_render_frame_feeds_live_effect_backlog_to_queue_guardrail();
17479    }
17480
17481    #[test]
17482    fn guardrails_queue_depth_zero_without_queue() {
17483        struct ZeroQueueModel;
17484
17485        #[derive(Debug)]
17486        enum ZeroMsg {}
17487
17488        impl From<Event> for ZeroMsg {
17489            fn from(_: Event) -> Self {
17490                unreachable!()
17491            }
17492        }
17493
17494        impl Model for ZeroQueueModel {
17495            type Message = ZeroMsg;
17496
17497            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
17498                Cmd::none()
17499            }
17500
17501            fn view(&self, frame: &mut Frame) {
17502                frame.buffer.set_raw(0, 0, Cell::from_char('Z'));
17503            }
17504        }
17505
17506        let config = ProgramConfig {
17507            guardrails: GuardrailsConfig {
17508                memory: MemoryBudgetConfig::default(),
17509                queue: QueueConfig {
17510                    warn_depth: 1,
17511                    ..QueueConfig::default()
17512                },
17513                ..Default::default()
17514            },
17515            ..Default::default()
17516        };
17517
17518        let mut program = headless_program_with_config(ZeroQueueModel, config);
17519        assert_eq!(program.task_executor.in_flight(), 0);
17520        program.dirty = true;
17521        program.render_frame().expect("render frame with no tasks");
17522        let snapshot = program.guardrails.snapshot();
17523        assert_eq!(snapshot.queue_depth, 0);
17524        assert_eq!(snapshot.frames_with_alerts, 0);
17525    }
17526
17527    /// CONTRACT (bd-1za0z): a soft memory alert must trigger a capacity trim
17528    /// (arena rebuild + pool gc) so the degradation actuator can actually
17529    /// move the sensor โ€” retained capacity alone must not pin alerts forever.
17530    #[test]
17531    fn headless_render_frame_soft_alert_trims_retained_capacity() {
17532        struct AlertModel;
17533
17534        #[derive(Debug)]
17535        enum AlertMsg {
17536            Noop,
17537        }
17538
17539        impl From<Event> for AlertMsg {
17540            fn from(_: Event) -> Self {
17541                AlertMsg::Noop
17542            }
17543        }
17544
17545        impl Model for AlertModel {
17546            type Message = AlertMsg;
17547
17548            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
17549                Cmd::none()
17550            }
17551
17552            fn view(&self, _frame: &mut Frame) {}
17553        }
17554
17555        let config = ProgramConfig {
17556            guardrails: GuardrailsConfig {
17557                memory: MemoryBudgetConfig {
17558                    soft_limit_bytes: 4096,
17559                    ..MemoryBudgetConfig::default()
17560                },
17561                queue: QueueConfig::default(),
17562                ..Default::default()
17563            },
17564            ..Default::default()
17565        };
17566
17567        let mut program = headless_program_with_config(AlertModel, config.clone());
17568
17569        // Control: same config, same render, no injected capacity โ€” its
17570        // post-frame arena size is the floor a successful trim must return
17571        // to (the render itself allocates a deterministic working set).
17572        let mut control = headless_program_with_config(AlertModel, config);
17573        control.dirty = true;
17574        control.render_frame().expect("control render");
17575        let control_bytes = control.frame_arena.allocated_bytes();
17576
17577        // Simulate retained capacity well above the soft limit: 256 KiB of
17578        // arena allocations that a reset-less sensor can never shed.
17579        let filler = vec![0u8; 256 * 1024];
17580        program.frame_arena.alloc_slice(&filler);
17581        assert!(program.frame_arena.allocated_bytes() >= 256 * 1024);
17582
17583        program.dirty = true;
17584        program
17585            .render_frame()
17586            .expect("render frame with soft alert");
17587        assert_eq!(
17588            program.last_soft_trim_frame,
17589            Some(program.frame_idx),
17590            "soft alert must trigger the capacity trim"
17591        );
17592
17593        // The trim released the injected chunk: the arena is back at the
17594        // control's size instead of carrying the extra 256 KiB.
17595        let after = program.frame_arena.allocated_bytes();
17596        assert_eq!(program.guardrails.snapshot().leak_mean_bytes, 0.0);
17597        assert!(!program.guardrails.snapshot().leak_alert);
17598        assert!(
17599            after <= control_bytes + 1024,
17600            "soft alert must trim retained capacity: after={after}, control={control_bytes}"
17601        );
17602    }
17603
17604    #[test]
17605    fn headless_render_frame_presents_when_budget_exhausted() {
17606        // frankentui#104: a budget with no time left at frame start used to
17607        // skip the frame before render, so a zero budget never showed
17608        // anything. Running out of time is not a reason to skip: the frame is
17609        // rendered and presented. Only an explicit SkipFrame degradation
17610        // skips (explicit_skip_frame_still_skips_before_render).
17611        let config = ProgramConfig {
17612            budget: FrameBudgetConfig::with_total(Duration::ZERO),
17613            ..Default::default()
17614        };
17615
17616        let mut program = headless_program_with_config(TestModel { value: 0 }, config);
17617        program.dirty = true;
17618        program.render_frame().expect("render frame");
17619
17620        assert!(program.budget.remaining().is_zero());
17621        assert!(
17622            !program.dirty,
17623            "a zero budget must still render and present the frame"
17624        );
17625        assert!(program.presenter.last_diff_strategy().is_some());
17626        assert_eq!(program.frame_idx, 1);
17627    }
17628
17629    #[test]
17630    fn headless_render_frame_emits_budget_evidence_with_controller() {
17631        use ftui_render::budget::BudgetControllerConfig;
17632
17633        struct RenderModel;
17634
17635        #[derive(Debug)]
17636        enum RenderMsg {
17637            Noop,
17638        }
17639
17640        impl From<Event> for RenderMsg {
17641            fn from(_: Event) -> Self {
17642                RenderMsg::Noop
17643            }
17644        }
17645
17646        impl Model for RenderModel {
17647            type Message = RenderMsg;
17648
17649            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
17650                Cmd::none()
17651            }
17652
17653            fn view(&self, frame: &mut Frame) {
17654                frame.buffer.set_raw(0, 0, Cell::from_char('E'));
17655            }
17656        }
17657
17658        let config =
17659            ProgramConfig::default().with_evidence_sink(EvidenceSinkConfig::enabled_stdout());
17660        let mut program = headless_program_with_config(RenderModel, config);
17661        program.budget = program
17662            .budget
17663            .with_controller(BudgetControllerConfig::default());
17664
17665        program.render_frame().expect("render frame");
17666        assert!(program.budget.telemetry().is_some());
17667        assert_eq!(program.frame_idx, 1);
17668    }
17669
17670    #[test]
17671    fn headless_handle_event_updates_model() {
17672        struct EventModel {
17673            events: usize,
17674            last_resize: Option<(u16, u16)>,
17675        }
17676
17677        #[derive(Debug)]
17678        enum EventMsg {
17679            Resize(u16, u16),
17680            Other,
17681        }
17682
17683        impl From<Event> for EventMsg {
17684            fn from(event: Event) -> Self {
17685                match event {
17686                    Event::Resize { width, height } => EventMsg::Resize(width, height),
17687                    _ => EventMsg::Other,
17688                }
17689            }
17690        }
17691
17692        impl Model for EventModel {
17693            type Message = EventMsg;
17694
17695            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
17696                self.events += 1;
17697                if let EventMsg::Resize(w, h) = msg {
17698                    self.last_resize = Some((w, h));
17699                }
17700                Cmd::none()
17701            }
17702
17703            fn view(&self, _frame: &mut Frame) {}
17704        }
17705
17706        let mut program = headless_program_with_config(
17707            EventModel {
17708                events: 0,
17709                last_resize: None,
17710            },
17711            ProgramConfig::default().with_resize_behavior(ResizeBehavior::Immediate),
17712        );
17713
17714        program
17715            .handle_event(Event::Key(ftui_core::event::KeyEvent::new(
17716                ftui_core::event::KeyCode::Char('x'),
17717            )))
17718            .expect("handle key");
17719        assert_eq!(program.model().events, 1);
17720
17721        program
17722            .handle_event(Event::Resize {
17723                width: 10,
17724                height: 5,
17725            })
17726            .expect("handle resize");
17727        assert_eq!(program.model().events, 2);
17728        assert_eq!(program.model().last_resize, Some((10, 5)));
17729        assert_eq!(program.width, 10);
17730        assert_eq!(program.height, 5);
17731    }
17732
17733    #[test]
17734    fn headless_handle_event_quit_skips_subscription_reconcile() {
17735        use crate::subscription::{StopSignal, SubId, Subscription, SubscriptionSender};
17736
17737        struct QuitSubModel {
17738            quitting: bool,
17739            subscription_starts: Arc<AtomicUsize>,
17740        }
17741
17742        #[derive(Debug)]
17743        enum QuitSubMsg {
17744            Quit,
17745            Other,
17746        }
17747
17748        impl From<Event> for QuitSubMsg {
17749            fn from(event: Event) -> Self {
17750                match event {
17751                    Event::Key(_) => Self::Quit,
17752                    _ => Self::Other,
17753                }
17754            }
17755        }
17756
17757        impl Model for QuitSubModel {
17758            type Message = QuitSubMsg;
17759
17760            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
17761                match msg {
17762                    QuitSubMsg::Quit => {
17763                        self.quitting = true;
17764                        Cmd::quit()
17765                    }
17766                    QuitSubMsg::Other => Cmd::none(),
17767                }
17768            }
17769
17770            fn view(&self, _frame: &mut Frame) {}
17771
17772            fn subscriptions(&self) -> Vec<Box<dyn Subscription<Self::Message>>> {
17773                if self.quitting {
17774                    vec![Box::new(QuitSubSubscription {
17775                        starts: Arc::clone(&self.subscription_starts),
17776                    })]
17777                } else {
17778                    vec![]
17779                }
17780            }
17781        }
17782
17783        struct QuitSubSubscription {
17784            starts: Arc<AtomicUsize>,
17785        }
17786
17787        impl Subscription<QuitSubMsg> for QuitSubSubscription {
17788            fn id(&self) -> SubId {
17789                7
17790            }
17791
17792            fn run(&self, _sender: SubscriptionSender<QuitSubMsg>, stop: StopSignal) {
17793                self.starts.fetch_add(1, Ordering::SeqCst);
17794                let _ = stop.wait_timeout(Duration::from_millis(10));
17795            }
17796        }
17797
17798        let subscription_starts = Arc::new(AtomicUsize::new(0));
17799        let mut program = headless_program_with_config(
17800            QuitSubModel {
17801                quitting: false,
17802                subscription_starts: Arc::clone(&subscription_starts),
17803            },
17804            ProgramConfig::default(),
17805        );
17806
17807        program
17808            .handle_event(Event::Key(ftui_core::event::KeyEvent::new(
17809                ftui_core::event::KeyCode::Char('q'),
17810            )))
17811            .expect("handle event");
17812
17813        assert!(!program.is_running());
17814        assert_eq!(program.subscriptions.active_count(), 0);
17815        assert_eq!(subscription_starts.load(Ordering::SeqCst), 0);
17816    }
17817
17818    #[test]
17819    fn headless_handle_resize_ignored_when_forced_size() {
17820        struct ResizeModel {
17821            resized: bool,
17822        }
17823
17824        #[derive(Debug)]
17825        enum ResizeMsg {
17826            Resize,
17827            Other,
17828        }
17829
17830        impl From<Event> for ResizeMsg {
17831            fn from(event: Event) -> Self {
17832                match event {
17833                    Event::Resize { .. } => ResizeMsg::Resize,
17834                    _ => ResizeMsg::Other,
17835                }
17836            }
17837        }
17838
17839        impl Model for ResizeModel {
17840            type Message = ResizeMsg;
17841
17842            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
17843                if matches!(msg, ResizeMsg::Resize) {
17844                    self.resized = true;
17845                }
17846                Cmd::none()
17847            }
17848
17849            fn view(&self, _frame: &mut Frame) {}
17850        }
17851
17852        let config = ProgramConfig::default().with_forced_size(80, 24);
17853        let mut program = headless_program_with_config(ResizeModel { resized: false }, config);
17854
17855        program
17856            .handle_event(Event::Resize {
17857                width: 120,
17858                height: 40,
17859            })
17860            .expect("handle resize");
17861
17862        assert_eq!(program.width, 80);
17863        assert_eq!(program.height, 24);
17864        assert!(!program.model().resized);
17865    }
17866
17867    #[test]
17868    fn headless_execute_cmd_batch_sequence_and_quit() {
17869        struct BatchModel {
17870            count: usize,
17871        }
17872
17873        #[derive(Debug)]
17874        enum BatchMsg {
17875            Inc,
17876        }
17877
17878        impl From<Event> for BatchMsg {
17879            fn from(_: Event) -> Self {
17880                BatchMsg::Inc
17881            }
17882        }
17883
17884        impl Model for BatchModel {
17885            type Message = BatchMsg;
17886
17887            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
17888                match msg {
17889                    BatchMsg::Inc => {
17890                        self.count += 1;
17891                        Cmd::none()
17892                    }
17893                }
17894            }
17895
17896            fn view(&self, _frame: &mut Frame) {}
17897        }
17898
17899        let mut program =
17900            headless_program_with_config(BatchModel { count: 0 }, ProgramConfig::default());
17901
17902        program
17903            .execute_cmd(Cmd::Batch(vec![
17904                Cmd::msg(BatchMsg::Inc),
17905                Cmd::Sequence(vec![
17906                    Cmd::msg(BatchMsg::Inc),
17907                    Cmd::quit(),
17908                    Cmd::msg(BatchMsg::Inc),
17909                ]),
17910            ]))
17911            .expect("batch cmd");
17912
17913        assert_eq!(program.model().count, 2);
17914        assert!(!program.running);
17915    }
17916
17917    #[test]
17918    fn headless_execute_cmd_runs_long_msg_chains_without_recursion() {
17919        // One step per `Cmd::Msg`, alternating a bare message with one
17920        // nested in a sequence. This recursed per step and overflowed the
17921        // stack at about 10k steps.
17922        struct Walker {
17923            steps: u32,
17924            order: Vec<&'static str>,
17925        }
17926
17927        #[derive(Debug)]
17928        enum WalkMsg {
17929            Step(u32),
17930            Mark(&'static str),
17931        }
17932
17933        impl From<Event> for WalkMsg {
17934            fn from(_: Event) -> Self {
17935                WalkMsg::Mark("event")
17936            }
17937        }
17938
17939        impl Model for Walker {
17940            type Message = WalkMsg;
17941
17942            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
17943                match msg {
17944                    WalkMsg::Step(0) => Cmd::quit(),
17945                    WalkMsg::Step(n) => {
17946                        self.steps += 1;
17947                        let step = Cmd::msg(WalkMsg::Step(n - 1));
17948                        if n % 2 == 0 {
17949                            step
17950                        } else {
17951                            Cmd::Sequence(vec![step, Cmd::msg(WalkMsg::Mark("after"))])
17952                        }
17953                    }
17954                    WalkMsg::Mark(label) => {
17955                        self.order.push(label);
17956                        Cmd::none()
17957                    }
17958                }
17959            }
17960
17961            fn view(&self, _frame: &mut Frame) {}
17962        }
17963
17964        let mut program = headless_program_with_config(
17965            Walker {
17966                steps: 0,
17967                order: Vec::new(),
17968            },
17969            ProgramConfig::default(),
17970        );
17971        program
17972            .execute_cmd(Cmd::msg(WalkMsg::Step(200_000)))
17973            .expect("chain");
17974        assert_eq!(program.model().steps, 200_000);
17975        // The chain ends in Quit, which stops every pending sequence.
17976        assert!(program.model().order.is_empty());
17977        assert!(!program.running);
17978
17979        // Without a quit, a sequence finishes its nested chain before its
17980        // next command, in the order recursion gave.
17981        program.running = true;
17982        program
17983            .execute_cmd(Cmd::Sequence(vec![
17984                Cmd::Batch(vec![
17985                    Cmd::msg(WalkMsg::Mark("a")),
17986                    Cmd::msg(WalkMsg::Mark("b")),
17987                ]),
17988                Cmd::msg(WalkMsg::Mark("c")),
17989            ]))
17990            .expect("sequence");
17991        assert_eq!(program.model().order, ["a", "b", "c"]);
17992    }
17993
17994    #[test]
17995    fn headless_process_subscription_messages_updates_model() {
17996        use crate::subscription::{StopSignal, SubId, Subscription, SubscriptionSender};
17997
17998        struct SubModel {
17999            pings: usize,
18000            ready_tx: mpsc::Sender<()>,
18001        }
18002
18003        #[derive(Debug)]
18004        enum SubMsg {
18005            Ping,
18006            Other,
18007        }
18008
18009        impl From<Event> for SubMsg {
18010            fn from(_: Event) -> Self {
18011                SubMsg::Other
18012            }
18013        }
18014
18015        impl Model for SubModel {
18016            type Message = SubMsg;
18017
18018            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
18019                if let SubMsg::Ping = msg {
18020                    self.pings += 1;
18021                }
18022                Cmd::none()
18023            }
18024
18025            fn view(&self, _frame: &mut Frame) {}
18026
18027            fn subscriptions(&self) -> Vec<Box<dyn Subscription<Self::Message>>> {
18028                vec![Box::new(TestSubscription {
18029                    ready_tx: self.ready_tx.clone(),
18030                })]
18031            }
18032        }
18033
18034        struct TestSubscription {
18035            ready_tx: mpsc::Sender<()>,
18036        }
18037
18038        impl Subscription<SubMsg> for TestSubscription {
18039            fn id(&self) -> SubId {
18040                1
18041            }
18042
18043            fn run(&self, sender: SubscriptionSender<SubMsg>, _stop: StopSignal) {
18044                let _ = sender.send(SubMsg::Ping);
18045                let _ = self.ready_tx.send(());
18046            }
18047        }
18048
18049        let (ready_tx, ready_rx) = mpsc::channel();
18050        let mut program =
18051            headless_program_with_config(SubModel { pings: 0, ready_tx }, ProgramConfig::default());
18052
18053        program.reconcile_subscriptions();
18054        ready_rx
18055            .recv_timeout(Duration::from_millis(200))
18056            .expect("subscription started");
18057        program
18058            .process_subscription_messages()
18059            .expect("process subscriptions");
18060
18061        assert_eq!(program.model().pings, 1);
18062    }
18063
18064    #[test]
18065    fn subscription_backlog_skips_idle_poll_without_starving_input_or_render() {
18066        use crate::subscription::{StopSignal, SubId, Subscription, SubscriptionSender};
18067        use std::sync::Mutex;
18068
18069        // Two full 64-message batches followed by one partial batch exercise
18070        // both prompt backlog draining and restoration of the normal timeout.
18071        const TOTAL: usize = 129;
18072        const IDLE_TIMEOUT: Duration = Duration::from_millis(100);
18073
18074        #[derive(Default)]
18075        struct Trace {
18076            delivered: usize,
18077            polls: Vec<(usize, Duration)>,
18078            renders: Vec<usize>,
18079        }
18080
18081        enum BurstMsg {
18082            Value(usize),
18083            Event(Event),
18084        }
18085
18086        impl From<Event> for BurstMsg {
18087            fn from(event: Event) -> Self {
18088                Self::Event(event)
18089            }
18090        }
18091
18092        struct BurstSubscription {
18093            ready: mpsc::Sender<()>,
18094        }
18095
18096        impl Subscription<BurstMsg> for BurstSubscription {
18097            fn id(&self) -> SubId {
18098                1
18099            }
18100
18101            fn run(&self, sender: SubscriptionSender<BurstMsg>, _stop: StopSignal) {
18102                for value in 0..TOTAL {
18103                    sender.send(BurstMsg::Value(value)).unwrap();
18104                }
18105                self.ready.send(()).unwrap();
18106            }
18107        }
18108
18109        struct BurstModel {
18110            received: Vec<usize>,
18111            input_at: Vec<usize>,
18112            ready: mpsc::Sender<()>,
18113            trace: Arc<Mutex<Trace>>,
18114        }
18115
18116        impl Model for BurstModel {
18117            type Message = BurstMsg;
18118
18119            fn update(&mut self, message: BurstMsg) -> Cmd<BurstMsg> {
18120                match message {
18121                    BurstMsg::Value(value) => {
18122                        self.received.push(value);
18123                        self.trace.lock().unwrap().delivered = self.received.len();
18124                    }
18125                    BurstMsg::Event(Event::Key(key)) if key.code == KeyCode::Char('q') => {
18126                        return Cmd::quit();
18127                    }
18128                    BurstMsg::Event(Event::Key(_)) => self.input_at.push(self.received.len()),
18129                    BurstMsg::Event(_) => {}
18130                }
18131                Cmd::none()
18132            }
18133
18134            fn view(&self, _frame: &mut Frame) {
18135                self.trace.lock().unwrap().renders.push(self.received.len());
18136            }
18137
18138            fn subscriptions(&self) -> Vec<Box<dyn Subscription<BurstMsg>>> {
18139                vec![Box::new(BurstSubscription {
18140                    ready: self.ready.clone(),
18141                })]
18142            }
18143        }
18144
18145        // The event source observes the real loop's requested timeouts. Its
18146        // initial barrier makes the whole burst pending before the first drain;
18147        // it supplies input between batches and quit only after complete delivery.
18148        struct ObservedSource {
18149            ready: Option<mpsc::Receiver<()>>,
18150            trace: Arc<Mutex<Trace>>,
18151            sent_input: bool,
18152            pending: Option<Event>,
18153        }
18154
18155        impl BackendEventSource for ObservedSource {
18156            type Error = io::Error;
18157
18158            fn size(&self) -> io::Result<(u16, u16)> {
18159                Ok((20, 4))
18160            }
18161
18162            fn set_features(&mut self, _features: BackendFeatures) -> io::Result<()> {
18163                Ok(())
18164            }
18165
18166            fn poll_event(&mut self, timeout: Duration) -> io::Result<bool> {
18167                if let Some(ready) = self.ready.take() {
18168                    ready
18169                        .recv_timeout(Duration::from_secs(2))
18170                        .map_err(io::Error::other)?;
18171                }
18172                let mut trace = self.trace.lock().unwrap();
18173                if trace.polls.len() >= 12 {
18174                    return Err(io::Error::other("subscription burst did not complete"));
18175                }
18176                let delivered = trace.delivered;
18177                trace.polls.push((delivered, timeout));
18178                drop(trace);
18179                if delivered == 64 && !self.sent_input {
18180                    self.sent_input = true;
18181                    self.pending = Some(Event::Key(KeyEvent::new(KeyCode::Char('x'))));
18182                } else if delivered == TOTAL {
18183                    self.pending = Some(Event::Key(KeyEvent::new(KeyCode::Char('q'))));
18184                }
18185                Ok(self.pending.is_some())
18186            }
18187
18188            fn read_event(&mut self) -> io::Result<Option<Event>> {
18189                Ok(self.pending.take())
18190            }
18191        }
18192
18193        let trace = Arc::new(Mutex::new(Trace::default()));
18194        let (ready_tx, ready_rx) = mpsc::channel();
18195        let model = BurstModel {
18196            received: Vec::new(),
18197            input_at: Vec::new(),
18198            ready: ready_tx,
18199            trace: Arc::clone(&trace),
18200        };
18201        let events = ObservedSource {
18202            ready: Some(ready_rx),
18203            trace: Arc::clone(&trace),
18204            sent_input: false,
18205            pending: None,
18206        };
18207        let writer = TerminalWriter::new(
18208            Vec::new(),
18209            ScreenMode::AltScreen,
18210            UiAnchor::Bottom,
18211            TerminalCapabilities::dumb(),
18212        );
18213        let config = ProgramConfig {
18214            poll_timeout: IDLE_TIMEOUT,
18215            ..ProgramConfig::default()
18216                .with_forced_size(20, 4)
18217                .with_signal_interception(false)
18218                .with_budget(FrameBudgetConfig::with_total(Duration::from_secs(5)))
18219        };
18220        let mut program = Program::with_event_source(
18221            model,
18222            events,
18223            BackendFeatures::default(),
18224            TerminalPresenter::new(writer),
18225            config,
18226        )
18227        .expect("program construction");
18228        program
18229            .run()
18230            .expect("burst completes through the real loop");
18231
18232        assert_eq!(program.model().received, (0..TOTAL).collect::<Vec<_>>());
18233        assert_eq!(program.model().input_at, [64]);
18234        let trace = trace.lock().unwrap();
18235        assert_eq!(trace.renders, [0, 64, 128, TOTAL]);
18236        assert_eq!(trace.polls.first(), Some(&(0, IDLE_TIMEOUT)));
18237        assert_eq!(trace.polls.last(), Some(&(TOTAL, IDLE_TIMEOUT)));
18238        for delivered in [64, 128] {
18239            let polls: Vec<_> = trace
18240                .polls
18241                .iter()
18242                .filter(|(count, _)| *count == delivered)
18243                .collect();
18244            assert!(!polls.is_empty(), "input must be polled between batches");
18245            assert!(
18246                polls.iter().all(|(_, timeout)| *timeout == Duration::ZERO),
18247                "queued subscription output must not incur an idle input wait: {polls:?}"
18248            );
18249        }
18250    }
18251
18252    #[test]
18253    fn headless_execute_cmd_task_spawns_and_reaps() {
18254        struct TaskModel {
18255            done: bool,
18256        }
18257
18258        #[derive(Debug)]
18259        enum TaskMsg {
18260            Done,
18261        }
18262
18263        impl From<Event> for TaskMsg {
18264            fn from(_: Event) -> Self {
18265                TaskMsg::Done
18266            }
18267        }
18268
18269        impl Model for TaskModel {
18270            type Message = TaskMsg;
18271
18272            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
18273                match msg {
18274                    TaskMsg::Done => {
18275                        self.done = true;
18276                        Cmd::none()
18277                    }
18278                }
18279            }
18280
18281            fn view(&self, _frame: &mut Frame) {}
18282        }
18283
18284        let mut program =
18285            headless_program_with_config(TaskModel { done: false }, ProgramConfig::default());
18286        program
18287            .execute_cmd(Cmd::task(|| TaskMsg::Done))
18288            .expect("task cmd");
18289
18290        let deadline = Instant::now() + Duration::from_millis(200);
18291        while !program.model().done && Instant::now() <= deadline {
18292            program
18293                .process_task_results()
18294                .expect("process task results");
18295            program.reap_finished_tasks();
18296        }
18297
18298        assert!(program.model().done, "task result did not arrive in time");
18299    }
18300
18301    #[test]
18302    fn headless_default_task_executor_is_spawned_for_structured_lane() {
18303        // Input-lag regression fix (#78): the default Structured lane must use
18304        // per-task `Spawned` execution, NOT the single-worker effect queue.
18305        // Routing every `Cmd::Task` through one serialized `effect_queue_loop`
18306        // worker added per-keystroke head-of-line latency for apps that forward
18307        // PTY output via per-pane polling tasks. Structured cancellation does
18308        // not require the effect queue, so the default backend is `Spawned`
18309        // ("spawned") here, matching v0.2.1 task concurrency.
18310        let program =
18311            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
18312        assert_eq!(program.task_executor.kind_name(), "spawned");
18313    }
18314
18315    #[test]
18316    fn headless_structured_lane_task_executor_writes_spawned_backend_evidence() {
18317        // Input-lag regression fix (#78): the default Structured lane emits the
18318        // "spawned" backend in startup evidence (was "queued"), reflecting the
18319        // restored per-task-thread execution.
18320        let evidence_path = temp_evidence_path("task_executor_spawned_backend");
18321        let sink_config = EvidenceSinkConfig::enabled_file(&evidence_path);
18322        let config = ProgramConfig::default().with_evidence_sink(sink_config);
18323        let _program = headless_program_with_config(TestModel { value: 0 }, config);
18324
18325        let backend_line = read_evidence_event(&evidence_path, "task_executor_backend");
18326        assert_eq!(backend_line["backend"], "spawned");
18327    }
18328
18329    #[test]
18330    fn headless_legacy_lane_task_executor_is_spawned() {
18331        let config = ProgramConfig::default().with_lane(RuntimeLane::Legacy);
18332        let program = headless_program_with_config(TestModel { value: 0 }, config);
18333        assert_eq!(program.task_executor.kind_name(), "spawned");
18334    }
18335
18336    #[test]
18337    fn headless_explicit_spawned_backend_overrides_structured_lane_default() {
18338        let config = ProgramConfig::default().with_effect_queue(
18339            EffectQueueConfig::default().with_backend(TaskExecutorBackend::Spawned),
18340        );
18341        let program = headless_program_with_config(TestModel { value: 0 }, config);
18342        assert_eq!(program.task_executor.kind_name(), "spawned");
18343    }
18344
18345    #[cfg(feature = "asupersync-executor")]
18346    #[test]
18347    fn headless_asupersync_task_executor_is_selected() {
18348        let config = ProgramConfig::default().with_effect_queue(
18349            EffectQueueConfig::default().with_backend(TaskExecutorBackend::Asupersync),
18350        );
18351        let program = headless_program_with_config(TestModel { value: 0 }, config);
18352        assert_eq!(program.task_executor.kind_name(), "asupersync");
18353    }
18354
18355    #[test]
18356    fn headless_persistence_commands_with_registry() {
18357        use crate::state_persistence::{MemoryStorage, StateRegistry};
18358        use std::sync::Arc;
18359
18360        let registry = Arc::new(StateRegistry::new(Box::new(MemoryStorage::new())));
18361        let config = ProgramConfig::default().with_registry(registry.clone());
18362        let mut program = headless_program_with_config(TestModel { value: 0 }, config);
18363
18364        assert!(program.has_persistence());
18365        assert!(program.state_registry().is_some());
18366
18367        program.execute_cmd(Cmd::save_state()).expect("save");
18368        program.execute_cmd(Cmd::restore_state()).expect("restore");
18369
18370        let saved = program.trigger_save().expect("trigger save");
18371        let loaded = program.trigger_load().expect("trigger load");
18372        assert!(!saved);
18373        assert_eq!(loaded, 0);
18374    }
18375
18376    #[test]
18377    fn headless_process_resize_coalescer_applies_pending_resize() {
18378        struct ResizeModel {
18379            last_size: Option<(u16, u16)>,
18380        }
18381
18382        #[derive(Debug)]
18383        enum ResizeMsg {
18384            Resize(u16, u16),
18385            Other,
18386        }
18387
18388        impl From<Event> for ResizeMsg {
18389            fn from(event: Event) -> Self {
18390                match event {
18391                    Event::Resize { width, height } => ResizeMsg::Resize(width, height),
18392                    _ => ResizeMsg::Other,
18393                }
18394            }
18395        }
18396
18397        impl Model for ResizeModel {
18398            type Message = ResizeMsg;
18399
18400            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
18401                if let ResizeMsg::Resize(w, h) = msg {
18402                    self.last_size = Some((w, h));
18403                }
18404                Cmd::none()
18405            }
18406
18407            fn view(&self, _frame: &mut Frame) {}
18408        }
18409
18410        let evidence_path = temp_evidence_path("fairness_allow");
18411        let sink_config = EvidenceSinkConfig::enabled_file(&evidence_path);
18412        let mut config = ProgramConfig::default().with_resize_behavior(ResizeBehavior::Throttled);
18413        config.resize_coalescer.steady_delay_ms = 0;
18414        config.resize_coalescer.burst_delay_ms = 0;
18415        config.resize_coalescer.hard_deadline_ms = 1_000;
18416        config.evidence_sink = sink_config.clone();
18417
18418        let mut program = headless_program_with_config(ResizeModel { last_size: None }, config);
18419        let sink = EvidenceSink::from_config(&sink_config)
18420            .expect("evidence sink config")
18421            .expect("evidence sink enabled");
18422        program.evidence_sink = Some(sink);
18423
18424        program.resize_coalescer.handle_resize(120, 40);
18425        assert!(program.resize_coalescer.has_pending());
18426
18427        program
18428            .process_resize_coalescer()
18429            .expect("process resize coalescer");
18430
18431        assert_eq!(program.width, 120);
18432        assert_eq!(program.height, 40);
18433        assert_eq!(program.model().last_size, Some((120, 40)));
18434
18435        let config_line = read_evidence_event(&evidence_path, "fairness_config");
18436        assert_eq!(config_line["event"], "fairness_config");
18437        assert!(config_line["enabled"].is_boolean());
18438        assert!(config_line["input_priority_threshold_ms"].is_number());
18439        assert!(config_line["dominance_threshold"].is_number());
18440        assert!(config_line["fairness_threshold"].is_number());
18441
18442        let decision_line = read_evidence_event(&evidence_path, "fairness_decision");
18443        assert_eq!(decision_line["event"], "fairness_decision");
18444        assert_eq!(decision_line["decision"], "allow");
18445        assert_eq!(decision_line["reason"], "none");
18446        assert!(decision_line["pending_input_latency_ms"].is_null());
18447        assert!(decision_line["jain_index"].is_number());
18448        assert!(decision_line["resize_dominance_count"].is_number());
18449        assert!(decision_line["dominance_threshold"].is_number());
18450        assert!(decision_line["fairness_threshold"].is_number());
18451        assert!(decision_line["input_priority_threshold_ms"].is_number());
18452    }
18453
18454    #[test]
18455    fn headless_process_resize_coalescer_yields_to_input() {
18456        struct ResizeModel {
18457            last_size: Option<(u16, u16)>,
18458        }
18459
18460        #[derive(Debug)]
18461        enum ResizeMsg {
18462            Resize(u16, u16),
18463            Other,
18464        }
18465
18466        impl From<Event> for ResizeMsg {
18467            fn from(event: Event) -> Self {
18468                match event {
18469                    Event::Resize { width, height } => ResizeMsg::Resize(width, height),
18470                    _ => ResizeMsg::Other,
18471                }
18472            }
18473        }
18474
18475        impl Model for ResizeModel {
18476            type Message = ResizeMsg;
18477
18478            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
18479                if let ResizeMsg::Resize(w, h) = msg {
18480                    self.last_size = Some((w, h));
18481                }
18482                Cmd::none()
18483            }
18484
18485            fn view(&self, _frame: &mut Frame) {}
18486        }
18487
18488        let evidence_path = temp_evidence_path("fairness_yield");
18489        let sink_config = EvidenceSinkConfig::enabled_file(&evidence_path);
18490        let mut config = ProgramConfig::default().with_resize_behavior(ResizeBehavior::Throttled);
18491        config.resize_coalescer.steady_delay_ms = 0;
18492        config.resize_coalescer.burst_delay_ms = 0;
18493        // Use a large hard deadline so elapsed wall-clock time between coalescer
18494        // construction and `handle_resize` never triggers an immediate apply.
18495        config.resize_coalescer.hard_deadline_ms = 10_000;
18496        config.evidence_sink = sink_config.clone();
18497
18498        let mut program = headless_program_with_config(ResizeModel { last_size: None }, config);
18499        let sink = EvidenceSink::from_config(&sink_config)
18500            .expect("evidence sink config")
18501            .expect("evidence sink enabled");
18502        program.evidence_sink = Some(sink);
18503
18504        program.fairness_guard = InputFairnessGuard::with_config(
18505            crate::input_fairness::FairnessConfig::default().with_max_latency(Duration::ZERO),
18506        );
18507        program
18508            .fairness_guard
18509            .input_arrived(Instant::now() - Duration::from_millis(1));
18510
18511        program.resize_coalescer.handle_resize(120, 40);
18512        assert!(program.resize_coalescer.has_pending());
18513
18514        program
18515            .process_resize_coalescer()
18516            .expect("process resize coalescer");
18517
18518        assert_eq!(program.width, 80);
18519        assert_eq!(program.height, 24);
18520        assert_eq!(program.model().last_size, None);
18521        assert!(program.resize_coalescer.has_pending());
18522
18523        let decision_line = read_evidence_event(&evidence_path, "fairness_decision");
18524        assert_eq!(decision_line["event"], "fairness_decision");
18525        assert_eq!(decision_line["decision"], "yield");
18526        assert_eq!(decision_line["reason"], "input_latency");
18527        assert!(decision_line["pending_input_latency_ms"].is_number());
18528        assert!(decision_line["jain_index"].is_number());
18529        assert!(decision_line["resize_dominance_count"].is_number());
18530        assert!(decision_line["dominance_threshold"].is_number());
18531        assert!(decision_line["fairness_threshold"].is_number());
18532        assert!(decision_line["input_priority_threshold_ms"].is_number());
18533    }
18534
18535    #[test]
18536    fn headless_input_event_starvation_defers_resize_coalescer_then_applies_next_cycle() {
18537        struct ResizeAndKeyModel {
18538            events: Vec<String>,
18539            last_size: Option<(u16, u16)>,
18540        }
18541
18542        #[derive(Debug)]
18543        enum Msg {
18544            Resize(u16, u16),
18545            Key(char),
18546            Other,
18547        }
18548
18549        impl From<Event> for Msg {
18550            fn from(event: Event) -> Self {
18551                match event {
18552                    Event::Resize { width, height } => Msg::Resize(width, height),
18553                    Event::Key(k) => match k.code {
18554                        KeyCode::Char(c) => Msg::Key(c),
18555                        _ => Msg::Other,
18556                    },
18557                    _ => Msg::Other,
18558                }
18559            }
18560        }
18561
18562        impl Model for ResizeAndKeyModel {
18563            type Message = Msg;
18564
18565            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
18566                match msg {
18567                    Msg::Resize(w, h) => {
18568                        self.events.push(format!("resize:{w}x{h}"));
18569                        self.last_size = Some((w, h));
18570                    }
18571                    Msg::Key(c) => {
18572                        self.events.push(format!("key:{c}"));
18573                    }
18574                    Msg::Other => {}
18575                }
18576                Cmd::none()
18577            }
18578
18579            fn view(&self, _frame: &mut Frame) {}
18580        }
18581
18582        let evidence_path = temp_evidence_path("fairness_handle_event_storm");
18583        let sink_config = EvidenceSinkConfig::enabled_file(&evidence_path);
18584        let mut config = ProgramConfig::default().with_resize_behavior(ResizeBehavior::Throttled);
18585        config.resize_coalescer.steady_delay_ms = 0;
18586        config.resize_coalescer.burst_delay_ms = 0;
18587        config.resize_coalescer.hard_deadline_ms = 10_000;
18588        config.evidence_sink = sink_config.clone();
18589
18590        let mut program = headless_program_with_config(
18591            ResizeAndKeyModel {
18592                events: Vec::new(),
18593                last_size: None,
18594            },
18595            config,
18596        );
18597        let sink = EvidenceSink::from_config(&sink_config)
18598            .expect("evidence sink config")
18599            .expect("evidence sink enabled");
18600        program.evidence_sink = Some(sink);
18601
18602        // Configure dominance threshold = 2 and disable fairness_index so we isolate
18603        // resize dominance across real handle_event() calls.
18604        program.fairness_guard =
18605            InputFairnessGuard::with_config(crate::input_fairness::FairnessConfig {
18606                input_priority_threshold: Duration::from_secs(10),
18607                dominance_threshold: 2,
18608                fairness_threshold: 0.5,
18609                enabled: true,
18610            });
18611
18612        // Key arrives, followed by 2 throttled resizes in the same burst before
18613        // process_resize_coalescer runs.
18614        program
18615            .handle_event(Event::Key(KeyEvent::new(KeyCode::Char('a'))))
18616            .expect("handle key");
18617        program
18618            .handle_event(Event::Resize {
18619                width: 100,
18620                height: 30,
18621            })
18622            .expect("handle resize 1");
18623        program
18624            .handle_event(Event::Resize {
18625                width: 120,
18626                height: 40,
18627            })
18628            .expect("handle resize 2");
18629
18630        // Key was dispatched, and resize was coalesced (not applied prematurely).
18631        assert_eq!(program.model().events, vec!["key:a"]);
18632        assert_eq!(program.model().last_size, None);
18633        assert!(program.resize_coalescer.has_pending());
18634
18635        // Cycle 1: process_resize_coalescer sees the pending input from this cycle
18636        // and yields due to resize dominance, deferring the pending resize.
18637        program
18638            .process_resize_coalescer()
18639            .expect("process resize coalescer cycle 1");
18640        assert_eq!(program.model().last_size, None);
18641        assert!(program.resize_coalescer.has_pending());
18642
18643        let decision_line = read_evidence_event(&evidence_path, "fairness_decision");
18644        assert_eq!(decision_line["decision"], "yield");
18645        assert_eq!(decision_line["reason"], "resize_dominance");
18646
18647        // Cycle 2: input turn completed and reset dominance, so the next cycle
18648        // applies the pending resize.
18649        program
18650            .process_resize_coalescer()
18651            .expect("process resize coalescer cycle 2");
18652        assert_eq!(program.model().last_size, Some((120, 40)));
18653        assert!(!program.resize_coalescer.has_pending());
18654        assert_eq!(program.model().events, vec!["key:a", "resize:120x40"]);
18655    }
18656
18657    #[test]
18658    fn headless_execute_cmd_task_with_effect_queue() {
18659        struct TaskModel {
18660            done: bool,
18661        }
18662
18663        #[derive(Debug)]
18664        enum TaskMsg {
18665            Done,
18666        }
18667
18668        impl From<Event> for TaskMsg {
18669            fn from(_: Event) -> Self {
18670                TaskMsg::Done
18671            }
18672        }
18673
18674        impl Model for TaskModel {
18675            type Message = TaskMsg;
18676
18677            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
18678                match msg {
18679                    TaskMsg::Done => {
18680                        self.done = true;
18681                        Cmd::none()
18682                    }
18683                }
18684            }
18685
18686            fn view(&self, _frame: &mut Frame) {}
18687        }
18688
18689        let effect_queue = EffectQueueConfig {
18690            enabled: true,
18691            backend: TaskExecutorBackend::EffectQueue,
18692            scheduler: SchedulerConfig {
18693                max_queue_size: 0,
18694                ..Default::default()
18695            },
18696            explicit_backend: true,
18697            ..Default::default()
18698        };
18699        let config = ProgramConfig::default().with_effect_queue(effect_queue);
18700        let mut program = headless_program_with_config(TaskModel { done: false }, config);
18701
18702        program
18703            .execute_cmd(Cmd::task(|| TaskMsg::Done))
18704            .expect("task cmd");
18705
18706        let deadline = Instant::now() + Duration::from_millis(200);
18707        while !program.model().done && Instant::now() <= deadline {
18708            program
18709                .process_task_results()
18710                .expect("process task results");
18711        }
18712
18713        assert!(
18714            program.model().done,
18715            "effect queue task result did not arrive in time"
18716        );
18717        assert_eq!(program.task_executor.kind_name(), "queued");
18718    }
18719
18720    #[test]
18721    fn headless_execute_cmd_task_with_spawned_backend_writes_completion_evidence() {
18722        struct TaskModel {
18723            done: bool,
18724        }
18725
18726        #[derive(Debug)]
18727        enum TaskMsg {
18728            Done,
18729        }
18730
18731        impl From<Event> for TaskMsg {
18732            fn from(_: Event) -> Self {
18733                TaskMsg::Done
18734            }
18735        }
18736
18737        impl Model for TaskModel {
18738            type Message = TaskMsg;
18739
18740            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
18741                match msg {
18742                    TaskMsg::Done => {
18743                        self.done = true;
18744                        Cmd::none()
18745                    }
18746                }
18747            }
18748
18749            fn view(&self, _frame: &mut Frame) {}
18750        }
18751
18752        let evidence_path = temp_evidence_path("task_executor_spawned_complete");
18753        let sink_config = EvidenceSinkConfig::enabled_file(&evidence_path);
18754        let config = ProgramConfig::default()
18755            .with_lane(RuntimeLane::Legacy)
18756            .with_evidence_sink(sink_config);
18757        let mut program = headless_program_with_config(TaskModel { done: false }, config);
18758
18759        program
18760            .execute_cmd(Cmd::task(|| TaskMsg::Done))
18761            .expect("task cmd");
18762
18763        let deadline = Instant::now() + Duration::from_millis(200);
18764        while !program.model().done && Instant::now() <= deadline {
18765            program
18766                .process_task_results()
18767                .expect("process task results");
18768            program.reap_finished_tasks();
18769        }
18770
18771        assert!(
18772            program.model().done,
18773            "spawned task result did not arrive in time"
18774        );
18775
18776        let completion_line = read_evidence_event(&evidence_path, "task_executor_complete");
18777        assert_eq!(completion_line["backend"], "spawned");
18778        assert!(completion_line["duration_us"].is_number());
18779    }
18780
18781    #[test]
18782    fn headless_effect_queue_task_panic_writes_panic_evidence_and_continues() {
18783        struct TaskModel {
18784            done: bool,
18785        }
18786
18787        #[derive(Debug)]
18788        enum TaskMsg {
18789            Done,
18790        }
18791
18792        impl From<Event> for TaskMsg {
18793            fn from(_: Event) -> Self {
18794                TaskMsg::Done
18795            }
18796        }
18797
18798        impl Model for TaskModel {
18799            type Message = TaskMsg;
18800
18801            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
18802                match msg {
18803                    TaskMsg::Done => {
18804                        self.done = true;
18805                        Cmd::none()
18806                    }
18807                }
18808            }
18809
18810            fn view(&self, _frame: &mut Frame) {}
18811        }
18812
18813        let evidence_path = temp_evidence_path("task_executor_queued_panic");
18814        let sink_config = EvidenceSinkConfig::enabled_file(&evidence_path);
18815        let config = ProgramConfig::default()
18816            .with_evidence_sink(sink_config)
18817            .with_effect_queue(
18818                EffectQueueConfig::default().with_backend(TaskExecutorBackend::EffectQueue),
18819            );
18820        let mut program = headless_program_with_config(TaskModel { done: false }, config);
18821
18822        program
18823            .execute_cmd(Cmd::task(|| -> TaskMsg { panic!("queued panic evidence") }))
18824            .expect("panic task cmd");
18825        program
18826            .execute_cmd(Cmd::task(|| TaskMsg::Done))
18827            .expect("follow-up task cmd");
18828
18829        let deadline = Instant::now() + Duration::from_millis(500);
18830        while !program.model().done && Instant::now() <= deadline {
18831            program
18832                .process_task_results()
18833                .expect("process task results");
18834        }
18835
18836        assert!(
18837            program.model().done,
18838            "effect queue should continue after a panicking task"
18839        );
18840
18841        let panic_line = read_evidence_event(&evidence_path, "task_executor_panic");
18842        assert_eq!(panic_line["backend"], "queued");
18843        assert_eq!(panic_line["panic_msg"], "queued panic evidence");
18844    }
18845
18846    #[cfg(feature = "asupersync-executor")]
18847    #[test]
18848    fn headless_execute_cmd_task_with_asupersync_backend() {
18849        struct TaskModel {
18850            done: bool,
18851        }
18852
18853        #[derive(Debug)]
18854        enum TaskMsg {
18855            Done,
18856        }
18857
18858        impl From<Event> for TaskMsg {
18859            fn from(_: Event) -> Self {
18860                TaskMsg::Done
18861            }
18862        }
18863
18864        impl Model for TaskModel {
18865            type Message = TaskMsg;
18866
18867            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
18868                match msg {
18869                    TaskMsg::Done => {
18870                        self.done = true;
18871                        Cmd::none()
18872                    }
18873                }
18874            }
18875
18876            fn view(&self, _frame: &mut Frame) {}
18877        }
18878
18879        let config = ProgramConfig::default().with_effect_queue(
18880            EffectQueueConfig::default().with_backend(TaskExecutorBackend::Asupersync),
18881        );
18882        let mut program = headless_program_with_config(TaskModel { done: false }, config);
18883
18884        program
18885            .execute_cmd(Cmd::task(|| TaskMsg::Done))
18886            .expect("task cmd");
18887
18888        let deadline = Instant::now() + Duration::from_millis(200);
18889        while !program.model().done && Instant::now() <= deadline {
18890            program
18891                .process_task_results()
18892                .expect("process task results");
18893            program.reap_finished_tasks();
18894        }
18895
18896        assert!(
18897            program.model().done,
18898            "asupersync task result did not arrive in time"
18899        );
18900        assert_eq!(program.task_executor.kind_name(), "asupersync");
18901    }
18902
18903    #[cfg(feature = "asupersync-executor")]
18904    #[test]
18905    fn headless_asupersync_task_executor_writes_backend_and_completion_evidence() {
18906        struct TaskModel {
18907            done: bool,
18908        }
18909
18910        #[derive(Debug)]
18911        enum TaskMsg {
18912            Done,
18913        }
18914
18915        impl From<Event> for TaskMsg {
18916            fn from(_: Event) -> Self {
18917                TaskMsg::Done
18918            }
18919        }
18920
18921        impl Model for TaskModel {
18922            type Message = TaskMsg;
18923
18924            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
18925                match msg {
18926                    TaskMsg::Done => {
18927                        self.done = true;
18928                        Cmd::none()
18929                    }
18930                }
18931            }
18932
18933            fn view(&self, _frame: &mut Frame) {}
18934        }
18935
18936        let evidence_path = temp_evidence_path("task_executor_asupersync_complete");
18937        let sink_config = EvidenceSinkConfig::enabled_file(&evidence_path);
18938        let config = ProgramConfig::default()
18939            .with_evidence_sink(sink_config)
18940            .with_effect_queue(
18941                EffectQueueConfig::default().with_backend(TaskExecutorBackend::Asupersync),
18942            );
18943        let mut program = headless_program_with_config(TaskModel { done: false }, config);
18944
18945        let backend_line = read_evidence_event(&evidence_path, "task_executor_backend");
18946        assert_eq!(backend_line["backend"], "asupersync");
18947
18948        program
18949            .execute_cmd(Cmd::task(|| TaskMsg::Done))
18950            .expect("task cmd");
18951
18952        let deadline = Instant::now() + Duration::from_millis(200);
18953        while !program.model().done && Instant::now() <= deadline {
18954            program
18955                .process_task_results()
18956                .expect("process task results");
18957            program.reap_finished_tasks();
18958        }
18959
18960        assert!(
18961            program.model().done,
18962            "asupersync task result did not arrive in time"
18963        );
18964
18965        let completion_line = read_evidence_event(&evidence_path, "task_executor_complete");
18966        assert_eq!(completion_line["backend"], "asupersync");
18967        assert!(completion_line["duration_us"].is_number());
18968    }
18969
18970    // =========================================================================
18971    // Asupersync executor: semantic parity, failure, stress, shutdown, and
18972    // backpressure coverage (bd-392ka).
18973    // =========================================================================
18974
18975    /// Run `count` tasks (each emitting its index) through `backend` headlessly
18976    /// and return the sorted multiset of delivered message payloads.
18977    #[cfg(feature = "asupersync-executor")]
18978    fn collect_task_batch(backend: TaskExecutorBackend, count: u32) -> Vec<u32> {
18979        struct CollectModel {
18980            got: Vec<u32>,
18981        }
18982        #[derive(Debug)]
18983        enum CollectMsg {
18984            Got(u32),
18985        }
18986        impl From<Event> for CollectMsg {
18987            fn from(_: Event) -> Self {
18988                CollectMsg::Got(u32::MAX)
18989            }
18990        }
18991        impl Model for CollectModel {
18992            type Message = CollectMsg;
18993            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
18994                match msg {
18995                    CollectMsg::Got(value) => self.got.push(value),
18996                }
18997                Cmd::none()
18998            }
18999            fn view(&self, _frame: &mut Frame) {}
19000        }
19001
19002        let config = ProgramConfig::default()
19003            .with_effect_queue(EffectQueueConfig::default().with_backend(backend));
19004        let mut program = headless_program_with_config(CollectModel { got: Vec::new() }, config);
19005        for index in 0..count {
19006            program
19007                .execute_cmd(Cmd::task(move || CollectMsg::Got(index)))
19008                .expect("task cmd");
19009        }
19010        let deadline = Instant::now() + Duration::from_secs(5);
19011        while program.model().got.len() < count as usize && Instant::now() <= deadline {
19012            program
19013                .process_task_results()
19014                .expect("process task results");
19015            program.reap_finished_tasks();
19016        }
19017        let mut got = program.model().got.clone();
19018        got.sort_unstable();
19019        got
19020    }
19021
19022    #[cfg(feature = "asupersync-executor")]
19023    #[test]
19024    fn asupersync_semantic_parity_with_spawned_backend() {
19025        // The same task batch must deliver an identical message multiset whether
19026        // run through the legacy Spawned backend or the Asupersync backend. This
19027        // is the evidence-backed semantic-parity check (a shadow-run in miniature).
19028        let expected: Vec<u32> = (0..16).collect();
19029        let spawned = collect_task_batch(TaskExecutorBackend::Spawned, 16);
19030        let asupersync = collect_task_batch(TaskExecutorBackend::Asupersync, 16);
19031        assert_eq!(
19032            spawned, expected,
19033            "spawned backend lost or reordered results"
19034        );
19035        assert_eq!(
19036            asupersync, expected,
19037            "asupersync backend diverged from the expected results"
19038        );
19039        assert_eq!(
19040            asupersync, spawned,
19041            "asupersync diverged from spawned (parity)"
19042        );
19043    }
19044
19045    #[cfg(feature = "asupersync-executor")]
19046    #[test]
19047    fn asupersync_stress_delivers_every_task() {
19048        // Under a large burst, every task result must arrive exactly once.
19049        let count: u32 = 200;
19050        let got = collect_task_batch(TaskExecutorBackend::Asupersync, count);
19051        assert_eq!(
19052            got.len(),
19053            count as usize,
19054            "asupersync dropped tasks under load"
19055        );
19056        assert_eq!(got, (0..count).collect::<Vec<_>>());
19057    }
19058
19059    #[cfg(feature = "asupersync-executor")]
19060    #[test]
19061    fn asupersync_task_panic_is_isolated() {
19062        struct PanicModel {
19063            survivor_seen: bool,
19064        }
19065        #[derive(Debug)]
19066        enum PanicMsg {
19067            Survivor,
19068        }
19069        impl From<Event> for PanicMsg {
19070            fn from(_: Event) -> Self {
19071                PanicMsg::Survivor
19072            }
19073        }
19074        impl Model for PanicModel {
19075            type Message = PanicMsg;
19076            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
19077                match msg {
19078                    PanicMsg::Survivor => self.survivor_seen = true,
19079                }
19080                Cmd::none()
19081            }
19082            fn view(&self, _frame: &mut Frame) {}
19083        }
19084
19085        let evidence_path = temp_evidence_path("asupersync_panic");
19086        let sink_config = EvidenceSinkConfig::enabled_file(&evidence_path);
19087        let config = ProgramConfig::default()
19088            .with_evidence_sink(sink_config)
19089            .with_effect_queue(
19090                EffectQueueConfig::default().with_backend(TaskExecutorBackend::Asupersync),
19091            );
19092        let mut program = headless_program_with_config(
19093            PanicModel {
19094                survivor_seen: false,
19095            },
19096            config,
19097        );
19098
19099        // A panicking task must neither crash the executor nor deliver a message...
19100        program
19101            .execute_cmd(Cmd::task(|| -> PanicMsg { panic!("asupersync boom") }))
19102            .expect("panic task cmd");
19103        // ...and a task submitted afterwards must still complete normally.
19104        program
19105            .execute_cmd(Cmd::task(|| PanicMsg::Survivor))
19106            .expect("survivor task cmd");
19107
19108        let deadline = Instant::now() + Duration::from_secs(5);
19109        // The survivor can finish before the other worker records its panic.
19110        // Completed handles also guarantee that their evidence writes finished.
19111        while (!program.model().survivor_seen || program.task_executor.in_flight() > 0)
19112            && Instant::now() <= deadline
19113        {
19114            program
19115                .process_task_results()
19116                .expect("process task results");
19117            program.reap_finished_tasks();
19118        }
19119        assert!(
19120            program.model().survivor_seen,
19121            "executor did not survive a panicking task"
19122        );
19123        assert_eq!(
19124            program.task_executor.in_flight(),
19125            0,
19126            "executor tasks did not finish before evidence was read"
19127        );
19128        let panic_line = read_evidence_event(&evidence_path, "task_executor_panic");
19129        assert_eq!(panic_line["backend"], "asupersync");
19130        assert_eq!(panic_line["panic_msg"], "asupersync boom");
19131    }
19132
19133    #[cfg(feature = "asupersync-executor")]
19134    #[test]
19135    fn asupersync_rejects_tasks_after_shutdown() {
19136        struct ShutdownModel {
19137            seen: bool,
19138        }
19139        #[derive(Debug)]
19140        enum ShutdownMsg {
19141            Seen,
19142        }
19143        impl From<Event> for ShutdownMsg {
19144            fn from(_: Event) -> Self {
19145                ShutdownMsg::Seen
19146            }
19147        }
19148        impl Model for ShutdownModel {
19149            type Message = ShutdownMsg;
19150            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
19151                match msg {
19152                    ShutdownMsg::Seen => self.seen = true,
19153                }
19154                Cmd::none()
19155            }
19156            fn view(&self, _frame: &mut Frame) {}
19157        }
19158
19159        let config = ProgramConfig::default().with_effect_queue(
19160            EffectQueueConfig::default().with_backend(TaskExecutorBackend::Asupersync),
19161        );
19162        let mut program = headless_program_with_config(ShutdownModel { seen: false }, config);
19163
19164        // After shutdown, new submissions are rejected (structured ownership):
19165        // the task never runs, so no message is delivered.
19166        program.task_executor.shutdown();
19167        program
19168            .execute_cmd(Cmd::task(|| ShutdownMsg::Seen))
19169            .expect("post-shutdown task cmd");
19170
19171        let deadline = Instant::now() + Duration::from_millis(200);
19172        while Instant::now() <= deadline {
19173            program
19174                .process_task_results()
19175                .expect("process task results");
19176            program.reap_finished_tasks();
19177        }
19178        assert!(
19179            !program.model().seen,
19180            "a task submitted after shutdown was executed"
19181        );
19182    }
19183
19184    #[test]
19185    fn spawned_executor_enforces_max_queue_depth_and_counts_drops() {
19186        let (result_tx, _result_rx) = mpsc::channel::<u32>();
19187        let (gate_tx, gate_rx) = mpsc::channel::<()>();
19188        let mut executor = SpawnTaskExecutor::new(result_tx, None, 1);
19189
19190        // First task occupies the single in-flight slot until gated.
19191        executor.submit(Box::new(move || {
19192            let _ = gate_rx.recv();
19193            1
19194        }));
19195        assert_eq!(executor.handles.len(), 1);
19196
19197        // Second submit exceeds the bound: shed + counted, no thread spawned.
19198        executor.submit(Box::new(|| 2));
19199        assert_eq!(executor.dropped, 1, "backpressure drop not counted");
19200        assert_eq!(executor.handles.len(), 1, "task spawned past the bound");
19201
19202        // Release the gate; post-shutdown submits are also counted drops.
19203        gate_tx.send(()).expect("release gate");
19204        executor.shutdown();
19205        executor.submit(Box::new(|| 3));
19206        assert_eq!(executor.dropped, 2, "post-shutdown drop not counted");
19207    }
19208
19209    #[cfg(feature = "asupersync-executor")]
19210    #[test]
19211    fn asupersync_backpressure_sheds_excess_in_flight_tasks() {
19212        struct SlowModel {
19213            done: u32,
19214        }
19215        #[derive(Debug)]
19216        enum SlowMsg {
19217            Done,
19218        }
19219        impl From<Event> for SlowMsg {
19220            fn from(_: Event) -> Self {
19221                SlowMsg::Done
19222            }
19223        }
19224        impl Model for SlowModel {
19225            type Message = SlowMsg;
19226            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
19227                match msg {
19228                    SlowMsg::Done => self.done += 1,
19229                }
19230                Cmd::none()
19231            }
19232            fn view(&self, _frame: &mut Frame) {}
19233        }
19234
19235        let evidence_path = temp_evidence_path("asupersync_backpressure");
19236        let sink_config = EvidenceSinkConfig::enabled_file(&evidence_path);
19237        let config = ProgramConfig::default()
19238            .with_evidence_sink(sink_config)
19239            .with_effect_queue(
19240                EffectQueueConfig::default()
19241                    .with_backend(TaskExecutorBackend::Asupersync)
19242                    .with_max_queue_depth(2),
19243            );
19244        let mut program = headless_program_with_config(SlowModel { done: 0 }, config);
19245
19246        // Submit more slow (still in-flight) tasks than the depth cap allows: the
19247        // first two occupy the in-flight slots, the rest are shed by backpressure.
19248        for _ in 0..6 {
19249            program
19250                .execute_cmd(Cmd::task(|| {
19251                    std::thread::sleep(Duration::from_millis(120));
19252                    SlowMsg::Done
19253                }))
19254                .expect("slow task cmd");
19255        }
19256
19257        // Backpressure must have fired with a recorded drop.
19258        let backpressure_line = read_evidence_event(&evidence_path, "task_executor_backpressure");
19259        assert_eq!(backpressure_line["backend"], "asupersync");
19260        assert_eq!(backpressure_line["action"], "drop");
19261
19262        // Drain the accepted tasks so teardown is prompt; no more than the depth
19263        // cap of tasks may complete.
19264        let deadline = Instant::now() + Duration::from_secs(5);
19265        while program.model().done < 2 && Instant::now() <= deadline {
19266            program
19267                .process_task_results()
19268                .expect("process task results");
19269            program.reap_finished_tasks();
19270        }
19271        assert!(
19272            program.model().done <= 2,
19273            "more tasks completed than the in-flight depth cap permits"
19274        );
19275    }
19276
19277    // =========================================================================
19278    // BatchController Tests (bd-4kq0.8.1)
19279    // =========================================================================
19280
19281    #[test]
19282    fn unit_tau_monotone() {
19283        // ฯ„ should decrease (or stay constant) as service time decreases,
19284        // since ฯ„ = E[S] ร— headroom.
19285        let mut bc = BatchController::new();
19286
19287        // High service time โ†’ high ฯ„
19288        bc.observe_service(Duration::from_millis(20));
19289        bc.observe_service(Duration::from_millis(20));
19290        bc.observe_service(Duration::from_millis(20));
19291        let tau_high = bc.tau_s();
19292
19293        // Low service time โ†’ lower ฯ„
19294        for _ in 0..20 {
19295            bc.observe_service(Duration::from_millis(1));
19296        }
19297        let tau_low = bc.tau_s();
19298
19299        assert!(
19300            tau_low <= tau_high,
19301            "ฯ„ should decrease with lower service time: tau_low={tau_low:.6}, tau_high={tau_high:.6}"
19302        );
19303    }
19304
19305    #[test]
19306    fn unit_tau_monotone_lambda() {
19307        // As arrival rate ฮป decreases (longer inter-arrival times),
19308        // ฯ„ should not increase (it's based on service time, not ฮป).
19309        // But ฯ should decrease.
19310        let mut bc = BatchController::new();
19311        let base = Instant::now();
19312
19313        // Fast arrivals (ฮป high)
19314        for i in 0..10 {
19315            bc.observe_arrival(base + Duration::from_millis(i * 10));
19316        }
19317        let rho_fast = bc.rho_est();
19318
19319        // Slow arrivals (ฮป low)
19320        for i in 10..20 {
19321            bc.observe_arrival(base + Duration::from_millis(100 + i * 100));
19322        }
19323        let rho_slow = bc.rho_est();
19324
19325        assert!(
19326            rho_slow < rho_fast,
19327            "ฯ should decrease with slower arrivals: rho_slow={rho_slow:.4}, rho_fast={rho_fast:.4}"
19328        );
19329    }
19330
19331    #[test]
19332    fn unit_stability() {
19333        // With reasonable service times, the controller should keep ฯ < 1.
19334        let mut bc = BatchController::new();
19335        let base = Instant::now();
19336
19337        // Moderate arrival rate: 30 events/sec
19338        for i in 0..30 {
19339            bc.observe_arrival(base + Duration::from_millis(i * 33));
19340            bc.observe_service(Duration::from_millis(5)); // 5ms render
19341        }
19342
19343        assert!(
19344            bc.is_stable(),
19345            "should be stable at 30 events/sec with 5ms service: ฯ={:.4}",
19346            bc.rho_est()
19347        );
19348        assert!(
19349            bc.rho_est() < 1.0,
19350            "utilization should be < 1: ฯ={:.4}",
19351            bc.rho_est()
19352        );
19353
19354        // ฯ„ must be > E[S] (stability requirement)
19355        assert!(
19356            bc.tau_s() > bc.service_est_s(),
19357            "ฯ„ ({:.6}) must exceed E[S] ({:.6}) for stability",
19358            bc.tau_s(),
19359            bc.service_est_s()
19360        );
19361    }
19362
19363    #[test]
19364    fn unit_stability_high_load() {
19365        // Even under high load, ฯ„ keeps the system stable.
19366        let mut bc = BatchController::new();
19367        let base = Instant::now();
19368
19369        // 100 events/sec with 8ms render
19370        for i in 0..50 {
19371            bc.observe_arrival(base + Duration::from_millis(i * 10));
19372            bc.observe_service(Duration::from_millis(8));
19373        }
19374
19375        // ฯ„ ร— ฯ_eff = E[S]/ฯ„ should be < 1
19376        let tau = bc.tau_s();
19377        let rho_eff = bc.service_est_s() / tau;
19378        assert!(
19379            rho_eff < 1.0,
19380            "effective utilization should be < 1: ฯ_eff={rho_eff:.4}, ฯ„={tau:.6}, E[S]={:.6}",
19381            bc.service_est_s()
19382        );
19383    }
19384
19385    #[test]
19386    fn batch_controller_defaults() {
19387        let bc = BatchController::new();
19388        assert!(bc.tau_s() >= bc.tau_min_s);
19389        assert!(bc.tau_s() <= bc.tau_max_s);
19390        assert_eq!(bc.observations(), 0);
19391        assert!(bc.is_stable());
19392    }
19393
19394    #[test]
19395    fn batch_controller_tau_clamped() {
19396        let mut bc = BatchController::new();
19397
19398        // Very fast service โ†’ ฯ„ clamped to tau_min
19399        for _ in 0..20 {
19400            bc.observe_service(Duration::from_micros(10));
19401        }
19402        assert!(
19403            bc.tau_s() >= bc.tau_min_s,
19404            "ฯ„ should be >= tau_min: ฯ„={:.6}, min={:.6}",
19405            bc.tau_s(),
19406            bc.tau_min_s
19407        );
19408
19409        // Very slow service โ†’ ฯ„ clamped to tau_max
19410        for _ in 0..20 {
19411            bc.observe_service(Duration::from_millis(100));
19412        }
19413        assert!(
19414            bc.tau_s() <= bc.tau_max_s,
19415            "ฯ„ should be <= tau_max: ฯ„={:.6}, max={:.6}",
19416            bc.tau_s(),
19417            bc.tau_max_s
19418        );
19419    }
19420
19421    #[test]
19422    fn batch_controller_duration_conversion() {
19423        let bc = BatchController::new();
19424        let tau = bc.tau();
19425        let tau_s = bc.tau_s();
19426        // Duration should match f64 representation
19427        let diff = (tau.as_secs_f64() - tau_s).abs();
19428        assert!(diff < 1e-9, "Duration conversion mismatch: {diff}");
19429    }
19430
19431    #[test]
19432    fn batch_controller_lambda_estimation() {
19433        let mut bc = BatchController::new();
19434        let base = Instant::now();
19435
19436        // 50 events/sec (20ms apart)
19437        for i in 0..20 {
19438            bc.observe_arrival(base + Duration::from_millis(i * 20));
19439        }
19440
19441        // ฮป should converge near 50
19442        let lambda = bc.lambda_est();
19443        assert!(
19444            lambda > 20.0 && lambda < 100.0,
19445            "ฮป should be near 50: got {lambda:.1}"
19446        );
19447    }
19448
19449    // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
19450    // Persistence Config Tests
19451    // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
19452
19453    #[test]
19454    fn cmd_save_state() {
19455        let cmd: Cmd<TestMsg> = Cmd::save_state();
19456        assert!(matches!(cmd, Cmd::SaveState));
19457    }
19458
19459    #[test]
19460    fn cmd_restore_state() {
19461        let cmd: Cmd<TestMsg> = Cmd::restore_state();
19462        assert!(matches!(cmd, Cmd::RestoreState));
19463    }
19464
19465    #[test]
19466    fn persistence_config_default() {
19467        let config = PersistenceConfig::default();
19468        assert!(config.registry.is_none());
19469        assert!(config.checkpoint_interval.is_none());
19470        assert!(config.auto_load);
19471        assert!(config.auto_save);
19472    }
19473
19474    #[test]
19475    fn persistence_config_disabled() {
19476        let config = PersistenceConfig::disabled();
19477        assert!(config.registry.is_none());
19478    }
19479
19480    #[test]
19481    fn persistence_config_with_registry() {
19482        use crate::state_persistence::{MemoryStorage, StateRegistry};
19483        use std::sync::Arc;
19484
19485        let registry = Arc::new(StateRegistry::new(Box::new(MemoryStorage::new())));
19486        let config = PersistenceConfig::with_registry(registry.clone());
19487
19488        assert!(config.registry.is_some());
19489        assert!(config.auto_load);
19490        assert!(config.auto_save);
19491    }
19492
19493    #[test]
19494    fn persistence_config_checkpoint_interval() {
19495        use crate::state_persistence::{MemoryStorage, StateRegistry};
19496        use std::sync::Arc;
19497
19498        let registry = Arc::new(StateRegistry::new(Box::new(MemoryStorage::new())));
19499        let config = PersistenceConfig::with_registry(registry)
19500            .checkpoint_every(Duration::from_secs(30))
19501            .auto_load(false)
19502            .auto_save(true);
19503
19504        assert!(config.checkpoint_interval.is_some());
19505        assert_eq!(config.checkpoint_interval.unwrap(), Duration::from_secs(30));
19506        assert!(!config.auto_load);
19507        assert!(config.auto_save);
19508    }
19509
19510    #[test]
19511    fn program_config_with_persistence() {
19512        use crate::state_persistence::{MemoryStorage, StateRegistry};
19513        use std::sync::Arc;
19514
19515        let registry = Arc::new(StateRegistry::new(Box::new(MemoryStorage::new())));
19516        let config = ProgramConfig::default().with_registry(registry);
19517
19518        assert!(config.persistence.registry.is_some());
19519    }
19520
19521    // =========================================================================
19522    // TaskSpec tests (bd-2yjus)
19523    // =========================================================================
19524
19525    #[test]
19526    fn task_spec_default() {
19527        let spec = TaskSpec::default();
19528        assert_eq!(spec.weight, DEFAULT_TASK_WEIGHT);
19529        assert_eq!(spec.estimate_ms, DEFAULT_TASK_ESTIMATE_MS);
19530        assert!(spec.name.is_none());
19531    }
19532
19533    #[test]
19534    fn task_spec_new() {
19535        let spec = TaskSpec::new(5.0, 20.0);
19536        assert_eq!(spec.weight, 5.0);
19537        assert_eq!(spec.estimate_ms, 20.0);
19538        assert!(spec.name.is_none());
19539    }
19540
19541    #[test]
19542    fn task_spec_with_name() {
19543        let spec = TaskSpec::default().with_name("fetch_data");
19544        assert_eq!(spec.name.as_deref(), Some("fetch_data"));
19545    }
19546
19547    #[test]
19548    fn task_spec_debug() {
19549        let spec = TaskSpec::new(2.0, 15.0).with_name("test");
19550        let debug = format!("{spec:?}");
19551        assert!(debug.contains("2.0"));
19552        assert!(debug.contains("15.0"));
19553        assert!(debug.contains("test"));
19554    }
19555
19556    // =========================================================================
19557    // Cmd::count() tests (bd-2yjus)
19558    // =========================================================================
19559
19560    #[test]
19561    fn cmd_count_none() {
19562        let cmd: Cmd<TestMsg> = Cmd::none();
19563        assert_eq!(cmd.count(), 0);
19564    }
19565
19566    #[test]
19567    fn cmd_count_atomic() {
19568        assert_eq!(Cmd::<TestMsg>::quit().count(), 1);
19569        assert_eq!(Cmd::<TestMsg>::msg(TestMsg::Increment).count(), 1);
19570        assert_eq!(Cmd::<TestMsg>::tick(Duration::from_millis(100)).count(), 1);
19571        assert_eq!(Cmd::<TestMsg>::log("hello").count(), 1);
19572        assert_eq!(Cmd::<TestMsg>::save_state().count(), 1);
19573        assert_eq!(Cmd::<TestMsg>::restore_state().count(), 1);
19574        assert_eq!(Cmd::<TestMsg>::set_mouse_capture(true).count(), 1);
19575    }
19576
19577    #[test]
19578    fn cmd_count_batch() {
19579        let cmd: Cmd<TestMsg> =
19580            Cmd::Batch(vec![Cmd::quit(), Cmd::msg(TestMsg::Increment), Cmd::none()]);
19581        assert_eq!(cmd.count(), 2); // quit + msg, none counts 0
19582    }
19583
19584    #[test]
19585    fn cmd_count_nested() {
19586        let cmd: Cmd<TestMsg> = Cmd::Batch(vec![
19587            Cmd::msg(TestMsg::Increment),
19588            Cmd::Sequence(vec![Cmd::quit(), Cmd::msg(TestMsg::Increment)]),
19589        ]);
19590        assert_eq!(cmd.count(), 3);
19591    }
19592
19593    // =========================================================================
19594    // Cmd::type_name() tests (bd-2yjus)
19595    // =========================================================================
19596
19597    #[test]
19598    fn cmd_type_name_all_variants() {
19599        assert_eq!(Cmd::<TestMsg>::none().type_name(), "None");
19600        assert_eq!(Cmd::<TestMsg>::quit().type_name(), "Quit");
19601        assert_eq!(
19602            Cmd::<TestMsg>::Batch(vec![Cmd::none()]).type_name(),
19603            "Batch"
19604        );
19605        assert_eq!(
19606            Cmd::<TestMsg>::Sequence(vec![Cmd::none()]).type_name(),
19607            "Sequence"
19608        );
19609        assert_eq!(Cmd::<TestMsg>::msg(TestMsg::Increment).type_name(), "Msg");
19610        assert_eq!(
19611            Cmd::<TestMsg>::tick(Duration::from_millis(1)).type_name(),
19612            "Tick"
19613        );
19614        assert_eq!(Cmd::<TestMsg>::log("x").type_name(), "Log");
19615        assert_eq!(
19616            Cmd::<TestMsg>::task(|| TestMsg::Increment).type_name(),
19617            "Task"
19618        );
19619        assert_eq!(Cmd::<TestMsg>::save_state().type_name(), "SaveState");
19620        assert_eq!(Cmd::<TestMsg>::restore_state().type_name(), "RestoreState");
19621        assert_eq!(
19622            Cmd::<TestMsg>::set_mouse_capture(true).type_name(),
19623            "SetMouseCapture"
19624        );
19625    }
19626
19627    // =========================================================================
19628    // Cmd::batch() / Cmd::sequence() edge-case tests (bd-2yjus)
19629    // =========================================================================
19630
19631    #[test]
19632    fn cmd_batch_empty_returns_none() {
19633        let cmd: Cmd<TestMsg> = Cmd::batch(vec![]);
19634        assert!(matches!(cmd, Cmd::None));
19635    }
19636
19637    #[test]
19638    fn cmd_batch_single_unwraps() {
19639        let cmd: Cmd<TestMsg> = Cmd::batch(vec![Cmd::quit()]);
19640        assert!(matches!(cmd, Cmd::Quit));
19641    }
19642
19643    #[test]
19644    fn cmd_batch_multiple_stays_batch() {
19645        let cmd: Cmd<TestMsg> = Cmd::batch(vec![Cmd::quit(), Cmd::msg(TestMsg::Increment)]);
19646        assert!(matches!(cmd, Cmd::Batch(_)));
19647    }
19648
19649    #[test]
19650    fn cmd_sequence_empty_returns_none() {
19651        let cmd: Cmd<TestMsg> = Cmd::sequence(vec![]);
19652        assert!(matches!(cmd, Cmd::None));
19653    }
19654
19655    #[test]
19656    fn cmd_sequence_single_unwraps_to_inner() {
19657        let cmd: Cmd<TestMsg> = Cmd::sequence(vec![Cmd::quit()]);
19658        assert!(matches!(cmd, Cmd::Quit));
19659    }
19660
19661    #[test]
19662    fn cmd_sequence_multiple_stays_sequence() {
19663        let cmd: Cmd<TestMsg> = Cmd::sequence(vec![Cmd::quit(), Cmd::msg(TestMsg::Increment)]);
19664        assert!(matches!(cmd, Cmd::Sequence(_)));
19665    }
19666
19667    // =========================================================================
19668    // Cmd task constructor variants (bd-2yjus)
19669    // =========================================================================
19670
19671    #[test]
19672    fn cmd_task_with_spec() {
19673        let spec = TaskSpec::new(3.0, 25.0).with_name("my_task");
19674        let cmd: Cmd<TestMsg> = Cmd::task_with_spec(spec, || TestMsg::Increment);
19675        match cmd {
19676            Cmd::Task(s, _) => {
19677                assert_eq!(s.weight, 3.0);
19678                assert_eq!(s.estimate_ms, 25.0);
19679                assert_eq!(s.name.as_deref(), Some("my_task"));
19680            }
19681            _ => panic!("expected Task variant"),
19682        }
19683    }
19684
19685    #[test]
19686    fn cmd_task_weighted() {
19687        let cmd: Cmd<TestMsg> = Cmd::task_weighted(2.0, 50.0, || TestMsg::Increment);
19688        match cmd {
19689            Cmd::Task(s, _) => {
19690                assert_eq!(s.weight, 2.0);
19691                assert_eq!(s.estimate_ms, 50.0);
19692                assert!(s.name.is_none());
19693            }
19694            _ => panic!("expected Task variant"),
19695        }
19696    }
19697
19698    #[test]
19699    fn cmd_task_named() {
19700        let cmd: Cmd<TestMsg> = Cmd::task_named("background_fetch", || TestMsg::Increment);
19701        match cmd {
19702            Cmd::Task(s, _) => {
19703                assert_eq!(s.weight, DEFAULT_TASK_WEIGHT);
19704                assert_eq!(s.estimate_ms, DEFAULT_TASK_ESTIMATE_MS);
19705                assert_eq!(s.name.as_deref(), Some("background_fetch"));
19706            }
19707            _ => panic!("expected Task variant"),
19708        }
19709    }
19710
19711    // =========================================================================
19712    // Cmd Debug formatting (bd-2yjus)
19713    // =========================================================================
19714
19715    #[test]
19716    fn cmd_debug_all_variant_strings() {
19717        assert_eq!(format!("{:?}", Cmd::<TestMsg>::none()), "None");
19718        assert_eq!(format!("{:?}", Cmd::<TestMsg>::quit()), "Quit");
19719        assert!(format!("{:?}", Cmd::<TestMsg>::msg(TestMsg::Increment)).starts_with("Msg("));
19720        assert!(
19721            format!("{:?}", Cmd::<TestMsg>::tick(Duration::from_millis(100))).starts_with("Tick(")
19722        );
19723        assert!(format!("{:?}", Cmd::<TestMsg>::log("hi")).starts_with("Log("));
19724        assert!(format!("{:?}", Cmd::<TestMsg>::task(|| TestMsg::Increment)).starts_with("Task"));
19725        assert_eq!(format!("{:?}", Cmd::<TestMsg>::save_state()), "SaveState");
19726        assert_eq!(
19727            format!("{:?}", Cmd::<TestMsg>::restore_state()),
19728            "RestoreState"
19729        );
19730        assert_eq!(
19731            format!("{:?}", Cmd::<TestMsg>::set_mouse_capture(true)),
19732            "SetMouseCapture(true)"
19733        );
19734    }
19735
19736    // =========================================================================
19737    // Cmd::set_mouse_capture headless execution (bd-2yjus)
19738    // =========================================================================
19739
19740    #[test]
19741    fn headless_execute_cmd_set_mouse_capture() {
19742        let mut program =
19743            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
19744        assert!(!program.backend_features.mouse_capture);
19745
19746        program
19747            .execute_cmd(Cmd::set_mouse_capture(true))
19748            .expect("set mouse capture true");
19749        assert!(program.backend_features.mouse_capture);
19750
19751        program
19752            .execute_cmd(Cmd::set_mouse_capture(false))
19753            .expect("set mouse capture false");
19754        assert!(!program.backend_features.mouse_capture);
19755    }
19756
19757    #[test]
19758    fn clipboard_commands_reach_writer_and_reply_reaches_model_once() {
19759        use ftui_core::event::{ClipboardEvent, ClipboardSource};
19760
19761        #[derive(Default)]
19762        struct ClipboardModel(Vec<String>);
19763        impl Model for ClipboardModel {
19764            type Message = Event;
19765            fn update(&mut self, event: Event) -> Cmd<Event> {
19766                match event {
19767                    Event::Tick => {
19768                        Cmd::sequence(vec![Cmd::set_clipboard("hi"), Cmd::get_clipboard()])
19769                    }
19770                    Event::Clipboard(reply) => {
19771                        self.0.push(reply.content);
19772                        Cmd::none()
19773                    }
19774                    _ => Cmd::none(),
19775                }
19776            }
19777            fn view(&self, _: &mut Frame) {}
19778        }
19779
19780        let mut program =
19781            headless_program_with_config(ClipboardModel::default(), ProgramConfig::default());
19782        let mut caps = TerminalCapabilities::basic();
19783        caps.osc52_clipboard = true;
19784        program.presenter = TerminalPresenter::new(TerminalWriter::new(
19785            Vec::new(),
19786            ScreenMode::AltScreen,
19787            UiAnchor::Bottom,
19788            caps,
19789        ));
19790        program.handle_event(Event::Tick).unwrap();
19791        assert!(
19792            program.model.0.is_empty(),
19793            "a query must not synthesize a reply"
19794        );
19795        program
19796            .handle_event(Event::Clipboard(ClipboardEvent::new(
19797                "hi",
19798                ClipboardSource::Osc52,
19799            )))
19800            .unwrap();
19801        assert_eq!(program.model.0, ["hi"]);
19802        let bytes = program.presenter.into_inner().unwrap();
19803        assert!(bytes.starts_with(b"\x1b]52;c;aGk=\x07\x1b]52;c;?\x07"));
19804        assert_eq!(Cmd::<()>::set_clipboard("hi").type_name(), "SetClipboard");
19805        assert_eq!(Cmd::<()>::get_clipboard().type_name(), "GetClipboard");
19806        assert!(
19807            !format!("{:?}", Cmd::<()>::set_clipboard("secret payload")).contains("secret payload")
19808        );
19809    }
19810
19811    #[test]
19812    fn clipboard_flushes_with_frame_or_without_a_future_frame() {
19813        #[derive(Clone, Default)]
19814        struct Capture(std::sync::Arc<std::sync::Mutex<(Vec<u8>, usize)>>);
19815        impl Write for Capture {
19816            fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
19817                let mut state = self.0.lock().unwrap();
19818                state.0.extend_from_slice(bytes);
19819                state.1 += 1;
19820                Ok(bytes.len())
19821            }
19822            fn flush(&mut self) -> io::Result<()> {
19823                Ok(())
19824            }
19825        }
19826        let capture = Capture::default();
19827        let mut caps = TerminalCapabilities::basic();
19828        caps.osc52_clipboard = true;
19829        let writer = TerminalWriter::new(
19830            capture.clone(),
19831            ScreenMode::AltScreen,
19832            UiAnchor::Bottom,
19833            caps,
19834        );
19835        let mut program = Program::with_event_source(
19836            TestModel { value: 0 },
19837            HeadlessEventSource::new(10, 3, BackendFeatures::default()),
19838            BackendFeatures::default(),
19839            TerminalPresenter::new(writer),
19840            ProgramConfig::default(),
19841        )
19842        .unwrap();
19843        program.dirty = true;
19844        program.execute_cmd(Cmd::set_clipboard("hi")).unwrap();
19845        program.execute_cmd(Cmd::get_clipboard()).unwrap();
19846        assert_eq!(capture.0.lock().unwrap().1, 0);
19847        program.render_frame().unwrap();
19848        {
19849            let state = capture.0.lock().unwrap();
19850            assert_eq!(state.1, 1, "controls and frame share the buffered write");
19851            assert!(state.0.starts_with(b"\x1b]52;c;aGk=\x07\x1b]52;c;?\x07"));
19852        }
19853        program.dirty = false;
19854        program.execute_cmd(Cmd::get_clipboard()).unwrap();
19855        assert_eq!(
19856            capture.0.lock().unwrap().1,
19857            2,
19858            "no frame: flush immediately"
19859        );
19860        program.dirty = true;
19861        program.execute_cmd(Cmd::set_clipboard("quit")).unwrap();
19862        program.execute_cmd(Cmd::quit()).unwrap();
19863        assert!(
19864            capture
19865                .0
19866                .lock()
19867                .unwrap()
19868                .0
19869                .ends_with(b"\x1b]52;c;cXVpdA==\x07")
19870        );
19871        program
19872            .execute_lifecycle_cmd(Cmd::set_clipboard("bye"))
19873            .unwrap();
19874        assert!(capture.0.lock().unwrap().0.ends_with(b"\x1b]52;c;Ynll\x07"));
19875        assert!(!program.running);
19876    }
19877
19878    // =========================================================================
19879    // ResizeBehavior tests (bd-2yjus)
19880    // =========================================================================
19881
19882    #[test]
19883    fn resize_behavior_uses_coalescer() {
19884        assert!(ResizeBehavior::Throttled.uses_coalescer());
19885        assert!(!ResizeBehavior::Immediate.uses_coalescer());
19886    }
19887
19888    #[test]
19889    fn resize_behavior_eq_and_debug() {
19890        assert_eq!(ResizeBehavior::Immediate, ResizeBehavior::Immediate);
19891        assert_ne!(ResizeBehavior::Immediate, ResizeBehavior::Throttled);
19892        let debug = format!("{:?}", ResizeBehavior::Throttled);
19893        assert_eq!(debug, "Throttled");
19894    }
19895
19896    // =========================================================================
19897    // WidgetRefreshConfig default values (bd-2yjus)
19898    // =========================================================================
19899
19900    #[test]
19901    fn widget_refresh_config_defaults() {
19902        let config = WidgetRefreshConfig::default();
19903        assert!(config.enabled);
19904        assert_eq!(config.staleness_window_ms, 1_000);
19905        assert_eq!(config.starve_ms, 3_000);
19906        assert_eq!(config.max_starved_per_frame, 2);
19907        assert_eq!(config.max_drop_fraction, 1.0);
19908        assert_eq!(config.weight_priority, 1.0);
19909        assert_eq!(config.weight_staleness, 0.5);
19910        assert_eq!(config.weight_focus, 0.75);
19911        assert_eq!(config.weight_interaction, 0.5);
19912        assert_eq!(config.starve_boost, 1.5);
19913        assert_eq!(config.min_cost_us, 1.0);
19914    }
19915
19916    // =========================================================================
19917    // EffectQueueConfig tests (bd-2yjus)
19918    // =========================================================================
19919
19920    #[test]
19921    fn effect_queue_config_default() {
19922        let config = EffectQueueConfig::default();
19923        assert!(!config.enabled);
19924        assert_eq!(config.backend, TaskExecutorBackend::Spawned);
19925        assert!(!config.explicit_backend);
19926        assert!(config.scheduler.smith_enabled);
19927        assert!(!config.scheduler.force_fifo);
19928        assert!(!config.scheduler.preemptive);
19929    }
19930
19931    #[test]
19932    fn effect_queue_config_with_enabled() {
19933        let config = EffectQueueConfig::default().with_enabled(true);
19934        assert!(config.enabled);
19935        assert_eq!(config.backend, TaskExecutorBackend::EffectQueue);
19936        assert!(config.explicit_backend);
19937    }
19938
19939    #[test]
19940    fn effect_queue_config_with_enabled_false_marks_explicit_spawned_backend() {
19941        let config = EffectQueueConfig::default().with_enabled(false);
19942        assert!(!config.enabled);
19943        assert_eq!(config.backend, TaskExecutorBackend::Spawned);
19944        assert!(config.explicit_backend);
19945    }
19946
19947    #[test]
19948    fn effect_queue_config_with_backend() {
19949        let config = EffectQueueConfig::default().with_backend(TaskExecutorBackend::EffectQueue);
19950        assert!(config.enabled);
19951        assert_eq!(config.backend, TaskExecutorBackend::EffectQueue);
19952        assert!(config.explicit_backend);
19953    }
19954
19955    #[cfg(feature = "asupersync-executor")]
19956    #[test]
19957    fn effect_queue_config_with_asupersync_backend_disables_effect_queue_flag() {
19958        let config = EffectQueueConfig::default().with_backend(TaskExecutorBackend::Asupersync);
19959        assert!(!config.enabled);
19960        assert_eq!(config.backend, TaskExecutorBackend::Asupersync);
19961    }
19962
19963    #[test]
19964    fn effect_queue_config_with_scheduler() {
19965        let sched = SchedulerConfig {
19966            force_fifo: true,
19967            ..Default::default()
19968        };
19969        let config = EffectQueueConfig::default().with_scheduler(sched);
19970        assert!(config.scheduler.force_fifo);
19971    }
19972
19973    // =========================================================================
19974    // InlineAutoRemeasureConfig defaults (bd-2yjus)
19975    // =========================================================================
19976
19977    #[test]
19978    fn inline_auto_remeasure_config_defaults() {
19979        let config = InlineAutoRemeasureConfig::default();
19980        assert_eq!(config.change_threshold_rows, 1);
19981        assert_eq!(config.voi.prior_alpha, 1.0);
19982        assert_eq!(config.voi.prior_beta, 9.0);
19983        assert_eq!(config.voi.max_interval_ms, 1000);
19984        assert_eq!(config.voi.min_interval_ms, 100);
19985        assert_eq!(config.voi.sample_cost, 0.08);
19986    }
19987
19988    // =========================================================================
19989    // HeadlessEventSource direct tests (bd-2yjus)
19990    // =========================================================================
19991
19992    #[test]
19993    fn headless_event_source_size() {
19994        let source = HeadlessEventSource::new(120, 40, BackendFeatures::default());
19995        assert_eq!(source.size().unwrap(), (120, 40));
19996    }
19997
19998    #[test]
19999    fn headless_event_source_poll_always_false() {
20000        let mut source = HeadlessEventSource::new(80, 24, BackendFeatures::default());
20001        assert!(!source.poll_event(Duration::from_millis(100)).unwrap());
20002    }
20003
20004    #[test]
20005    fn headless_event_source_read_always_none() {
20006        let mut source = HeadlessEventSource::new(80, 24, BackendFeatures::default());
20007        assert!(source.read_event().unwrap().is_none());
20008    }
20009
20010    #[test]
20011    fn headless_event_source_set_features() {
20012        let mut source = HeadlessEventSource::new(80, 24, BackendFeatures::default());
20013        let features = BackendFeatures {
20014            mouse_capture: true,
20015            bracketed_paste: true,
20016            focus_events: true,
20017            kitty_keyboard: true,
20018        };
20019        source.set_features(features).unwrap();
20020        assert_eq!(source.features, features);
20021    }
20022
20023    #[test]
20024    fn immediate_drain_budget_adds_backoff_poll_under_burst() {
20025        use ftui_core::event::{KeyCode, KeyEvent};
20026
20027        struct DrainBurstModel {
20028            processed: usize,
20029            quit_after: usize,
20030        }
20031
20032        #[derive(Debug)]
20033        #[allow(dead_code)]
20034        enum DrainBurstMsg {
20035            Event(Event),
20036        }
20037
20038        impl From<Event> for DrainBurstMsg {
20039            fn from(event: Event) -> Self {
20040                DrainBurstMsg::Event(event)
20041            }
20042        }
20043
20044        impl Model for DrainBurstModel {
20045            type Message = DrainBurstMsg;
20046
20047            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
20048                match msg {
20049                    DrainBurstMsg::Event(_) => {
20050                        self.processed = self.processed.saturating_add(1);
20051                        if self.processed >= self.quit_after {
20052                            Cmd::quit()
20053                        } else {
20054                            Cmd::none()
20055                        }
20056                    }
20057                }
20058            }
20059
20060            fn view(&self, _frame: &mut Frame) {}
20061        }
20062
20063        struct DrainBurstEventSource {
20064            queue: VecDeque<Event>,
20065            poll_timeouts: Arc<std::sync::Mutex<Vec<Duration>>>,
20066            size: (u16, u16),
20067        }
20068
20069        impl BackendEventSource for DrainBurstEventSource {
20070            type Error = io::Error;
20071
20072            fn size(&self) -> Result<(u16, u16), Self::Error> {
20073                Ok(self.size)
20074            }
20075
20076            fn set_features(&mut self, _features: BackendFeatures) -> Result<(), Self::Error> {
20077                Ok(())
20078            }
20079
20080            fn poll_event(&mut self, timeout: Duration) -> Result<bool, Self::Error> {
20081                self.poll_timeouts.lock().unwrap().push(timeout);
20082                Ok(!self.queue.is_empty())
20083            }
20084
20085            fn read_event(&mut self) -> Result<Option<Event>, Self::Error> {
20086                Ok(self.queue.pop_front())
20087            }
20088        }
20089
20090        let burst_events = 24usize;
20091        let poll_timeouts = Arc::new(std::sync::Mutex::new(Vec::new()));
20092        let mut queue = VecDeque::new();
20093        for _ in 0..burst_events {
20094            queue.push_back(Event::Key(KeyEvent::new(KeyCode::Char('x'))));
20095        }
20096
20097        let events = DrainBurstEventSource {
20098            queue,
20099            poll_timeouts: poll_timeouts.clone(),
20100            size: (80, 24),
20101        };
20102        let writer = TerminalWriter::new(
20103            Vec::<u8>::new(),
20104            ScreenMode::AltScreen,
20105            UiAnchor::Bottom,
20106            TerminalCapabilities::dumb(),
20107        );
20108        let config = ProgramConfig::default()
20109            .with_forced_size(80, 24)
20110            .with_signal_interception(false)
20111            .with_immediate_drain(ImmediateDrainConfig {
20112                max_zero_timeout_polls_per_burst: 3,
20113                max_burst_duration: Duration::from_secs(1),
20114                backoff_timeout: Duration::from_millis(1),
20115            });
20116
20117        let model = DrainBurstModel {
20118            processed: 0,
20119            quit_after: burst_events,
20120        };
20121        let mut program = Program::with_event_source(
20122            model,
20123            events,
20124            BackendFeatures::default(),
20125            TerminalPresenter::new(writer),
20126            config,
20127        )
20128        .expect("program creation");
20129        program.run().expect("run burst");
20130
20131        assert_eq!(program.model().processed, burst_events);
20132
20133        let stats = program.immediate_drain_stats();
20134        assert_eq!(stats.bursts, 1);
20135        assert!(stats.capped_bursts >= 1);
20136        assert!(stats.backoff_polls >= 1);
20137        assert!(stats.zero_timeout_polls >= 1);
20138        assert!(stats.max_zero_timeout_polls_in_burst <= 3);
20139
20140        let timeouts = poll_timeouts.lock().unwrap();
20141        assert!(timeouts.contains(&Duration::ZERO));
20142        assert!(timeouts.contains(&Duration::from_millis(1)));
20143    }
20144
20145    /// Regression test for frankentui#95: an event source that reports poll
20146    /// readiness but yields no event from `read_event` (spurious readiness,
20147    /// as the Windows console can produce) must not stall or busy-spin the
20148    /// event loop. The runtime must treat `read_event() == Ok(None)` as
20149    /// "nothing decodable", finish the drain burst via its bounded
20150    /// zero-timeout polls, and return to the timed outer poll so ticks and
20151    /// queued messages keep flowing.
20152    #[test]
20153    fn spurious_poll_readiness_does_not_stall_event_loop() {
20154        struct SpuriousModel {
20155            ticks: usize,
20156            quit_after: usize,
20157        }
20158
20159        #[derive(Debug)]
20160        enum SpuriousMsg {
20161            Tick,
20162            Other,
20163        }
20164
20165        impl From<Event> for SpuriousMsg {
20166            fn from(event: Event) -> Self {
20167                match event {
20168                    Event::Tick => SpuriousMsg::Tick,
20169                    _ => SpuriousMsg::Other,
20170                }
20171            }
20172        }
20173
20174        impl Model for SpuriousModel {
20175            type Message = SpuriousMsg;
20176
20177            fn init(&mut self) -> Cmd<Self::Message> {
20178                Cmd::tick(Duration::from_millis(1))
20179            }
20180
20181            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
20182                match msg {
20183                    SpuriousMsg::Tick => {
20184                        self.ticks = self.ticks.saturating_add(1);
20185                        if self.ticks >= self.quit_after {
20186                            Cmd::quit()
20187                        } else {
20188                            Cmd::none()
20189                        }
20190                    }
20191                    SpuriousMsg::Other => Cmd::none(),
20192                }
20193            }
20194
20195            fn view(&self, _frame: &mut Frame) {}
20196        }
20197
20198        struct SpuriousReadySource {
20199            spurious_polls_remaining: usize,
20200            read_calls: Arc<std::sync::atomic::AtomicUsize>,
20201        }
20202
20203        impl BackendEventSource for SpuriousReadySource {
20204            type Error = io::Error;
20205
20206            fn size(&self) -> Result<(u16, u16), Self::Error> {
20207                Ok((80, 24))
20208            }
20209
20210            fn set_features(&mut self, _features: BackendFeatures) -> Result<(), Self::Error> {
20211                Ok(())
20212            }
20213
20214            fn poll_event(&mut self, _timeout: Duration) -> Result<bool, Self::Error> {
20215                if self.spurious_polls_remaining > 0 {
20216                    self.spurious_polls_remaining -= 1;
20217                    Ok(true)
20218                } else {
20219                    Ok(false)
20220                }
20221            }
20222
20223            fn read_event(&mut self) -> Result<Option<Event>, Self::Error> {
20224                // Readiness was spurious: nothing decodable is ever produced.
20225                self.read_calls
20226                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
20227                Ok(None)
20228            }
20229        }
20230
20231        let spurious_polls = 5usize;
20232        let read_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
20233        let events = SpuriousReadySource {
20234            spurious_polls_remaining: spurious_polls,
20235            read_calls: read_calls.clone(),
20236        };
20237        let writer = TerminalWriter::new(
20238            Vec::<u8>::new(),
20239            ScreenMode::AltScreen,
20240            UiAnchor::Bottom,
20241            TerminalCapabilities::dumb(),
20242        );
20243        let config = ProgramConfig::default()
20244            .with_forced_size(80, 24)
20245            .with_signal_interception(false);
20246
20247        let model = SpuriousModel {
20248            ticks: 0,
20249            quit_after: 3,
20250        };
20251        let mut program = Program::with_event_source(
20252            model,
20253            events,
20254            BackendFeatures::default(),
20255            TerminalPresenter::new(writer),
20256            config,
20257        )
20258        .expect("program creation");
20259        // If spurious readiness parked the loop (the frankentui#95 failure
20260        // mode with a blocking read), this would hang instead of returning.
20261        program.run().expect("run with spurious readiness");
20262
20263        assert_eq!(program.model().ticks, 3, "ticks must keep flowing");
20264        // Every `true` poll is followed by exactly one read attempt; a
20265        // spurious-ready source must produce a bounded number of empty reads,
20266        // not an unbounded spin.
20267        assert_eq!(
20268            read_calls.load(std::sync::atomic::Ordering::Relaxed),
20269            spurious_polls
20270        );
20271    }
20272
20273    #[test]
20274    fn immediate_drain_zero_poll_limit_is_clamped() {
20275        use ftui_core::event::{KeyCode, KeyEvent};
20276
20277        struct ClampModel {
20278            processed: usize,
20279            quit_after: usize,
20280        }
20281
20282        #[derive(Debug)]
20283        #[allow(dead_code)]
20284        enum ClampMsg {
20285            Event(Event),
20286        }
20287
20288        impl From<Event> for ClampMsg {
20289            fn from(event: Event) -> Self {
20290                ClampMsg::Event(event)
20291            }
20292        }
20293
20294        impl Model for ClampModel {
20295            type Message = ClampMsg;
20296
20297            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
20298                match msg {
20299                    ClampMsg::Event(_) => {
20300                        self.processed = self.processed.saturating_add(1);
20301                        if self.processed >= self.quit_after {
20302                            Cmd::quit()
20303                        } else {
20304                            Cmd::none()
20305                        }
20306                    }
20307                }
20308            }
20309
20310            fn view(&self, _frame: &mut Frame) {}
20311        }
20312
20313        struct ClampSource {
20314            queue: VecDeque<Event>,
20315        }
20316
20317        impl BackendEventSource for ClampSource {
20318            type Error = io::Error;
20319
20320            fn size(&self) -> Result<(u16, u16), Self::Error> {
20321                Ok((80, 24))
20322            }
20323
20324            fn set_features(&mut self, _features: BackendFeatures) -> Result<(), Self::Error> {
20325                Ok(())
20326            }
20327
20328            fn poll_event(&mut self, _timeout: Duration) -> Result<bool, Self::Error> {
20329                Ok(!self.queue.is_empty())
20330            }
20331
20332            fn read_event(&mut self) -> Result<Option<Event>, Self::Error> {
20333                Ok(self.queue.pop_front())
20334            }
20335        }
20336
20337        let burst_events = 8usize;
20338        let mut queue = VecDeque::new();
20339        for _ in 0..burst_events {
20340            queue.push_back(Event::Key(KeyEvent::new(KeyCode::Char('z'))));
20341        }
20342        let events = ClampSource { queue };
20343
20344        let writer = TerminalWriter::new(
20345            Vec::<u8>::new(),
20346            ScreenMode::AltScreen,
20347            UiAnchor::Bottom,
20348            TerminalCapabilities::dumb(),
20349        );
20350        let config = ProgramConfig::default()
20351            .with_forced_size(80, 24)
20352            .with_signal_interception(false)
20353            .with_immediate_drain(ImmediateDrainConfig {
20354                max_zero_timeout_polls_per_burst: 0,
20355                max_burst_duration: Duration::from_secs(1),
20356                backoff_timeout: Duration::from_millis(1),
20357            });
20358        let model = ClampModel {
20359            processed: 0,
20360            quit_after: burst_events,
20361        };
20362
20363        let mut program = Program::with_event_source(
20364            model,
20365            events,
20366            BackendFeatures::default(),
20367            TerminalPresenter::new(writer),
20368            config,
20369        )
20370        .expect("program creation");
20371        program.run().expect("run clamp");
20372
20373        let stats = program.immediate_drain_stats();
20374        assert!(stats.max_zero_timeout_polls_in_burst <= 1);
20375    }
20376
20377    #[test]
20378    fn quit_stops_draining_remaining_burst_events() {
20379        use ftui_core::event::{KeyCode, KeyEvent};
20380
20381        struct QuitBurstModel {
20382            processed: usize,
20383            quit_after: usize,
20384        }
20385
20386        #[derive(Debug)]
20387        #[allow(dead_code)]
20388        enum QuitBurstMsg {
20389            Event(Event),
20390        }
20391
20392        impl From<Event> for QuitBurstMsg {
20393            fn from(event: Event) -> Self {
20394                Self::Event(event)
20395            }
20396        }
20397
20398        impl Model for QuitBurstModel {
20399            type Message = QuitBurstMsg;
20400
20401            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
20402                match msg {
20403                    QuitBurstMsg::Event(_) => {
20404                        self.processed = self.processed.saturating_add(1);
20405                        if self.processed >= self.quit_after {
20406                            Cmd::quit()
20407                        } else {
20408                            Cmd::none()
20409                        }
20410                    }
20411                }
20412            }
20413
20414            fn view(&self, _frame: &mut Frame) {}
20415        }
20416
20417        struct QuitBurstSource {
20418            queue: VecDeque<Event>,
20419        }
20420
20421        impl BackendEventSource for QuitBurstSource {
20422            type Error = io::Error;
20423
20424            fn size(&self) -> Result<(u16, u16), Self::Error> {
20425                Ok((80, 24))
20426            }
20427
20428            fn set_features(&mut self, _features: BackendFeatures) -> Result<(), Self::Error> {
20429                Ok(())
20430            }
20431
20432            fn poll_event(&mut self, _timeout: Duration) -> Result<bool, Self::Error> {
20433                Ok(!self.queue.is_empty())
20434            }
20435
20436            fn read_event(&mut self) -> Result<Option<Event>, Self::Error> {
20437                Ok(self.queue.pop_front())
20438            }
20439        }
20440
20441        let total_events = 8usize;
20442        let quit_after = 3usize;
20443        let mut queue = VecDeque::new();
20444        for _ in 0..total_events {
20445            queue.push_back(Event::Key(KeyEvent::new(KeyCode::Char('q'))));
20446        }
20447
20448        let writer = TerminalWriter::new(
20449            Vec::<u8>::new(),
20450            ScreenMode::AltScreen,
20451            UiAnchor::Bottom,
20452            TerminalCapabilities::dumb(),
20453        );
20454        let config = ProgramConfig::default()
20455            .with_forced_size(80, 24)
20456            .with_signal_interception(false)
20457            .with_immediate_drain(ImmediateDrainConfig {
20458                max_zero_timeout_polls_per_burst: 64,
20459                max_burst_duration: Duration::from_secs(1),
20460                backoff_timeout: Duration::from_millis(1),
20461            });
20462        let model = QuitBurstModel {
20463            processed: 0,
20464            quit_after,
20465        };
20466        let events = QuitBurstSource { queue };
20467
20468        let mut program = Program::with_event_source(
20469            model,
20470            events,
20471            BackendFeatures::default(),
20472            TerminalPresenter::new(writer),
20473            config,
20474        )
20475        .expect("program creation");
20476        program.run().expect("run burst quit");
20477
20478        assert_eq!(program.model().processed, quit_after);
20479    }
20480
20481    // =========================================================================
20482    // Program helper methods (bd-2yjus)
20483    // =========================================================================
20484
20485    #[test]
20486    fn headless_program_quit_and_is_running() {
20487        let mut program =
20488            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
20489        assert!(program.is_running());
20490
20491        program.quit();
20492        assert!(!program.is_running());
20493    }
20494
20495    #[test]
20496    fn headless_program_model_mut() {
20497        let mut program =
20498            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
20499        assert_eq!(program.model().value, 0);
20500
20501        program.model_mut().value = 42;
20502        assert_eq!(program.model().value, 42);
20503    }
20504
20505    #[test]
20506    fn headless_program_request_redraw() {
20507        let mut program =
20508            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
20509        program.dirty = false;
20510
20511        program.request_redraw();
20512        assert!(program.dirty);
20513    }
20514
20515    #[test]
20516    fn headless_program_last_widget_signals_initially_empty() {
20517        let program =
20518            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
20519        assert!(program.last_widget_signals().is_empty());
20520    }
20521
20522    #[test]
20523    fn headless_program_no_persistence_by_default() {
20524        let program =
20525            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
20526        assert!(!program.has_persistence());
20527        assert!(program.state_registry().is_none());
20528    }
20529
20530    // =========================================================================
20531    // classify_event_for_fairness (bd-2yjus)
20532    // =========================================================================
20533
20534    #[test]
20535    fn classify_event_fairness_key_is_input() {
20536        let event = Event::Key(ftui_core::event::KeyEvent::new(
20537            ftui_core::event::KeyCode::Char('a'),
20538        ));
20539        let classification = DefaultProgram::<TestModel>::classify_event_for_fairness(&event);
20540        assert_eq!(classification, FairnessEventType::Input);
20541    }
20542
20543    #[test]
20544    fn classify_event_fairness_resize_is_resize() {
20545        let event = Event::Resize {
20546            width: 80,
20547            height: 24,
20548        };
20549        let classification = DefaultProgram::<TestModel>::classify_event_for_fairness(&event);
20550        assert_eq!(classification, FairnessEventType::Resize);
20551    }
20552
20553    #[test]
20554    fn classify_event_fairness_tick_is_tick() {
20555        let event = Event::Tick;
20556        let classification = DefaultProgram::<TestModel>::classify_event_for_fairness(&event);
20557        assert_eq!(classification, FairnessEventType::Tick);
20558    }
20559
20560    #[test]
20561    fn classify_event_fairness_paste_is_input() {
20562        let event = Event::Paste(ftui_core::event::PasteEvent::bracketed("hello"));
20563        let classification = DefaultProgram::<TestModel>::classify_event_for_fairness(&event);
20564        assert_eq!(classification, FairnessEventType::Input);
20565    }
20566
20567    #[test]
20568    fn classify_event_fairness_focus_is_input() {
20569        let event = Event::Focus(true);
20570        let classification = DefaultProgram::<TestModel>::classify_event_for_fairness(&event);
20571        assert_eq!(classification, FairnessEventType::Input);
20572    }
20573
20574    // =========================================================================
20575    // ProgramConfig builder methods (bd-2yjus)
20576    // =========================================================================
20577
20578    #[test]
20579    fn program_config_with_diff_config() {
20580        let diff = RuntimeDiffConfig::default();
20581        let config = ProgramConfig::default().with_diff_config(diff.clone());
20582        // Just verify it doesn't panic and the field is set
20583        let _ = format!("{:?}", config);
20584    }
20585
20586    #[test]
20587    fn program_config_with_evidence_sink() {
20588        let config =
20589            ProgramConfig::default().with_evidence_sink(EvidenceSinkConfig::enabled_stdout());
20590        let _ = format!("{:?}", config);
20591    }
20592
20593    #[test]
20594    fn program_config_with_render_trace() {
20595        let config = ProgramConfig::default().with_render_trace(RenderTraceConfig::default());
20596        let _ = format!("{:?}", config);
20597    }
20598
20599    #[test]
20600    fn program_config_with_locale() {
20601        let config = ProgramConfig::default().with_locale("fr");
20602        let _ = format!("{:?}", config);
20603    }
20604
20605    #[test]
20606    fn program_config_with_locale_context() {
20607        let config = ProgramConfig::default().with_locale_context(LocaleContext::new("de"));
20608        let _ = format!("{:?}", config);
20609    }
20610
20611    #[test]
20612    fn program_config_without_forced_size() {
20613        let config = ProgramConfig::default()
20614            .with_forced_size(80, 24)
20615            .without_forced_size();
20616        assert!(config.forced_size.is_none());
20617    }
20618
20619    #[test]
20620    fn program_config_forced_size_clamps_min() {
20621        let config = ProgramConfig::default().with_forced_size(0, 0);
20622        assert_eq!(config.forced_size, Some((1, 1)));
20623    }
20624
20625    #[test]
20626    fn program_config_with_widget_refresh() {
20627        let wrc = WidgetRefreshConfig {
20628            enabled: false,
20629            ..Default::default()
20630        };
20631        let config = ProgramConfig::default().with_widget_refresh(wrc);
20632        assert!(!config.widget_refresh.enabled);
20633    }
20634
20635    #[test]
20636    fn program_config_with_effect_queue() {
20637        let eqc = EffectQueueConfig::default().with_enabled(true);
20638        let config = ProgramConfig::default().with_effect_queue(eqc);
20639        assert!(config.effect_queue.enabled);
20640        assert_eq!(
20641            config.effect_queue.backend,
20642            TaskExecutorBackend::EffectQueue
20643        );
20644    }
20645
20646    #[test]
20647    fn program_config_with_resize_coalescer_custom() {
20648        let cc = CoalescerConfig {
20649            steady_delay_ms: 42,
20650            ..Default::default()
20651        };
20652        let config = ProgramConfig::default().with_resize_coalescer(cc);
20653        assert_eq!(config.resize_coalescer.steady_delay_ms, 42);
20654    }
20655
20656    #[test]
20657    fn program_config_with_inline_auto_remeasure() {
20658        let config = ProgramConfig::default()
20659            .with_inline_auto_remeasure(InlineAutoRemeasureConfig::default());
20660        assert!(config.inline_auto_remeasure.is_some());
20661
20662        let config = config.without_inline_auto_remeasure();
20663        assert!(config.inline_auto_remeasure.is_none());
20664    }
20665
20666    #[test]
20667    fn program_config_with_persistence_full() {
20668        let pc = PersistenceConfig::disabled();
20669        let config = ProgramConfig::default().with_persistence(pc);
20670        assert!(config.persistence.registry.is_none());
20671    }
20672
20673    #[test]
20674    fn program_config_with_conformal_config() {
20675        let config = ProgramConfig::default()
20676            .with_conformal_config(ConformalConfig::default())
20677            .without_conformal();
20678        assert!(config.conformal_config.is_none());
20679    }
20680
20681    // =========================================================================
20682    // Rollout config builder methods (bd-2crbt)
20683    // =========================================================================
20684
20685    #[test]
20686    fn program_config_with_lane() {
20687        let config = ProgramConfig::default().with_lane(RuntimeLane::Asupersync);
20688        assert_eq!(config.runtime_lane, RuntimeLane::Asupersync);
20689    }
20690
20691    #[test]
20692    fn program_config_default_lane_resolves_to_spawned_backend() {
20693        // Input-lag regression fix (#78): the default Structured lane now
20694        // resolves to per-task `Spawned` execution instead of the single-worker
20695        // `EffectQueue`. Structured cancellation is independent of the task
20696        // executor backend, so the lane no longer serializes `Cmd::Task` through
20697        // one `effect_queue_loop` worker (which caused per-keystroke head-of-line
20698        // latency for PTY-forwarding apps). `enabled` is the legacy convenience
20699        // flag mirroring the backend, so it is now false for the default lane.
20700        let config = ProgramConfig::default();
20701        let resolved = config.resolved_effect_queue_config(config.runtime_lane.resolve());
20702        assert!(!resolved.enabled);
20703        assert_eq!(resolved.backend, TaskExecutorBackend::Spawned);
20704    }
20705
20706    #[test]
20707    fn program_config_legacy_lane_resolves_to_spawned_backend() {
20708        let resolved = ProgramConfig::default()
20709            .with_lane(RuntimeLane::Legacy)
20710            .resolved_effect_queue_config(RuntimeLane::Legacy);
20711        assert!(!resolved.enabled);
20712        assert_eq!(resolved.backend, TaskExecutorBackend::Spawned);
20713    }
20714
20715    #[cfg(not(feature = "asupersync-executor"))]
20716    #[test]
20717    fn asupersync_lane_falls_back_to_structured_without_feature() {
20718        use tracing_subscriber::prelude::*;
20719
20720        let capture = A11yTraceCapture::default();
20721        let subscriber = tracing_subscriber::registry().with(capture.clone().with_filter(
20722            tracing_subscriber::filter::filter_fn(|metadata| {
20723                *metadata.level() == tracing::Level::WARN
20724                    && metadata.target() == crate::telemetry_schema::TARGET_RUNTIME
20725            }),
20726        ));
20727        tracing::subscriber::with_default(subscriber, || {
20728            assert_eq!(RuntimeLane::Asupersync.resolve(), RuntimeLane::Structured);
20729        });
20730        let warning = capture.0.lock().expect("capture lock");
20731        assert_eq!(warning.lines().count(), 1, "{warning}");
20732        assert!(warning.contains("missing_feature=\"asupersync-executor\""));
20733        assert!(warning.contains("requested=\"asupersync\""));
20734        assert!(warning.contains("resolved=\"structured\""));
20735    }
20736
20737    #[cfg(not(feature = "asupersync-executor"))]
20738    #[test]
20739    fn public_constructor_reports_fallback_once_and_actual_backend() {
20740        use tracing_subscriber::prelude::*;
20741
20742        for (effect_queue, expected_backend) in [
20743            (EffectQueueConfig::default(), "spawned"),
20744            (
20745                EffectQueueConfig::default().with_backend(TaskExecutorBackend::Spawned),
20746                "spawned",
20747            ),
20748            (
20749                EffectQueueConfig::default().with_backend(TaskExecutorBackend::EffectQueue),
20750                "queued",
20751            ),
20752        ] {
20753            let capture = A11yTraceCapture::default();
20754            let subscriber = tracing_subscriber::registry().with(capture.clone().with_filter(
20755                tracing_subscriber::filter::filter_fn(|metadata| {
20756                    metadata.target() == crate::telemetry_schema::TARGET_RUNTIME
20757                }),
20758            ));
20759            tracing::subscriber::with_default(subscriber, || {
20760                let config = ProgramConfig::default()
20761                    .with_lane(RuntimeLane::Asupersync)
20762                    .with_effect_queue(effect_queue)
20763                    .with_signal_interception(false);
20764                let features = BackendFeatures::default();
20765                let events = HeadlessEventSource::new(80, 24, features);
20766                let writer = TerminalWriter::with_diff_config(
20767                    Vec::new(),
20768                    config.screen_mode,
20769                    config.ui_anchor,
20770                    TerminalCapabilities::basic(),
20771                    config.diff_config.clone(),
20772                );
20773                let program = Program::with_event_source(
20774                    TestModel { value: 0 },
20775                    events,
20776                    features,
20777                    TerminalPresenter::new(writer),
20778                    config,
20779                )
20780                .expect("fallback executor initializes");
20781                assert_eq!(program.task_executor.kind_name(), expected_backend);
20782            });
20783            let output = capture.0.lock().expect("capture lock");
20784            assert_eq!(output.matches("missing_feature=").count(), 1, "{output}");
20785            assert!(output.contains("missing_feature=\"asupersync-executor\""));
20786            assert!(output.contains("requested=\"asupersync\""));
20787            assert!(output.contains("resolved=\"structured\""));
20788            let startup: Vec<_> = output
20789                .lines()
20790                .filter(|line| line.contains("runtime startup:"))
20791                .collect();
20792            assert_eq!(startup.len(), 1, "{output}");
20793            assert!(startup[0].contains("requested_lane=\"asupersync\""));
20794            assert!(startup[0].contains("resolved_lane=\"structured\""));
20795            assert!(startup[0].contains(&format!("task_backend=\"{expected_backend}\"")));
20796        }
20797    }
20798
20799    #[cfg(feature = "asupersync-executor")]
20800    #[test]
20801    fn asupersync_lane_resolves_to_asupersync_backend_when_feature_enabled() {
20802        let resolved_lane = RuntimeLane::Asupersync.resolve();
20803        assert_eq!(resolved_lane, RuntimeLane::Asupersync);
20804        assert_eq!(
20805            resolved_lane.task_executor_backend(),
20806            TaskExecutorBackend::Asupersync
20807        );
20808        let config = ProgramConfig::default()
20809            .with_lane(RuntimeLane::Asupersync)
20810            .with_signal_interception(false);
20811        let resolved = config.resolved_effect_queue_config(resolved_lane);
20812        assert_eq!(resolved.backend, TaskExecutorBackend::Asupersync);
20813        assert!(!resolved.enabled);
20814
20815        // Use the public constructor, not the manually assembled test Program.
20816        let features = BackendFeatures::default();
20817        let events = HeadlessEventSource::new(80, 24, features);
20818        let writer = TerminalWriter::with_diff_config(
20819            Vec::new(),
20820            config.screen_mode,
20821            config.ui_anchor,
20822            TerminalCapabilities::basic(),
20823            config.diff_config.clone(),
20824        );
20825        let mut program = Program::with_event_source(
20826            TestModel { value: 0 },
20827            events,
20828            features,
20829            TerminalPresenter::new(writer),
20830            config,
20831        )
20832        .expect("Asupersync lane initializes its executor");
20833        assert_eq!(program.task_executor.kind_name(), "asupersync");
20834        let executions = Arc::new(AtomicUsize::new(0));
20835        for _ in 0..32 {
20836            let executions = Arc::clone(&executions);
20837            program
20838                .execute_cmd(Cmd::task(move || {
20839                    executions.fetch_add(1, Ordering::SeqCst);
20840                    TestMsg::Increment
20841                }))
20842                .expect("submit through selected lane");
20843        }
20844        let deadline = Instant::now() + Duration::from_secs(5);
20845        while (program.model().value < 32 || program.task_executor.in_flight() > 0)
20846            && Instant::now() < deadline
20847        {
20848            program
20849                .process_task_results()
20850                .expect("deliver task results");
20851            program.reap_finished_tasks();
20852            thread::yield_now();
20853        }
20854        assert_eq!(program.model().value, 32, "every result reaches the model");
20855        assert_eq!(
20856            executions.load(Ordering::SeqCst),
20857            32,
20858            "effects execute once"
20859        );
20860        assert_eq!(program.task_executor.in_flight(), 0);
20861    }
20862
20863    #[test]
20864    fn asupersync_lane_preserves_explicit_task_backend() {
20865        for backend in [
20866            TaskExecutorBackend::Spawned,
20867            TaskExecutorBackend::EffectQueue,
20868        ] {
20869            let config = ProgramConfig::default()
20870                .with_lane(RuntimeLane::Asupersync)
20871                .with_effect_queue(EffectQueueConfig::default().with_backend(backend));
20872            assert_eq!(
20873                config
20874                    .resolved_effect_queue_config(config.runtime_lane.resolve())
20875                    .backend,
20876                backend
20877            );
20878        }
20879    }
20880
20881    #[test]
20882    fn program_config_explicit_spawned_backend_is_preserved() {
20883        let resolved = ProgramConfig::default()
20884            .with_effect_queue(EffectQueueConfig::default().with_enabled(false))
20885            .resolved_effect_queue_config(RuntimeLane::Structured);
20886        assert!(!resolved.enabled);
20887        assert_eq!(resolved.backend, TaskExecutorBackend::Spawned);
20888    }
20889
20890    #[test]
20891    fn program_config_with_rollout_policy() {
20892        let config = ProgramConfig::default().with_rollout_policy(RolloutPolicy::Shadow);
20893        assert_eq!(config.rollout_policy, RolloutPolicy::Shadow);
20894    }
20895
20896    #[test]
20897    fn rollout_policy_labels() {
20898        assert_eq!(RolloutPolicy::Off.label(), "off");
20899        assert_eq!(RolloutPolicy::Shadow.label(), "shadow");
20900        assert_eq!(RolloutPolicy::Enabled.label(), "enabled");
20901        assert_eq!(format!("{}", RolloutPolicy::Shadow), "shadow");
20902    }
20903
20904    #[test]
20905    fn rollout_policy_is_shadow() {
20906        assert!(!RolloutPolicy::Off.is_shadow());
20907        assert!(RolloutPolicy::Shadow.is_shadow());
20908        assert!(!RolloutPolicy::Enabled.is_shadow());
20909    }
20910
20911    #[test]
20912    fn rollout_policy_default_is_off() {
20913        assert_eq!(RolloutPolicy::default(), RolloutPolicy::Off);
20914    }
20915
20916    #[test]
20917    fn runtime_lane_parse_legacy() {
20918        assert_eq!(RuntimeLane::parse("legacy"), Some(RuntimeLane::Legacy));
20919    }
20920
20921    #[test]
20922    fn runtime_lane_parse_structured_case_insensitive() {
20923        assert_eq!(
20924            RuntimeLane::parse("Structured"),
20925            Some(RuntimeLane::Structured)
20926        );
20927    }
20928
20929    #[test]
20930    fn runtime_lane_parse_asupersync_uppercase() {
20931        assert_eq!(
20932            RuntimeLane::parse("ASUPERSYNC"),
20933            Some(RuntimeLane::Asupersync)
20934        );
20935    }
20936
20937    #[test]
20938    fn runtime_lane_parse_unrecognized() {
20939        assert_eq!(RuntimeLane::parse("bogus"), None);
20940    }
20941
20942    #[test]
20943    fn rollout_policy_parse_shadow() {
20944        assert_eq!(RolloutPolicy::parse("shadow"), Some(RolloutPolicy::Shadow));
20945    }
20946
20947    #[test]
20948    fn rollout_policy_parse_enabled() {
20949        assert_eq!(
20950            RolloutPolicy::parse("enabled"),
20951            Some(RolloutPolicy::Enabled)
20952        );
20953    }
20954
20955    #[test]
20956    fn rollout_policy_parse_off() {
20957        assert_eq!(RolloutPolicy::parse("off"), Some(RolloutPolicy::Off));
20958    }
20959
20960    #[test]
20961    fn rollout_policy_parse_unrecognized() {
20962        assert_eq!(RolloutPolicy::parse("bogus"), None);
20963    }
20964
20965    #[test]
20966    fn structured_and_legacy_lanes_keep_default_backend() {
20967        for lane in [RuntimeLane::Legacy, RuntimeLane::Structured] {
20968            let resolved_lane = lane.resolve();
20969            assert_eq!(resolved_lane, lane);
20970            assert_eq!(resolved_lane.task_executor_backend(), DEFAULT_TASK_BACKEND);
20971            let resolved_config = ProgramConfig::default()
20972                .with_lane(lane)
20973                .resolved_effect_queue_config(resolved_lane);
20974            assert_eq!(resolved_config.backend, DEFAULT_TASK_BACKEND);
20975        }
20976    }
20977
20978    #[test]
20979    fn env_override_lane_asupersync_round_trips() {
20980        let direct = ProgramConfig::default().with_env_values(Some("asupersync"), Some("shadow"));
20981        assert_eq!(direct.runtime_lane, RuntimeLane::Asupersync);
20982        assert_eq!(direct.rollout_policy, RolloutPolicy::Shadow);
20983
20984        if std::env::var("FTUI_TEST_ENV_OVERRIDE_CHILD").is_ok() {
20985            let via_env = ProgramConfig::default().with_env_overrides();
20986            assert_eq!(via_env.runtime_lane, RuntimeLane::Asupersync);
20987            assert_eq!(via_env.rollout_policy, RolloutPolicy::Shadow);
20988            return;
20989        }
20990
20991        let exe = std::env::current_exe().expect("current test executable");
20992        let output = std::process::Command::new(exe)
20993            .arg("--exact")
20994            .arg("program::tests::env_override_lane_asupersync_round_trips")
20995            .arg("--nocapture")
20996            .env("FTUI_TEST_ENV_OVERRIDE_CHILD", "1")
20997            .env("FTUI_RUNTIME_LANE", "asupersync")
20998            .env("FTUI_ROLLOUT_POLICY", "shadow")
20999            .output()
21000            .expect("spawn child test");
21001        assert!(
21002            output.status.success(),
21003            "child test failed: stdout={}\nstderr={}",
21004            String::from_utf8_lossy(&output.stdout),
21005            String::from_utf8_lossy(&output.stderr)
21006        );
21007    }
21008
21009    struct ShadowVisibleModel {
21010        value: i32,
21011    }
21012
21013    impl Model for ShadowVisibleModel {
21014        type Message = TestMsg;
21015
21016        fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
21017            if let TestMsg::Increment = msg {
21018                self.value += 1;
21019            }
21020            Cmd::none()
21021        }
21022
21023        fn view(&self, frame: &mut Frame) {
21024            let text = format!("value={}", self.value);
21025            for (col, ch) in text.chars().enumerate() {
21026                if (col as u16) < frame.width() {
21027                    frame
21028                        .buffer
21029                        .set_raw(col as u16, 0, ftui_render::cell::Cell::from_char(ch));
21030                }
21031            }
21032        }
21033    }
21034
21035    #[test]
21036    fn shadow_policy_writes_shadow_frame_evidence() {
21037        let path = std::env::temp_dir().join(format!(
21038            "ftui_shadow_frame_evidence_{}_{}.jsonl",
21039            std::process::id(),
21040            std::time::SystemTime::now()
21041                .duration_since(std::time::UNIX_EPOCH)
21042                .unwrap_or_default()
21043                .as_nanos()
21044        ));
21045        let config = ProgramConfig::fullscreen()
21046            .with_lane(RuntimeLane::Structured)
21047            .with_rollout_policy(RolloutPolicy::Shadow)
21048            .with_evidence_sink(crate::evidence_sink::EvidenceSinkConfig::enabled_file(
21049                &path,
21050            ))
21051            .with_signal_interception(false);
21052
21053        let mut program =
21054            headless_program_with_resolved_config(ShadowVisibleModel { value: 0 }, config);
21055        for i in 0..5 {
21056            program.model_mut().value = i;
21057            program.render_frame().expect("render shadow frame");
21058        }
21059
21060        let contents = std::fs::read_to_string(&path).expect("read shadow evidence");
21061        let shadow_lines: Vec<serde_json::Value> = contents
21062            .lines()
21063            .filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
21064            .filter(|v| v.get("event").and_then(|e| e.as_str()) == Some("shadow_frame"))
21065            .collect();
21066        if shadow_lines.len() != 5 {
21067            eprintln!("captured evidence:\n{contents}");
21068        }
21069        assert_eq!(shadow_lines.len(), 5);
21070        for (expected_idx, row) in shadow_lines.iter().enumerate() {
21071            assert_eq!(
21072                row.get("frame").and_then(|v| v.as_u64()),
21073                Some(expected_idx as u64)
21074            );
21075            let checksum = row
21076                .get("checksum")
21077                .and_then(|v| v.as_str())
21078                .expect("checksum string");
21079            assert_eq!(checksum.len(), 16, "checksum={checksum}");
21080            assert!(
21081                checksum
21082                    .chars()
21083                    .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()),
21084                "checksum must be 16 lowercase hex digits: {checksum}"
21085            );
21086            assert_eq!(row.get("lane").and_then(|v| v.as_str()), Some("structured"));
21087            assert_eq!(
21088                row.get("requested_lane").and_then(|v| v.as_str()),
21089                Some("structured")
21090            );
21091            assert_eq!(
21092                row.get("rollout_policy").and_then(|v| v.as_str()),
21093                Some("shadow")
21094            );
21095            assert_eq!(
21096                row.get("task_backend").and_then(|v| v.as_str()),
21097                Some("spawned")
21098            );
21099            assert_eq!(row.get("cols").and_then(|v| v.as_u64()), Some(80));
21100            assert_eq!(row.get("rows").and_then(|v| v.as_u64()), Some(24));
21101            assert!(row.get("ts_ns").and_then(|v| v.as_u64()).is_some());
21102        }
21103    }
21104
21105    #[test]
21106    fn off_and_enabled_policies_write_no_shadow_frames() {
21107        for policy in [RolloutPolicy::Off, RolloutPolicy::Enabled] {
21108            let path = std::env::temp_dir().join(format!(
21109                "ftui_no_shadow_frames_{}_{}_{}.jsonl",
21110                policy.label(),
21111                std::process::id(),
21112                std::time::SystemTime::now()
21113                    .duration_since(std::time::UNIX_EPOCH)
21114                    .unwrap_or_default()
21115                    .as_nanos()
21116            ));
21117            let config = ProgramConfig::fullscreen()
21118                .with_lane(RuntimeLane::Structured)
21119                .with_rollout_policy(policy)
21120                .with_evidence_sink(crate::evidence_sink::EvidenceSinkConfig::enabled_file(
21121                    &path,
21122                ))
21123                .with_signal_interception(false);
21124
21125            let mut program =
21126                headless_program_with_resolved_config(ShadowVisibleModel { value: 0 }, config);
21127            for i in 0..5 {
21128                program.model_mut().value = i;
21129                program.render_frame().expect("render frame");
21130            }
21131
21132            let contents = std::fs::read_to_string(&path).unwrap_or_default();
21133            let shadow_count = contents
21134                .lines()
21135                .filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
21136                .filter(|v| v.get("event").and_then(|e| e.as_str()) == Some("shadow_frame"))
21137                .count();
21138            assert_eq!(
21139                shadow_count, 0,
21140                "policy {:?} must not write shadow_frame lines:\n{contents}",
21141                policy
21142            );
21143        }
21144    }
21145
21146    #[test]
21147    fn shadow_frame_checksum_is_deterministic_for_identical_frames() {
21148        let mut checksums_per_run = Vec::new();
21149        for run_idx in 0..2 {
21150            let path = std::env::temp_dir().join(format!(
21151                "ftui_shadow_det_{}_{}_{}.jsonl",
21152                run_idx,
21153                std::process::id(),
21154                std::time::SystemTime::now()
21155                    .duration_since(std::time::UNIX_EPOCH)
21156                    .unwrap_or_default()
21157                    .as_nanos()
21158            ));
21159            let config = ProgramConfig::fullscreen()
21160                .with_lane(RuntimeLane::Structured)
21161                .with_rollout_policy(RolloutPolicy::Shadow)
21162                .with_evidence_sink(crate::evidence_sink::EvidenceSinkConfig::enabled_file(
21163                    &path,
21164                ))
21165                .with_signal_interception(false);
21166
21167            let mut program =
21168                headless_program_with_resolved_config(ShadowVisibleModel { value: 0 }, config);
21169            for step in [10, 20, 30, 40, 50] {
21170                program.model_mut().value = step;
21171                program.render_frame().expect("render frame");
21172            }
21173
21174            let contents = std::fs::read_to_string(&path).expect("read shadow evidence");
21175            let checksums: Vec<String> = contents
21176                .lines()
21177                .filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
21178                .filter(|v| v.get("event").and_then(|e| e.as_str()) == Some("shadow_frame"))
21179                .map(|v| {
21180                    v.get("checksum")
21181                        .and_then(|c| c.as_str())
21182                        .expect("checksum")
21183                        .to_string()
21184                })
21185                .collect();
21186            assert_eq!(checksums.len(), 5);
21187            checksums_per_run.push(checksums);
21188        }
21189        assert_eq!(checksums_per_run[0], checksums_per_run[1]);
21190        assert_ne!(checksums_per_run[0][0], checksums_per_run[0][1]);
21191    }
21192
21193    // =========================================================================
21194    // PersistenceConfig Debug (bd-2yjus)
21195    // =========================================================================
21196
21197    #[test]
21198    fn persistence_config_debug() {
21199        let config = PersistenceConfig::default();
21200        let debug = format!("{config:?}");
21201        assert!(debug.contains("PersistenceConfig"));
21202        assert!(debug.contains("auto_load"));
21203        assert!(debug.contains("auto_save"));
21204    }
21205
21206    // =========================================================================
21207    // FrameTimingConfig (bd-2yjus)
21208    // =========================================================================
21209
21210    #[test]
21211    fn frame_timing_config_debug() {
21212        use std::sync::Arc;
21213
21214        struct DummySink;
21215        impl FrameTimingSink for DummySink {
21216            fn record_frame(&self, _timing: &FrameTiming) {}
21217        }
21218
21219        let config = FrameTimingConfig::new(Arc::new(DummySink));
21220        let debug = format!("{config:?}");
21221        assert!(debug.contains("FrameTimingConfig"));
21222    }
21223
21224    #[test]
21225    fn program_config_with_frame_timing() {
21226        use std::sync::Arc;
21227
21228        struct DummySink;
21229        impl FrameTimingSink for DummySink {
21230            fn record_frame(&self, _timing: &FrameTiming) {}
21231        }
21232
21233        let config =
21234            ProgramConfig::default().with_frame_timing(FrameTimingConfig::new(Arc::new(DummySink)));
21235        assert!(config.frame_timing.is_some());
21236    }
21237
21238    // =========================================================================
21239    // BudgetDecisionEvidence helper functions (bd-2yjus)
21240    // =========================================================================
21241
21242    #[test]
21243    fn budget_decision_evidence_decision_from_levels() {
21244        use ftui_render::budget::DegradationLevel;
21245        // Degrade: after > before
21246        assert_eq!(
21247            BudgetDecisionEvidence::decision_from_levels(
21248                DegradationLevel::Full,
21249                DegradationLevel::SimpleBorders
21250            ),
21251            BudgetDecision::Degrade
21252        );
21253        // Upgrade: after < before
21254        assert_eq!(
21255            BudgetDecisionEvidence::decision_from_levels(
21256                DegradationLevel::SimpleBorders,
21257                DegradationLevel::Full
21258            ),
21259            BudgetDecision::Upgrade
21260        );
21261        // Hold: same
21262        assert_eq!(
21263            BudgetDecisionEvidence::decision_from_levels(
21264                DegradationLevel::Full,
21265                DegradationLevel::Full
21266            ),
21267            BudgetDecision::Hold
21268        );
21269    }
21270
21271    // =========================================================================
21272    // WidgetRefreshPlan (bd-2yjus)
21273    // =========================================================================
21274
21275    #[test]
21276    fn widget_refresh_plan_clear() {
21277        let mut plan = WidgetRefreshPlan::new();
21278        plan.frame_idx = 5;
21279        plan.budget_us = 100.0;
21280        plan.signal_count = 3;
21281        plan.over_budget = true;
21282        plan.clear();
21283        assert_eq!(plan.frame_idx, 0);
21284        assert_eq!(plan.budget_us, 0.0);
21285        assert_eq!(plan.signal_count, 0);
21286        assert!(!plan.over_budget);
21287    }
21288
21289    #[test]
21290    fn widget_refresh_plan_as_budget_empty_signals() {
21291        let plan = WidgetRefreshPlan::new();
21292        let budget = plan.as_budget();
21293        // With signal_count == 0, should be allow_all (allows any widget)
21294        assert!(budget.allows(0, false));
21295        assert!(budget.allows(999, false));
21296    }
21297
21298    #[test]
21299    fn widget_refresh_plan_to_jsonl_structure() {
21300        let plan = WidgetRefreshPlan::new();
21301        let jsonl = plan.to_jsonl();
21302        assert!(jsonl.contains("\"event\":\"widget_refresh\""));
21303        assert!(jsonl.contains("\"frame_idx\":0"));
21304        assert!(jsonl.contains("\"selected\":[]"));
21305    }
21306
21307    // =========================================================================
21308    // BatchController Default trait (bd-2yjus)
21309    // =========================================================================
21310
21311    #[test]
21312    fn batch_controller_default_trait() {
21313        let bc = BatchController::default();
21314        let bc2 = BatchController::new();
21315        // Should be equivalent
21316        assert_eq!(bc.tau_s(), bc2.tau_s());
21317        assert_eq!(bc.observations(), bc2.observations());
21318    }
21319
21320    #[test]
21321    fn batch_controller_observe_arrival_stale_gap_ignored() {
21322        let mut bc = BatchController::new();
21323        let base = Instant::now();
21324        // First arrival
21325        bc.observe_arrival(base);
21326        // Stale gap > 10s should be ignored
21327        bc.observe_arrival(base + Duration::from_secs(15));
21328        assert_eq!(bc.observations(), 0);
21329    }
21330
21331    #[test]
21332    fn batch_controller_observe_service_out_of_range() {
21333        let mut bc = BatchController::new();
21334        let original_service = bc.service_est_s();
21335        // Out-of-range (>= 10s) should be ignored
21336        bc.observe_service(Duration::from_secs(15));
21337        assert_eq!(bc.service_est_s(), original_service);
21338    }
21339
21340    #[test]
21341    fn batch_controller_lambda_zero_inter_arrival() {
21342        // When ema_inter_arrival_s is effectively 0, lambda should be 0
21343        let bc = BatchController {
21344            ema_inter_arrival_s: 0.0,
21345            ..BatchController::new()
21346        };
21347        assert_eq!(bc.lambda_est(), 0.0);
21348    }
21349
21350    // =========================================================================
21351    // Headless program: Cmd::Log with and without trailing newline (bd-2yjus)
21352    // =========================================================================
21353
21354    #[test]
21355    fn headless_execute_cmd_log_appends_newline_if_missing() {
21356        let mut program =
21357            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
21358        program.execute_cmd(Cmd::log("no newline")).expect("log");
21359
21360        let bytes = program.presenter.into_inner().expect("writer output");
21361        let output = String::from_utf8_lossy(&bytes);
21362        // The sanitized output should end with a newline
21363        assert!(output.contains("no newline"));
21364    }
21365
21366    #[test]
21367    fn headless_execute_cmd_log_preserves_trailing_newline() {
21368        let mut program =
21369            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
21370        program
21371            .execute_cmd(Cmd::log("with newline\n"))
21372            .expect("log");
21373
21374        let bytes = program.presenter.into_inner().expect("writer output");
21375        let output = String::from_utf8_lossy(&bytes);
21376        assert!(output.contains("with newline"));
21377    }
21378
21379    #[test]
21380    fn model_log_commands_filter_before_line_formatting() {
21381        let mut program =
21382            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
21383        let mut caps = TerminalCapabilities::basic();
21384        caps.scroll_region = true;
21385        program.presenter = TerminalPresenter::new(TerminalWriter::new(
21386            Vec::new(),
21387            ScreenMode::Inline { ui_height: 3 },
21388            UiAnchor::Bottom,
21389            caps,
21390        ));
21391        program.presenter.set_size(80, 24);
21392        program
21393            .presenter
21394            .present_ui(&Buffer::new(80, 3), None, false)
21395            .expect("establish log region");
21396        assert!(program.presenter.writer.scroll_region_active());
21397        for text in ["first\nsecond", "first\r\nsecond\r\n"] {
21398            program.execute_cmd(Cmd::log(text)).expect("log lines");
21399        }
21400        program
21401            .execute_cmd(Cmd::log("joined\r\x00\nnext"))
21402            .expect("filter before normalizing a revealed CRLF");
21403        program
21404            .execute_cmd(Cmd::log("a\x1b]0;hidden\nline\x07b"))
21405            .expect("filter embedded control newline");
21406        program
21407            .execute_cmd(Cmd::log_sgr_only("\x1b[31mred\x1b[2J\nplain"))
21408            .expect("colored command");
21409        let output = String::from_utf8(program.presenter.into_inner().unwrap()).unwrap();
21410        assert_eq!(output.matches("first\r\nsecond\r\n").count(), 2);
21411        assert!(output.contains("joined\r\nnext\r\n"));
21412        assert!(!output.contains("joined\r\r\n"));
21413        // The sanitizer aborts an OSC at LF, preserving that newline and the
21414        // printable suffix, while stripping the OSC prefix and BEL.
21415        assert!(output.contains("a\r\nlineb\r\n"));
21416        assert!(!output.contains("hidden"));
21417        assert!(!output.contains("\x1b[2J"));
21418        assert!(output.contains("\x1b[31mred\x1b[0m\r\n"));
21419        assert!(output.contains("\x1b[0m\r\nplain\x1b[0m\r\n"));
21420    }
21421
21422    #[test]
21423    fn model_log_command_propagates_output_failure() {
21424        struct FailingWriter;
21425        impl Write for FailingWriter {
21426            fn write(&mut self, _: &[u8]) -> io::Result<usize> {
21427                Err(io::Error::new(
21428                    io::ErrorKind::BrokenPipe,
21429                    "log write failed",
21430                ))
21431            }
21432            fn flush(&mut self) -> io::Result<()> {
21433                Ok(())
21434            }
21435        }
21436        struct LoggingModel;
21437        impl Model for LoggingModel {
21438            type Message = Event;
21439            fn init(&mut self) -> Cmd<Event> {
21440                Cmd::sequence(vec![Cmd::log_sgr_only("\x1b[31mvisible"), Cmd::quit()])
21441            }
21442            fn update(&mut self, _: Event) -> Cmd<Event> {
21443                Cmd::none()
21444            }
21445            fn view(&self, _: &mut Frame) {
21446                panic!("log failure must be returned before rendering");
21447            }
21448        }
21449        let features = BackendFeatures::default();
21450        let config = ProgramConfig {
21451            screen_mode: ScreenMode::Inline { ui_height: 3 },
21452            ..ProgramConfig::default()
21453        }
21454        .with_signal_interception(false);
21455        let writer = TerminalWriter::new(
21456            FailingWriter,
21457            config.screen_mode,
21458            config.ui_anchor,
21459            TerminalCapabilities::basic(),
21460        );
21461        let mut program = Program::with_event_source(
21462            LoggingModel,
21463            HeadlessEventSource::new(80, 24, features),
21464            features,
21465            TerminalPresenter::new(writer),
21466            config,
21467        )
21468        .expect("construct real Program");
21469        assert_eq!(program.run().unwrap_err().kind(), io::ErrorKind::BrokenPipe);
21470    }
21471
21472    // =========================================================================
21473    // Headless program: immediate resize behavior (bd-2yjus)
21474    // =========================================================================
21475
21476    #[test]
21477    fn headless_handle_event_immediate_resize() {
21478        struct ResizeModel {
21479            last_size: Option<(u16, u16)>,
21480        }
21481
21482        #[derive(Debug)]
21483        enum ResizeMsg {
21484            Resize(u16, u16),
21485            Other,
21486        }
21487
21488        impl From<Event> for ResizeMsg {
21489            fn from(event: Event) -> Self {
21490                match event {
21491                    Event::Resize { width, height } => ResizeMsg::Resize(width, height),
21492                    _ => ResizeMsg::Other,
21493                }
21494            }
21495        }
21496
21497        impl Model for ResizeModel {
21498            type Message = ResizeMsg;
21499
21500            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
21501                if let ResizeMsg::Resize(w, h) = msg {
21502                    self.last_size = Some((w, h));
21503                }
21504                Cmd::none()
21505            }
21506
21507            fn view(&self, _frame: &mut Frame) {}
21508        }
21509
21510        let config = ProgramConfig::default().with_resize_behavior(ResizeBehavior::Immediate);
21511        let mut program = headless_program_with_config(ResizeModel { last_size: None }, config);
21512
21513        program
21514            .handle_event(Event::Resize {
21515                width: 120,
21516                height: 40,
21517            })
21518            .expect("handle resize");
21519
21520        assert_eq!(program.width, 120);
21521        assert_eq!(program.height, 40);
21522        assert_eq!(program.model().last_size, Some((120, 40)));
21523    }
21524
21525    // =========================================================================
21526    // Headless program: resize clamps zero dimensions (bd-2yjus)
21527    // =========================================================================
21528
21529    #[test]
21530    fn headless_apply_resize_clamps_zero_to_one() {
21531        struct SimpleModel;
21532
21533        #[derive(Debug)]
21534        enum SimpleMsg {
21535            Noop,
21536        }
21537
21538        impl From<Event> for SimpleMsg {
21539            fn from(_: Event) -> Self {
21540                SimpleMsg::Noop
21541            }
21542        }
21543
21544        impl Model for SimpleModel {
21545            type Message = SimpleMsg;
21546
21547            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
21548                Cmd::none()
21549            }
21550
21551            fn view(&self, _frame: &mut Frame) {}
21552        }
21553
21554        let mut program = headless_program_with_config(SimpleModel, ProgramConfig::default());
21555        program
21556            .apply_resize(0, 0, Duration::ZERO, false)
21557            .expect("resize");
21558
21559        // Zero dimensions should be clamped to 1
21560        assert_eq!(program.width, 1);
21561        assert_eq!(program.height, 1);
21562    }
21563
21564    // =========================================================================
21565    // PaneTerminalAdapter::force_cancel_all (bd-24v9m)
21566    // =========================================================================
21567
21568    #[test]
21569    fn force_cancel_all_idle_returns_none() {
21570        let mut adapter =
21571            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
21572        assert!(adapter.force_cancel_all().is_none());
21573    }
21574
21575    #[test]
21576    fn force_cancel_all_after_pointer_down_returns_diagnostics() {
21577        let mut adapter =
21578            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
21579        let target = pane_target(SplitAxis::Horizontal);
21580
21581        let down = Event::Mouse(MouseEvent::new(
21582            MouseEventKind::Down(MouseButton::Left),
21583            5,
21584            5,
21585        ));
21586        let _ = adapter.translate(&down, Some(target));
21587        assert!(adapter.active_pointer_id().is_some());
21588
21589        let diag = adapter
21590            .force_cancel_all()
21591            .expect("should produce diagnostics");
21592        assert!(diag.had_active_pointer);
21593        assert_eq!(diag.active_pointer_id, Some(1));
21594        assert!(diag.machine_transition.is_some());
21595
21596        // Adapter should be fully idle afterwards
21597        assert_eq!(adapter.active_pointer_id(), None);
21598        assert!(matches!(adapter.machine_state(), PaneDragResizeState::Idle));
21599    }
21600
21601    #[test]
21602    fn force_cancel_all_during_drag_returns_diagnostics() {
21603        let mut adapter =
21604            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
21605        let target = pane_target(SplitAxis::Vertical);
21606
21607        // Down โ†’ arm
21608        let down = Event::Mouse(MouseEvent::new(
21609            MouseEventKind::Down(MouseButton::Left),
21610            3,
21611            3,
21612        ));
21613        let _ = adapter.translate(&down, Some(target));
21614
21615        // Drag โ†’ transition to Dragging
21616        let drag = Event::Mouse(MouseEvent::new(
21617            MouseEventKind::Drag(MouseButton::Left),
21618            8,
21619            3,
21620        ));
21621        let _ = adapter.translate(&drag, None);
21622
21623        let diag = adapter
21624            .force_cancel_all()
21625            .expect("should produce diagnostics");
21626        assert!(diag.had_active_pointer);
21627        assert!(diag.machine_transition.is_some());
21628        let transition = diag.machine_transition.unwrap();
21629        assert!(matches!(
21630            transition.effect,
21631            PaneDragResizeEffect::Canceled {
21632                reason: PaneCancelReason::Programmatic,
21633                ..
21634            }
21635        ));
21636    }
21637
21638    #[test]
21639    fn force_cancel_all_is_idempotent() {
21640        let mut adapter =
21641            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
21642        let target = pane_target(SplitAxis::Horizontal);
21643
21644        let down = Event::Mouse(MouseEvent::new(
21645            MouseEventKind::Down(MouseButton::Left),
21646            5,
21647            5,
21648        ));
21649        let _ = adapter.translate(&down, Some(target));
21650
21651        let first = adapter.force_cancel_all();
21652        assert!(first.is_some());
21653
21654        let second = adapter.force_cancel_all();
21655        assert!(second.is_none());
21656    }
21657
21658    // =========================================================================
21659    // PaneInteractionGuard (bd-24v9m)
21660    // =========================================================================
21661
21662    #[test]
21663    fn pane_interaction_guard_finish_when_idle() {
21664        let mut adapter =
21665            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
21666        let guard = PaneInteractionGuard::new(&mut adapter);
21667        let diag = guard.finish();
21668        assert!(diag.is_none());
21669    }
21670
21671    #[test]
21672    fn pane_interaction_guard_finish_returns_diagnostics() {
21673        let mut adapter =
21674            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
21675        let target = pane_target(SplitAxis::Horizontal);
21676
21677        // Start a drag interaction through the adapter directly
21678        let down = Event::Mouse(MouseEvent::new(
21679            MouseEventKind::Down(MouseButton::Left),
21680            5,
21681            5,
21682        ));
21683        let _ = adapter.translate(&down, Some(target));
21684
21685        let guard = PaneInteractionGuard::new(&mut adapter);
21686        let diag = guard.finish().expect("should produce diagnostics");
21687        assert!(diag.had_active_pointer);
21688        assert_eq!(diag.active_pointer_id, Some(1));
21689    }
21690
21691    #[test]
21692    fn pane_interaction_guard_drop_cancels_active_interaction() {
21693        let mut adapter =
21694            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
21695        let target = pane_target(SplitAxis::Vertical);
21696
21697        let down = Event::Mouse(MouseEvent::new(
21698            MouseEventKind::Down(MouseButton::Left),
21699            7,
21700            7,
21701        ));
21702        let _ = adapter.translate(&down, Some(target));
21703        assert!(adapter.active_pointer_id().is_some());
21704
21705        {
21706            let _guard = PaneInteractionGuard::new(&mut adapter);
21707            // guard drops here without finish()
21708        }
21709
21710        // After guard drop, adapter should be idle
21711        assert_eq!(adapter.active_pointer_id(), None);
21712        assert!(matches!(adapter.machine_state(), PaneDragResizeState::Idle));
21713    }
21714
21715    #[test]
21716    fn pane_interaction_guard_adapter_access_works() {
21717        let mut adapter =
21718            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
21719        let target = pane_target(SplitAxis::Horizontal);
21720
21721        let mut guard = PaneInteractionGuard::new(&mut adapter);
21722
21723        // Use the adapter through the guard
21724        let down = Event::Mouse(MouseEvent::new(
21725            MouseEventKind::Down(MouseButton::Left),
21726            5,
21727            5,
21728        ));
21729        let dispatch = guard.adapter().translate(&down, Some(target));
21730        assert!(dispatch.primary_event.is_some());
21731
21732        // finish should clean up the interaction started through the guard
21733        let diag = guard.finish().expect("should produce diagnostics");
21734        assert!(diag.had_active_pointer);
21735    }
21736
21737    #[test]
21738    fn pane_interaction_guard_finish_then_drop_is_safe() {
21739        let mut adapter =
21740            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
21741        let target = pane_target(SplitAxis::Horizontal);
21742
21743        let down = Event::Mouse(MouseEvent::new(
21744            MouseEventKind::Down(MouseButton::Left),
21745            5,
21746            5,
21747        ));
21748        let _ = adapter.translate(&down, Some(target));
21749
21750        let guard = PaneInteractionGuard::new(&mut adapter);
21751        let _diag = guard.finish();
21752        // guard is consumed by finish(), so drop doesn't double-cancel
21753        // This test proves the API is safe: finish() takes `self` not `&mut self`
21754        assert_eq!(adapter.active_pointer_id(), None);
21755    }
21756
21757    // =========================================================================
21758    // PaneCapabilityMatrix (bd-6u66i)
21759    // =========================================================================
21760
21761    fn caps_modern() -> TerminalCapabilities {
21762        TerminalCapabilities::modern()
21763    }
21764
21765    fn caps_with_mux(
21766        mux: PaneMuxEnvironment,
21767    ) -> ftui_core::terminal_capabilities::TerminalCapabilities {
21768        let mut caps = TerminalCapabilities::modern();
21769        match mux {
21770            PaneMuxEnvironment::Tmux => caps.in_tmux = true,
21771            PaneMuxEnvironment::Screen => caps.in_screen = true,
21772            PaneMuxEnvironment::Zellij => caps.in_zellij = true,
21773            PaneMuxEnvironment::WeztermMux => caps.in_wezterm_mux = true,
21774            PaneMuxEnvironment::None => {}
21775        }
21776        caps
21777    }
21778
21779    #[test]
21780    fn capability_matrix_bare_terminal_modern() {
21781        let caps = caps_modern();
21782        let mat = PaneCapabilityMatrix::from_capabilities(&caps);
21783
21784        assert_eq!(mat.mux, PaneMuxEnvironment::None);
21785        assert!(mat.mouse_sgr);
21786        assert!(mat.mouse_drag_reliable);
21787        assert!(mat.mouse_button_discrimination);
21788        assert!(mat.focus_events);
21789        assert!(mat.unicode_box_drawing);
21790        assert!(mat.true_color);
21791        assert!(!mat.degraded);
21792        assert!(mat.drag_enabled());
21793        assert!(mat.focus_cancel_effective());
21794        assert!(mat.limitations().is_empty());
21795    }
21796
21797    #[test]
21798    fn capability_matrix_tmux() {
21799        let caps = caps_with_mux(PaneMuxEnvironment::Tmux);
21800        let mat = PaneCapabilityMatrix::from_capabilities(&caps);
21801
21802        assert_eq!(mat.mux, PaneMuxEnvironment::Tmux);
21803        // Focus cancel path is conservatively disabled in all muxes.
21804        assert!(mat.mouse_drag_reliable);
21805        assert!(!mat.focus_events);
21806        assert!(mat.drag_enabled());
21807        assert!(!mat.focus_cancel_effective());
21808        assert!(mat.degraded);
21809    }
21810
21811    #[test]
21812    fn capability_matrix_screen_degrades_drag() {
21813        let caps = caps_with_mux(PaneMuxEnvironment::Screen);
21814        let mat = PaneCapabilityMatrix::from_capabilities(&caps);
21815
21816        assert_eq!(mat.mux, PaneMuxEnvironment::Screen);
21817        assert!(!mat.mouse_drag_reliable);
21818        assert!(!mat.focus_events);
21819        assert!(!mat.drag_enabled());
21820        assert!(!mat.focus_cancel_effective());
21821        assert!(mat.degraded);
21822
21823        let lims = mat.limitations();
21824        assert!(lims.iter().any(|l| l.id == "mouse_drag_unreliable"));
21825        assert!(lims.iter().any(|l| l.id == "no_focus_events"));
21826    }
21827
21828    #[test]
21829    fn capability_matrix_zellij() {
21830        let caps = caps_with_mux(PaneMuxEnvironment::Zellij);
21831        let mat = PaneCapabilityMatrix::from_capabilities(&caps);
21832
21833        assert_eq!(mat.mux, PaneMuxEnvironment::Zellij);
21834        assert!(mat.mouse_drag_reliable);
21835        assert!(!mat.focus_events);
21836        assert!(mat.drag_enabled());
21837        assert!(!mat.focus_cancel_effective());
21838        assert!(mat.degraded);
21839    }
21840
21841    #[test]
21842    fn capability_matrix_wezterm_mux_disables_focus_cancel_path() {
21843        let caps = caps_with_mux(PaneMuxEnvironment::WeztermMux);
21844        let mat = PaneCapabilityMatrix::from_capabilities(&caps);
21845
21846        assert_eq!(mat.mux, PaneMuxEnvironment::WeztermMux);
21847        assert!(mat.mouse_drag_reliable);
21848        assert!(!mat.focus_events);
21849        assert!(mat.drag_enabled());
21850        assert!(!mat.focus_cancel_effective());
21851        assert!(mat.degraded);
21852    }
21853
21854    #[test]
21855    fn capability_matrix_no_sgr_mouse() {
21856        let mut caps = caps_modern();
21857        caps.mouse_sgr = false;
21858        let mat = PaneCapabilityMatrix::from_capabilities(&caps);
21859
21860        assert!(!mat.mouse_sgr);
21861        assert!(!mat.mouse_button_discrimination);
21862        assert!(mat.degraded);
21863
21864        let lims = mat.limitations();
21865        assert!(lims.iter().any(|l| l.id == "no_sgr_mouse"));
21866        assert!(lims.iter().any(|l| l.id == "no_button_discrimination"));
21867    }
21868
21869    #[test]
21870    fn capability_matrix_no_focus_events() {
21871        let mut caps = caps_modern();
21872        caps.focus_events = false;
21873        let mat = PaneCapabilityMatrix::from_capabilities(&caps);
21874
21875        assert!(!mat.focus_events);
21876        assert!(!mat.focus_cancel_effective());
21877        assert!(mat.degraded);
21878
21879        let lims = mat.limitations();
21880        assert!(lims.iter().any(|l| l.id == "no_focus_events"));
21881    }
21882
21883    #[test]
21884    fn capability_matrix_dumb_terminal() {
21885        let caps = TerminalCapabilities::dumb();
21886        let mat = PaneCapabilityMatrix::from_capabilities(&caps);
21887
21888        assert_eq!(mat.mux, PaneMuxEnvironment::None);
21889        assert!(!mat.mouse_sgr);
21890        assert!(!mat.focus_events);
21891        assert!(!mat.unicode_box_drawing);
21892        assert!(!mat.true_color);
21893        assert!(mat.degraded);
21894        assert!(mat.limitations().len() >= 3);
21895    }
21896
21897    #[test]
21898    fn capability_matrix_limitations_have_fallbacks() {
21899        let caps = TerminalCapabilities::dumb();
21900        let mat = PaneCapabilityMatrix::from_capabilities(&caps);
21901
21902        for lim in mat.limitations() {
21903            assert!(!lim.id.is_empty());
21904            assert!(!lim.description.is_empty());
21905            assert!(!lim.fallback.is_empty());
21906        }
21907    }
21908
21909    // ========================================================================
21910    // Screen transition detection tests (A.2 + D.3)
21911    // ========================================================================
21912
21913    /// A multi-screen model that implements ScreenTickDispatch, for testing
21914    /// the `check_screen_transition` logic.
21915    struct MultiScreenModel {
21916        active: String,
21917        screens: Vec<String>,
21918        ticked_screens: Vec<(String, u64)>,
21919    }
21920
21921    #[derive(Debug)]
21922    enum MultiScreenMsg {
21923        #[expect(dead_code)]
21924        Event(Event),
21925    }
21926
21927    impl From<Event> for MultiScreenMsg {
21928        fn from(event: Event) -> Self {
21929            MultiScreenMsg::Event(event)
21930        }
21931    }
21932
21933    impl Model for MultiScreenModel {
21934        type Message = MultiScreenMsg;
21935
21936        fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
21937            match msg {
21938                MultiScreenMsg::Event(_) => Cmd::none(),
21939            }
21940        }
21941
21942        fn view(&self, _frame: &mut Frame) {}
21943
21944        fn as_screen_tick_dispatch(
21945            &mut self,
21946        ) -> Option<&mut dyn crate::tick_strategy::ScreenTickDispatch> {
21947            Some(self)
21948        }
21949    }
21950
21951    impl crate::tick_strategy::ScreenTickDispatch for MultiScreenModel {
21952        fn screen_ids(&self) -> Vec<String> {
21953            self.screens.clone()
21954        }
21955
21956        fn active_screen_id(&self) -> String {
21957            self.active.clone()
21958        }
21959
21960        fn tick_screen(&mut self, screen_id: &str, tick_count: u64) {
21961            self.ticked_screens.push((screen_id.to_owned(), tick_count));
21962        }
21963    }
21964
21965    /// Shared log for recording strategy transitions (inspectable after test).
21966    type TransitionLog = Arc<std::sync::Mutex<Vec<(String, String)>>>;
21967
21968    /// A recording tick strategy that logs `on_screen_transition` calls
21969    /// to a shared log that can be inspected from test assertions.
21970    struct RecordingStrategy {
21971        log: TransitionLog,
21972    }
21973
21974    impl RecordingStrategy {
21975        fn new(log: TransitionLog) -> Self {
21976            Self { log }
21977        }
21978    }
21979
21980    impl crate::tick_strategy::TickStrategy for RecordingStrategy {
21981        fn should_tick(
21982            &mut self,
21983            _screen_id: &str,
21984            _tick_count: u64,
21985            _active_screen: &str,
21986        ) -> crate::tick_strategy::TickDecision {
21987            crate::tick_strategy::TickDecision::Skip
21988        }
21989
21990        fn on_screen_transition(&mut self, from: &str, to: &str) {
21991            self.log
21992                .lock()
21993                .unwrap()
21994                .push((from.to_owned(), to.to_owned()));
21995        }
21996
21997        fn name(&self) -> &str {
21998            "Recording"
21999        }
22000
22001        fn debug_stats(&self) -> Vec<(String, String)> {
22002            vec![("strategy".into(), "Recording".into())]
22003        }
22004    }
22005
22006    /// Helper to create a headless Program with a multi-screen model and
22007    /// a recording tick strategy. Returns the program and a shared log of
22008    /// `on_screen_transition` calls for assertions.
22009    fn headless_multi_screen_program(
22010        active: &str,
22011        screens: &[&str],
22012    ) -> (
22013        Program<MultiScreenModel, HeadlessEventSource, TerminalPresenter<Vec<u8>>>,
22014        TransitionLog,
22015    ) {
22016        let model = MultiScreenModel {
22017            active: active.to_owned(),
22018            screens: screens.iter().map(|s| (*s).to_owned()).collect(),
22019            ticked_screens: Vec::new(),
22020        };
22021        let events = HeadlessEventSource::new(80, 24, BackendFeatures::default());
22022        let writer = TerminalWriter::new(
22023            Vec::<u8>::new(),
22024            ScreenMode::AltScreen,
22025            UiAnchor::Bottom,
22026            TerminalCapabilities::dumb(),
22027        );
22028        let config = ProgramConfig {
22029            forced_size: Some((80, 24)),
22030            tick_strategy: Some(crate::tick_strategy::TickStrategyKind::ActiveOnly),
22031            ..ProgramConfig::default()
22032        };
22033        let mut prog = Program::with_event_source(
22034            model,
22035            events,
22036            BackendFeatures::default(),
22037            TerminalPresenter::new(writer),
22038            config,
22039        )
22040        .expect("headless program creation failed");
22041
22042        // Replace the default strategy with our recording strategy.
22043        let log: TransitionLog = Arc::new(std::sync::Mutex::new(Vec::new()));
22044        prog.tick_strategy = Some(Box::new(RecordingStrategy::new(log.clone())));
22045
22046        (prog, log)
22047    }
22048
22049    #[test]
22050    fn check_screen_transition_first_call_records_active() {
22051        let (mut prog, log) = headless_multi_screen_program("A", &["A", "B", "C"]);
22052
22053        assert!(prog.last_active_screen_for_strategy.is_none());
22054        prog.check_screen_transition();
22055        assert_eq!(prog.last_active_screen_for_strategy.as_deref(), Some("A"));
22056
22057        // First observation: no transition event, no force-tick.
22058        assert!(prog.model.ticked_screens.is_empty());
22059        assert!(log.lock().unwrap().is_empty());
22060    }
22061
22062    #[test]
22063    fn check_screen_transition_no_change_is_noop() {
22064        let (mut prog, log) = headless_multi_screen_program("A", &["A", "B", "C"]);
22065
22066        // First call: records.
22067        prog.check_screen_transition();
22068
22069        // Second call with same active screen: no-op.
22070        prog.check_screen_transition();
22071        assert_eq!(prog.last_active_screen_for_strategy.as_deref(), Some("A"));
22072
22073        // No force-tick, no transition notification.
22074        assert!(prog.model.ticked_screens.is_empty());
22075        assert!(log.lock().unwrap().is_empty());
22076    }
22077
22078    #[test]
22079    fn check_screen_transition_detects_switch_and_force_ticks() {
22080        let (mut prog, log) = headless_multi_screen_program("A", &["A", "B", "C"]);
22081
22082        prog.check_screen_transition(); // records "A"
22083
22084        // Simulate model switching to screen "B".
22085        prog.model.active = "B".to_owned();
22086        prog.check_screen_transition();
22087
22088        // D.3: force-tick should have been dispatched for "B".
22089        assert_eq!(prog.model.ticked_screens.len(), 1);
22090        assert_eq!(prog.model.ticked_screens[0].0, "B");
22091
22092        // A.2: strategy should have been notified of A โ†’ B.
22093        let transitions = log.lock().unwrap();
22094        assert_eq!(transitions.len(), 1);
22095        assert_eq!(transitions[0], ("A".to_owned(), "B".to_owned()));
22096
22097        // last_active should now be "B".
22098        assert_eq!(prog.last_active_screen_for_strategy.as_deref(), Some("B"));
22099    }
22100
22101    #[test]
22102    fn check_screen_transition_marks_dirty_on_change() {
22103        let (mut prog, _log) = headless_multi_screen_program("A", &["A", "B"]);
22104
22105        prog.check_screen_transition();
22106        prog.dirty = false;
22107
22108        prog.model.active = "B".to_owned();
22109        prog.check_screen_transition();
22110
22111        assert!(prog.dirty);
22112    }
22113
22114    #[test]
22115    fn check_screen_transition_not_dirty_when_unchanged() {
22116        let (mut prog, _log) = headless_multi_screen_program("A", &["A", "B"]);
22117
22118        prog.check_screen_transition();
22119        prog.dirty = false;
22120
22121        prog.check_screen_transition();
22122
22123        assert!(!prog.dirty);
22124    }
22125
22126    #[test]
22127    fn check_screen_transition_noop_without_strategy() {
22128        let (mut prog, _log) = headless_multi_screen_program("A", &["A", "B"]);
22129
22130        // Remove the tick strategy.
22131        prog.tick_strategy = None;
22132
22133        prog.check_screen_transition();
22134        assert!(prog.last_active_screen_for_strategy.is_none());
22135    }
22136
22137    #[test]
22138    fn check_screen_transition_multiple_switches_notifies_strategy() {
22139        let (mut prog, log) = headless_multi_screen_program("A", &["A", "B", "C"]);
22140
22141        prog.check_screen_transition(); // records "A"
22142
22143        // A โ†’ B
22144        prog.model.active = "B".to_owned();
22145        prog.check_screen_transition();
22146        assert_eq!(prog.model.ticked_screens.len(), 1);
22147        assert_eq!(prog.model.ticked_screens[0].0, "B");
22148
22149        // B โ†’ C
22150        prog.model.active = "C".to_owned();
22151        prog.check_screen_transition();
22152        assert_eq!(prog.model.ticked_screens.len(), 2);
22153        assert_eq!(prog.model.ticked_screens[1].0, "C");
22154
22155        // C โ†’ A
22156        prog.model.active = "A".to_owned();
22157        prog.check_screen_transition();
22158        assert_eq!(prog.model.ticked_screens.len(), 3);
22159        assert_eq!(prog.model.ticked_screens[2].0, "A");
22160
22161        // A.2: strategy should have all three transitions.
22162        let transitions = log.lock().unwrap();
22163        assert_eq!(transitions.len(), 3);
22164        assert_eq!(transitions[0], ("A".to_owned(), "B".to_owned()));
22165        assert_eq!(transitions[1], ("B".to_owned(), "C".to_owned()));
22166        assert_eq!(transitions[2], ("C".to_owned(), "A".to_owned()));
22167    }
22168
22169    #[test]
22170    fn check_screen_transition_uses_current_tick_count() {
22171        let (mut prog, _log) = headless_multi_screen_program("A", &["A", "B"]);
22172        prog.tick_count = 42;
22173
22174        prog.check_screen_transition(); // records "A"
22175
22176        prog.model.active = "B".to_owned();
22177        prog.check_screen_transition();
22178
22179        // Force-tick should use the current tick_count.
22180        assert_eq!(prog.model.ticked_screens[0].1, 42);
22181    }
22182
22183    #[test]
22184    fn check_screen_transition_reconciles_subscriptions_after_force_tick() {
22185        use crate::subscription::{StopSignal, SubId, Subscription, SubscriptionSender};
22186
22187        struct TransitionSubModel {
22188            active: String,
22189            screens: Vec<String>,
22190            subscribed: bool,
22191        }
22192
22193        #[derive(Debug)]
22194        #[allow(dead_code)]
22195        enum TransitionSubMsg {
22196            Event(Event),
22197        }
22198
22199        impl From<Event> for TransitionSubMsg {
22200            fn from(event: Event) -> Self {
22201                Self::Event(event)
22202            }
22203        }
22204
22205        impl Model for TransitionSubModel {
22206            type Message = TransitionSubMsg;
22207
22208            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
22209                Cmd::none()
22210            }
22211
22212            fn view(&self, _frame: &mut Frame) {}
22213
22214            fn subscriptions(&self) -> Vec<Box<dyn Subscription<Self::Message>>> {
22215                if self.subscribed {
22216                    vec![Box::new(TransitionSubscription)]
22217                } else {
22218                    vec![]
22219                }
22220            }
22221
22222            fn as_screen_tick_dispatch(
22223                &mut self,
22224            ) -> Option<&mut dyn crate::tick_strategy::ScreenTickDispatch> {
22225                Some(self)
22226            }
22227        }
22228
22229        impl crate::tick_strategy::ScreenTickDispatch for TransitionSubModel {
22230            fn screen_ids(&self) -> Vec<String> {
22231                self.screens.clone()
22232            }
22233
22234            fn active_screen_id(&self) -> String {
22235                self.active.clone()
22236            }
22237
22238            fn tick_screen(&mut self, screen_id: &str, _tick_count: u64) {
22239                if screen_id == self.active {
22240                    self.subscribed = true;
22241                }
22242            }
22243        }
22244
22245        struct TransitionSubscription;
22246
22247        impl Subscription<TransitionSubMsg> for TransitionSubscription {
22248            fn id(&self) -> SubId {
22249                1
22250            }
22251
22252            fn run(&self, _sender: SubscriptionSender<TransitionSubMsg>, _stop: StopSignal) {}
22253        }
22254
22255        struct TransitionStrategy;
22256
22257        impl crate::tick_strategy::TickStrategy for TransitionStrategy {
22258            fn should_tick(
22259                &mut self,
22260                _screen_id: &str,
22261                _tick_count: u64,
22262                _active_screen: &str,
22263            ) -> crate::tick_strategy::TickDecision {
22264                crate::tick_strategy::TickDecision::Skip
22265            }
22266
22267            fn on_screen_transition(&mut self, _from: &str, _to: &str) {}
22268
22269            fn name(&self) -> &str {
22270                "TransitionStrategy"
22271            }
22272
22273            fn debug_stats(&self) -> Vec<(String, String)> {
22274                vec![]
22275            }
22276        }
22277
22278        let model = TransitionSubModel {
22279            active: "A".to_owned(),
22280            screens: vec!["A".to_owned(), "B".to_owned()],
22281            subscribed: false,
22282        };
22283        let events = HeadlessEventSource::new(80, 24, BackendFeatures::default());
22284        let writer = TerminalWriter::new(
22285            Vec::<u8>::new(),
22286            ScreenMode::AltScreen,
22287            UiAnchor::Bottom,
22288            TerminalCapabilities::dumb(),
22289        );
22290        let config = ProgramConfig::default().with_forced_size(80, 24);
22291
22292        let mut program = Program::with_event_source(
22293            model,
22294            events,
22295            BackendFeatures::default(),
22296            TerminalPresenter::new(writer),
22297            config,
22298        )
22299        .expect("program creation");
22300        program.tick_strategy = Some(Box::new(TransitionStrategy));
22301
22302        program.check_screen_transition();
22303        assert_eq!(program.subscriptions.active_count(), 0);
22304
22305        program.model.active = "B".to_owned();
22306        program.check_screen_transition();
22307
22308        assert!(program.model().subscribed);
22309        assert_eq!(program.subscriptions.active_count(), 1);
22310    }
22311
22312    #[test]
22313    fn tick_strategy_stats_returns_empty_without_strategy() {
22314        let (mut prog, _log) = headless_multi_screen_program("A", &["A", "B"]);
22315        prog.tick_strategy = None;
22316        assert!(prog.tick_strategy_stats().is_empty());
22317    }
22318
22319    #[test]
22320    fn tick_strategy_stats_returns_strategy_fields() {
22321        let (prog, _log) = headless_multi_screen_program("A", &["A", "B"]);
22322        let stats = prog.tick_strategy_stats();
22323        // RecordingStrategy returns [("strategy", "Recording")]
22324        assert!(
22325            !stats.is_empty(),
22326            "stats should not be empty when strategy is configured"
22327        );
22328    }
22329
22330    // =========================================================================
22331    // BackendPresenter decoupling tests (bd-g00-root-epic-ewths.17.7)
22332    // =========================================================================
22333
22334    struct CountingPresenter {
22335        caps: TerminalCapabilities,
22336        pool: ftui_render::grapheme_pool::GraphemePool,
22337        links: ftui_render::link_registry::LinkRegistry,
22338        present_count: usize,
22339        log_lines: Vec<String>,
22340    }
22341
22342    impl CountingPresenter {
22343        fn new() -> Self {
22344            Self {
22345                caps: TerminalCapabilities::basic(),
22346                pool: ftui_render::grapheme_pool::GraphemePool::new(),
22347                links: ftui_render::link_registry::LinkRegistry::new(),
22348                present_count: 0,
22349                log_lines: Vec::new(),
22350            }
22351        }
22352    }
22353
22354    impl BackendPresenter for CountingPresenter {
22355        type Error = io::Error;
22356
22357        fn capabilities(&self) -> &TerminalCapabilities {
22358            &self.caps
22359        }
22360
22361        fn present_ui(
22362            &mut self,
22363            _buf: &Buffer,
22364            _diff: Option<&ftui_render::diff::BufferDiff>,
22365            _full_repaint_hint: bool,
22366        ) -> Result<(), Self::Error> {
22367            self.present_count += 1;
22368            Ok(())
22369        }
22370
22371        fn present_ui_owned(
22372            &mut self,
22373            _buf: Buffer,
22374            _cursor: Option<(u16, u16)>,
22375            _cursor_visible: bool,
22376        ) -> Result<(), Self::Error> {
22377            self.present_count += 1;
22378            Ok(())
22379        }
22380
22381        fn write_log(&mut self, text: &str) -> Result<(), Self::Error> {
22382            self.log_lines.push(text.to_owned());
22383            Ok(())
22384        }
22385
22386        fn write_log_line_with_mode(
22387            &mut self,
22388            text: &str,
22389            _mode: SanitizeMode,
22390        ) -> Result<(), Self::Error> {
22391            self.log_lines.push(text.to_owned());
22392            Ok(())
22393        }
22394
22395        fn pool_and_links_mut(
22396            &mut self,
22397        ) -> (
22398            &mut ftui_render::grapheme_pool::GraphemePool,
22399            &mut ftui_render::link_registry::LinkRegistry,
22400        ) {
22401            (&mut self.pool, &mut self.links)
22402        }
22403
22404        fn pool_mut(&mut self) -> &mut ftui_render::grapheme_pool::GraphemePool {
22405            &mut self.pool
22406        }
22407    }
22408
22409    #[test]
22410    fn program_presents_through_backend_presenter() {
22411        let model = TestModel { value: 42 };
22412        let events = HeadlessEventSource::new(80, 24, BackendFeatures::default());
22413        let presenter = CountingPresenter::new();
22414        let config = ProgramConfig::default().with_forced_size(80, 24);
22415
22416        let mut program = Program::with_event_source(
22417            model,
22418            events,
22419            BackendFeatures::default(),
22420            presenter,
22421            config,
22422        )
22423        .expect("program creation with CountingPresenter");
22424
22425        // Initial render frame calls present_ui / present_ui_owned
22426        program.render_frame().expect("render frame");
22427        assert_eq!(program.presenter.present_count, 1);
22428
22429        // Second render frame increments present count
22430        program.dirty = true;
22431        program.render_frame().expect("second render frame");
22432        assert_eq!(program.presenter.present_count, 2);
22433
22434        // Logging via Cmd::log forwards through write_log / write_log_line_with_mode
22435        program
22436            .execute_cmd(Cmd::log("hello from counting presenter"))
22437            .expect("execute log command");
22438        assert_eq!(program.presenter.log_lines.len(), 1);
22439        assert!(program.presenter.log_lines[0].contains("hello from counting presenter"));
22440    }
22441
22442    #[test]
22443    fn native_and_crossterm_constructors_build_terminal_presenter() {
22444        // Compile-time / type-level verification that DefaultProgram and
22445        // Program::with_config / with_native_backend build Program with TerminalPresenter<Stdout>.
22446
22447        fn assert_uses_terminal_presenter<M: Model, E: BackendEventSource<Error = io::Error>>(
22448            _p: &Program<M, E, TerminalPresenter<Stdout>>,
22449        ) {
22450        }
22451
22452        fn assert_default_program_alias<M: Model>(_p: &DefaultProgram<M>) {
22453            assert_uses_terminal_presenter(_p);
22454        }
22455
22456        let _ = assert_uses_terminal_presenter::<TestModel, CrosstermEventSource>;
22457        let _ = assert_default_program_alias::<TestModel>;
22458
22459        // Also test TerminalPresenter::with_writer type check and basic construction
22460        let sink = Vec::<u8>::new();
22461        let presenter = TerminalPresenter::with_writer(
22462            sink,
22463            ScreenMode::AltScreen,
22464            UiAnchor::Bottom,
22465            TerminalCapabilities::basic(),
22466        );
22467        assert_eq!(presenter.writer.screen_mode(), ScreenMode::AltScreen);
22468    }
22469
22470    // =========================================================================
22471    // Job control: suspend and resume (bd-d4dtr, docs/spec/suspend-resume.md)
22472    // =========================================================================
22473    //
22474    // None of these raise a real stop signal: a stopped test process hangs the
22475    // suite. `stop_process` is replaced with a recorder, and every step of the
22476    // sequence writes to a per-thread log so the ORDER is asserted, which is
22477    // the part that breaks silently (ยง10).
22478
22479    thread_local! {
22480        static JOB_LOG: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };
22481        /// Terminal size the source reports once the process is "continued".
22482        static SIZE_AFTER_STOP: std::cell::Cell<Option<(u16, u16)>> = const { std::cell::Cell::new(None) };
22483    }
22484
22485    fn job_log(entry: impl Into<String>) {
22486        JOB_LOG.with(|log| log.borrow_mut().push(entry.into()));
22487    }
22488
22489    fn take_job_log() -> Vec<String> {
22490        JOB_LOG.with(|log| std::mem::take(&mut *log.borrow_mut()))
22491    }
22492
22493    fn recording_stop(signal: i32) -> io::Result<()> {
22494        job_log(format!("stop({signal})"));
22495        Ok(())
22496    }
22497
22498    fn stop_while_the_terminal_is_resized(signal: i32) -> io::Result<()> {
22499        SIZE_AFTER_STOP.with(|size| size.set(Some((100, 30))));
22500        recording_stop(signal)
22501    }
22502
22503    struct SuspendableSource {
22504        size: (u16, u16),
22505        releases_terminal: bool,
22506    }
22507
22508    impl BackendEventSource for SuspendableSource {
22509        type Error = io::Error;
22510
22511        fn size(&self) -> Result<(u16, u16), io::Error> {
22512            Ok(SIZE_AFTER_STOP
22513                .with(std::cell::Cell::get)
22514                .unwrap_or(self.size))
22515        }
22516
22517        fn set_features(&mut self, _features: BackendFeatures) -> Result<(), io::Error> {
22518            Ok(())
22519        }
22520
22521        fn poll_event(&mut self, _timeout: Duration) -> Result<bool, io::Error> {
22522            Ok(false)
22523        }
22524
22525        fn read_event(&mut self) -> Result<Option<Event>, io::Error> {
22526            Ok(None)
22527        }
22528
22529        fn supports_suspend(&self) -> bool {
22530            true
22531        }
22532
22533        fn suspend(&mut self) -> Result<bool, io::Error> {
22534            job_log("events.suspend");
22535            Ok(self.releases_terminal)
22536        }
22537
22538        fn resume(&mut self) -> Result<(), io::Error> {
22539            job_log("events.resume");
22540            Ok(())
22541        }
22542    }
22543
22544    struct RecordingPresenter(CountingPresenter);
22545
22546    impl BackendPresenter for RecordingPresenter {
22547        type Error = io::Error;
22548
22549        fn capabilities(&self) -> &TerminalCapabilities {
22550            self.0.capabilities()
22551        }
22552
22553        fn write_log(&mut self, text: &str) -> Result<(), Self::Error> {
22554            self.0.write_log(text)
22555        }
22556
22557        fn present_ui(
22558            &mut self,
22559            buf: &Buffer,
22560            diff: Option<&ftui_render::diff::BufferDiff>,
22561            full_repaint_hint: bool,
22562        ) -> Result<(), Self::Error> {
22563            self.0.present_ui(buf, diff, full_repaint_hint)
22564        }
22565
22566        fn resize(&mut self, cols: u16, rows: u16) {
22567            job_log(format!("presenter.resize({cols}x{rows})"));
22568        }
22569
22570        fn suspend(&mut self) -> Result<(), Self::Error> {
22571            job_log("presenter.suspend");
22572            Ok(())
22573        }
22574
22575        fn pool_and_links_mut(
22576            &mut self,
22577        ) -> (
22578            &mut ftui_render::grapheme_pool::GraphemePool,
22579            &mut ftui_render::link_registry::LinkRegistry,
22580        ) {
22581            self.0.pool_and_links_mut()
22582        }
22583
22584        fn pool_mut(&mut self) -> &mut ftui_render::grapheme_pool::GraphemePool {
22585            self.0.pool_mut()
22586        }
22587    }
22588
22589    /// Records every event the model receives, by name.
22590    #[derive(Default)]
22591    struct SeenEvents {
22592        seen: Vec<String>,
22593    }
22594
22595    struct SeenEvent(Event);
22596
22597    impl From<Event> for SeenEvent {
22598        fn from(event: Event) -> Self {
22599            Self(event)
22600        }
22601    }
22602
22603    impl Model for SeenEvents {
22604        type Message = SeenEvent;
22605
22606        fn update(&mut self, msg: SeenEvent) -> Cmd<SeenEvent> {
22607            self.seen.push(match msg.0 {
22608                Event::Resize { width, height } => format!("resize({width}x{height})"),
22609                Event::Key(key) => format!("key({:?},{:?})", key.code, key.modifiers),
22610                other => format!("{other:?}"),
22611            });
22612            Cmd::none()
22613        }
22614
22615        fn view(&self, _frame: &mut Frame) {}
22616    }
22617
22618    fn suspendable_program(
22619        config: ProgramConfig,
22620        releases_terminal: bool,
22621    ) -> Program<SeenEvents, SuspendableSource, RecordingPresenter> {
22622        SIZE_AFTER_STOP.with(|size| size.set(None));
22623        let mut program = Program::with_event_source(
22624            SeenEvents::default(),
22625            SuspendableSource {
22626                size: (80, 24),
22627                releases_terminal,
22628            },
22629            BackendFeatures::default(),
22630            RecordingPresenter(CountingPresenter::new()),
22631            // No OS handlers: stop requests come only from injection.
22632            config.with_signal_interception(false),
22633        )
22634        .expect("program over a suspendable source");
22635        program.stop_process = recording_stop;
22636        take_job_log();
22637        program
22638    }
22639
22640    #[test]
22641    fn stop_request_releases_stops_and_restores_in_order() {
22642        let mut program = suspendable_program(ProgramConfig::default(), true);
22643        program.dirty = false;
22644        program.inject_suspend_signal(20);
22645        program.service_suspend().expect("suspend and resume");
22646
22647        assert_eq!(
22648            take_job_log(),
22649            [
22650                "presenter.suspend",
22651                "events.suspend",
22652                "stop(20)",
22653                "events.resume",
22654                "presenter.resize(80x24)",
22655            ],
22656            "presenter before backend on the way down, backend before repaint on the way up"
22657        );
22658        assert!(program.dirty, "a full repaint follows resume");
22659        assert!(
22660            program.model().seen.is_empty(),
22661            "same size: no Resize for the model"
22662        );
22663
22664        // The request was consumed: a second pass does nothing.
22665        program.service_suspend().expect("idle pass");
22666        assert!(take_job_log().is_empty());
22667    }
22668
22669    #[test]
22670    fn size_change_while_stopped_resizes_the_model_before_the_repaint() {
22671        let mut program = suspendable_program(ProgramConfig::default(), true);
22672        program.stop_process = stop_while_the_terminal_is_resized;
22673        program.inject_suspend_signal(20);
22674        program.service_suspend().expect("suspend and resume");
22675
22676        let log = take_job_log();
22677        assert_eq!(
22678            log.last().map(String::as_str),
22679            Some("presenter.resize(100x30)")
22680        );
22681        assert_eq!(program.model().seen, ["resize(100x30)"]);
22682        assert_eq!((program.width, program.height), (100, 30));
22683    }
22684
22685    #[test]
22686    fn pending_termination_outranks_a_stop_request() {
22687        let mut program = suspendable_program(ProgramConfig::default(), true);
22688        // Observe only this instance's termination slot, never the global one.
22689        program.intercept_signals = true;
22690        program.global_signal_slot = false;
22691        program.inject_termination_signal(15);
22692        program.inject_suspend_signal(20);
22693        program.service_suspend().expect("no suspend");
22694
22695        assert!(
22696            take_job_log().is_empty(),
22697            "exit path wins; nothing is released"
22698        );
22699        assert_eq!(program.pending_termination_signal(), Some(15));
22700    }
22701
22702    #[test]
22703    fn stop_requests_are_ignored_without_job_control() {
22704        let mut program =
22705            suspendable_program(ProgramConfig::default().with_job_control(false), true);
22706        program.inject_suspend_signal(20);
22707        program.service_suspend().expect("ignored");
22708        assert!(take_job_log().is_empty());
22709    }
22710
22711    #[test]
22712    fn a_source_that_releases_nothing_is_never_stopped() {
22713        let mut program = suspendable_program(ProgramConfig::default(), false);
22714        program.dirty = false;
22715        program.inject_suspend_signal(20);
22716        program.service_suspend().expect("no stop");
22717
22718        assert_eq!(
22719            take_job_log(),
22720            [
22721                "presenter.suspend",
22722                "events.suspend",
22723                "presenter.resize(80x24)"
22724            ],
22725            "no stop with the terminal still raw, and a full repaint instead"
22726        );
22727        assert!(program.dirty);
22728    }
22729
22730    #[test]
22731    fn headless_programs_never_suspend() {
22732        let mut program =
22733            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
22734        program.stop_process = recording_stop;
22735        program.inject_suspend_signal(20);
22736        program.service_suspend().expect("ignored");
22737        assert!(take_job_log().is_empty());
22738    }
22739
22740    #[test]
22741    fn ctrl_z_reaches_the_model_unless_suspend_is_opted_into() {
22742        let ctrl_z = || {
22743            Event::Key(
22744                ftui_core::event::KeyEvent::new(KeyCode::Char('z')).with_modifiers(Modifiers::CTRL),
22745            )
22746        };
22747
22748        // Default: Ctrl-Z is an ordinary key (undo in TextArea and the editors).
22749        let mut program = suspendable_program(ProgramConfig::default(), true);
22750        program.handle_event(ctrl_z()).expect("key");
22751        assert_eq!(program.model().seen.len(), 1, "{:?}", program.model().seen);
22752        program.service_suspend().expect("nothing pending");
22753        assert!(take_job_log().is_empty());
22754
22755        // Opted in: the key becomes a SIGTSTP request and the model never sees it.
22756        let mut program =
22757            suspendable_program(ProgramConfig::default().with_ctrl_z_suspend(true), true);
22758        program.handle_event(ctrl_z()).expect("key");
22759        assert!(
22760            program.model().seen.is_empty(),
22761            "{:?}",
22762            program.model().seen
22763        );
22764        program.service_suspend().expect("suspend");
22765        assert!(take_job_log().contains(&format!(
22766            "stop({})",
22767            ftui_core::job_control::KEYBOARD_STOP_SIGNAL
22768        )));
22769
22770        // Other Ctrl chords are untouched.
22771        program
22772            .handle_event(Event::Key(
22773                ftui_core::event::KeyEvent::new(KeyCode::Char('y')).with_modifiers(Modifiers::CTRL),
22774            ))
22775            .expect("key");
22776        assert_eq!(program.model().seen.len(), 1);
22777    }
22778
22779    #[test]
22780    fn suspend_and_resume_write_evidence_rows() {
22781        let path = temp_evidence_path("job_control");
22782        let mut program = suspendable_program(
22783            ProgramConfig::default().with_evidence_sink(EvidenceSinkConfig::enabled_file(&path)),
22784            true,
22785        );
22786        program.stop_process = stop_while_the_terminal_is_resized;
22787        program.inject_suspend_signal(20);
22788        program.service_suspend().expect("suspend and resume");
22789        take_job_log();
22790
22791        let suspend = read_evidence_event(&path, "suspend");
22792        assert_eq!(suspend["signal"], 20);
22793        assert_eq!(
22794            (suspend["cols"].as_u64(), suspend["rows"].as_u64()),
22795            (Some(80), Some(24))
22796        );
22797        assert!(suspend.get("size_changed").is_none());
22798
22799        let resume = read_evidence_event(&path, "resume");
22800        assert_eq!(resume["signal"], 20);
22801        assert_eq!(
22802            (resume["cols"].as_u64(), resume["rows"].as_u64()),
22803            (Some(100), Some(30))
22804        );
22805        assert_eq!(resume["size_changed"], true);
22806    }
22807
22808    #[test]
22809    fn cmd_log_dispatches_to_writer_modes() {
22810        let mut program = headless_program_with_config(
22811            TestModel { value: 0 },
22812            ProgramConfig::inline(3)
22813                .with_budget(FrameBudgetConfig::with_total(Duration::from_secs(5))),
22814        );
22815        program
22816            .execute_cmd(Cmd::log("a\x1b[31mb"))
22817            .expect("sanitized log");
22818        program
22819            .execute_cmd(Cmd::log_sgr_only("c\x1b[31md\x1b[2J"))
22820            .expect("sgr_only log");
22821        program
22822            .execute_cmd(Cmd::log_raw("\x1b[31mz"))
22823            .expect("raw log");
22824        program.render_frame().expect("render_frame flushes logs");
22825
22826        let raw_bytes = program.presenter.into_inner().expect("presenter output");
22827        let out = String::from_utf8_lossy(&raw_bytes).into_owned();
22828        assert!(
22829            out.contains("ab"),
22830            "Sanitized mode must strip escapes from 'a\\x1b[31mb'; out={out:?}"
22831        );
22832        assert!(
22833            out.contains("c\x1b[31md"),
22834            "SgrOnly mode must retain SGR '\\x1b[31m'; out={out:?}"
22835        );
22836        assert!(
22837            !out.contains("\x1b[2J"),
22838            "SgrOnly mode must strip non-SGR '\\x1b[2J'; out={out:?}"
22839        );
22840        assert!(
22841            out.contains("\x1b[31mz"),
22842            "Raw mode must emit '\\x1b[31mz' verbatim; out={out:?}"
22843        );
22844    }
22845}