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;
68use crate::terminal_writer::{RuntimeDiffConfig, ScreenMode, TerminalWriter, UiAnchor};
69use crate::voi_sampling::{VoiConfig, VoiSampler};
70use crate::{BucketKey, ConformalConfig, ConformalPrediction, ConformalPredictor, ConformalStatus};
71#[cfg(feature = "asupersync-executor")]
72use asupersync::runtime::{BlockingTaskHandle, Runtime as AsupersyncRuntime, RuntimeBuilder};
73use ftui_a11y::tree::{A11yTree, A11yTreeBuilder, ScreenReaderAnnouncement, ScreenReaderPolicy};
74use ftui_backend::{BackendEventSource, BackendFeatures};
75use ftui_core::event::{
76    Event, KeyCode, KeyEvent, KeyEventKind, Modifiers, MouseButton, MouseEvent, MouseEventKind,
77};
78#[cfg(feature = "crossterm-compat")]
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::sanitize;
102use std::any::Any;
103use std::collections::HashMap;
104use std::io::{self, Stdout, Write};
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, 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, 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 (FTUI_SYNC_OUTPUT / FTUI_SCROLL_REGION) 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, W>(mut program: Program<M, E, W>) -> io::Result<()>
304where
305    M: Model,
306    E: BackendEventSource<Error = io::Error>,
307    W: Write + Send,
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
548fn signal_termination_from_error(err: &io::Error) -> Option<i32> {
549    err.get_ref()
550        .and_then(|inner| inner.downcast_ref::<SignalTerminationError>())
551        .map(|inner| inner.signal)
552}
553
554/// Sink for frame timing events.
555pub trait FrameTimingSink: Send + Sync {
556    fn record_frame(&self, timing: &FrameTiming);
557}
558
559/// Configuration for frame timing capture.
560#[derive(Clone)]
561pub struct FrameTimingConfig {
562    pub sink: Arc<dyn FrameTimingSink>,
563}
564
565impl FrameTimingConfig {
566    #[must_use]
567    pub fn new(sink: Arc<dyn FrameTimingSink>) -> Self {
568        Self { sink }
569    }
570}
571
572impl std::fmt::Debug for FrameTimingConfig {
573    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
574        f.debug_struct("FrameTimingConfig")
575            .field("sink", &"<dyn FrameTimingSink>")
576            .finish()
577    }
578}
579
580/// Commands represent side effects to be executed by the runtime.
581///
582/// Commands are returned from `init()` and `update()` to trigger
583/// actions like quitting, sending messages, or scheduling ticks.
584#[derive(Default)]
585pub enum Cmd<M> {
586    /// No operation.
587    #[default]
588    None,
589    /// Quit the application.
590    Quit,
591    /// Execute multiple commands as a batch (currently sequential).
592    Batch(Vec<Cmd<M>>),
593    /// Execute commands sequentially.
594    Sequence(Vec<Cmd<M>>),
595    /// Send a message to the model.
596    Msg(M),
597    /// Schedule a tick after a duration.
598    Tick(Duration),
599    /// Write a log message to the terminal output.
600    ///
601    /// This writes to the scrollback region in inline mode, or is ignored/handled
602    /// appropriately in alternate screen mode. Safe to use with the One-Writer Rule.
603    Log(String),
604    /// Execute a blocking operation on a background thread.
605    ///
606    /// When effect queue scheduling is enabled, tasks are enqueued and executed
607    /// in Smith-rule order on a dedicated worker thread. Otherwise the closure
608    /// runs on a spawned thread immediately. The return value is sent back
609    /// as a message to the model.
610    Task(TaskSpec, Box<dyn FnOnce() -> M + Send>),
611    /// Save widget state to the persistence registry.
612    ///
613    /// Triggers a flush of the state registry to the storage backend.
614    /// No-op if persistence is not configured.
615    SaveState,
616    /// Restore widget state from the persistence registry.
617    ///
618    /// Triggers a load from the storage backend and updates the cache.
619    /// No-op if persistence is not configured. Returns a message via
620    /// callback if state was successfully restored.
621    RestoreState,
622    /// Toggle mouse capture at runtime.
623    ///
624    /// Instructs the terminal session to enable or disable mouse event capture.
625    /// No-op in test simulators.
626    SetMouseCapture(bool),
627    /// Replace the tick strategy at runtime.
628    ///
629    /// Takes ownership of a boxed strategy. Use when switching from one
630    /// strategy to another (e.g., `Uniform` → `Predictive` after loading
631    /// persisted transition data).
632    SetTickStrategy(Box<dyn crate::tick_strategy::TickStrategy>),
633}
634
635impl<M: std::fmt::Debug> std::fmt::Debug for Cmd<M> {
636    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
637        match self {
638            Self::None => write!(f, "None"),
639            Self::Quit => write!(f, "Quit"),
640            Self::Batch(cmds) => f.debug_tuple("Batch").field(cmds).finish(),
641            Self::Sequence(cmds) => f.debug_tuple("Sequence").field(cmds).finish(),
642            Self::Msg(m) => f.debug_tuple("Msg").field(m).finish(),
643            Self::Tick(d) => f.debug_tuple("Tick").field(d).finish(),
644            Self::Log(s) => f.debug_tuple("Log").field(s).finish(),
645            Self::Task(spec, _) => f.debug_struct("Task").field("spec", spec).finish(),
646            Self::SaveState => write!(f, "SaveState"),
647            Self::RestoreState => write!(f, "RestoreState"),
648            Self::SetMouseCapture(b) => write!(f, "SetMouseCapture({b})"),
649            Self::SetTickStrategy(s) => write!(f, "SetTickStrategy({})", s.name()),
650        }
651    }
652}
653
654impl<M> Cmd<M> {
655    /// Create a no-op command.
656    #[inline]
657    pub fn none() -> Self {
658        Self::None
659    }
660
661    /// Create a quit command.
662    #[inline]
663    pub fn quit() -> Self {
664        Self::Quit
665    }
666
667    /// Create a message command.
668    #[inline]
669    pub fn msg(m: M) -> Self {
670        Self::Msg(m)
671    }
672
673    /// Create a log command.
674    ///
675    /// The message will be sanitized and written to the terminal log (scrollback).
676    /// A newline is appended if not present.
677    #[inline]
678    pub fn log(msg: impl Into<String>) -> Self {
679        Self::Log(msg.into())
680    }
681
682    /// Create a batch of commands.
683    pub fn batch(cmds: Vec<Self>) -> Self {
684        if cmds.is_empty() {
685            Self::None
686        } else if cmds.len() == 1 {
687            cmds.into_iter().next().unwrap_or(Self::None)
688        } else {
689            Self::Batch(cmds)
690        }
691    }
692
693    /// Create a sequence of commands.
694    pub fn sequence(cmds: Vec<Self>) -> Self {
695        if cmds.is_empty() {
696            Self::None
697        } else if cmds.len() == 1 {
698            cmds.into_iter().next().unwrap_or(Self::None)
699        } else {
700            Self::Sequence(cmds)
701        }
702    }
703
704    /// Return a stable name for telemetry and tracing.
705    #[inline]
706    pub fn type_name(&self) -> &'static str {
707        match self {
708            Self::None => "None",
709            Self::Quit => "Quit",
710            Self::Batch(_) => "Batch",
711            Self::Sequence(_) => "Sequence",
712            Self::Msg(_) => "Msg",
713            Self::Tick(_) => "Tick",
714            Self::Log(_) => "Log",
715            Self::Task(..) => "Task",
716            Self::SaveState => "SaveState",
717            Self::RestoreState => "RestoreState",
718            Self::SetMouseCapture(_) => "SetMouseCapture",
719            Self::SetTickStrategy(_) => "SetTickStrategy",
720        }
721    }
722
723    /// Create a tick command.
724    #[inline]
725    pub fn tick(duration: Duration) -> Self {
726        Self::Tick(duration)
727    }
728
729    /// Create a background task command.
730    ///
731    /// The closure runs on a spawned thread (or the effect queue worker when
732    /// scheduling is enabled). When it completes, the returned message is
733    /// sent back to the model's `update()`.
734    pub fn task<F>(f: F) -> Self
735    where
736        F: FnOnce() -> M + Send + 'static,
737    {
738        Self::Task(TaskSpec::default(), Box::new(f))
739    }
740
741    /// Create a background task command with explicit scheduling metadata.
742    pub fn task_with_spec<F>(spec: TaskSpec, f: F) -> Self
743    where
744        F: FnOnce() -> M + Send + 'static,
745    {
746        Self::Task(spec, Box::new(f))
747    }
748
749    /// Create a background task command with explicit weight and estimate.
750    pub fn task_weighted<F>(weight: f64, estimate_ms: f64, f: F) -> Self
751    where
752        F: FnOnce() -> M + Send + 'static,
753    {
754        Self::Task(TaskSpec::new(weight, estimate_ms), Box::new(f))
755    }
756
757    /// Create a named background task command.
758    pub fn task_named<F>(name: impl Into<String>, f: F) -> Self
759    where
760        F: FnOnce() -> M + Send + 'static,
761    {
762        Self::Task(TaskSpec::default().with_name(name), Box::new(f))
763    }
764
765    /// Replace the active tick strategy at runtime.
766    ///
767    /// Use when switching strategies (e.g., `Uniform` → `Predictive` after
768    /// loading persisted transition data).
769    pub fn set_tick_strategy(strategy: impl crate::tick_strategy::TickStrategy + 'static) -> Self {
770        Self::SetTickStrategy(Box::new(strategy))
771    }
772
773    /// Create a save state command.
774    ///
775    /// Triggers a flush of the state registry to the storage backend.
776    /// No-op if persistence is not configured.
777    #[inline]
778    pub fn save_state() -> Self {
779        Self::SaveState
780    }
781
782    /// Create a restore state command.
783    ///
784    /// Triggers a load from the storage backend.
785    /// No-op if persistence is not configured.
786    #[inline]
787    pub fn restore_state() -> Self {
788        Self::RestoreState
789    }
790
791    /// Create a mouse capture toggle command.
792    ///
793    /// Instructs the runtime to enable or disable mouse event capture on the
794    /// underlying terminal session.
795    #[inline]
796    pub fn set_mouse_capture(enabled: bool) -> Self {
797        Self::SetMouseCapture(enabled)
798    }
799
800    /// Count the number of atomic commands in this command.
801    ///
802    /// Returns 0 for None, 1 for atomic commands, and recursively counts for Batch/Sequence.
803    pub fn count(&self) -> usize {
804        match self {
805            Self::None => 0,
806            Self::Batch(cmds) | Self::Sequence(cmds) => cmds.iter().map(Self::count).sum(),
807            _ => 1,
808        }
809    }
810}
811
812/// Resize handling behavior for the runtime.
813#[derive(Debug, Clone, Copy, PartialEq, Eq)]
814pub enum ResizeBehavior {
815    /// Apply resize immediately (no debounce, no placeholder).
816    Immediate,
817    /// Coalesce resize events for continuous reflow.
818    Throttled,
819}
820
821impl ResizeBehavior {
822    const fn uses_coalescer(self) -> bool {
823        matches!(self, ResizeBehavior::Throttled)
824    }
825}
826
827/// Policy controlling when terminal mouse capture is enabled.
828///
829/// Mouse capture can steal normal scrollback interaction in inline mode.
830/// `Auto` keeps inline mode scrollback-safe while still enabling mouse in
831/// alt-screen mode.
832#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
833pub enum MouseCapturePolicy {
834    /// Enable in alt-screen mode, disable in inline modes.
835    #[default]
836    Auto,
837    /// Always enable mouse capture.
838    On,
839    /// Always disable mouse capture.
840    Off,
841}
842
843impl MouseCapturePolicy {
844    /// Resolve the policy to a concrete mouse-capture toggle.
845    #[must_use]
846    pub const fn resolve(self, screen_mode: ScreenMode) -> bool {
847        match self {
848            Self::Auto => matches!(screen_mode, ScreenMode::AltScreen),
849            Self::On => true,
850            Self::Off => false,
851        }
852    }
853}
854
855const PANE_TERMINAL_DEFAULT_HIT_THICKNESS: u16 = 3;
856const PANE_TERMINAL_TARGET_AXIS_MASK: u64 = 0b1;
857
858/// One splitter handle region in terminal cell-space.
859#[derive(Debug, Clone, Copy, PartialEq, Eq)]
860pub struct PaneTerminalSplitterHandle {
861    /// Semantic resize target represented by this handle.
862    pub target: PaneResizeTarget,
863    /// Cell-space hit rectangle for this handle.
864    pub rect: Rect,
865    /// Split boundary coordinate used for deterministic nearest-target ranking.
866    pub boundary: i32,
867}
868
869/// Build deterministic splitter handle regions for terminal hit-testing.
870///
871/// Handles are emitted in split-id order and are clamped to the split rect.
872#[must_use]
873pub fn pane_terminal_splitter_handles(
874    tree: &PaneTree,
875    layout: &PaneLayout,
876    hit_thickness: u16,
877) -> Vec<PaneTerminalSplitterHandle> {
878    let thickness = if hit_thickness == 0 {
879        PANE_TERMINAL_DEFAULT_HIT_THICKNESS
880    } else {
881        hit_thickness
882    };
883    let mut handles = Vec::new();
884    for node in tree.nodes() {
885        let PaneNodeKind::Split(split) = &node.kind else {
886            continue;
887        };
888        let Some(split_rect) = layout.rect(node.id) else {
889            continue;
890        };
891        if split_rect.is_empty() {
892            continue;
893        }
894        let Some(first_rect) = layout.rect(split.first) else {
895            continue;
896        };
897        let Some(second_rect) = layout.rect(split.second) else {
898            continue;
899        };
900
901        let boundary_u16 = match split.axis {
902            SplitAxis::Horizontal => {
903                // Horizontal split => left/right panes => vertical splitter line.
904                if second_rect.x == split_rect.x {
905                    first_rect.right()
906                } else {
907                    second_rect.x
908                }
909            }
910            SplitAxis::Vertical => {
911                // Vertical split => top/bottom panes => horizontal splitter line.
912                if second_rect.y == split_rect.y {
913                    first_rect.bottom()
914                } else {
915                    second_rect.y
916                }
917            }
918        };
919        let Some(rect) = splitter_hit_rect(split.axis, split_rect, boundary_u16, thickness) else {
920            continue;
921        };
922        handles.push(PaneTerminalSplitterHandle {
923            target: PaneResizeTarget {
924                split_id: node.id,
925                axis: split.axis,
926            },
927            rect,
928            boundary: i32::from(boundary_u16),
929        });
930    }
931    handles
932}
933
934/// Resolve a semantic splitter target from a terminal cell position.
935///
936/// If multiple handles overlap, chooses deterministically by:
937/// 1) smallest distance to the splitter boundary, then
938/// 2) smaller split_id, then
939/// 3) horizontal axis before vertical axis.
940#[must_use]
941pub fn pane_terminal_resolve_splitter_target(
942    handles: &[PaneTerminalSplitterHandle],
943    x: u16,
944    y: u16,
945) -> Option<PaneResizeTarget> {
946    let px = i32::from(x);
947    let py = i32::from(y);
948    let mut best: Option<((u32, u64, u8), PaneResizeTarget)> = None;
949
950    for handle in handles {
951        if !rect_contains_cell(handle.rect, x, y) {
952            continue;
953        }
954        let distance = match handle.target.axis {
955            SplitAxis::Horizontal => px.abs_diff(handle.boundary),
956            SplitAxis::Vertical => py.abs_diff(handle.boundary),
957        };
958        let axis_rank = match handle.target.axis {
959            SplitAxis::Horizontal => 0,
960            SplitAxis::Vertical => 1,
961        };
962        let key = (distance, handle.target.split_id.get(), axis_rank);
963        if best.as_ref().is_none_or(|(best_key, _)| key < *best_key) {
964            best = Some((key, handle.target));
965        }
966    }
967
968    best.map(|(_, target)| target)
969}
970
971/// Register pane splitter handles into the frame hit-grid.
972///
973/// Each handle is registered as `HitRegion::Handle` with encoded target data.
974/// Returns number of successfully-registered regions.
975pub fn register_pane_terminal_splitter_hits(
976    frame: &mut Frame,
977    handles: &[PaneTerminalSplitterHandle],
978    hit_id_base: u32,
979) -> usize {
980    let mut registered = 0usize;
981    for (idx, handle) in handles.iter().enumerate() {
982        let Ok(offset) = u32::try_from(idx) else {
983            break;
984        };
985        let hit_id = HitId::new(hit_id_base.saturating_add(offset));
986        if frame.register_hit(
987            handle.rect,
988            hit_id,
989            HitRegion::Handle,
990            encode_pane_resize_target(handle.target),
991        ) {
992            registered = registered.saturating_add(1);
993        }
994    }
995    registered
996}
997
998/// Decode pane resize target from a hit-grid tuple produced by pane handle registration.
999#[must_use]
1000pub fn pane_terminal_target_from_hit(hit: (HitId, HitRegion, HitData)) -> Option<PaneResizeTarget> {
1001    let (_, region, data) = hit;
1002    if region != HitRegion::Handle {
1003        return None;
1004    }
1005    decode_pane_resize_target(data)
1006}
1007
1008fn splitter_hit_rect(
1009    axis: SplitAxis,
1010    split_rect: Rect,
1011    boundary: u16,
1012    thickness: u16,
1013) -> Option<Rect> {
1014    let half = thickness.saturating_sub(1) / 2;
1015    match axis {
1016        SplitAxis::Horizontal => {
1017            let start = boundary.saturating_sub(half).max(split_rect.x);
1018            let end = boundary
1019                .saturating_add(thickness.saturating_sub(half))
1020                .min(split_rect.right());
1021            let width = end.saturating_sub(start);
1022            (width > 0 && split_rect.height > 0).then_some(Rect::new(
1023                start,
1024                split_rect.y,
1025                width,
1026                split_rect.height,
1027            ))
1028        }
1029        SplitAxis::Vertical => {
1030            let start = boundary.saturating_sub(half).max(split_rect.y);
1031            let end = boundary
1032                .saturating_add(thickness.saturating_sub(half))
1033                .min(split_rect.bottom());
1034            let height = end.saturating_sub(start);
1035            (height > 0 && split_rect.width > 0).then_some(Rect::new(
1036                split_rect.x,
1037                start,
1038                split_rect.width,
1039                height,
1040            ))
1041        }
1042    }
1043}
1044
1045fn rect_contains_cell(rect: Rect, x: u16, y: u16) -> bool {
1046    x >= rect.x && x < rect.right() && y >= rect.y && y < rect.bottom()
1047}
1048
1049fn encode_pane_resize_target(target: PaneResizeTarget) -> HitData {
1050    let axis = match target.axis {
1051        SplitAxis::Horizontal => 0_u64,
1052        SplitAxis::Vertical => PANE_TERMINAL_TARGET_AXIS_MASK,
1053    };
1054    (target.split_id.get() << 1) | axis
1055}
1056
1057fn decode_pane_resize_target(data: HitData) -> Option<PaneResizeTarget> {
1058    let axis = if data & PANE_TERMINAL_TARGET_AXIS_MASK == 0 {
1059        SplitAxis::Horizontal
1060    } else {
1061        SplitAxis::Vertical
1062    };
1063    let split_id = ftui_layout::PaneId::new(data >> 1).ok()?;
1064    Some(PaneResizeTarget { split_id, axis })
1065}
1066
1067// ============================================================================
1068// Pane capability matrix for multiplexer / terminal compat (bd-6u66i)
1069// ============================================================================
1070
1071/// Which multiplexer environment the terminal is running inside.
1072#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1073pub enum PaneMuxEnvironment {
1074    /// No multiplexer detected — direct terminal access.
1075    None,
1076    /// tmux (TMUX env var set, or DA2 terminal type 84).
1077    Tmux,
1078    /// GNU Screen (STY env var set, or DA2 terminal type 83).
1079    Screen,
1080    /// Zellij (ZELLIJ env var set).
1081    Zellij,
1082    /// WezTerm mux-served pane/session.
1083    WeztermMux,
1084}
1085
1086/// Resolved capability matrix describing which pane interaction features
1087/// are available in the current terminal + multiplexer environment.
1088///
1089/// Derived from [`TerminalCapabilities`] via [`PaneCapabilityMatrix::from_capabilities`].
1090/// The adapter uses this to decide which code-paths are safe and which
1091/// need deterministic fallbacks.
1092#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1093pub struct PaneCapabilityMatrix {
1094    /// Detected multiplexer environment.
1095    pub mux: PaneMuxEnvironment,
1096
1097    // --- Mouse input capabilities ---
1098    /// SGR (1006) extended mouse protocol available.
1099    /// Without this, mouse coordinates are limited to 223 columns/rows.
1100    pub mouse_sgr: bool,
1101    /// Mouse drag events are reliably delivered.
1102    /// False in some screen versions where drag tracking is incomplete.
1103    pub mouse_drag_reliable: bool,
1104    /// Mouse button events include correct button identity on release.
1105    /// X10/normal mode sends button 3 for all releases; SGR preserves it.
1106    pub mouse_button_discrimination: bool,
1107
1108    // --- Focus / lifecycle ---
1109    /// Terminal delivers CSI I / CSI O focus events.
1110    pub focus_events: bool,
1111    /// Bracketed paste mode available (affects interaction cancel heuristics).
1112    pub bracketed_paste: bool,
1113
1114    // --- Rendering affordances ---
1115    /// Unicode box-drawing glyphs available for splitter rendering.
1116    pub unicode_box_drawing: bool,
1117    /// True-color support for splitter highlight/drag feedback.
1118    pub true_color: bool,
1119
1120    // --- Fallback summary ---
1121    /// One or more pane features are degraded due to environment constraints.
1122    pub degraded: bool,
1123}
1124
1125/// Human-readable description of a known limitation and its fallback.
1126#[derive(Debug, Clone, PartialEq, Eq)]
1127pub struct PaneCapabilityLimitation {
1128    /// Short identifier (e.g. `"mouse_drag_unreliable"`).
1129    pub id: &'static str,
1130    /// What the limitation is.
1131    pub description: &'static str,
1132    /// What the adapter does instead.
1133    pub fallback: &'static str,
1134}
1135
1136impl PaneCapabilityMatrix {
1137    /// Derive the pane capability matrix from terminal capabilities.
1138    ///
1139    /// This is the single source of truth for which pane features are
1140    /// available. All fallback decisions flow from this matrix.
1141    #[must_use]
1142    pub fn from_capabilities(
1143        caps: &ftui_core::terminal_capabilities::TerminalCapabilities,
1144    ) -> Self {
1145        let mux = if caps.in_tmux {
1146            PaneMuxEnvironment::Tmux
1147        } else if caps.in_screen {
1148            PaneMuxEnvironment::Screen
1149        } else if caps.in_zellij {
1150            PaneMuxEnvironment::Zellij
1151        } else if caps.in_wezterm_mux {
1152            PaneMuxEnvironment::WeztermMux
1153        } else {
1154            PaneMuxEnvironment::None
1155        };
1156
1157        let mouse_sgr = caps.mouse_sgr;
1158
1159        // GNU Screen has historically unreliable drag event delivery.
1160        // tmux and zellij forward drags correctly in modern versions.
1161        let mouse_drag_reliable = !matches!(mux, PaneMuxEnvironment::Screen);
1162
1163        // Button discrimination requires SGR mouse protocol.
1164        // Without it, X10/normal mode reports button 3 for all releases.
1165        let mouse_button_discrimination = mouse_sgr;
1166
1167        // Focus events are conservatively disabled in any mux context.
1168        let focus_events = caps.focus_events && !caps.in_any_mux();
1169
1170        let bracketed_paste = caps.bracketed_paste;
1171        let unicode_box_drawing = caps.unicode_box_drawing;
1172        let true_color = caps.supports_true_color();
1173
1174        let degraded =
1175            !mouse_sgr || !mouse_drag_reliable || !mouse_button_discrimination || !focus_events;
1176
1177        Self {
1178            mux,
1179            mouse_sgr,
1180            mouse_drag_reliable,
1181            mouse_button_discrimination,
1182            focus_events,
1183            bracketed_paste,
1184            unicode_box_drawing,
1185            true_color,
1186            degraded,
1187        }
1188    }
1189
1190    /// Whether pane drag interactions should be enabled at all.
1191    ///
1192    /// Drag requires at minimum mouse event support. If drag events
1193    /// are unreliable (e.g. GNU Screen), drag is disabled and the
1194    /// adapter falls back to keyboard-only resize.
1195    #[must_use]
1196    pub const fn drag_enabled(&self) -> bool {
1197        self.mouse_drag_reliable
1198    }
1199
1200    /// Whether focus-loss auto-cancel is effective.
1201    ///
1202    /// When focus events are unavailable, the adapter cannot detect
1203    /// window blur — interactions must rely on timeout or explicit
1204    /// keyboard cancel instead.
1205    #[must_use]
1206    pub const fn focus_cancel_effective(&self) -> bool {
1207        self.focus_events
1208    }
1209
1210    /// Collect all active limitations with their fallback descriptions.
1211    #[must_use]
1212    pub fn limitations(&self) -> Vec<PaneCapabilityLimitation> {
1213        let mut out = Vec::new();
1214
1215        if !self.mouse_sgr {
1216            out.push(PaneCapabilityLimitation {
1217                id: "no_sgr_mouse",
1218                description: "SGR mouse protocol not available; coordinates limited to 223 columns/rows",
1219                fallback: "Pane splitters beyond column 223 are unreachable by mouse; use keyboard resize",
1220            });
1221        }
1222
1223        if !self.mouse_drag_reliable {
1224            out.push(PaneCapabilityLimitation {
1225                id: "mouse_drag_unreliable",
1226                description: "Mouse drag events are unreliably delivered (e.g. GNU Screen)",
1227                fallback: "Mouse drag disabled; use keyboard arrow keys to resize panes",
1228            });
1229        }
1230
1231        if !self.mouse_button_discrimination {
1232            out.push(PaneCapabilityLimitation {
1233                id: "no_button_discrimination",
1234                description: "Mouse release events do not identify which button was released",
1235                fallback: "Any mouse release cancels the active drag; multi-button interactions unavailable",
1236            });
1237        }
1238
1239        if !self.focus_events {
1240            out.push(PaneCapabilityLimitation {
1241                id: "no_focus_events",
1242                description: "Terminal does not deliver focus-in/focus-out events",
1243                fallback: "Focus-loss auto-cancel disabled; use Escape key to cancel active drag",
1244            });
1245        }
1246
1247        out
1248    }
1249}
1250
1251/// Configuration for terminal-to-pane semantic input translation.
1252///
1253/// This adapter normalizes terminal `Event` streams into
1254/// `PaneSemanticInputEvent` values accepted by `PaneDragResizeMachine`.
1255#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1256pub struct PaneTerminalAdapterConfig {
1257    /// Drag start threshold in pane-local units.
1258    pub drag_threshold: u16,
1259    /// Drag update hysteresis threshold in pane-local units.
1260    pub update_hysteresis: u16,
1261    /// Mouse button required to begin a drag sequence.
1262    pub activation_button: PanePointerButton,
1263    /// Minimum drag delta (Manhattan distance, cells) before forwarding
1264    /// updates while already in the dragging state.
1265    pub drag_update_coalesce_distance: u16,
1266    /// Cancel active interactions on focus loss.
1267    pub cancel_on_focus_lost: bool,
1268    /// Cancel active interactions on terminal resize.
1269    pub cancel_on_resize: bool,
1270}
1271
1272impl Default for PaneTerminalAdapterConfig {
1273    fn default() -> Self {
1274        Self {
1275            drag_threshold: PANE_DRAG_RESIZE_DEFAULT_THRESHOLD,
1276            update_hysteresis: PANE_DRAG_RESIZE_DEFAULT_HYSTERESIS,
1277            activation_button: PanePointerButton::Primary,
1278            drag_update_coalesce_distance: 2,
1279            cancel_on_focus_lost: true,
1280            cancel_on_resize: true,
1281        }
1282    }
1283}
1284
1285#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1286struct PaneTerminalActivePointer {
1287    pointer_id: u32,
1288    target: PaneResizeTarget,
1289    button: PanePointerButton,
1290    last_position: PanePointerPosition,
1291    cumulative_delta_x: i32,
1292    cumulative_delta_y: i32,
1293    direction_changes: u16,
1294    sample_count: u32,
1295    previous_step_delta_x: i32,
1296    previous_step_delta_y: i32,
1297    start_time: Instant,
1298}
1299
1300/// Lifecycle phase observed while translating a terminal event.
1301#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1302pub enum PaneTerminalLifecyclePhase {
1303    MouseDown,
1304    MouseDrag,
1305    MouseMove,
1306    MouseUp,
1307    MouseScroll,
1308    KeyResize,
1309    KeyCancel,
1310    FocusLoss,
1311    ResizeInterrupt,
1312    Other,
1313}
1314
1315/// Deterministic reason a terminal event did not map to pane semantics.
1316#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1317pub enum PaneTerminalIgnoredReason {
1318    MissingTarget,
1319    NoActivePointer,
1320    PointerButtonMismatch,
1321    ActivationButtonRequired,
1322    WindowNotFocused,
1323    UnsupportedKey,
1324    FocusGainNoop,
1325    ResizeNoop,
1326    DragCoalesced,
1327    NonSemanticEvent,
1328    MachineRejectedEvent,
1329}
1330
1331/// Translation outcome for one raw terminal event.
1332#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1333pub enum PaneTerminalLogOutcome {
1334    SemanticForwarded,
1335    SemanticForwardedAfterRecovery,
1336    Ignored(PaneTerminalIgnoredReason),
1337}
1338
1339/// Structured translation log entry for one raw terminal event.
1340#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1341pub struct PaneTerminalLogEntry {
1342    pub phase: PaneTerminalLifecyclePhase,
1343    pub sequence: Option<u64>,
1344    pub pointer_id: Option<u32>,
1345    pub target: Option<PaneResizeTarget>,
1346    pub recovery_cancel_sequence: Option<u64>,
1347    pub outcome: PaneTerminalLogOutcome,
1348}
1349
1350/// Output of one terminal event translation step.
1351///
1352/// `recovery_*` fields are populated when the adapter first emits an internal
1353/// cancel (for stale/missing mouse-up recovery) and then forwards the incoming
1354/// event as a fresh semantic event.
1355#[derive(Debug, Clone, PartialEq)]
1356pub struct PaneTerminalDispatch {
1357    pub primary_event: Option<PaneSemanticInputEvent>,
1358    pub primary_transition: Option<PaneDragResizeTransition>,
1359    pub motion: Option<PaneMotionVector>,
1360    pub inertial_throw: Option<PaneInertialThrow>,
1361    pub projected_position: Option<PanePointerPosition>,
1362    pub recovery_event: Option<PaneSemanticInputEvent>,
1363    pub recovery_transition: Option<PaneDragResizeTransition>,
1364    pub log: PaneTerminalLogEntry,
1365}
1366
1367impl PaneTerminalDispatch {
1368    fn ignored(
1369        phase: PaneTerminalLifecyclePhase,
1370        reason: PaneTerminalIgnoredReason,
1371        pointer_id: Option<u32>,
1372        target: Option<PaneResizeTarget>,
1373    ) -> Self {
1374        Self {
1375            primary_event: None,
1376            primary_transition: None,
1377            motion: None,
1378            inertial_throw: None,
1379            projected_position: None,
1380            recovery_event: None,
1381            recovery_transition: None,
1382            log: PaneTerminalLogEntry {
1383                phase,
1384                sequence: None,
1385                pointer_id,
1386                target,
1387                recovery_cancel_sequence: None,
1388                outcome: PaneTerminalLogOutcome::Ignored(reason),
1389            },
1390        }
1391    }
1392
1393    fn forwarded(
1394        phase: PaneTerminalLifecyclePhase,
1395        pointer_id: Option<u32>,
1396        target: Option<PaneResizeTarget>,
1397        event: PaneSemanticInputEvent,
1398        transition: PaneDragResizeTransition,
1399    ) -> Self {
1400        let sequence = Some(event.sequence);
1401        Self {
1402            primary_event: Some(event),
1403            primary_transition: Some(transition),
1404            motion: None,
1405            inertial_throw: None,
1406            projected_position: None,
1407            recovery_event: None,
1408            recovery_transition: None,
1409            log: PaneTerminalLogEntry {
1410                phase,
1411                sequence,
1412                pointer_id,
1413                target,
1414                recovery_cancel_sequence: None,
1415                outcome: PaneTerminalLogOutcome::SemanticForwarded,
1416            },
1417        }
1418    }
1419
1420    /// Derive dynamic snap profile from translated pointer motion.
1421    #[must_use]
1422    pub fn pressure_snap_profile(&self) -> Option<PanePressureSnapProfile> {
1423        self.motion.map(PanePressureSnapProfile::from_motion)
1424    }
1425}
1426
1427/// Deterministic terminal adapter mapping raw `Event` values into
1428/// schema-validated pane semantic interaction events.
1429#[derive(Debug, Clone)]
1430pub struct PaneTerminalAdapter {
1431    machine: PaneDragResizeMachine,
1432    config: PaneTerminalAdapterConfig,
1433    active: Option<PaneTerminalActivePointer>,
1434    window_focused: bool,
1435    next_sequence: u64,
1436}
1437
1438impl PaneTerminalAdapter {
1439    /// Construct a new adapter with validated drag thresholds.
1440    pub fn new(config: PaneTerminalAdapterConfig) -> Result<Self, PaneDragResizeMachineError> {
1441        let config = PaneTerminalAdapterConfig {
1442            drag_update_coalesce_distance: config.drag_update_coalesce_distance.max(1),
1443            ..config
1444        };
1445        let machine = PaneDragResizeMachine::new_with_hysteresis(
1446            config.drag_threshold,
1447            config.update_hysteresis,
1448        )?;
1449        Ok(Self {
1450            machine,
1451            config,
1452            active: None,
1453            window_focused: true,
1454            next_sequence: 1,
1455        })
1456    }
1457
1458    /// Adapter configuration.
1459    #[must_use]
1460    pub const fn config(&self) -> PaneTerminalAdapterConfig {
1461        self.config
1462    }
1463
1464    /// Active pointer id currently tracked by the adapter, if any.
1465    #[must_use]
1466    pub fn active_pointer_id(&self) -> Option<u32> {
1467        self.active.map(|active| active.pointer_id)
1468    }
1469
1470    /// Whether the host window is currently focused.
1471    #[must_use]
1472    pub const fn window_focused(&self) -> bool {
1473        self.window_focused
1474    }
1475
1476    /// Current pane drag/resize machine state.
1477    #[must_use]
1478    pub const fn machine_state(&self) -> PaneDragResizeState {
1479        self.machine.state()
1480    }
1481
1482    /// Translate one raw terminal event into pane semantic event(s).
1483    ///
1484    /// `target_hint` is provided by host hit-testing (upcoming pane-terminal
1485    /// tasks). Pointer drag/move/up reuse active target continuity once armed.
1486    pub fn translate(
1487        &mut self,
1488        event: &Event,
1489        target_hint: Option<PaneResizeTarget>,
1490    ) -> PaneTerminalDispatch {
1491        match event {
1492            Event::Mouse(mouse) => self.translate_mouse(*mouse, target_hint),
1493            Event::Key(key) => self.translate_key(*key, target_hint),
1494            Event::Focus(focused) => self.translate_focus(*focused),
1495            Event::Resize { .. } => self.translate_resize(),
1496            _ => PaneTerminalDispatch::ignored(
1497                PaneTerminalLifecyclePhase::Other,
1498                PaneTerminalIgnoredReason::NonSemanticEvent,
1499                None,
1500                target_hint,
1501            ),
1502        }
1503    }
1504
1505    /// Translate one raw terminal event while resolving splitter targets from
1506    /// terminal hit regions.
1507    ///
1508    /// This is a convenience wrapper for host code that already has splitter
1509    /// handle regions from [`pane_terminal_splitter_handles`].
1510    pub fn translate_with_handles(
1511        &mut self,
1512        event: &Event,
1513        handles: &[PaneTerminalSplitterHandle],
1514    ) -> PaneTerminalDispatch {
1515        let active_target = self.active.map(|active| active.target);
1516        let target_hint = match event {
1517            Event::Mouse(mouse) => {
1518                let resolved = pane_terminal_resolve_splitter_target(handles, mouse.x, mouse.y);
1519                match mouse.kind {
1520                    MouseEventKind::Down(_)
1521                    | MouseEventKind::ScrollUp
1522                    | MouseEventKind::ScrollDown
1523                    | MouseEventKind::ScrollLeft
1524                    | MouseEventKind::ScrollRight => resolved,
1525                    MouseEventKind::Drag(_) | MouseEventKind::Moved | MouseEventKind::Up(_) => {
1526                        resolved.or(active_target)
1527                    }
1528                }
1529            }
1530            Event::Key(_) => active_target,
1531            _ => None,
1532        };
1533        self.translate(event, target_hint)
1534    }
1535
1536    fn translate_mouse(
1537        &mut self,
1538        mouse: MouseEvent,
1539        target_hint: Option<PaneResizeTarget>,
1540    ) -> PaneTerminalDispatch {
1541        let position = mouse_position(mouse);
1542        let modifiers = pane_modifiers(mouse.modifiers);
1543        match mouse.kind {
1544            MouseEventKind::Down(button) => {
1545                let pane_button = pane_button(button);
1546                if pane_button != self.config.activation_button {
1547                    return PaneTerminalDispatch::ignored(
1548                        PaneTerminalLifecyclePhase::MouseDown,
1549                        PaneTerminalIgnoredReason::ActivationButtonRequired,
1550                        Some(pointer_id_for_button(pane_button)),
1551                        target_hint,
1552                    );
1553                }
1554                let Some(target) = target_hint else {
1555                    return PaneTerminalDispatch::ignored(
1556                        PaneTerminalLifecyclePhase::MouseDown,
1557                        PaneTerminalIgnoredReason::MissingTarget,
1558                        Some(pointer_id_for_button(pane_button)),
1559                        None,
1560                    );
1561                };
1562
1563                let recovery = self.cancel_active_internal(PaneCancelReason::PointerCancel);
1564                let pointer_id = pointer_id_for_button(pane_button);
1565                let kind = PaneSemanticInputEventKind::PointerDown {
1566                    target,
1567                    pointer_id,
1568                    button: pane_button,
1569                    position,
1570                };
1571                let mut dispatch = self.forward_semantic(
1572                    PaneTerminalLifecyclePhase::MouseDown,
1573                    Some(pointer_id),
1574                    Some(target),
1575                    kind,
1576                    modifiers,
1577                );
1578                if dispatch.primary_transition.is_some() {
1579                    self.active = Some(PaneTerminalActivePointer {
1580                        pointer_id,
1581                        target,
1582                        button: pane_button,
1583                        last_position: position,
1584                        cumulative_delta_x: 0,
1585                        cumulative_delta_y: 0,
1586                        direction_changes: 0,
1587                        sample_count: 0,
1588                        previous_step_delta_x: 0,
1589                        previous_step_delta_y: 0,
1590                        start_time: Instant::now(),
1591                    });
1592                }
1593                if let Some((cancel_event, cancel_transition)) = recovery {
1594                    dispatch.recovery_event = Some(cancel_event);
1595                    dispatch.recovery_transition = Some(cancel_transition);
1596                    dispatch.log.recovery_cancel_sequence =
1597                        dispatch.recovery_event.as_ref().map(|event| event.sequence);
1598                    if matches!(
1599                        dispatch.log.outcome,
1600                        PaneTerminalLogOutcome::SemanticForwarded
1601                    ) {
1602                        dispatch.log.outcome =
1603                            PaneTerminalLogOutcome::SemanticForwardedAfterRecovery;
1604                    }
1605                }
1606                dispatch
1607            }
1608            MouseEventKind::Drag(button) => {
1609                let pane_button = pane_button(button);
1610                let Some(active) = self.active else {
1611                    return PaneTerminalDispatch::ignored(
1612                        PaneTerminalLifecyclePhase::MouseDrag,
1613                        PaneTerminalIgnoredReason::NoActivePointer,
1614                        Some(pointer_id_for_button(pane_button)),
1615                        target_hint,
1616                    );
1617                };
1618                if active.button != pane_button {
1619                    return PaneTerminalDispatch::ignored(
1620                        PaneTerminalLifecyclePhase::MouseDrag,
1621                        PaneTerminalIgnoredReason::PointerButtonMismatch,
1622                        Some(pointer_id_for_button(pane_button)),
1623                        Some(active.target),
1624                    );
1625                }
1626                self.apply_pointer_motion(
1627                    active,
1628                    position,
1629                    modifiers,
1630                    PaneTerminalLifecyclePhase::MouseDrag,
1631                )
1632            }
1633            MouseEventKind::Moved => {
1634                let Some(active) = self.active else {
1635                    return PaneTerminalDispatch::ignored(
1636                        PaneTerminalLifecyclePhase::MouseMove,
1637                        PaneTerminalIgnoredReason::NoActivePointer,
1638                        None,
1639                        target_hint,
1640                    );
1641                };
1642                self.apply_pointer_motion(
1643                    active,
1644                    position,
1645                    modifiers,
1646                    PaneTerminalLifecyclePhase::MouseMove,
1647                )
1648            }
1649            MouseEventKind::Up(button) => {
1650                let pane_button = pane_button(button);
1651                let Some(active) = self.active else {
1652                    return PaneTerminalDispatch::ignored(
1653                        PaneTerminalLifecyclePhase::MouseUp,
1654                        PaneTerminalIgnoredReason::NoActivePointer,
1655                        Some(pointer_id_for_button(pane_button)),
1656                        target_hint,
1657                    );
1658                };
1659                if active.button != pane_button {
1660                    return PaneTerminalDispatch::ignored(
1661                        PaneTerminalLifecyclePhase::MouseUp,
1662                        PaneTerminalIgnoredReason::PointerButtonMismatch,
1663                        Some(pointer_id_for_button(pane_button)),
1664                        Some(active.target),
1665                    );
1666                }
1667                let kind = PaneSemanticInputEventKind::PointerUp {
1668                    target: active.target,
1669                    pointer_id: active.pointer_id,
1670                    button: active.button,
1671                    position,
1672                };
1673                let mut dispatch = self.forward_semantic(
1674                    PaneTerminalLifecyclePhase::MouseUp,
1675                    Some(active.pointer_id),
1676                    Some(active.target),
1677                    kind,
1678                    modifiers,
1679                );
1680                if dispatch.primary_transition.is_some() {
1681                    let duration = active.start_time.elapsed().as_millis() as u32;
1682                    let motion = PaneMotionVector::from_delta(
1683                        active.cumulative_delta_x,
1684                        active.cumulative_delta_y,
1685                        duration,
1686                        active.direction_changes,
1687                    );
1688                    let inertial_throw = PaneInertialThrow::from_motion(motion);
1689                    dispatch.motion = Some(motion);
1690                    dispatch.projected_position = Some(inertial_throw.projected_pointer(position));
1691                    dispatch.inertial_throw = Some(inertial_throw);
1692                    self.active = None;
1693                }
1694                dispatch
1695            }
1696            MouseEventKind::ScrollUp
1697            | MouseEventKind::ScrollDown
1698            | MouseEventKind::ScrollLeft
1699            | MouseEventKind::ScrollRight => {
1700                let target = target_hint.or(self.active.map(|active| active.target));
1701                let Some(target) = target else {
1702                    return PaneTerminalDispatch::ignored(
1703                        PaneTerminalLifecyclePhase::MouseScroll,
1704                        PaneTerminalIgnoredReason::MissingTarget,
1705                        None,
1706                        None,
1707                    );
1708                };
1709                let lines = match mouse.kind {
1710                    MouseEventKind::ScrollUp | MouseEventKind::ScrollLeft => -1,
1711                    MouseEventKind::ScrollDown | MouseEventKind::ScrollRight => 1,
1712                    _ => unreachable!("handled by outer match"),
1713                };
1714                let kind = PaneSemanticInputEventKind::WheelNudge { target, lines };
1715                self.forward_semantic(
1716                    PaneTerminalLifecyclePhase::MouseScroll,
1717                    None,
1718                    Some(target),
1719                    kind,
1720                    modifiers,
1721                )
1722            }
1723        }
1724    }
1725
1726    /// Shared motion bookkeeping for the `Drag` and `Moved` mouse arms.
1727    ///
1728    /// Once each arm's arm-specific guards pass (`Drag` additionally checks the
1729    /// pressed button), both perform byte-identical work: compute the step
1730    /// delta, honor drag coalescing, fold direction-change and cumulative-motion
1731    /// tracking into `active`, forward a `PointerMove`, and — only on a committed
1732    /// transition — advance `last_position` and attach the motion vector. The
1733    /// sole caller-specific input is `phase` (`MouseDrag` vs `MouseMove`), used
1734    /// for both the coalesced-ignore and the forwarded event so each caller's
1735    /// diagnostics are unchanged. This is a pure extraction of the two
1736    /// previously-duplicated arm bodies — event ordering and semantics are
1737    /// identical, and the single shared path is cheaper to audit and roll back.
1738    fn apply_pointer_motion(
1739        &mut self,
1740        mut active: PaneTerminalActivePointer,
1741        position: PanePointerPosition,
1742        modifiers: PaneModifierSnapshot,
1743        phase: PaneTerminalLifecyclePhase,
1744    ) -> PaneTerminalDispatch {
1745        let delta_x = position.x.saturating_sub(active.last_position.x);
1746        let delta_y = position.y.saturating_sub(active.last_position.y);
1747        if self.should_coalesce_drag(delta_x, delta_y) {
1748            return PaneTerminalDispatch::ignored(
1749                phase,
1750                PaneTerminalIgnoredReason::DragCoalesced,
1751                Some(active.pointer_id),
1752                Some(active.target),
1753            );
1754        }
1755        if active.sample_count > 0 {
1756            let flipped_x = delta_x.signum() != 0
1757                && active.previous_step_delta_x.signum() != 0
1758                && delta_x.signum() != active.previous_step_delta_x.signum();
1759            let flipped_y = delta_y.signum() != 0
1760                && active.previous_step_delta_y.signum() != 0
1761                && delta_y.signum() != active.previous_step_delta_y.signum();
1762            if flipped_x || flipped_y {
1763                active.direction_changes = active.direction_changes.saturating_add(1);
1764            }
1765        }
1766        active.cumulative_delta_x = active.cumulative_delta_x.saturating_add(delta_x);
1767        active.cumulative_delta_y = active.cumulative_delta_y.saturating_add(delta_y);
1768        active.sample_count = active.sample_count.saturating_add(1);
1769        active.previous_step_delta_x = delta_x;
1770        active.previous_step_delta_y = delta_y;
1771        let kind = PaneSemanticInputEventKind::PointerMove {
1772            target: active.target,
1773            pointer_id: active.pointer_id,
1774            position,
1775            delta_x,
1776            delta_y,
1777        };
1778        let mut dispatch = self.forward_semantic(
1779            phase,
1780            Some(active.pointer_id),
1781            Some(active.target),
1782            kind,
1783            modifiers,
1784        );
1785        if dispatch.primary_transition.is_some() {
1786            active.last_position = position;
1787            self.active = Some(active);
1788            let duration = active.start_time.elapsed().as_millis() as u32;
1789            dispatch.motion = Some(PaneMotionVector::from_delta(
1790                active.cumulative_delta_x,
1791                active.cumulative_delta_y,
1792                duration,
1793                active.direction_changes,
1794            ));
1795        }
1796        dispatch
1797    }
1798
1799    fn translate_key(
1800        &mut self,
1801        key: KeyEvent,
1802        target_hint: Option<PaneResizeTarget>,
1803    ) -> PaneTerminalDispatch {
1804        if !self.window_focused {
1805            return PaneTerminalDispatch::ignored(
1806                PaneTerminalLifecyclePhase::KeyResize,
1807                PaneTerminalIgnoredReason::WindowNotFocused,
1808                self.active_pointer_id(),
1809                target_hint.or(self.active.map(|active| active.target)),
1810            );
1811        }
1812        if key.kind == KeyEventKind::Release {
1813            return PaneTerminalDispatch::ignored(
1814                PaneTerminalLifecyclePhase::Other,
1815                PaneTerminalIgnoredReason::UnsupportedKey,
1816                None,
1817                target_hint,
1818            );
1819        }
1820        if matches!(key.code, KeyCode::Escape) {
1821            return self.cancel_active_dispatch(
1822                PaneTerminalLifecyclePhase::KeyCancel,
1823                PaneCancelReason::EscapeKey,
1824                PaneTerminalIgnoredReason::NoActivePointer,
1825            );
1826        }
1827        let target = target_hint.or(self.active.map(|active| active.target));
1828        let Some(target) = target else {
1829            return PaneTerminalDispatch::ignored(
1830                PaneTerminalLifecyclePhase::KeyResize,
1831                PaneTerminalIgnoredReason::MissingTarget,
1832                None,
1833                None,
1834            );
1835        };
1836        let Some(direction) = keyboard_resize_direction(key.code, target.axis) else {
1837            return PaneTerminalDispatch::ignored(
1838                PaneTerminalLifecyclePhase::KeyResize,
1839                PaneTerminalIgnoredReason::UnsupportedKey,
1840                None,
1841                Some(target),
1842            );
1843        };
1844        let units = keyboard_resize_units(key.modifiers);
1845        let kind = PaneSemanticInputEventKind::KeyboardResize {
1846            target,
1847            direction,
1848            units,
1849        };
1850        self.forward_semantic(
1851            PaneTerminalLifecyclePhase::KeyResize,
1852            self.active_pointer_id(),
1853            Some(target),
1854            kind,
1855            pane_modifiers(key.modifiers),
1856        )
1857    }
1858
1859    fn translate_focus(&mut self, focused: bool) -> PaneTerminalDispatch {
1860        if focused {
1861            self.window_focused = true;
1862            return PaneTerminalDispatch::ignored(
1863                PaneTerminalLifecyclePhase::Other,
1864                PaneTerminalIgnoredReason::FocusGainNoop,
1865                self.active_pointer_id(),
1866                self.active.map(|active| active.target),
1867            );
1868        }
1869        self.window_focused = false;
1870        if !self.config.cancel_on_focus_lost {
1871            return PaneTerminalDispatch::ignored(
1872                PaneTerminalLifecyclePhase::FocusLoss,
1873                PaneTerminalIgnoredReason::ResizeNoop,
1874                self.active_pointer_id(),
1875                self.active.map(|active| active.target),
1876            );
1877        }
1878        self.cancel_active_dispatch(
1879            PaneTerminalLifecyclePhase::FocusLoss,
1880            PaneCancelReason::FocusLost,
1881            PaneTerminalIgnoredReason::NoActivePointer,
1882        )
1883    }
1884
1885    fn translate_resize(&mut self) -> PaneTerminalDispatch {
1886        if !self.config.cancel_on_resize {
1887            return PaneTerminalDispatch::ignored(
1888                PaneTerminalLifecyclePhase::ResizeInterrupt,
1889                PaneTerminalIgnoredReason::ResizeNoop,
1890                self.active_pointer_id(),
1891                self.active.map(|active| active.target),
1892            );
1893        }
1894        self.cancel_active_dispatch(
1895            PaneTerminalLifecyclePhase::ResizeInterrupt,
1896            PaneCancelReason::Programmatic,
1897            PaneTerminalIgnoredReason::ResizeNoop,
1898        )
1899    }
1900
1901    fn cancel_active_dispatch(
1902        &mut self,
1903        phase: PaneTerminalLifecyclePhase,
1904        reason: PaneCancelReason,
1905        no_active_reason: PaneTerminalIgnoredReason,
1906    ) -> PaneTerminalDispatch {
1907        let Some(active) = self.active else {
1908            return PaneTerminalDispatch::ignored(phase, no_active_reason, None, None);
1909        };
1910        let kind = PaneSemanticInputEventKind::Cancel {
1911            target: Some(active.target),
1912            reason,
1913        };
1914        let dispatch = self.forward_semantic(
1915            phase,
1916            Some(active.pointer_id),
1917            Some(active.target),
1918            kind,
1919            PaneModifierSnapshot::default(),
1920        );
1921        if dispatch.primary_transition.is_some() {
1922            self.active = None;
1923        }
1924        dispatch
1925    }
1926
1927    fn cancel_active_internal(
1928        &mut self,
1929        reason: PaneCancelReason,
1930    ) -> Option<(PaneSemanticInputEvent, PaneDragResizeTransition)> {
1931        let active = self.active?;
1932        let kind = PaneSemanticInputEventKind::Cancel {
1933            target: Some(active.target),
1934            reason,
1935        };
1936        let result = self
1937            .apply_semantic(kind, PaneModifierSnapshot::default())
1938            .ok();
1939        if result.is_some() {
1940            self.active = None;
1941        }
1942        result
1943    }
1944
1945    fn forward_semantic(
1946        &mut self,
1947        phase: PaneTerminalLifecyclePhase,
1948        pointer_id: Option<u32>,
1949        target: Option<PaneResizeTarget>,
1950        kind: PaneSemanticInputEventKind,
1951        modifiers: PaneModifierSnapshot,
1952    ) -> PaneTerminalDispatch {
1953        match self.apply_semantic(kind, modifiers) {
1954            Ok((event, transition)) => {
1955                PaneTerminalDispatch::forwarded(phase, pointer_id, target, event, transition)
1956            }
1957            Err(_) => PaneTerminalDispatch::ignored(
1958                phase,
1959                PaneTerminalIgnoredReason::MachineRejectedEvent,
1960                pointer_id,
1961                target,
1962            ),
1963        }
1964    }
1965
1966    fn apply_semantic(
1967        &mut self,
1968        kind: PaneSemanticInputEventKind,
1969        modifiers: PaneModifierSnapshot,
1970    ) -> Result<(PaneSemanticInputEvent, PaneDragResizeTransition), PaneDragResizeMachineError>
1971    {
1972        let mut event = PaneSemanticInputEvent::new(self.next_sequence(), kind);
1973        event.modifiers = modifiers;
1974        let transition = self.machine.apply_event(&event)?;
1975        Ok((event, transition))
1976    }
1977
1978    fn next_sequence(&mut self) -> u64 {
1979        let sequence = self.next_sequence;
1980        self.next_sequence = self.next_sequence.saturating_add(1);
1981        sequence
1982    }
1983
1984    fn should_coalesce_drag(&self, delta_x: i32, delta_y: i32) -> bool {
1985        if !matches!(self.machine.state(), PaneDragResizeState::Dragging { .. }) {
1986            return false;
1987        }
1988        let movement = delta_x
1989            .unsigned_abs()
1990            .saturating_add(delta_y.unsigned_abs());
1991        movement < u32::from(self.config.drag_update_coalesce_distance)
1992    }
1993
1994    /// Force-cancel any active pane interaction and return diagnostic info.
1995    ///
1996    /// This is the safety-valve for cleanup paths (RAII guard drops, signal
1997    /// handlers, panic hooks) where constructing a proper semantic event is
1998    /// not feasible. It resets both the underlying drag/resize state machine
1999    /// and the adapter's active-pointer tracking.
2000    ///
2001    /// Returns `None` if no interaction was active.
2002    pub fn force_cancel_all(&mut self) -> Option<PaneCleanupDiagnostics> {
2003        let was_active = self.active.is_some();
2004        let machine_state_before = self.machine.state();
2005        let machine_transition = self.machine.force_cancel();
2006        let active_pointer = self.active.take();
2007        if !was_active && machine_transition.is_none() {
2008            return None;
2009        }
2010        Some(PaneCleanupDiagnostics {
2011            had_active_pointer: was_active,
2012            active_pointer_id: active_pointer.map(|a| a.pointer_id),
2013            machine_state_before,
2014            machine_transition,
2015        })
2016    }
2017}
2018
2019/// Structured diagnostics emitted when pane interaction state is force-cleaned.
2020///
2021/// Fields mirror the pane layout types which are already `Serialize`/`Deserialize`,
2022/// so callers can convert this struct to JSON for evidence logging.
2023#[derive(Debug, Clone, PartialEq, Eq)]
2024pub struct PaneCleanupDiagnostics {
2025    /// Whether the adapter had an active pointer tracker when cleanup ran.
2026    pub had_active_pointer: bool,
2027    /// The pointer ID that was active (if any).
2028    pub active_pointer_id: Option<u32>,
2029    /// The machine state before force-cancel was applied.
2030    pub machine_state_before: PaneDragResizeState,
2031    /// The transition produced by force-cancel, or `None` if the machine
2032    /// was already idle.
2033    pub machine_transition: Option<PaneDragResizeTransition>,
2034}
2035
2036/// RAII guard that ensures pane interaction state is cleanly canceled on drop.
2037///
2038/// When a pane interaction session is active and the guard drops (due to
2039/// panic, scope exit, or any other unwind), it force-cancels any in-progress
2040/// drag/resize and collects cleanup diagnostics.
2041///
2042/// # Usage
2043///
2044/// ```ignore
2045/// let guard = PaneInteractionGuard::new(&mut adapter);
2046/// // ... pane interaction event loop ...
2047/// // If this scope panics, guard's Drop will force-cancel the drag machine
2048/// let diagnostics = guard.finish(); // explicit clean finish
2049/// ```
2050pub struct PaneInteractionGuard<'a> {
2051    adapter: &'a mut PaneTerminalAdapter,
2052    finished: bool,
2053    diagnostics: Option<PaneCleanupDiagnostics>,
2054}
2055
2056impl<'a> PaneInteractionGuard<'a> {
2057    /// Create a new guard wrapping the given adapter.
2058    pub fn new(adapter: &'a mut PaneTerminalAdapter) -> Self {
2059        Self {
2060            adapter,
2061            finished: false,
2062            diagnostics: None,
2063        }
2064    }
2065
2066    /// Access the wrapped adapter for normal event translation.
2067    pub fn adapter(&mut self) -> &mut PaneTerminalAdapter {
2068        self.adapter
2069    }
2070
2071    /// Explicitly finish the guard, returning any cleanup diagnostics.
2072    ///
2073    /// Calling `finish()` is optional — the guard will also clean up on drop.
2074    /// However, `finish()` gives the caller access to the diagnostics.
2075    pub fn finish(mut self) -> Option<PaneCleanupDiagnostics> {
2076        self.finished = true;
2077        let diagnostics = self.adapter.force_cancel_all();
2078        self.diagnostics = diagnostics.clone();
2079        diagnostics
2080    }
2081}
2082
2083impl Drop for PaneInteractionGuard<'_> {
2084    fn drop(&mut self) {
2085        if !self.finished {
2086            self.diagnostics = self.adapter.force_cancel_all();
2087        }
2088    }
2089}
2090
2091fn pane_button(button: MouseButton) -> PanePointerButton {
2092    match button {
2093        MouseButton::Left => PanePointerButton::Primary,
2094        MouseButton::Right => PanePointerButton::Secondary,
2095        MouseButton::Middle => PanePointerButton::Middle,
2096    }
2097}
2098
2099fn pointer_id_for_button(button: PanePointerButton) -> u32 {
2100    match button {
2101        PanePointerButton::Primary => 1,
2102        PanePointerButton::Secondary => 2,
2103        PanePointerButton::Middle => 3,
2104    }
2105}
2106
2107fn mouse_position(mouse: MouseEvent) -> PanePointerPosition {
2108    PanePointerPosition::new(i32::from(mouse.x), i32::from(mouse.y))
2109}
2110
2111fn pane_modifiers(modifiers: Modifiers) -> PaneModifierSnapshot {
2112    PaneModifierSnapshot {
2113        shift: modifiers.contains(Modifiers::SHIFT),
2114        alt: modifiers.contains(Modifiers::ALT),
2115        ctrl: modifiers.contains(Modifiers::CTRL),
2116        meta: modifiers.contains(Modifiers::SUPER),
2117    }
2118}
2119
2120fn keyboard_resize_direction(code: KeyCode, axis: SplitAxis) -> Option<PaneResizeDirection> {
2121    match (axis, code) {
2122        (SplitAxis::Horizontal, KeyCode::Left) => Some(PaneResizeDirection::Decrease),
2123        (SplitAxis::Horizontal, KeyCode::Right) => Some(PaneResizeDirection::Increase),
2124        (SplitAxis::Vertical, KeyCode::Up) => Some(PaneResizeDirection::Decrease),
2125        (SplitAxis::Vertical, KeyCode::Down) => Some(PaneResizeDirection::Increase),
2126        (_, KeyCode::Char('-')) => Some(PaneResizeDirection::Decrease),
2127        (_, KeyCode::Char('+') | KeyCode::Char('=')) => Some(PaneResizeDirection::Increase),
2128        _ => None,
2129    }
2130}
2131
2132fn keyboard_resize_units(modifiers: Modifiers) -> u16 {
2133    if modifiers.contains(Modifiers::SHIFT) {
2134        5
2135    } else {
2136        1
2137    }
2138}
2139
2140/// Configuration for state persistence in the program runtime.
2141///
2142/// Controls when and how widget state is saved/restored.
2143#[derive(Clone)]
2144pub struct PersistenceConfig {
2145    /// State registry for persistence. If None, persistence is disabled.
2146    pub registry: Option<std::sync::Arc<StateRegistry>>,
2147    /// Interval for periodic checkpoint saves. None disables checkpoints.
2148    pub checkpoint_interval: Option<Duration>,
2149    /// Automatically load state on program start.
2150    pub auto_load: bool,
2151    /// Automatically save state on program exit.
2152    pub auto_save: bool,
2153}
2154
2155impl Default for PersistenceConfig {
2156    fn default() -> Self {
2157        Self {
2158            registry: None,
2159            checkpoint_interval: None,
2160            auto_load: true,
2161            auto_save: true,
2162        }
2163    }
2164}
2165
2166impl std::fmt::Debug for PersistenceConfig {
2167    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2168        f.debug_struct("PersistenceConfig")
2169            .field(
2170                "registry",
2171                &self.registry.as_ref().map(|r| r.backend_name()),
2172            )
2173            .field("checkpoint_interval", &self.checkpoint_interval)
2174            .field("auto_load", &self.auto_load)
2175            .field("auto_save", &self.auto_save)
2176            .finish()
2177    }
2178}
2179
2180impl PersistenceConfig {
2181    /// Create a disabled persistence config.
2182    #[must_use]
2183    pub fn disabled() -> Self {
2184        Self::default()
2185    }
2186
2187    /// Create a persistence config with the given registry.
2188    #[must_use]
2189    pub fn with_registry(registry: std::sync::Arc<StateRegistry>) -> Self {
2190        Self {
2191            registry: Some(registry),
2192            ..Default::default()
2193        }
2194    }
2195
2196    /// Set the checkpoint interval.
2197    #[must_use]
2198    pub fn checkpoint_every(mut self, interval: Duration) -> Self {
2199        self.checkpoint_interval = Some(interval);
2200        self
2201    }
2202
2203    /// Enable or disable auto-load on start.
2204    #[must_use]
2205    pub fn auto_load(mut self, enabled: bool) -> Self {
2206        self.auto_load = enabled;
2207        self
2208    }
2209
2210    /// Enable or disable auto-save on exit.
2211    #[must_use]
2212    pub fn auto_save(mut self, enabled: bool) -> Self {
2213        self.auto_save = enabled;
2214        self
2215    }
2216}
2217
2218/// Configuration for widget refresh selection under render budget.
2219///
2220/// Defaults are conservative and deterministic:
2221/// - enabled: true
2222/// - staleness_window_ms: 1_000
2223/// - starve_ms: 3_000
2224/// - max_starved_per_frame: 2
2225/// - max_drop_fraction: 1.0 (disabled)
2226/// - weights: priority 1.0, staleness 0.5, focus 0.75, interaction 0.5
2227/// - starve_boost: 1.5
2228/// - min_cost_us: 1.0
2229#[derive(Debug, Clone)]
2230pub struct WidgetRefreshConfig {
2231    /// Enable budgeted widget refresh selection.
2232    pub enabled: bool,
2233    /// Staleness decay window (ms) used to normalize staleness scores.
2234    pub staleness_window_ms: u64,
2235    /// Staleness threshold that triggers starvation guard (ms).
2236    pub starve_ms: u64,
2237    /// Maximum number of starved widgets to force in per frame.
2238    pub max_starved_per_frame: usize,
2239    /// Maximum fraction of non-essential widgets that may be dropped.
2240    /// Set to 1.0 to disable the guardrail.
2241    pub max_drop_fraction: f32,
2242    /// Weight for base priority signal.
2243    pub weight_priority: f32,
2244    /// Weight for staleness signal.
2245    pub weight_staleness: f32,
2246    /// Weight for focus boost.
2247    pub weight_focus: f32,
2248    /// Weight for interaction boost.
2249    pub weight_interaction: f32,
2250    /// Additive boost to value for starved widgets.
2251    pub starve_boost: f32,
2252    /// Minimum cost (us) to avoid divide-by-zero.
2253    pub min_cost_us: f32,
2254}
2255
2256impl Default for WidgetRefreshConfig {
2257    fn default() -> Self {
2258        Self {
2259            enabled: true,
2260            staleness_window_ms: 1_000,
2261            starve_ms: 3_000,
2262            max_starved_per_frame: 2,
2263            max_drop_fraction: 1.0,
2264            weight_priority: 1.0,
2265            weight_staleness: 0.5,
2266            weight_focus: 0.75,
2267            weight_interaction: 0.5,
2268            starve_boost: 1.5,
2269            min_cost_us: 1.0,
2270        }
2271    }
2272}
2273
2274/// Configuration for effect queue scheduling.
2275#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2276pub enum TaskExecutorBackend {
2277    /// Spawn one native thread per task and reap finished handles on the main loop.
2278    #[default]
2279    Spawned,
2280    /// Route tasks through the runtime's queueing scheduler.
2281    EffectQueue,
2282    /// Route blocking task closures through an Asupersync blocking pool.
2283    #[cfg(feature = "asupersync-executor")]
2284    Asupersync,
2285}
2286
2287#[derive(Debug, Clone)]
2288pub struct EffectQueueConfig {
2289    /// Whether effect queue scheduling is enabled.
2290    ///
2291    /// This legacy convenience flag is kept in sync with `backend`. New code
2292    /// should prefer `backend` for executor selection.
2293    pub enabled: bool,
2294    /// Which task executor backend to use for `Cmd::Task`.
2295    pub backend: TaskExecutorBackend,
2296    /// Scheduler configuration (Smith's rule by default).
2297    pub scheduler: SchedulerConfig,
2298    /// Maximum queue depth before backpressure kicks in (bd-2zd0a).
2299    ///
2300    /// When the queue depth exceeds this limit, new tasks are dropped with
2301    /// a `tracing::warn!` and the `effects_queue_dropped` counter increments.
2302    /// A value of `0` means unbounded (no backpressure).
2303    pub max_queue_depth: usize,
2304    /// Whether the backend selection was set explicitly by the caller.
2305    explicit_backend: bool,
2306}
2307
2308impl Default for EffectQueueConfig {
2309    fn default() -> Self {
2310        let scheduler = SchedulerConfig {
2311            smith_enabled: true,
2312            force_fifo: false,
2313            preemptive: false,
2314            aging_factor: 0.0,
2315            wait_starve_ms: 0.0,
2316            enable_logging: false,
2317            ..Default::default()
2318        };
2319        Self {
2320            enabled: false,
2321            backend: TaskExecutorBackend::Spawned,
2322            scheduler,
2323            max_queue_depth: 0,
2324            explicit_backend: false,
2325        }
2326    }
2327}
2328
2329impl EffectQueueConfig {
2330    /// Enable effect queue scheduling with the provided scheduler config.
2331    #[must_use]
2332    pub fn with_enabled(mut self, enabled: bool) -> Self {
2333        self.enabled = enabled;
2334        self.backend = if enabled {
2335            TaskExecutorBackend::EffectQueue
2336        } else {
2337            TaskExecutorBackend::Spawned
2338        };
2339        self.explicit_backend = true;
2340        self
2341    }
2342
2343    /// Select the task executor backend for `Cmd::Task`.
2344    #[must_use]
2345    pub fn with_backend(mut self, backend: TaskExecutorBackend) -> Self {
2346        self.enabled = matches!(backend, TaskExecutorBackend::EffectQueue);
2347        self.backend = backend;
2348        self.explicit_backend = true;
2349        self
2350    }
2351
2352    /// Override the scheduler configuration.
2353    #[must_use]
2354    pub fn with_scheduler(mut self, scheduler: SchedulerConfig) -> Self {
2355        self.scheduler = scheduler;
2356        self
2357    }
2358
2359    /// Set the maximum queue depth for backpressure (bd-2zd0a).
2360    ///
2361    /// When the queue depth exceeds this limit, new tasks are dropped.
2362    /// A value of `0` means unbounded (no backpressure, the default).
2363    #[must_use]
2364    pub fn with_max_queue_depth(mut self, depth: usize) -> Self {
2365        self.max_queue_depth = depth;
2366        self
2367    }
2368
2369    #[must_use]
2370    fn uses_legacy_default_backend(&self) -> bool {
2371        !self.explicit_backend && !self.enabled && self.backend == TaskExecutorBackend::Spawned
2372    }
2373}
2374
2375/// Immediate event-drain policy for the runtime main loop.
2376///
2377/// When a poll reports readiness, the runtime drains events by repeatedly
2378/// checking `poll_event(Duration::ZERO)` to avoid latency between buffered
2379/// inputs. This policy bounds that immediate-drain path so bursty workloads do
2380/// not devolve into zero-timeout spin storms.
2381#[derive(Debug, Clone)]
2382pub struct ImmediateDrainConfig {
2383    /// Maximum consecutive zero-timeout polls allowed in a single burst window.
2384    pub max_zero_timeout_polls_per_burst: usize,
2385    /// Maximum wall-clock time spent in a single immediate-drain burst window.
2386    pub max_burst_duration: Duration,
2387    /// Non-zero poll timeout used when the burst window budget is exhausted.
2388    pub backoff_timeout: Duration,
2389}
2390
2391impl Default for ImmediateDrainConfig {
2392    fn default() -> Self {
2393        Self {
2394            max_zero_timeout_polls_per_burst: 64,
2395            max_burst_duration: Duration::from_millis(2),
2396            backoff_timeout: Duration::from_millis(1),
2397        }
2398    }
2399}
2400
2401/// Runtime counters for immediate-drain behavior.
2402#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2403pub struct ImmediateDrainStats {
2404    /// Number of event-drain bursts observed.
2405    pub bursts: u64,
2406    /// Total zero-timeout polls executed (`poll_event(Duration::ZERO)`).
2407    pub zero_timeout_polls: u64,
2408    /// Total non-zero backoff polls executed after exhausting burst budget.
2409    pub backoff_polls: u64,
2410    /// Number of bursts that hit the configured immediate-drain cap.
2411    pub capped_bursts: u64,
2412    /// Max number of zero-timeout polls seen in a single burst window.
2413    pub max_zero_timeout_polls_in_burst: u64,
2414}
2415
2416/// User-visible runtime mode reported by the conservative load governor.
2417///
2418/// These modes mirror the `bd-8vstx` runtime contract:
2419///
2420/// - `Healthy`: admit all work normally; no explicit fallback is active.
2421/// - `Stressed`: strict work is preserved while visible/coalescible or
2422///   background work may be slowed before user-visible ambiguity appears.
2423/// - `Degraded`: bounded fallback is active; strict interactive semantics
2424///   still hold while background/best-effort work is deferred or dropped.
2425/// - `Recovered`: a degraded interval has closed after the configured
2426///   hysteresis window; the next steady interval returns to `Healthy`.
2427/// - `Unsafe`: a strict semantic guarantee cannot be preserved, so optimistic
2428///   degradation must stop and the caller must surface explicit failure.
2429#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2430pub enum RuntimeLoadMode {
2431    /// No sustained pressure and no active fallback.
2432    Healthy,
2433    /// Elevated pressure while strict guarantees still hold.
2434    Stressed,
2435    /// Explicit bounded fallback is active.
2436    Degraded,
2437    /// Recovery interval has been observed and reported.
2438    Recovered,
2439    /// A strict semantic guarantee was violated.
2440    Unsafe,
2441}
2442
2443impl RuntimeLoadMode {
2444    /// Stable string for evidence logs.
2445    #[inline]
2446    #[must_use]
2447    pub const fn as_str(self) -> &'static str {
2448        match self {
2449            Self::Healthy => "healthy",
2450            Self::Stressed => "stressed",
2451            Self::Degraded => "degraded",
2452            Self::Recovered => "recovered",
2453            Self::Unsafe => "unsafe",
2454        }
2455    }
2456}
2457
2458/// Pressure envelope inferred from measured runtime signals.
2459#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2460pub enum RuntimePressureClass {
2461    /// Within steady-state envelope.
2462    SteadyState,
2463    /// Early overload band; bounded coalescing/deferment may begin.
2464    SoftOverload,
2465    /// Degraded band; explicit fallback is active.
2466    HardOverload,
2467    /// Terminal strict-semantics failure.
2468    Unsafe,
2469}
2470
2471impl RuntimePressureClass {
2472    /// Stable string for evidence logs.
2473    #[inline]
2474    #[must_use]
2475    pub const fn as_str(self) -> &'static str {
2476        match self {
2477            Self::SteadyState => "steady_state",
2478            Self::SoftOverload => "soft_overload",
2479            Self::HardOverload => "hard_overload",
2480            Self::Unsafe => "unsafe",
2481        }
2482    }
2483}
2484
2485/// Work disposition allowed by the current runtime mode.
2486#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2487pub enum RuntimeWorkDisposition {
2488    /// Admit all work normally.
2489    AdmitAll,
2490    /// Preserve strict work; coalesce visible work and slow background work.
2491    CoalesceVisibleDeferBackground,
2492    /// Preserve strict work; defer background work and drop best-effort work.
2493    DeferBackgroundDropBestEffort,
2494    /// Re-admit deferred work after the hysteresis window closed.
2495    ReadmitAfterHysteresis,
2496    /// Stop optimistic degradation because a strict guarantee failed.
2497    FailFastStrictGuarantee,
2498}
2499
2500impl RuntimeWorkDisposition {
2501    /// Stable string for evidence logs.
2502    #[inline]
2503    #[must_use]
2504    pub const fn as_str(self) -> &'static str {
2505        match self {
2506            Self::AdmitAll => "admit_all",
2507            Self::CoalesceVisibleDeferBackground => "coalesce_visible_defer_background",
2508            Self::DeferBackgroundDropBestEffort => "defer_background_drop_best_effort",
2509            Self::ReadmitAfterHysteresis => "readmit_after_hysteresis",
2510            Self::FailFastStrictGuarantee => "fail_fast_strict_guarantee",
2511        }
2512    }
2513}
2514
2515/// Conservative policy for classifying runtime load.
2516///
2517/// The first runtime governor intentionally uses one primary control family:
2518/// render-budget degradation and explicit coalescing/admission evidence. Queue
2519/// watermarks are advisory inputs when a queue cap exists; when the queue is
2520/// uncapped, frame-budget and coalescer signals drive fallback classification.
2521#[derive(Debug, Clone, Copy, PartialEq)]
2522pub struct LoadGovernorPolicy {
2523    /// Queue occupancy ratio that enters `stressed`.
2524    pub stressed_queue_watermark: f64,
2525    /// Queue occupancy ratio that enters `degraded`.
2526    pub degraded_queue_watermark: f64,
2527    /// Queue occupancy ratio required before closing a degraded interval.
2528    pub recovery_queue_watermark: f64,
2529    /// Consecutive steady intervals required before reporting recovery.
2530    pub recovery_intervals: u8,
2531    /// Frame-time ratio over budget that enters `stressed` when uncapped.
2532    pub budget_overrun_soft_ratio: f64,
2533}
2534
2535impl Default for LoadGovernorPolicy {
2536    fn default() -> Self {
2537        Self {
2538            stressed_queue_watermark: 0.5,
2539            degraded_queue_watermark: 0.8,
2540            recovery_queue_watermark: 0.25,
2541            recovery_intervals: 3,
2542            budget_overrun_soft_ratio: 1.0,
2543        }
2544    }
2545}
2546
2547impl LoadGovernorPolicy {
2548    #[must_use]
2549    fn normalized(self) -> Self {
2550        let recovery = normalize_ratio(self.recovery_queue_watermark, 0.25);
2551        let stressed = normalize_ratio(self.stressed_queue_watermark, 0.5).max(recovery);
2552        let degraded = normalize_ratio(self.degraded_queue_watermark, 0.8).max(stressed);
2553        Self {
2554            recovery_queue_watermark: recovery,
2555            stressed_queue_watermark: stressed,
2556            degraded_queue_watermark: degraded,
2557            recovery_intervals: self.recovery_intervals.max(1),
2558            budget_overrun_soft_ratio: normalize_positive_ratio(
2559                self.budget_overrun_soft_ratio,
2560                1.0,
2561            ),
2562        }
2563    }
2564}
2565
2566#[inline]
2567fn normalize_ratio(value: f64, fallback: f64) -> f64 {
2568    if value.is_finite() {
2569        value.clamp(0.0, 1.0)
2570    } else {
2571        fallback
2572    }
2573}
2574
2575#[inline]
2576fn normalize_positive_ratio(value: f64, fallback: f64) -> f64 {
2577    if value.is_finite() && value > 0.0 {
2578        value
2579    } else {
2580        fallback
2581    }
2582}
2583
2584/// Conservative runtime load-governor configuration.
2585///
2586/// The first runtime governor keeps one primary control objective:
2587/// responsiveness under render pressure. It drives adaptive render degradation
2588/// through `RenderBudget`, classifies runtime mode with queue/coalescer inputs,
2589/// and emits replayable evidence for the allowed work disposition. Disabling
2590/// this config falls back to the legacy threshold path.
2591#[derive(Debug, Clone, PartialEq)]
2592pub struct LoadGovernorConfig {
2593    /// Whether the adaptive governor is active.
2594    pub enabled: bool,
2595    /// Controller used to decide degrade/upgrade transitions from frame timing.
2596    pub budget_controller: BudgetControllerConfig,
2597    /// Runtime-mode and work-disposition classification policy.
2598    pub policy: LoadGovernorPolicy,
2599}
2600
2601impl Default for LoadGovernorConfig {
2602    fn default() -> Self {
2603        Self {
2604            enabled: true,
2605            budget_controller: BudgetControllerConfig::default(),
2606            policy: LoadGovernorPolicy::default(),
2607        }
2608    }
2609}
2610
2611impl LoadGovernorConfig {
2612    /// Create an enabled governor with conservative defaults.
2613    #[must_use]
2614    pub fn enabled() -> Self {
2615        Self::default()
2616    }
2617
2618    /// Disable the governor and use the legacy render-budget threshold path.
2619    #[must_use]
2620    pub fn disabled() -> Self {
2621        Self {
2622            enabled: false,
2623            budget_controller: BudgetControllerConfig::default(),
2624            policy: LoadGovernorPolicy::default(),
2625        }
2626    }
2627
2628    /// Toggle governor activation.
2629    #[must_use]
2630    pub fn with_enabled(mut self, enabled: bool) -> Self {
2631        self.enabled = enabled;
2632        self
2633    }
2634
2635    /// Replace the adaptive budget controller configuration.
2636    #[must_use]
2637    pub fn with_budget_controller(mut self, config: BudgetControllerConfig) -> Self {
2638        self.budget_controller = config;
2639        self
2640    }
2641
2642    /// Replace the runtime-mode classification policy.
2643    #[must_use]
2644    pub fn with_policy(mut self, policy: LoadGovernorPolicy) -> Self {
2645        self.policy = policy.normalized();
2646        self
2647    }
2648}
2649
2650#[derive(Debug, Clone, Copy)]
2651struct LoadGovernorObservation {
2652    frame_time_us: f64,
2653    budget_us: f64,
2654    degradation: DegradationLevel,
2655    queue: crate::effect_system::QueueTelemetry,
2656    resize_coalescing_active: bool,
2657    strict_semantics_violation: bool,
2658}
2659
2660#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2661struct LoadGovernorSnapshot {
2662    mode: RuntimeLoadMode,
2663    mode_before: RuntimeLoadMode,
2664    pressure_class: RuntimePressureClass,
2665    disposition: RuntimeWorkDisposition,
2666    reason_code: &'static str,
2667    transition: bool,
2668    strict_semantics_preserved: bool,
2669    queue_in_flight: u64,
2670    queue_max_depth: Option<usize>,
2671    queue_dropped_delta: u64,
2672    resize_coalescing_active: bool,
2673    recovery_intervals_observed: u8,
2674    recovery_intervals_required: u8,
2675    deferred_work_total: u64,
2676    coalesced_work_total: u64,
2677    dropped_work_total: u64,
2678}
2679
2680#[derive(Debug, Clone)]
2681struct LoadGovernorState {
2682    enabled: bool,
2683    policy: LoadGovernorPolicy,
2684    max_queue_depth: usize,
2685    mode: RuntimeLoadMode,
2686    recovery_intervals_observed: u8,
2687    last_queue_dropped: u64,
2688    queue_baseline_initialized: bool,
2689    deferred_work_total: u64,
2690    coalesced_work_total: u64,
2691    dropped_work_total: u64,
2692}
2693
2694impl LoadGovernorState {
2695    fn new(config: LoadGovernorConfig, max_queue_depth: usize) -> Self {
2696        Self {
2697            enabled: config.enabled,
2698            policy: config.policy.normalized(),
2699            max_queue_depth,
2700            mode: RuntimeLoadMode::Healthy,
2701            recovery_intervals_observed: 0,
2702            last_queue_dropped: 0,
2703            queue_baseline_initialized: false,
2704            deferred_work_total: 0,
2705            coalesced_work_total: 0,
2706            dropped_work_total: 0,
2707        }
2708    }
2709
2710    fn observe(&mut self, observation: LoadGovernorObservation) -> LoadGovernorSnapshot {
2711        if !self.enabled {
2712            return self.snapshot(
2713                RuntimeLoadMode::Healthy,
2714                RuntimeLoadMode::Healthy,
2715                RuntimePressureClass::SteadyState,
2716                RuntimeWorkDisposition::AdmitAll,
2717                "governor_disabled",
2718                false,
2719                true,
2720                observation,
2721                0,
2722            );
2723        }
2724
2725        let dropped_delta = self.queue_dropped_delta(observation.queue.dropped);
2726        let pressure = self.classify_pressure(observation, dropped_delta);
2727        let mode_before = self.mode;
2728        let reason_code = self.reason_code(observation, pressure, dropped_delta);
2729
2730        match pressure {
2731            RuntimePressureClass::Unsafe => {
2732                self.mode = RuntimeLoadMode::Unsafe;
2733                self.recovery_intervals_observed = 0;
2734            }
2735            // Strict-semantics failure is terminal: once Unsafe is entered the
2736            // governor latches there regardless of later pressure (this mirrors
2737            // the `Unsafe => {}` arm in `observe_steady_interval`, which already
2738            // refuses to recover Unsafe under steady load). Without this guard,
2739            // a subsequent overload interval would downgrade Unsafe to
2740            // Degraded/Stressed and then recover to Healthy, silently escaping
2741            // the fail-fast guarantee. Only an explicit reset clears Unsafe.
2742            _ if self.mode == RuntimeLoadMode::Unsafe => {
2743                self.recovery_intervals_observed = 0;
2744            }
2745            RuntimePressureClass::HardOverload => {
2746                self.mode = RuntimeLoadMode::Degraded;
2747                self.recovery_intervals_observed = 0;
2748            }
2749            RuntimePressureClass::SoftOverload => {
2750                if self.mode != RuntimeLoadMode::Degraded {
2751                    self.mode = RuntimeLoadMode::Stressed;
2752                }
2753                self.recovery_intervals_observed = 0;
2754            }
2755            RuntimePressureClass::SteadyState => self.observe_steady_interval(),
2756        }
2757
2758        self.record_work_disposition(observation, dropped_delta);
2759        let disposition = Self::disposition_for_mode(self.mode);
2760        self.snapshot(
2761            self.mode,
2762            mode_before,
2763            pressure,
2764            disposition,
2765            if self.mode == RuntimeLoadMode::Unsafe {
2766                // Whether freshly violated this interval or latched from a prior
2767                // one, the terminal cause is always the strict-semantics failure.
2768                "strict_semantics_violation"
2769            } else if self.mode == RuntimeLoadMode::Recovered {
2770                "recovery_hysteresis_satisfied"
2771            } else if mode_before == RuntimeLoadMode::Recovered
2772                && self.mode == RuntimeLoadMode::Healthy
2773            {
2774                "recovered_interval_closed"
2775            } else {
2776                reason_code
2777            },
2778            mode_before != self.mode,
2779            // Reflect the latched mode, not the instantaneous pressure: once the
2780            // governor is Unsafe, strict semantics stay unpreserved even on an
2781            // interval whose raw pressure classified lower.
2782            self.mode != RuntimeLoadMode::Unsafe,
2783            observation,
2784            dropped_delta,
2785        )
2786    }
2787
2788    fn queue_dropped_delta(&mut self, dropped_total: u64) -> u64 {
2789        if !self.queue_baseline_initialized {
2790            self.queue_baseline_initialized = true;
2791            self.last_queue_dropped = dropped_total;
2792            return 0;
2793        }
2794        let delta = dropped_total.saturating_sub(self.last_queue_dropped);
2795        self.last_queue_dropped = dropped_total;
2796        delta
2797    }
2798
2799    fn classify_pressure(
2800        &self,
2801        observation: LoadGovernorObservation,
2802        dropped_delta: u64,
2803    ) -> RuntimePressureClass {
2804        if observation.strict_semantics_violation {
2805            return RuntimePressureClass::Unsafe;
2806        }
2807        if dropped_delta > 0
2808            || self
2809                .queue_ratio(observation.queue.in_flight)
2810                .is_some_and(|ratio| ratio >= self.policy.degraded_queue_watermark)
2811            || observation.degradation > DegradationLevel::Full
2812        {
2813            return RuntimePressureClass::HardOverload;
2814        }
2815        if self
2816            .queue_ratio(observation.queue.in_flight)
2817            .is_some_and(|ratio| ratio >= self.policy.stressed_queue_watermark)
2818            || observation.resize_coalescing_active
2819            || observation.frame_time_us
2820                > observation.budget_us * self.policy.budget_overrun_soft_ratio
2821        {
2822            return RuntimePressureClass::SoftOverload;
2823        }
2824        RuntimePressureClass::SteadyState
2825    }
2826
2827    fn observe_steady_interval(&mut self) {
2828        match self.mode {
2829            RuntimeLoadMode::Degraded => {
2830                self.recovery_intervals_observed = self
2831                    .recovery_intervals_observed
2832                    .saturating_add(1)
2833                    .min(self.policy.recovery_intervals);
2834                if self.recovery_intervals_observed >= self.policy.recovery_intervals {
2835                    self.mode = RuntimeLoadMode::Recovered;
2836                }
2837            }
2838            RuntimeLoadMode::Recovered | RuntimeLoadMode::Stressed => {
2839                self.mode = RuntimeLoadMode::Healthy;
2840                self.recovery_intervals_observed = 0;
2841            }
2842            RuntimeLoadMode::Healthy => {
2843                self.recovery_intervals_observed = 0;
2844            }
2845            RuntimeLoadMode::Unsafe => {}
2846        }
2847    }
2848
2849    fn record_work_disposition(
2850        &mut self,
2851        observation: LoadGovernorObservation,
2852        dropped_delta: u64,
2853    ) {
2854        if dropped_delta > 0 {
2855            self.dropped_work_total = self.dropped_work_total.saturating_add(dropped_delta);
2856        }
2857        match self.mode {
2858            RuntimeLoadMode::Stressed => {
2859                if observation.resize_coalescing_active {
2860                    self.coalesced_work_total = self.coalesced_work_total.saturating_add(1);
2861                }
2862            }
2863            RuntimeLoadMode::Degraded => {
2864                self.deferred_work_total = self.deferred_work_total.saturating_add(1);
2865                if observation.resize_coalescing_active {
2866                    self.coalesced_work_total = self.coalesced_work_total.saturating_add(1);
2867                }
2868            }
2869            RuntimeLoadMode::Healthy | RuntimeLoadMode::Recovered | RuntimeLoadMode::Unsafe => {}
2870        }
2871    }
2872
2873    fn reason_code(
2874        &self,
2875        observation: LoadGovernorObservation,
2876        pressure: RuntimePressureClass,
2877        dropped_delta: u64,
2878    ) -> &'static str {
2879        match pressure {
2880            RuntimePressureClass::Unsafe => "strict_semantics_violation",
2881            RuntimePressureClass::HardOverload if dropped_delta > 0 => "effect_queue_drop",
2882            RuntimePressureClass::HardOverload
2883                if self
2884                    .queue_ratio(observation.queue.in_flight)
2885                    .is_some_and(|ratio| ratio >= self.policy.degraded_queue_watermark) =>
2886            {
2887                "queue_degraded_watermark"
2888            }
2889            RuntimePressureClass::HardOverload => "budget_degradation_active",
2890            RuntimePressureClass::SoftOverload
2891                if self
2892                    .queue_ratio(observation.queue.in_flight)
2893                    .is_some_and(|ratio| ratio >= self.policy.stressed_queue_watermark) =>
2894            {
2895                "queue_stressed_watermark"
2896            }
2897            RuntimePressureClass::SoftOverload if observation.resize_coalescing_active => {
2898                "resize_coalescing_active"
2899            }
2900            RuntimePressureClass::SoftOverload => "frame_budget_overrun",
2901            RuntimePressureClass::SteadyState if self.mode == RuntimeLoadMode::Degraded => {
2902                "recovery_hysteresis_pending"
2903            }
2904            RuntimePressureClass::SteadyState => "steady_state",
2905        }
2906    }
2907
2908    fn queue_ratio(&self, in_flight: u64) -> Option<f64> {
2909        (self.max_queue_depth > 0).then(|| in_flight as f64 / self.max_queue_depth as f64)
2910    }
2911
2912    const fn disposition_for_mode(mode: RuntimeLoadMode) -> RuntimeWorkDisposition {
2913        match mode {
2914            RuntimeLoadMode::Healthy => RuntimeWorkDisposition::AdmitAll,
2915            RuntimeLoadMode::Stressed => RuntimeWorkDisposition::CoalesceVisibleDeferBackground,
2916            RuntimeLoadMode::Degraded => RuntimeWorkDisposition::DeferBackgroundDropBestEffort,
2917            RuntimeLoadMode::Recovered => RuntimeWorkDisposition::ReadmitAfterHysteresis,
2918            RuntimeLoadMode::Unsafe => RuntimeWorkDisposition::FailFastStrictGuarantee,
2919        }
2920    }
2921
2922    // Internal constructor that gathers all snapshot fields in one place; the
2923    // wide signature is intentional (a builder would add indirection for a
2924    // private helper). Pre-existing lint, unrelated to the #78 fix.
2925    #[allow(clippy::too_many_arguments)]
2926    fn snapshot(
2927        &self,
2928        mode: RuntimeLoadMode,
2929        mode_before: RuntimeLoadMode,
2930        pressure_class: RuntimePressureClass,
2931        disposition: RuntimeWorkDisposition,
2932        reason_code: &'static str,
2933        transition: bool,
2934        strict_semantics_preserved: bool,
2935        observation: LoadGovernorObservation,
2936        dropped_delta: u64,
2937    ) -> LoadGovernorSnapshot {
2938        LoadGovernorSnapshot {
2939            mode,
2940            mode_before,
2941            pressure_class,
2942            disposition,
2943            reason_code,
2944            transition,
2945            strict_semantics_preserved,
2946            queue_in_flight: observation.queue.in_flight,
2947            queue_max_depth: (self.max_queue_depth > 0).then_some(self.max_queue_depth),
2948            queue_dropped_delta: dropped_delta,
2949            resize_coalescing_active: observation.resize_coalescing_active,
2950            recovery_intervals_observed: self.recovery_intervals_observed,
2951            recovery_intervals_required: self.policy.recovery_intervals,
2952            deferred_work_total: self.deferred_work_total,
2953            coalesced_work_total: self.coalesced_work_total,
2954            dropped_work_total: self.dropped_work_total,
2955        }
2956    }
2957}
2958
2959/// Runtime lane for the Asupersync migration rollout.
2960///
2961/// Controls which subscription/effect execution backend is active.
2962/// The default is `Structured`, reflecting the completed CancellationToken migration (bd-3tmu4).
2963///
2964/// # Migration rollout
2965///
2966/// 1. `Legacy` — pre-migration thread-based subscriptions with manual stop coordination
2967/// 2. `Structured` — CancellationToken-backed subscriptions (current default after bd-3tmu4)
2968/// 3. `Asupersync` — full Asupersync-native execution (future)
2969///
2970/// Selection is logged at startup so operators can tell which lane is active.
2971/// Fallback from `Asupersync` → `Structured` → `Legacy` is automatic on error.
2972#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
2973pub enum RuntimeLane {
2974    /// Pre-migration behavior: thread-based subscriptions with manual stop coordination.
2975    /// This is the safe default that preserves all existing semantics.
2976    Legacy,
2977    /// Structured cancellation: subscriptions use CancellationToken internally.
2978    /// Externally observable behavior is identical to Legacy.
2979    #[default]
2980    Structured,
2981    /// Full Asupersync-native execution (reserved for future use).
2982    /// Falls back to Structured if Asupersync primitives are unavailable.
2983    Asupersync,
2984}
2985
2986impl RuntimeLane {
2987    /// Resolve the effective lane, applying fallback rules.
2988    ///
2989    /// If the requested lane is not yet implemented, falls back to the
2990    /// highest available lane. Currently: Asupersync → Structured.
2991    #[must_use]
2992    pub fn resolve(self) -> Self {
2993        match self {
2994            Self::Asupersync => {
2995                tracing::info!(
2996                    target: crate::telemetry_schema::TARGET_RUNTIME,
2997                    requested = "asupersync",
2998                    resolved = "structured",
2999                    "Asupersync lane not yet available; falling back to structured cancellation"
3000                );
3001                Self::Structured
3002            }
3003            other => other,
3004        }
3005    }
3006
3007    /// Returns a human-readable label for logging.
3008    #[must_use]
3009    pub fn label(self) -> &'static str {
3010        match self {
3011            Self::Legacy => "legacy",
3012            Self::Structured => "structured",
3013            Self::Asupersync => "asupersync",
3014        }
3015    }
3016
3017    /// Check if this lane uses structured cancellation (CancellationToken).
3018    #[must_use]
3019    pub fn uses_structured_cancellation(self) -> bool {
3020        matches!(self, Self::Structured | Self::Asupersync)
3021    }
3022
3023    /// Resolve the default task executor backend for this lane.
3024    ///
3025    /// # Input-lag regression fix (#78)
3026    ///
3027    /// The `Structured` lane changes *subscription cancellation* semantics
3028    /// (CancellationToken-backed stop signals in `subscription.rs`); it must
3029    /// NOT also collapse `Cmd::Task` concurrency. Earlier this returned
3030    /// `EffectQueue`, which routed every `Cmd::Task` through a single
3031    /// `effect_queue_loop` worker thread with a Smith's-rule (SPT) scheduler,
3032    /// serializing all tasks. Apps that forward PTY output via per-pane
3033    /// `Cmd::task` polling loops (e.g. 10ms drains) then contended for one
3034    /// serialized worker, adding per-keystroke head-of-line latency versus
3035    /// v0.2.1, where each `Cmd::task` got its own `std::thread::spawn`.
3036    ///
3037    /// Structured cancellation does not depend on the effect queue (stop
3038    /// signals are token-backed regardless of executor backend), so the two
3039    /// concerns are decoupled here: `Structured` keeps the structured
3040    /// cancellation semantics but restores per-task-thread (`Spawned`)
3041    /// execution. Apps that explicitly opt into `EffectQueue` still get it
3042    /// (the lane default only applies when the app uses the legacy default
3043    /// backend — see `EffectQueueConfig::uses_legacy_default_backend`).
3044    #[must_use]
3045    fn task_executor_backend(self) -> TaskExecutorBackend {
3046        match self {
3047            // Legacy and Structured both use per-task `Spawned` execution.
3048            // (Structured only changes cancellation semantics, not concurrency
3049            // — see the regression note above.) Kept as a combined arm so the
3050            // `match_same_arms` lint stays happy under `-D warnings`.
3051            Self::Legacy | Self::Structured => TaskExecutorBackend::Spawned,
3052            Self::Asupersync => {
3053                #[cfg(feature = "asupersync-executor")]
3054                {
3055                    TaskExecutorBackend::Asupersync
3056                }
3057                #[cfg(not(feature = "asupersync-executor"))]
3058                {
3059                    TaskExecutorBackend::EffectQueue
3060                }
3061            }
3062        }
3063    }
3064
3065    /// Read the lane from the `FTUI_RUNTIME_LANE` environment variable.
3066    ///
3067    /// Accepted values (case-insensitive): `legacy`, `structured`, `asupersync`.
3068    /// Returns `None` if the variable is unset or contains an unrecognized value.
3069    #[must_use]
3070    pub fn from_env() -> Option<Self> {
3071        let val = std::env::var("FTUI_RUNTIME_LANE").ok()?;
3072        Self::parse(&val)
3073    }
3074
3075    /// Parse a lane name (case-insensitive).
3076    ///
3077    /// Returns `None` for unrecognized values.
3078    #[must_use]
3079    pub fn parse(s: &str) -> Option<Self> {
3080        match s.to_ascii_lowercase().as_str() {
3081            "legacy" => Some(Self::Legacy),
3082            "structured" => Some(Self::Structured),
3083            "asupersync" => Some(Self::Asupersync),
3084            _ => {
3085                tracing::warn!(
3086                    target: crate::telemetry_schema::TARGET_RUNTIME,
3087                    value = s,
3088                    "RuntimeLane::parse: unrecognized value"
3089                );
3090                None
3091            }
3092        }
3093    }
3094}
3095
3096/// Rollout policy for the Asupersync migration (bd-2crbt).
3097///
3098/// Controls how the runtime lane transition is managed:
3099///
3100/// - `Off` — use only the configured lane, no shadow comparison.
3101/// - `Shadow` — run both baseline and candidate lanes, compare outputs,
3102///   but use only the baseline lane for actual rendering. Evidence is emitted
3103///   to the configured JSONL sink for operator review.
3104/// - `Enabled` — use the candidate lane for rendering (requires prior shadow
3105///   evidence showing deterministic match).
3106///
3107/// The policy is logged at startup and can be overridden via the
3108/// `FTUI_ROLLOUT_POLICY` environment variable (`off`, `shadow`, `enabled`).
3109#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
3110pub enum RolloutPolicy {
3111    /// No rollout activity — use the configured lane directly.
3112    #[default]
3113    Off,
3114    /// Shadow-run comparison mode: run both lanes, emit evidence, use baseline.
3115    Shadow,
3116    /// Candidate lane is live — requires prior shadow evidence.
3117    Enabled,
3118}
3119
3120impl RolloutPolicy {
3121    /// Read the policy from the `FTUI_ROLLOUT_POLICY` environment variable.
3122    ///
3123    /// Accepted values (case-insensitive): `off`, `shadow`, `enabled`.
3124    /// Returns `None` if unset or unrecognized.
3125    #[must_use]
3126    pub fn from_env() -> Option<Self> {
3127        let val = std::env::var("FTUI_ROLLOUT_POLICY").ok()?;
3128        Self::parse(&val)
3129    }
3130
3131    /// Parse a rollout policy name (case-insensitive).
3132    ///
3133    /// Returns `None` for unrecognized values.
3134    #[must_use]
3135    pub fn parse(s: &str) -> Option<Self> {
3136        match s.to_ascii_lowercase().as_str() {
3137            "off" => Some(Self::Off),
3138            "shadow" => Some(Self::Shadow),
3139            "enabled" => Some(Self::Enabled),
3140            _ => {
3141                tracing::warn!(
3142                    target: crate::telemetry_schema::TARGET_RUNTIME,
3143                    value = s,
3144                    "RolloutPolicy::parse: unrecognized value"
3145                );
3146                None
3147            }
3148        }
3149    }
3150
3151    /// Returns a human-readable label for logging.
3152    #[must_use]
3153    pub fn label(self) -> &'static str {
3154        match self {
3155            Self::Off => "off",
3156            Self::Shadow => "shadow",
3157            Self::Enabled => "enabled",
3158        }
3159    }
3160
3161    /// Whether this policy involves shadow comparison.
3162    #[must_use]
3163    pub fn is_shadow(self) -> bool {
3164        matches!(self, Self::Shadow)
3165    }
3166}
3167
3168impl std::fmt::Display for RolloutPolicy {
3169    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3170        f.write_str(self.label())
3171    }
3172}
3173
3174impl std::fmt::Display for RuntimeLane {
3175    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3176        f.write_str(self.label())
3177    }
3178}
3179
3180/// Configuration for the program runtime.
3181#[derive(Debug, Clone)]
3182pub struct ProgramConfig {
3183    /// Screen mode (inline or alternate screen).
3184    pub screen_mode: ScreenMode,
3185    /// UI anchor for inline mode.
3186    pub ui_anchor: UiAnchor,
3187    /// Frame budget configuration.
3188    pub budget: FrameBudgetConfig,
3189    /// Runtime load-governor configuration.
3190    pub load_governor: LoadGovernorConfig,
3191    /// Diff strategy configuration for the terminal writer.
3192    pub diff_config: RuntimeDiffConfig,
3193    /// Evidence JSONL sink configuration.
3194    pub evidence_sink: EvidenceSinkConfig,
3195    /// Render-trace recorder configuration.
3196    pub render_trace: RenderTraceConfig,
3197    /// Optional frame timing sink.
3198    pub frame_timing: Option<FrameTimingConfig>,
3199    /// Conformal predictor configuration for frame-time risk gating.
3200    pub conformal_config: Option<ConformalConfig>,
3201    /// Locale context used for rendering.
3202    pub locale_context: LocaleContext,
3203    /// Input poll timeout.
3204    pub poll_timeout: Duration,
3205    /// Immediate event-drain policy for burst handling.
3206    pub immediate_drain: ImmediateDrainConfig,
3207    /// Resize coalescer configuration.
3208    pub resize_coalescer: CoalescerConfig,
3209    /// Resize handling behavior (immediate/throttled).
3210    pub resize_behavior: ResizeBehavior,
3211    /// Forced terminal size override (when set, resize events are ignored).
3212    pub forced_size: Option<(u16, u16)>,
3213    /// Mouse capture policy (`Auto`, `On`, `Off`).
3214    ///
3215    /// `Auto` is inline-safe: off in inline modes, on in alt-screen mode.
3216    pub mouse_capture_policy: MouseCapturePolicy,
3217    /// Enable bracketed paste.
3218    pub bracketed_paste: bool,
3219    /// Enable focus reporting.
3220    pub focus_reporting: bool,
3221    /// Enable Kitty keyboard protocol (repeat/release events).
3222    pub kitty_keyboard: bool,
3223    /// State persistence configuration.
3224    pub persistence: PersistenceConfig,
3225    /// Inline auto UI height remeasurement policy.
3226    pub inline_auto_remeasure: Option<InlineAutoRemeasureConfig>,
3227    /// Gesture recognition (clicks, drags, long press, chords) delivered to
3228    /// [`Model::on_gesture`]; `None` (the default) runs no recognizer.
3229    pub gestures: Option<ftui_core::gesture::GestureConfig>,
3230    /// Accessibility tree collection. When set, every rendered frame builds
3231    /// an [`A11yTree`] from the nodes widgets push into the [`Frame`], diffs
3232    /// it against the previous frame and derives screen-reader
3233    /// announcements under this policy. Tracing and evidence export metadata
3234    /// only by default; [`Model::on_accessibility`] receives the complete
3235    /// local announcements. `None` (the default) collects nothing and adds
3236    /// no per-frame work.
3237    pub accessibility: Option<ScreenReaderPolicy>,
3238    /// Include announcement text in the explicitly configured evidence sink.
3239    ///
3240    /// Defaults to `false`: evidence rows contain `"text": null`. Enable only
3241    /// for an intentional local content capture; labels and edited text may
3242    /// be sensitive. Ordinary tracing never includes announcement content,
3243    /// and this setting does not change the local accessibility callback.
3244    pub accessibility_evidence_text: bool,
3245    /// Widget refresh selection configuration.
3246    pub widget_refresh: WidgetRefreshConfig,
3247    /// Effect queue scheduling configuration.
3248    pub effect_queue: EffectQueueConfig,
3249    /// Frame guardrails configuration (memory + queue safety limits).
3250    pub guardrails: GuardrailsConfig,
3251    /// Install signal handlers for cleanup on SIGINT/SIGTERM/SIGHUP.
3252    ///
3253    /// Defaults to `true` for application safety. Set to `false` in tests or
3254    /// when the embedding application manages signals.
3255    pub intercept_signals: bool,
3256    /// Optional tick strategy for selective background screen ticking.
3257    ///
3258    /// When `None` (default), all screens tick every frame (current behavior).
3259    /// When set, the runtime consults the strategy for each inactive screen.
3260    pub tick_strategy: Option<crate::tick_strategy::TickStrategyKind>,
3261    /// Runtime execution lane for the Asupersync migration rollout.
3262    ///
3263    /// Controls which subscription/effect backend is active.
3264    /// Defaults to `Structured` (CancellationToken-backed, current migration state).
3265    /// Logged at startup so operators can identify the active lane.
3266    pub runtime_lane: RuntimeLane,
3267    /// Rollout policy for the Asupersync migration (bd-2crbt).
3268    ///
3269    /// Controls whether shadow-run comparison is active during this session.
3270    /// When `Shadow`, both the baseline and candidate lanes run in parallel
3271    /// and evidence is emitted; rendering uses the baseline lane only.
3272    pub rollout_policy: RolloutPolicy,
3273}
3274
3275impl Default for ProgramConfig {
3276    fn default() -> Self {
3277        Self {
3278            screen_mode: ScreenMode::Inline { ui_height: 4 },
3279            ui_anchor: UiAnchor::Bottom,
3280            budget: FrameBudgetConfig::default(),
3281            load_governor: LoadGovernorConfig::default(),
3282            diff_config: RuntimeDiffConfig::default(),
3283            evidence_sink: EvidenceSinkConfig::default(),
3284            render_trace: RenderTraceConfig::default(),
3285            frame_timing: None,
3286            // Conformal frame-time risk gating is on by default: the predictor
3287            // only starts gating once a bucket has `min_samples` (20) real
3288            // frame timings, so a fresh program renders at full fidelity
3289            // during warm-up and degrades only on measured evidence. Use
3290            // `without_conformal()` to opt out.
3291            conformal_config: Some(ConformalConfig::default()),
3292            locale_context: LocaleContext::global(),
3293            poll_timeout: Duration::from_millis(100),
3294            immediate_drain: ImmediateDrainConfig::default(),
3295            resize_coalescer: CoalescerConfig::default(),
3296            resize_behavior: ResizeBehavior::Throttled,
3297            forced_size: None,
3298            mouse_capture_policy: MouseCapturePolicy::Auto,
3299            bracketed_paste: true,
3300            focus_reporting: false,
3301            kitty_keyboard: false,
3302            persistence: PersistenceConfig::default(),
3303            inline_auto_remeasure: None,
3304            gestures: None,
3305            accessibility: None,
3306            accessibility_evidence_text: false,
3307            widget_refresh: WidgetRefreshConfig::default(),
3308            effect_queue: EffectQueueConfig::default(),
3309            guardrails: GuardrailsConfig::default(),
3310            intercept_signals: true,
3311            tick_strategy: None,
3312            runtime_lane: RuntimeLane::default(),
3313            rollout_policy: RolloutPolicy::default(),
3314        }
3315    }
3316}
3317
3318impl ProgramConfig {
3319    /// Create config for fullscreen applications.
3320    pub fn fullscreen() -> Self {
3321        Self {
3322            screen_mode: ScreenMode::AltScreen,
3323            ..Default::default()
3324        }
3325    }
3326
3327    /// Create config for inline mode with specified height.
3328    pub fn inline(height: u16) -> Self {
3329        Self {
3330            screen_mode: ScreenMode::Inline { ui_height: height },
3331            ..Default::default()
3332        }
3333    }
3334
3335    /// Create config for inline mode with automatic UI height.
3336    pub fn inline_auto(min_height: u16, max_height: u16) -> Self {
3337        Self {
3338            screen_mode: ScreenMode::InlineAuto {
3339                min_height,
3340                max_height,
3341            },
3342            inline_auto_remeasure: Some(InlineAutoRemeasureConfig::default()),
3343            ..Default::default()
3344        }
3345    }
3346
3347    /// Run a gesture recognizer over the input stream and deliver recognized
3348    /// gestures to [`Model::on_gesture`]. Mouse gestures need mouse capture
3349    /// (see [`Self::with_mouse_capture_policy`]).
3350    #[must_use]
3351    pub fn with_gestures(mut self, config: ftui_core::gesture::GestureConfig) -> Self {
3352        self.gestures = Some(config);
3353        self
3354    }
3355
3356    /// Build an accessibility tree every frame and derive screen-reader
3357    /// announcements under `policy` (see [`Self::accessibility`]). Read the
3358    /// results through [`Program::accessibility_tree`] and
3359    /// [`Program::accessibility_announcements`].
3360    #[must_use]
3361    pub fn with_accessibility(mut self, policy: ScreenReaderPolicy) -> Self {
3362        self.accessibility = Some(policy);
3363        self
3364    }
3365
3366    /// Opt into announcement content in the configured evidence sink.
3367    /// See [`Self::accessibility_evidence_text`] for the privacy contract.
3368    #[must_use]
3369    pub fn with_accessibility_evidence_text(mut self, include_text: bool) -> Self {
3370        self.accessibility_evidence_text = include_text;
3371        self
3372    }
3373
3374    /// Enable mouse support.
3375    #[must_use]
3376    pub fn with_mouse(mut self) -> Self {
3377        self.mouse_capture_policy = MouseCapturePolicy::On;
3378        self
3379    }
3380
3381    /// Set mouse capture policy.
3382    #[must_use]
3383    pub fn with_mouse_capture_policy(mut self, policy: MouseCapturePolicy) -> Self {
3384        self.mouse_capture_policy = policy;
3385        self
3386    }
3387
3388    /// Force mouse capture enabled/disabled regardless of screen mode.
3389    #[must_use]
3390    pub fn with_mouse_enabled(mut self, enabled: bool) -> Self {
3391        self.mouse_capture_policy = if enabled {
3392            MouseCapturePolicy::On
3393        } else {
3394            MouseCapturePolicy::Off
3395        };
3396        self
3397    }
3398
3399    /// Resolve mouse capture using the configured policy and screen mode.
3400    #[must_use]
3401    pub const fn resolved_mouse_capture(&self) -> bool {
3402        self.mouse_capture_policy.resolve(self.screen_mode)
3403    }
3404
3405    /// Set the budget configuration.
3406    #[must_use]
3407    pub fn with_budget(mut self, budget: FrameBudgetConfig) -> Self {
3408        self.budget = budget;
3409        self
3410    }
3411
3412    /// Set the runtime load-governor configuration.
3413    #[must_use]
3414    pub fn with_load_governor(mut self, config: LoadGovernorConfig) -> Self {
3415        self.load_governor = config;
3416        self
3417    }
3418
3419    /// Disable the adaptive load governor and use legacy render-budget behavior.
3420    #[must_use]
3421    pub fn without_load_governor(mut self) -> Self {
3422        self.load_governor = LoadGovernorConfig::disabled();
3423        self
3424    }
3425
3426    /// Set the diff strategy configuration for the terminal writer.
3427    #[must_use]
3428    pub fn with_diff_config(mut self, diff_config: RuntimeDiffConfig) -> Self {
3429        self.diff_config = diff_config;
3430        self
3431    }
3432
3433    /// Set the evidence JSONL sink configuration.
3434    #[must_use]
3435    pub fn with_evidence_sink(mut self, config: EvidenceSinkConfig) -> Self {
3436        self.evidence_sink = config;
3437        self
3438    }
3439
3440    /// Set the render-trace recorder configuration.
3441    #[must_use]
3442    pub fn with_render_trace(mut self, config: RenderTraceConfig) -> Self {
3443        self.render_trace = config;
3444        self
3445    }
3446
3447    /// Set a frame timing sink for per-frame profiling.
3448    #[must_use]
3449    pub fn with_frame_timing(mut self, config: FrameTimingConfig) -> Self {
3450        self.frame_timing = Some(config);
3451        self
3452    }
3453
3454    /// Enable conformal frame-time risk gating with the given config.
3455    #[must_use]
3456    pub fn with_conformal_config(mut self, config: ConformalConfig) -> Self {
3457        self.conformal_config = Some(config);
3458        self
3459    }
3460
3461    /// Disable conformal frame-time risk gating.
3462    #[must_use]
3463    pub fn without_conformal(mut self) -> Self {
3464        self.conformal_config = None;
3465        self
3466    }
3467
3468    /// Set the locale context used for rendering.
3469    #[must_use]
3470    pub fn with_locale_context(mut self, locale_context: LocaleContext) -> Self {
3471        self.locale_context = locale_context;
3472        self
3473    }
3474
3475    /// Set the base locale used for rendering.
3476    #[must_use]
3477    pub fn with_locale(mut self, locale: impl Into<crate::locale::Locale>) -> Self {
3478        self.locale_context = LocaleContext::new(locale);
3479        self
3480    }
3481
3482    /// Set the widget refresh selection configuration.
3483    #[must_use]
3484    pub fn with_widget_refresh(mut self, config: WidgetRefreshConfig) -> Self {
3485        self.widget_refresh = config;
3486        self
3487    }
3488
3489    /// Set the effect queue scheduling configuration.
3490    #[must_use]
3491    pub fn with_effect_queue(mut self, config: EffectQueueConfig) -> Self {
3492        self.effect_queue = config;
3493        self
3494    }
3495
3496    /// Set the resize coalescer configuration.
3497    #[must_use]
3498    pub fn with_resize_coalescer(mut self, config: CoalescerConfig) -> Self {
3499        self.resize_coalescer = config;
3500        self
3501    }
3502
3503    /// Set the resize handling behavior.
3504    #[must_use]
3505    pub fn with_resize_behavior(mut self, behavior: ResizeBehavior) -> Self {
3506        self.resize_behavior = behavior;
3507        self
3508    }
3509
3510    /// Force a fixed terminal size (cols, rows). Resize events are ignored.
3511    #[must_use]
3512    pub fn with_forced_size(mut self, width: u16, height: u16) -> Self {
3513        let width = width.max(1);
3514        let height = height.max(1);
3515        self.forced_size = Some((width, height));
3516        self
3517    }
3518
3519    /// Clear any forced terminal size override.
3520    #[must_use]
3521    pub fn without_forced_size(mut self) -> Self {
3522        self.forced_size = None;
3523        self
3524    }
3525
3526    /// Toggle legacy immediate-resize behavior for migration.
3527    #[must_use]
3528    pub fn with_legacy_resize(mut self, enabled: bool) -> Self {
3529        if enabled {
3530            self.resize_behavior = ResizeBehavior::Immediate;
3531        }
3532        self
3533    }
3534
3535    /// Set the persistence configuration.
3536    #[must_use]
3537    pub fn with_persistence(mut self, persistence: PersistenceConfig) -> Self {
3538        self.persistence = persistence;
3539        self
3540    }
3541
3542    /// Enable persistence with the given registry.
3543    #[must_use]
3544    pub fn with_registry(mut self, registry: std::sync::Arc<StateRegistry>) -> Self {
3545        self.persistence = PersistenceConfig::with_registry(registry);
3546        self
3547    }
3548
3549    /// Enable inline auto UI height remeasurement with the given policy.
3550    #[must_use]
3551    pub fn with_inline_auto_remeasure(mut self, config: InlineAutoRemeasureConfig) -> Self {
3552        self.inline_auto_remeasure = Some(config);
3553        self
3554    }
3555
3556    /// Disable inline auto UI height remeasurement.
3557    #[must_use]
3558    pub fn without_inline_auto_remeasure(mut self) -> Self {
3559        self.inline_auto_remeasure = None;
3560        self
3561    }
3562
3563    /// Enable or disable signal interception (SIGHUP/SIGTERM/SIGINT) for cleanup.
3564    #[must_use]
3565    pub fn with_signal_interception(mut self, enabled: bool) -> Self {
3566        self.intercept_signals = enabled;
3567        self
3568    }
3569
3570    /// Set frame guardrails configuration.
3571    #[must_use]
3572    pub fn with_guardrails(mut self, config: GuardrailsConfig) -> Self {
3573        self.guardrails = config;
3574        self
3575    }
3576
3577    /// Set the immediate event-drain policy for burst handling.
3578    #[must_use]
3579    pub fn with_immediate_drain(mut self, config: ImmediateDrainConfig) -> Self {
3580        self.immediate_drain = config;
3581        self
3582    }
3583
3584    /// Set the tick strategy for selective background screen ticking.
3585    ///
3586    /// When set, the runtime consults the strategy to decide which inactive
3587    /// screens should tick on each frame. Without a strategy, all screens
3588    /// tick every frame (backwards-compatible default).
3589    ///
3590    /// ```ignore
3591    /// ProgramConfig::default()
3592    ///     .with_tick_strategy(TickStrategyKind::Uniform { divisor: 5 })
3593    /// ```
3594    #[must_use]
3595    pub fn with_tick_strategy(mut self, strategy: crate::tick_strategy::TickStrategyKind) -> Self {
3596        self.tick_strategy = Some(strategy);
3597        self
3598    }
3599
3600    /// Set the runtime execution lane.
3601    #[must_use]
3602    pub fn with_lane(mut self, lane: RuntimeLane) -> Self {
3603        self.runtime_lane = lane;
3604        self
3605    }
3606
3607    /// Set the rollout policy for the Asupersync migration.
3608    #[must_use]
3609    pub fn with_rollout_policy(mut self, policy: RolloutPolicy) -> Self {
3610        self.rollout_policy = policy;
3611        self
3612    }
3613
3614    /// Apply environment-variable overrides for lane and rollout policy.
3615    ///
3616    /// Reads `FTUI_RUNTIME_LANE` and `FTUI_ROLLOUT_POLICY`. Unset variables
3617    /// are ignored. Unrecognized values emit a `tracing::warn` and are
3618    /// ignored (the programmatic default or prior builder value is retained).
3619    #[must_use]
3620    pub fn with_env_overrides(mut self) -> Self {
3621        if let Some(lane) = RuntimeLane::from_env() {
3622            self.runtime_lane = lane;
3623        }
3624        if let Some(policy) = RolloutPolicy::from_env() {
3625            self.rollout_policy = policy;
3626        }
3627        self
3628    }
3629
3630    #[must_use]
3631    fn resolved_effect_queue_config(&self) -> EffectQueueConfig {
3632        if !self.effect_queue.uses_legacy_default_backend() {
3633            return self.effect_queue.clone();
3634        }
3635
3636        self.effect_queue
3637            .clone()
3638            .with_backend(self.runtime_lane.resolve().task_executor_backend())
3639    }
3640}
3641
3642fn render_budget_from_program_config(config: &ProgramConfig) -> RenderBudget {
3643    let budget = RenderBudget::from_config(&config.budget);
3644    if config.load_governor.enabled {
3645        let mut controller = config.load_governor.budget_controller.clone();
3646        controller.target = config.budget.total;
3647        budget.with_controller(controller)
3648    } else {
3649        budget
3650    }
3651}
3652
3653enum EffectCommand<M> {
3654    Enqueue(TaskSpec, Box<dyn FnOnce() -> M + Send>),
3655    Shutdown,
3656}
3657
3658#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3659enum EffectLoopControl {
3660    Continue,
3661    ShutdownRequested,
3662}
3663
3664struct EffectQueue<M: Send + 'static> {
3665    sender: mpsc::Sender<EffectCommand<M>>,
3666    handle: Option<JoinHandle<()>>,
3667    closed: bool,
3668    /// Tasks accepted by the loop thread and not yet run (published by the
3669    /// loop each iteration; read by the frame guardrail).
3670    depth: std::sync::Arc<std::sync::atomic::AtomicUsize>,
3671}
3672
3673impl<M: Send + 'static> EffectQueue<M> {
3674    fn start(
3675        config: EffectQueueConfig,
3676        result_sender: mpsc::Sender<M>,
3677        evidence_sink: Option<EvidenceSink>,
3678    ) -> io::Result<Self> {
3679        let (tx, rx) = mpsc::channel::<EffectCommand<M>>();
3680        let depth = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
3681        let loop_depth = std::sync::Arc::clone(&depth);
3682        let handle = thread::Builder::new()
3683            .name("ftui-effects".into())
3684            .spawn(move || {
3685                effect_queue_loop(config, rx, result_sender, evidence_sink, &loop_depth);
3686            })?;
3687
3688        Ok(Self {
3689            sender: tx,
3690            handle: Some(handle),
3691            closed: false,
3692            depth,
3693        })
3694    }
3695
3696    /// Tasks accepted by the queue that have not run yet.
3697    fn in_flight(&self) -> usize {
3698        self.depth.load(std::sync::atomic::Ordering::Relaxed)
3699    }
3700
3701    fn enqueue(&self, spec: TaskSpec, task: Box<dyn FnOnce() -> M + Send>) {
3702        if self.closed {
3703            crate::effect_system::record_queue_drop("post_shutdown");
3704            tracing::debug!("rejecting task enqueue after effect queue shutdown");
3705            return;
3706        }
3707        if self
3708            .sender
3709            .send(EffectCommand::Enqueue(spec, task))
3710            .is_err()
3711        {
3712            crate::effect_system::record_queue_drop("channel_closed");
3713        }
3714    }
3715
3716    /// Timeout for the effect-queue thread to finish after sending Shutdown.
3717    const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(2);
3718    /// Poll interval when waiting for the effect-queue thread (bd-170o5).
3719    ///
3720    /// This sleep-poll pattern is the idiomatic Rust approach for bounded
3721    /// thread joins — `JoinHandle` has no `join_timeout` in stable Rust.
3722    /// 1ms is chosen to minimize shutdown latency while avoiding spin.
3723    const SHUTDOWN_POLL: Duration = Duration::from_millis(1);
3724
3725    fn shutdown(&mut self) {
3726        self.closed = true;
3727        let _ = self.sender.send(EffectCommand::Shutdown);
3728        if let Some(handle) = self.handle.take() {
3729            let start = Instant::now();
3730            // Fast path: most shutdowns complete nearly instantly after the
3731            // Shutdown command is drained. Check once before entering poll loop.
3732            if handle.is_finished() {
3733                let _ = handle.join();
3734                let elapsed_us = start.elapsed().as_micros() as u64;
3735                tracing::debug!(
3736                    target: crate::telemetry_schema::TARGET_RUNTIME,
3737                    elapsed_us,
3738                    "effect-queue shutdown (fast path)"
3739                );
3740                return;
3741            }
3742            // Slow path: bounded poll loop for in-flight tasks (bd-170o5).
3743            while !handle.is_finished() {
3744                if start.elapsed() >= Self::SHUTDOWN_TIMEOUT {
3745                    tracing::warn!(
3746                        target: crate::telemetry_schema::TARGET_RUNTIME,
3747                        timeout_ms = Self::SHUTDOWN_TIMEOUT.as_millis() as u64,
3748                        "effect-queue thread did not stop within timeout; detaching"
3749                    );
3750                    return;
3751                }
3752                thread::sleep(Self::SHUTDOWN_POLL);
3753            }
3754            let _ = handle.join();
3755            let elapsed_us = start.elapsed().as_micros() as u64;
3756            tracing::debug!(
3757                target: crate::telemetry_schema::TARGET_RUNTIME,
3758                elapsed_us,
3759                "effect-queue shutdown (slow path)"
3760            );
3761        }
3762    }
3763}
3764
3765impl<M: Send + 'static> Drop for EffectQueue<M> {
3766    fn drop(&mut self) {
3767        self.shutdown();
3768    }
3769}
3770
3771struct SpawnTaskExecutor<M: Send + 'static> {
3772    result_sender: mpsc::Sender<M>,
3773    evidence_sink: Option<EvidenceSink>,
3774    handles: Vec<JoinHandle<()>>,
3775    /// Backpressure bound on in-flight spawned threads (`0` = unbounded),
3776    /// matching the EffectQueue / asupersync lanes.
3777    max_queue_depth: usize,
3778    /// Tasks shed by backpressure or post-shutdown rejection.
3779    dropped: u64,
3780    closed: bool,
3781}
3782
3783impl<M: Send + 'static> SpawnTaskExecutor<M> {
3784    const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(2);
3785    /// Poll interval for bounded thread joins (bd-170o5).
3786    ///
3787    /// Same rationale as `EffectQueue::SHUTDOWN_POLL` — `JoinHandle` has no
3788    /// `join_timeout` in stable Rust, so we poll `is_finished()` with a
3789    /// 1ms sleep to minimize shutdown latency while avoiding spin.
3790    const SHUTDOWN_POLL: Duration = Duration::from_millis(1);
3791
3792    fn new(
3793        result_sender: mpsc::Sender<M>,
3794        evidence_sink: Option<EvidenceSink>,
3795        max_queue_depth: usize,
3796    ) -> Self {
3797        Self {
3798            result_sender,
3799            evidence_sink,
3800            handles: Vec::new(),
3801            max_queue_depth,
3802            dropped: 0,
3803            closed: false,
3804        }
3805    }
3806
3807    fn submit(&mut self, task: Box<dyn FnOnce() -> M + Send>) {
3808        if self.closed {
3809            self.dropped += 1;
3810            crate::effect_system::record_queue_drop("post_shutdown");
3811            tracing::debug!("rejecting spawned task submit after shutdown");
3812            return;
3813        }
3814        // Join finished threads first so the in-flight depth used for
3815        // backpressure reflects only tasks that are still running.
3816        self.reap_finished();
3817        // Backpressure: bound the number of in-flight spawned threads. The
3818        // `with_max_queue_depth` contract promises drops + counters for every
3819        // backend; this lane previously spawned unboundedly and counted
3820        // nothing. `0` means unbounded.
3821        if self.max_queue_depth > 0 && self.handles.len() >= self.max_queue_depth {
3822            self.dropped += 1;
3823            crate::effect_system::record_queue_drop("backpressure");
3824            emit_task_executor_backpressure_evidence(
3825                self.evidence_sink.as_ref(),
3826                "spawned",
3827                "drop",
3828                self.handles.len(),
3829                self.max_queue_depth,
3830                self.dropped,
3831            );
3832            return;
3833        }
3834        crate::effect_system::record_queue_enqueue(self.handles.len() as u64 + 1);
3835        let sender = self.result_sender.clone();
3836        let evidence_sink = self.evidence_sink.clone();
3837        let handle = thread::spawn(move || {
3838            let _ = run_task_closure(task, "spawned", evidence_sink.as_ref(), &sender);
3839            crate::effect_system::record_queue_processed();
3840        });
3841        self.handles.push(handle);
3842    }
3843
3844    fn reap_finished(&mut self) {
3845        if self.handles.is_empty() {
3846            return;
3847        }
3848
3849        let mut i = 0;
3850        while i < self.handles.len() {
3851            if self.handles[i].is_finished() {
3852                let handle = self.handles.swap_remove(i);
3853                let _ = handle.join();
3854            } else {
3855                i += 1;
3856            }
3857        }
3858    }
3859
3860    fn shutdown(&mut self) {
3861        self.closed = true;
3862        let start = Instant::now();
3863        // Fast path: reap any already-finished handles first.
3864        self.reap_finished();
3865        if self.handles.is_empty() {
3866            let elapsed_us = start.elapsed().as_micros() as u64;
3867            tracing::debug!(
3868                target: crate::telemetry_schema::TARGET_RUNTIME,
3869                elapsed_us,
3870                "spawn-executor shutdown (fast path, all tasks already finished)"
3871            );
3872            return;
3873        }
3874        // Slow path: bounded poll loop for in-flight tasks (bd-170o5).
3875        let pending_at_start = self.handles.len();
3876        while self.handles.iter().any(|handle| !handle.is_finished()) {
3877            if start.elapsed() >= Self::SHUTDOWN_TIMEOUT {
3878                let still_pending = self
3879                    .handles
3880                    .iter()
3881                    .filter(|handle| !handle.is_finished())
3882                    .count();
3883                tracing::warn!(
3884                    target: crate::telemetry_schema::TARGET_RUNTIME,
3885                    timeout_ms = Self::SHUTDOWN_TIMEOUT.as_millis() as u64,
3886                    pending_handles = still_pending,
3887                    "background task threads did not stop within timeout; detaching"
3888                );
3889                self.handles.clear();
3890                return;
3891            }
3892            thread::sleep(Self::SHUTDOWN_POLL);
3893        }
3894        self.reap_finished();
3895        let elapsed_us = start.elapsed().as_micros() as u64;
3896        tracing::debug!(
3897            target: crate::telemetry_schema::TARGET_RUNTIME,
3898            elapsed_us,
3899            pending_at_start,
3900            "spawn-executor shutdown (slow path)"
3901        );
3902    }
3903}
3904
3905#[cfg(feature = "asupersync-executor")]
3906struct AsupersyncTaskExecutor<M: Send + 'static> {
3907    result_sender: mpsc::Sender<M>,
3908    evidence_sink: Option<EvidenceSink>,
3909    runtime: AsupersyncRuntime,
3910    handles: Vec<BlockingTaskHandle>,
3911    /// Backpressure cap on in-flight blocking tasks (`0` = unbounded). Mirrors
3912    /// the `EffectQueue` lane's `max_queue_depth` so both backends shed load and
3913    /// report queue telemetry identically.
3914    max_queue_depth: usize,
3915    /// Total tasks rejected by backpressure or post-shutdown submission.
3916    dropped: u64,
3917    closed: bool,
3918}
3919
3920#[cfg(feature = "asupersync-executor")]
3921impl<M: Send + 'static> AsupersyncTaskExecutor<M> {
3922    const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(2);
3923
3924    fn new(
3925        result_sender: mpsc::Sender<M>,
3926        evidence_sink: Option<EvidenceSink>,
3927        max_queue_depth: usize,
3928    ) -> io::Result<Self> {
3929        let max_threads = thread::available_parallelism().map_or(1, |count| count.get().max(1));
3930        let runtime = RuntimeBuilder::new()
3931            .blocking_threads(1, max_threads)
3932            .thread_name_prefix("ftui-asupersync-task")
3933            .build()
3934            .map_err(|error| {
3935                io::Error::other(format!("asupersync runtime init failed: {error}"))
3936            })?;
3937
3938        Ok(Self {
3939            result_sender,
3940            evidence_sink,
3941            runtime,
3942            handles: Vec::new(),
3943            max_queue_depth,
3944            dropped: 0,
3945            closed: false,
3946        })
3947    }
3948
3949    fn submit(&mut self, task: Box<dyn FnOnce() -> M + Send>) {
3950        if self.closed {
3951            self.dropped += 1;
3952            crate::effect_system::record_queue_drop("post_shutdown");
3953            tracing::debug!("rejecting asupersync task submit after shutdown");
3954            return;
3955        }
3956        // Prune completed handles so the in-flight depth used for backpressure
3957        // reflects only tasks that are still running or queued in the pool.
3958        self.handles.retain(|handle| !handle.is_done());
3959        // Backpressure: bound the number of in-flight blocking tasks, matching
3960        // the EffectQueue lane (bd-2zd0a). `0` means unbounded.
3961        if self.max_queue_depth > 0 && self.handles.len() >= self.max_queue_depth {
3962            self.dropped += 1;
3963            crate::effect_system::record_queue_drop("backpressure");
3964            emit_task_executor_backpressure_evidence(
3965                self.evidence_sink.as_ref(),
3966                "asupersync",
3967                "drop",
3968                self.handles.len(),
3969                self.max_queue_depth,
3970                self.dropped,
3971            );
3972            return;
3973        }
3974        crate::effect_system::record_queue_enqueue(self.handles.len() as u64 + 1);
3975        let sender = self.result_sender.clone();
3976        let evidence_sink = self.evidence_sink.clone();
3977        let handle = self
3978            .runtime
3979            .spawn_blocking(move || {
3980                let _ = run_task_closure(task, "asupersync", evidence_sink.as_ref(), &sender);
3981                crate::effect_system::record_queue_processed();
3982            })
3983            .expect("asupersync blocking pool must be configured");
3984        self.handles.push(handle);
3985    }
3986
3987    fn reap_finished(&mut self) {
3988        self.handles.retain(|handle| !handle.is_done());
3989    }
3990
3991    fn shutdown(&mut self) {
3992        self.closed = true;
3993        let deadline = Instant::now() + Self::SHUTDOWN_TIMEOUT;
3994        for handle in &self.handles {
3995            let remaining = deadline.saturating_duration_since(Instant::now());
3996            if remaining.is_zero() || !handle.wait_timeout(remaining) {
3997                tracing::warn!(
3998                    timeout_ms = Self::SHUTDOWN_TIMEOUT.as_millis() as u64,
3999                    pending_handles = self
4000                        .handles
4001                        .iter()
4002                        .filter(|pending| !pending.is_done())
4003                        .count(),
4004                    "Asupersync blocking tasks did not stop within timeout; detaching"
4005                );
4006                self.handles.clear();
4007                return;
4008            }
4009        }
4010        self.handles.clear();
4011    }
4012}
4013
4014enum TaskExecutor<M: Send + 'static> {
4015    Spawned(SpawnTaskExecutor<M>),
4016    Queued(EffectQueue<M>),
4017    #[cfg(feature = "asupersync-executor")]
4018    Asupersync(AsupersyncTaskExecutor<M>),
4019}
4020
4021impl<M: Send + 'static> TaskExecutor<M> {
4022    fn new(
4023        config: &EffectQueueConfig,
4024        result_sender: mpsc::Sender<M>,
4025        evidence_sink: Option<EvidenceSink>,
4026    ) -> io::Result<Self> {
4027        let executor = match config.backend {
4028            TaskExecutorBackend::Spawned => Self::Spawned(SpawnTaskExecutor::new(
4029                result_sender,
4030                evidence_sink.clone(),
4031                config.max_queue_depth,
4032            )),
4033            TaskExecutorBackend::EffectQueue => Self::Queued(EffectQueue::start(
4034                config.clone(),
4035                result_sender,
4036                evidence_sink.clone(),
4037            )?),
4038            #[cfg(feature = "asupersync-executor")]
4039            TaskExecutorBackend::Asupersync => Self::Asupersync(AsupersyncTaskExecutor::new(
4040                result_sender,
4041                evidence_sink.clone(),
4042                config.max_queue_depth,
4043            )?),
4044        };
4045
4046        emit_task_executor_backend_evidence(evidence_sink.as_ref(), executor.kind_name_for_logs());
4047        Ok(executor)
4048    }
4049
4050    fn submit(&mut self, spec: TaskSpec, task: Box<dyn FnOnce() -> M + Send>) {
4051        match self {
4052            Self::Spawned(executor) => executor.submit(task),
4053            Self::Queued(queue) => queue.enqueue(spec, task),
4054            #[cfg(feature = "asupersync-executor")]
4055            Self::Asupersync(executor) => executor.submit(task),
4056        }
4057    }
4058
4059    fn reap_finished(&mut self) {
4060        match self {
4061            Self::Spawned(executor) => executor.reap_finished(),
4062            #[cfg(feature = "asupersync-executor")]
4063            Self::Asupersync(executor) => executor.reap_finished(),
4064            Self::Queued(_) => {}
4065        }
4066    }
4067
4068    /// Tasks this executor accepted that have not produced their message
4069    /// yet: live worker threads for the spawned and asupersync lanes, the
4070    /// loop's unrun task map for the effect queue. Per program, unlike the
4071    /// process-global `effect_system::queue_telemetry()` counters, so one
4072    /// program's backlog never shows up in another's frame guardrail.
4073    fn in_flight(&mut self) -> usize {
4074        match self {
4075            Self::Spawned(executor) => {
4076                executor.reap_finished();
4077                executor.handles.len()
4078            }
4079            #[cfg(feature = "asupersync-executor")]
4080            Self::Asupersync(executor) => {
4081                executor.reap_finished();
4082                executor.handles.len()
4083            }
4084            Self::Queued(queue) => queue.in_flight(),
4085        }
4086    }
4087
4088    fn shutdown(&mut self) {
4089        match self {
4090            Self::Spawned(executor) => executor.shutdown(),
4091            Self::Queued(queue) => queue.shutdown(),
4092            #[cfg(feature = "asupersync-executor")]
4093            Self::Asupersync(executor) => executor.shutdown(),
4094        }
4095    }
4096
4097    #[cfg(test)]
4098    fn kind_name(&self) -> &'static str {
4099        self.kind_name_for_logs()
4100    }
4101
4102    fn kind_name_for_logs(&self) -> &'static str {
4103        match self {
4104            Self::Spawned(_) => "spawned",
4105            Self::Queued(_) => "queued",
4106            #[cfg(feature = "asupersync-executor")]
4107            Self::Asupersync(_) => "asupersync",
4108        }
4109    }
4110}
4111
4112fn emit_task_executor_backend_evidence(sink: Option<&EvidenceSink>, backend: &str) {
4113    let Some(sink) = sink else {
4114        return;
4115    };
4116    let _ = sink.write_jsonl(&format!(
4117        r#"{{"event":"task_executor_backend","backend":"{backend}"}}"#
4118    ));
4119}
4120
4121fn emit_task_executor_completion_evidence(
4122    sink: Option<&EvidenceSink>,
4123    backend: &str,
4124    duration_us: u64,
4125) {
4126    let Some(sink) = sink else {
4127        return;
4128    };
4129    let _ = sink.write_jsonl(&format!(
4130        r#"{{"event":"task_executor_complete","backend":"{backend}","duration_us":{duration_us}}}"#
4131    ));
4132}
4133
4134fn emit_task_executor_panic_evidence(sink: Option<&EvidenceSink>, backend: &str, panic_msg: &str) {
4135    let Some(sink) = sink else {
4136        return;
4137    };
4138    let escaped = panic_msg
4139        .replace('\\', "\\\\")
4140        .replace('"', "\\\"")
4141        .replace('\n', "\\n")
4142        .replace('\r', "\\r")
4143        .replace('\t', "\\t");
4144    let _ = sink.write_jsonl(&format!(
4145        r#"{{"event":"task_executor_panic","backend":"{backend}","panic_msg":"{escaped}"}}"#
4146    ));
4147}
4148
4149fn emit_task_executor_backpressure_evidence(
4150    sink: Option<&EvidenceSink>,
4151    backend: &str,
4152    action: &str,
4153    queue_length: usize,
4154    max_queue_size: usize,
4155    total_rejected: u64,
4156) {
4157    let Some(sink) = sink else {
4158        return;
4159    };
4160    let _ = sink.write_jsonl(&format!(
4161        r#"{{"event":"task_executor_backpressure","backend":"{backend}","action":"{action}","queue_length":{queue_length},"max_queue_size":{max_queue_size},"total_rejected":{total_rejected}}}"#
4162    ));
4163}
4164
4165fn panic_payload_message(payload: Box<dyn Any + Send>) -> String {
4166    if let Some(s) = payload.downcast_ref::<&str>() {
4167        (*s).to_owned()
4168    } else if let Some(s) = payload.downcast_ref::<String>() {
4169        s.clone()
4170    } else {
4171        "unknown panic payload".to_owned()
4172    }
4173}
4174
4175fn log_task_executor_panic(backend: &str, panic_msg: &str) {
4176    #[cfg(feature = "tracing")]
4177    tracing::error!(
4178        executor_backend = backend,
4179        panic_msg,
4180        "task executor task panicked"
4181    );
4182    #[cfg(not(feature = "tracing"))]
4183    eprintln!("ftui: task executor task panicked ({backend}): {panic_msg}");
4184}
4185
4186fn run_task_closure<M: Send + 'static>(
4187    task: Box<dyn FnOnce() -> M + Send>,
4188    backend: &str,
4189    evidence_sink: Option<&EvidenceSink>,
4190    result_sender: &mpsc::Sender<M>,
4191) -> bool {
4192    let start = Instant::now();
4193    // This is a RECOVERABLE panic boundary — the program keeps running.
4194    // Suppress the terminal panic hook: without this, a panicking task
4195    // triggers best_effort_cleanup mid-run (scroll-region reset, alt-screen
4196    // leave, raw-mode exit) and the still-live UI renders onto a cooked,
4197    // echoing main screen.
4198    let caught =
4199        ftui_core::with_panic_cleanup_suppressed(|| panic::catch_unwind(AssertUnwindSafe(task)));
4200    match caught {
4201        Ok(msg) => {
4202            let duration_us = start.elapsed().as_micros() as u64;
4203            tracing::debug!(
4204                target: crate::telemetry_schema::TARGET_EFFECT,
4205                command_type = "task",
4206                executor_backend = backend,
4207                duration_us = duration_us,
4208                effect_duration_us = duration_us,
4209                "task effect completed"
4210            );
4211            emit_task_executor_completion_evidence(evidence_sink, backend, duration_us);
4212            let _ = result_sender.send(msg);
4213            true
4214        }
4215        Err(payload) => {
4216            let panic_msg = panic_payload_message(payload);
4217            log_task_executor_panic(backend, &panic_msg);
4218            emit_task_executor_panic_evidence(evidence_sink, backend, &panic_msg);
4219            false
4220        }
4221    }
4222}
4223
4224fn effect_queue_loop<M: Send + 'static>(
4225    config: EffectQueueConfig,
4226    rx: mpsc::Receiver<EffectCommand<M>>,
4227    result_sender: mpsc::Sender<M>,
4228    evidence_sink: Option<EvidenceSink>,
4229    depth: &std::sync::atomic::AtomicUsize,
4230) {
4231    let mut scheduler = QueueingScheduler::new(config.scheduler);
4232    let mut tasks: HashMap<u64, Box<dyn FnOnce() -> M + Send>> = HashMap::new();
4233    let mut shutdown_requested = false;
4234    let max_depth = config.max_queue_depth;
4235
4236    loop {
4237        // Publish the accepted-but-unrun depth for the frame guardrail; the
4238        // loop comes back here after every command batch and every task.
4239        depth.store(tasks.len(), std::sync::atomic::Ordering::Relaxed);
4240        if tasks.is_empty() {
4241            if shutdown_requested {
4242                return;
4243            }
4244            match rx.recv() {
4245                Ok(cmd) => {
4246                    if matches!(
4247                        handle_effect_command(
4248                            cmd,
4249                            &mut scheduler,
4250                            &mut tasks,
4251                            &result_sender,
4252                            evidence_sink.as_ref(),
4253                            max_depth,
4254                        ),
4255                        EffectLoopControl::ShutdownRequested
4256                    ) {
4257                        shutdown_requested = true;
4258                    }
4259                }
4260                Err(_) => return,
4261            }
4262        }
4263
4264        while let Ok(cmd) = rx.try_recv() {
4265            if shutdown_requested && matches!(cmd, EffectCommand::Enqueue(_, _)) {
4266                crate::effect_system::record_queue_drop("post_shutdown");
4267                continue;
4268            }
4269            if matches!(
4270                handle_effect_command(
4271                    cmd,
4272                    &mut scheduler,
4273                    &mut tasks,
4274                    &result_sender,
4275                    evidence_sink.as_ref(),
4276                    max_depth,
4277                ),
4278                EffectLoopControl::ShutdownRequested
4279            ) {
4280                shutdown_requested = true;
4281            }
4282        }
4283
4284        if tasks.is_empty() {
4285            if shutdown_requested {
4286                return;
4287            }
4288            continue;
4289        }
4290
4291        let Some(job) = scheduler.peek_next().cloned() else {
4292            continue;
4293        };
4294
4295        if let Some(ref sink) = evidence_sink {
4296            let evidence = scheduler.evidence();
4297            let _ = sink.write_jsonl(&evidence.to_jsonl("effect_queue_select"));
4298        }
4299
4300        let completed = scheduler.tick(job.remaining_time);
4301        for job_id in completed {
4302            if let Some(task) = tasks.remove(&job_id) {
4303                let _ = run_task_closure(task, "queued", evidence_sink.as_ref(), &result_sender);
4304                crate::effect_system::record_queue_processed();
4305            }
4306        }
4307    }
4308}
4309
4310fn handle_effect_command<M: Send + 'static>(
4311    cmd: EffectCommand<M>,
4312    scheduler: &mut QueueingScheduler,
4313    tasks: &mut HashMap<u64, Box<dyn FnOnce() -> M + Send>>,
4314    result_sender: &mpsc::Sender<M>,
4315    evidence_sink: Option<&EvidenceSink>,
4316    max_depth: usize,
4317) -> EffectLoopControl {
4318    match cmd {
4319        EffectCommand::Enqueue(spec, task) => {
4320            // Backpressure: drop task if queue depth exceeds limit (bd-2zd0a)
4321            if max_depth > 0 && tasks.len() >= max_depth {
4322                crate::effect_system::record_queue_drop("backpressure");
4323                return EffectLoopControl::Continue;
4324            }
4325            let weight_source = if spec.weight == DEFAULT_TASK_WEIGHT {
4326                WeightSource::Default
4327            } else {
4328                WeightSource::Explicit
4329            };
4330            let estimate_source = if spec.estimate_ms == DEFAULT_TASK_ESTIMATE_MS {
4331                EstimateSource::Default
4332            } else {
4333                EstimateSource::Explicit
4334            };
4335            let id = scheduler.submit_with_sources(
4336                spec.weight,
4337                spec.estimate_ms,
4338                weight_source,
4339                estimate_source,
4340                spec.name,
4341            );
4342            if let Some(id) = id {
4343                tasks.insert(id, task);
4344                crate::effect_system::record_queue_enqueue(tasks.len() as u64);
4345            } else {
4346                let stats = scheduler.stats();
4347                emit_task_executor_backpressure_evidence(
4348                    evidence_sink,
4349                    "queued",
4350                    "inline_fallback",
4351                    stats.queue_length,
4352                    scheduler.max_queue_size(),
4353                    stats.total_rejected,
4354                );
4355                let _ =
4356                    run_task_closure(task, "queued-inline-fallback", evidence_sink, result_sender);
4357            }
4358            EffectLoopControl::Continue
4359        }
4360        EffectCommand::Shutdown => EffectLoopControl::ShutdownRequested,
4361    }
4362}
4363
4364// removed: legacy ResizeDebouncer (superseded by ResizeCoalescer)
4365
4366/// Policy for remeasuring inline auto UI height.
4367///
4368/// Uses VOI (value-of-information) sampling to decide when to perform
4369/// a costly full-height measurement, with any-time valid guarantees via
4370/// the embedded e-process in `VoiSampler`.
4371#[derive(Debug, Clone)]
4372pub struct InlineAutoRemeasureConfig {
4373    /// VOI sampling configuration.
4374    pub voi: VoiConfig,
4375    /// Minimum row delta to count as a "violation".
4376    pub change_threshold_rows: u16,
4377}
4378
4379impl Default for InlineAutoRemeasureConfig {
4380    fn default() -> Self {
4381        Self {
4382            voi: VoiConfig {
4383                // Height changes are expected to be rare; bias toward fewer samples.
4384                prior_alpha: 1.0,
4385                prior_beta: 9.0,
4386                // Allow ~1s max latency to adapt to growth/shrink.
4387                max_interval_ms: 1000,
4388                // Avoid over-sampling in high-FPS loops.
4389                min_interval_ms: 100,
4390                // Disable event forcing; use time-based gating.
4391                max_interval_events: 0,
4392                min_interval_events: 0,
4393                // Treat sampling as moderately expensive.
4394                sample_cost: 0.08,
4395                ..VoiConfig::default()
4396            },
4397            change_threshold_rows: 1,
4398        }
4399    }
4400}
4401
4402#[derive(Debug)]
4403struct InlineAutoRemeasureState {
4404    config: InlineAutoRemeasureConfig,
4405    sampler: VoiSampler,
4406}
4407
4408impl InlineAutoRemeasureState {
4409    fn new(config: InlineAutoRemeasureConfig) -> Self {
4410        let sampler = VoiSampler::new(config.voi.clone());
4411        Self { config, sampler }
4412    }
4413
4414    fn reset(&mut self) {
4415        self.sampler = VoiSampler::new(self.config.voi.clone());
4416    }
4417}
4418
4419#[derive(Debug, Clone)]
4420struct ConformalEvidence {
4421    bucket_key: String,
4422    n_b: usize,
4423    alpha: f64,
4424    q_b: Option<f64>,
4425    y_hat: f64,
4426    upper_us: Option<f64>,
4427    risk: bool,
4428    status: ConformalStatus,
4429    required_rank: usize,
4430    fallback_level: u8,
4431    window_size: usize,
4432    reset_count: u64,
4433}
4434
4435impl ConformalEvidence {
4436    fn from_prediction(prediction: &ConformalPrediction) -> Self {
4437        Self {
4438            bucket_key: prediction.bucket.to_string(),
4439            n_b: prediction.sample_count,
4440            alpha: prediction.alpha,
4441            q_b: prediction.quantile,
4442            y_hat: prediction.y_hat,
4443            upper_us: prediction.upper_us,
4444            risk: prediction.risk,
4445            status: prediction.status,
4446            required_rank: prediction.required_rank,
4447            fallback_level: prediction.fallback_level,
4448            window_size: prediction.window_size,
4449            reset_count: prediction.reset_count,
4450        }
4451    }
4452}
4453
4454#[derive(Debug, Clone)]
4455struct BudgetDecisionEvidence {
4456    frame_idx: u64,
4457    decision: BudgetDecision,
4458    controller_decision: BudgetDecision,
4459    degradation_before: DegradationLevel,
4460    degradation_after: DegradationLevel,
4461    frame_time_us: f64,
4462    budget_us: f64,
4463    pid_output: f64,
4464    pid_p: f64,
4465    pid_i: f64,
4466    pid_d: f64,
4467    e_value: f64,
4468    frames_observed: u32,
4469    frames_since_change: u32,
4470    in_warmup: bool,
4471    controller_reason: BudgetDecisionReason,
4472    load_governor: LoadGovernorSnapshot,
4473    /// Detector that made the resize coalescer's latest regime decision.
4474    resize_detector: &'static str,
4475    conformal: Option<ConformalEvidence>,
4476}
4477
4478impl BudgetDecisionEvidence {
4479    fn decision_from_levels(before: DegradationLevel, after: DegradationLevel) -> BudgetDecision {
4480        if after > before {
4481            BudgetDecision::Degrade
4482        } else if after < before {
4483            BudgetDecision::Upgrade
4484        } else {
4485            BudgetDecision::Hold
4486        }
4487    }
4488
4489    #[must_use]
4490    fn to_jsonl(&self) -> String {
4491        let conformal = self.conformal.as_ref();
4492        let bucket_key = Self::opt_str(conformal.map(|c| c.bucket_key.as_str()));
4493        let n_b = Self::opt_usize(conformal.map(|c| c.n_b));
4494        let alpha = crate::conformal_predictor::finite_json_number(conformal.map(|c| c.alpha), 17);
4495        let q_b = Self::opt_f64(conformal.and_then(|c| c.q_b));
4496        let y_hat = Self::opt_f64(conformal.map(|c| c.y_hat));
4497        let upper_us = Self::opt_f64(conformal.and_then(|c| c.upper_us));
4498        let risk = Self::opt_bool(conformal.map(|c| c.risk));
4499        let conformal_status = Self::opt_str(conformal.map(|c| c.status.as_str()));
4500        let required_rank = Self::opt_usize(conformal.map(|c| c.required_rank));
4501        let fallback_level = Self::opt_u8(conformal.map(|c| c.fallback_level));
4502        let window_size = Self::opt_usize(conformal.map(|c| c.window_size));
4503        let reset_count = Self::opt_u64(conformal.map(|c| c.reset_count));
4504        let queue_max_depth = Self::opt_usize(self.load_governor.queue_max_depth);
4505
4506        format!(
4507            r#"{{"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},"frames_observed":{},"frames_since_change":{},"in_warmup":{},"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":{}}}"#,
4508            self.frame_idx,
4509            self.decision.as_str(),
4510            self.controller_decision.as_str(),
4511            self.controller_reason.as_str(),
4512            self.degradation_before.as_str(),
4513            self.degradation_after.as_str(),
4514            self.frame_time_us,
4515            self.budget_us,
4516            self.pid_output,
4517            self.pid_p,
4518            self.pid_i,
4519            self.pid_d,
4520            self.e_value,
4521            self.frames_observed,
4522            self.frames_since_change,
4523            self.in_warmup,
4524            self.load_governor.mode.as_str(),
4525            self.load_governor.mode_before.as_str(),
4526            self.load_governor.pressure_class.as_str(),
4527            self.load_governor.disposition.as_str(),
4528            self.load_governor.reason_code,
4529            self.load_governor.transition,
4530            self.load_governor.strict_semantics_preserved,
4531            self.load_governor.queue_in_flight,
4532            queue_max_depth,
4533            self.load_governor.queue_dropped_delta,
4534            self.load_governor.resize_coalescing_active,
4535            self.resize_detector,
4536            self.load_governor.recovery_intervals_observed,
4537            self.load_governor.recovery_intervals_required,
4538            self.load_governor.deferred_work_total,
4539            self.load_governor.coalesced_work_total,
4540            self.load_governor.dropped_work_total,
4541            bucket_key,
4542            n_b,
4543            alpha,
4544            q_b,
4545            y_hat,
4546            upper_us,
4547            risk,
4548            conformal_status,
4549            required_rank,
4550            fallback_level,
4551            window_size,
4552            reset_count
4553        )
4554    }
4555
4556    fn opt_f64(value: Option<f64>) -> String {
4557        crate::conformal_predictor::finite_json_number(value, 6)
4558    }
4559
4560    fn opt_u64(value: Option<u64>) -> String {
4561        value
4562            .map(|v| v.to_string())
4563            .unwrap_or_else(|| "null".to_string())
4564    }
4565
4566    fn opt_u8(value: Option<u8>) -> String {
4567        value
4568            .map(|v| v.to_string())
4569            .unwrap_or_else(|| "null".to_string())
4570    }
4571
4572    fn opt_usize(value: Option<usize>) -> String {
4573        value
4574            .map(|v| v.to_string())
4575            .unwrap_or_else(|| "null".to_string())
4576    }
4577
4578    fn opt_bool(value: Option<bool>) -> String {
4579        value
4580            .map(|v| v.to_string())
4581            .unwrap_or_else(|| "null".to_string())
4582    }
4583
4584    fn opt_str(value: Option<&str>) -> String {
4585        value
4586            .map(|v| {
4587                format!(
4588                    "\"{}\"",
4589                    v.replace('\\', "\\\\")
4590                        .replace('"', "\\\"")
4591                        .replace('\n', "\\n")
4592                        .replace('\r', "\\r")
4593                        .replace('\t', "\\t")
4594                )
4595            })
4596            .unwrap_or_else(|| "null".to_string())
4597    }
4598}
4599
4600#[derive(Debug, Clone)]
4601struct FairnessConfigEvidence {
4602    enabled: bool,
4603    input_priority_threshold_ms: u64,
4604    dominance_threshold: u32,
4605    fairness_threshold: f64,
4606}
4607
4608impl FairnessConfigEvidence {
4609    #[must_use]
4610    fn to_jsonl(&self) -> String {
4611        format!(
4612            r#"{{"event":"fairness_config","enabled":{},"input_priority_threshold_ms":{},"dominance_threshold":{},"fairness_threshold":{:.6}}}"#,
4613            self.enabled,
4614            self.input_priority_threshold_ms,
4615            self.dominance_threshold,
4616            self.fairness_threshold
4617        )
4618    }
4619}
4620
4621#[derive(Debug, Clone)]
4622struct FairnessDecisionEvidence {
4623    frame_idx: u64,
4624    decision: &'static str,
4625    reason: &'static str,
4626    pending_input_latency_ms: Option<u64>,
4627    jain_index: f64,
4628    resize_dominance_count: u32,
4629    dominance_threshold: u32,
4630    fairness_threshold: f64,
4631    input_priority_threshold_ms: u64,
4632}
4633
4634impl FairnessDecisionEvidence {
4635    #[must_use]
4636    fn to_jsonl(&self) -> String {
4637        let pending_latency = self
4638            .pending_input_latency_ms
4639            .map(|v| v.to_string())
4640            .unwrap_or_else(|| "null".to_string());
4641        format!(
4642            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":{}}}"#,
4643            self.frame_idx,
4644            self.decision,
4645            self.reason,
4646            pending_latency,
4647            self.jain_index,
4648            self.resize_dominance_count,
4649            self.dominance_threshold,
4650            self.fairness_threshold,
4651            self.input_priority_threshold_ms
4652        )
4653    }
4654}
4655
4656#[derive(Debug, Clone)]
4657struct WidgetRefreshEntry {
4658    widget_id: u64,
4659    essential: bool,
4660    starved: bool,
4661    value: f32,
4662    cost_us: f32,
4663    score: f32,
4664    staleness_ms: u64,
4665}
4666
4667impl WidgetRefreshEntry {
4668    fn to_json(&self) -> String {
4669        format!(
4670            r#"{{"id":{},"cost_us":{:.3},"value":{:.4},"score":{:.4},"essential":{},"starved":{},"staleness_ms":{}}}"#,
4671            self.widget_id,
4672            self.cost_us,
4673            self.value,
4674            self.score,
4675            self.essential,
4676            self.starved,
4677            self.staleness_ms
4678        )
4679    }
4680}
4681
4682#[derive(Debug, Clone)]
4683struct WidgetRefreshPlan {
4684    frame_idx: u64,
4685    budget_us: f64,
4686    degradation: DegradationLevel,
4687    essentials_cost_us: f64,
4688    selected_cost_us: f64,
4689    selected_value: f64,
4690    signal_count: usize,
4691    selected: Vec<WidgetRefreshEntry>,
4692    skipped_count: usize,
4693    skipped_starved: usize,
4694    starved_selected: usize,
4695    over_budget: bool,
4696}
4697
4698impl WidgetRefreshPlan {
4699    fn new() -> Self {
4700        Self {
4701            frame_idx: 0,
4702            budget_us: 0.0,
4703            degradation: DegradationLevel::Full,
4704            essentials_cost_us: 0.0,
4705            selected_cost_us: 0.0,
4706            selected_value: 0.0,
4707            signal_count: 0,
4708            selected: Vec::new(),
4709            skipped_count: 0,
4710            skipped_starved: 0,
4711            starved_selected: 0,
4712            over_budget: false,
4713        }
4714    }
4715
4716    fn clear(&mut self) {
4717        self.frame_idx = 0;
4718        self.budget_us = 0.0;
4719        self.degradation = DegradationLevel::Full;
4720        self.essentials_cost_us = 0.0;
4721        self.selected_cost_us = 0.0;
4722        self.selected_value = 0.0;
4723        self.signal_count = 0;
4724        self.selected.clear();
4725        self.skipped_count = 0;
4726        self.skipped_starved = 0;
4727        self.starved_selected = 0;
4728        self.over_budget = false;
4729    }
4730
4731    fn as_budget(&self) -> WidgetBudget {
4732        if self.signal_count == 0 {
4733            return WidgetBudget::allow_all();
4734        }
4735        let ids = self.selected.iter().map(|entry| entry.widget_id).collect();
4736        WidgetBudget::allow_only(ids)
4737    }
4738
4739    fn recompute(
4740        &mut self,
4741        frame_idx: u64,
4742        budget_us: f64,
4743        degradation: DegradationLevel,
4744        signals: &[WidgetSignal],
4745        config: &WidgetRefreshConfig,
4746    ) {
4747        self.clear();
4748        self.frame_idx = frame_idx;
4749        self.budget_us = budget_us;
4750        self.degradation = degradation;
4751
4752        if !config.enabled || signals.is_empty() {
4753            return;
4754        }
4755
4756        self.signal_count = signals.len();
4757        let mut essentials_cost = 0.0f64;
4758        let mut selected_cost = 0.0f64;
4759        let mut selected_value = 0.0f64;
4760
4761        let staleness_window = config.staleness_window_ms.max(1) as f32;
4762        let mut candidates: Vec<WidgetRefreshEntry> = Vec::with_capacity(signals.len());
4763
4764        for signal in signals {
4765            let starved = config.starve_ms > 0 && signal.staleness_ms >= config.starve_ms;
4766            let staleness_score = (signal.staleness_ms as f32 / staleness_window).min(1.0);
4767            let mut value = config.weight_priority * signal.priority
4768                + config.weight_staleness * staleness_score
4769                + config.weight_focus * signal.focus_boost
4770                + config.weight_interaction * signal.interaction_boost;
4771            if starved {
4772                value += config.starve_boost;
4773            }
4774            let raw_cost = if signal.recent_cost_us > 0.0 {
4775                signal.recent_cost_us
4776            } else {
4777                signal.cost_estimate_us
4778            };
4779            let cost_us = raw_cost.max(config.min_cost_us);
4780            let score = if cost_us > 0.0 {
4781                value / cost_us
4782            } else {
4783                value
4784            };
4785
4786            let entry = WidgetRefreshEntry {
4787                widget_id: signal.widget_id,
4788                essential: signal.essential,
4789                starved,
4790                value,
4791                cost_us,
4792                score,
4793                staleness_ms: signal.staleness_ms,
4794            };
4795
4796            if degradation >= DegradationLevel::EssentialOnly && !signal.essential {
4797                self.skipped_count += 1;
4798                if starved {
4799                    self.skipped_starved = self.skipped_starved.saturating_add(1);
4800                }
4801                continue;
4802            }
4803
4804            if signal.essential {
4805                essentials_cost += cost_us as f64;
4806                selected_cost += cost_us as f64;
4807                selected_value += value as f64;
4808                if starved {
4809                    self.starved_selected = self.starved_selected.saturating_add(1);
4810                }
4811                self.selected.push(entry);
4812            } else {
4813                candidates.push(entry);
4814            }
4815        }
4816
4817        let mut remaining = budget_us - selected_cost;
4818
4819        if degradation < DegradationLevel::EssentialOnly {
4820            let nonessential_total = candidates.len();
4821            let max_drop_fraction = config.max_drop_fraction.clamp(0.0, 1.0);
4822            let enforce_drop_rate = max_drop_fraction < 1.0 && nonessential_total > 0;
4823            let min_nonessential_selected = if enforce_drop_rate {
4824                let min_fraction = (1.0 - max_drop_fraction).max(0.0);
4825                ((min_fraction * nonessential_total as f32).ceil() as usize).min(nonessential_total)
4826            } else {
4827                0
4828            };
4829
4830            candidates.sort_by(|a, b| {
4831                b.starved
4832                    .cmp(&a.starved)
4833                    .then_with(|| b.score.total_cmp(&a.score))
4834                    .then_with(|| b.value.total_cmp(&a.value))
4835                    .then_with(|| a.cost_us.total_cmp(&b.cost_us))
4836                    .then_with(|| a.widget_id.cmp(&b.widget_id))
4837            });
4838
4839            let mut forced_starved = 0usize;
4840            let mut nonessential_selected = 0usize;
4841            let mut skipped_candidates = if enforce_drop_rate {
4842                Vec::with_capacity(candidates.len())
4843            } else {
4844                Vec::new()
4845            };
4846
4847            for entry in candidates.into_iter() {
4848                if entry.starved && forced_starved >= config.max_starved_per_frame {
4849                    self.skipped_count += 1;
4850                    self.skipped_starved = self.skipped_starved.saturating_add(1);
4851                    if enforce_drop_rate {
4852                        skipped_candidates.push(entry);
4853                    }
4854                    continue;
4855                }
4856
4857                if remaining >= entry.cost_us as f64 {
4858                    remaining -= entry.cost_us as f64;
4859                    selected_cost += entry.cost_us as f64;
4860                    selected_value += entry.value as f64;
4861                    if entry.starved {
4862                        self.starved_selected = self.starved_selected.saturating_add(1);
4863                        forced_starved += 1;
4864                    }
4865                    nonessential_selected += 1;
4866                    self.selected.push(entry);
4867                } else if entry.starved
4868                    && forced_starved < config.max_starved_per_frame
4869                    && nonessential_selected == 0
4870                {
4871                    // Starvation guard: ensure at least one starved widget can refresh.
4872                    selected_cost += entry.cost_us as f64;
4873                    selected_value += entry.value as f64;
4874                    self.starved_selected = self.starved_selected.saturating_add(1);
4875                    forced_starved += 1;
4876                    nonessential_selected += 1;
4877                    self.selected.push(entry);
4878                } else {
4879                    self.skipped_count += 1;
4880                    if entry.starved {
4881                        self.skipped_starved = self.skipped_starved.saturating_add(1);
4882                    }
4883                    if enforce_drop_rate {
4884                        skipped_candidates.push(entry);
4885                    }
4886                }
4887            }
4888
4889            if enforce_drop_rate && nonessential_selected < min_nonessential_selected {
4890                for entry in skipped_candidates.into_iter() {
4891                    if nonessential_selected >= min_nonessential_selected {
4892                        break;
4893                    }
4894                    if entry.starved && forced_starved >= config.max_starved_per_frame {
4895                        continue;
4896                    }
4897                    selected_cost += entry.cost_us as f64;
4898                    selected_value += entry.value as f64;
4899                    if entry.starved {
4900                        self.starved_selected = self.starved_selected.saturating_add(1);
4901                        forced_starved += 1;
4902                        self.skipped_starved = self.skipped_starved.saturating_sub(1);
4903                    }
4904                    self.skipped_count = self.skipped_count.saturating_sub(1);
4905                    nonessential_selected += 1;
4906                    self.selected.push(entry);
4907                }
4908            }
4909        }
4910
4911        self.essentials_cost_us = essentials_cost;
4912        self.selected_cost_us = selected_cost;
4913        self.selected_value = selected_value;
4914        self.over_budget = selected_cost > budget_us;
4915    }
4916
4917    #[must_use]
4918    fn to_jsonl(&self) -> String {
4919        let mut out = String::with_capacity(256 + self.selected.len() * 96);
4920        out.push_str(r#"{"event":"widget_refresh""#);
4921        out.push_str(&format!(
4922            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":{}"#,
4923            self.frame_idx,
4924            self.budget_us,
4925            self.degradation.as_str(),
4926            self.essentials_cost_us,
4927            self.selected_cost_us,
4928            self.selected_value,
4929            self.selected.len(),
4930            self.skipped_count,
4931            self.starved_selected,
4932            self.skipped_starved,
4933            self.over_budget
4934        ));
4935        out.push_str(r#","selected":["#);
4936        for (i, entry) in self.selected.iter().enumerate() {
4937            if i > 0 {
4938                out.push(',');
4939            }
4940            out.push_str(&entry.to_json());
4941        }
4942        out.push_str("]}");
4943        out
4944    }
4945}
4946
4947// =============================================================================
4948// CrosstermEventSource: BackendEventSource adapter for TerminalSession
4949// =============================================================================
4950
4951#[cfg(feature = "crossterm-compat")]
4952/// Adapter that wraps [`TerminalSession`] to implement [`BackendEventSource`].
4953///
4954/// This provides the bridge between the legacy crossterm-based terminal session
4955/// and the new backend abstraction. Once the native `ftui-tty` backend fully
4956/// replaces crossterm, this adapter will be removed.
4957pub struct CrosstermEventSource {
4958    session: TerminalSession,
4959    features: BackendFeatures,
4960}
4961
4962#[cfg(feature = "crossterm-compat")]
4963impl CrosstermEventSource {
4964    /// Create a new crossterm event source from a terminal session.
4965    pub fn new(session: TerminalSession, initial_features: BackendFeatures) -> Self {
4966        Self {
4967            session,
4968            features: initial_features,
4969        }
4970    }
4971}
4972
4973#[cfg(feature = "crossterm-compat")]
4974impl BackendEventSource for CrosstermEventSource {
4975    type Error = io::Error;
4976
4977    fn size(&self) -> Result<(u16, u16), io::Error> {
4978        self.session.size()
4979    }
4980
4981    fn set_features(&mut self, features: BackendFeatures) -> Result<(), io::Error> {
4982        if features.mouse_capture != self.features.mouse_capture {
4983            self.session.set_mouse_capture(features.mouse_capture)?;
4984        }
4985        // bracketed_paste, focus_events, and kitty_keyboard are set at session
4986        // construction and cleaned up in TerminalSession::Drop. Runtime toggling
4987        // is not supported by the crossterm backend.
4988        self.features = features;
4989        Ok(())
4990    }
4991
4992    fn poll_event(&mut self, timeout: Duration) -> Result<bool, io::Error> {
4993        self.session.poll_event(timeout)
4994    }
4995
4996    fn read_event(&mut self) -> Result<Option<Event>, io::Error> {
4997        self.session.read_event()
4998    }
4999}
5000
5001// =============================================================================
5002// HeadlessEventSource: no-op event source for headless/test programs
5003// =============================================================================
5004
5005/// A no-op event source for headless and test programs.
5006///
5007/// Returns a fixed terminal size, accepts feature changes silently, and never
5008/// produces events. This allows the test helper to construct a `Program`
5009/// without depending on crossterm or a real terminal.
5010pub struct HeadlessEventSource {
5011    width: u16,
5012    height: u16,
5013    features: BackendFeatures,
5014}
5015
5016impl HeadlessEventSource {
5017    /// Create a headless event source with the given terminal size.
5018    pub fn new(width: u16, height: u16, features: BackendFeatures) -> Self {
5019        Self {
5020            width,
5021            height,
5022            features,
5023        }
5024    }
5025}
5026
5027impl BackendEventSource for HeadlessEventSource {
5028    type Error = io::Error;
5029
5030    fn size(&self) -> Result<(u16, u16), io::Error> {
5031        Ok((self.width, self.height))
5032    }
5033
5034    fn set_features(&mut self, features: BackendFeatures) -> Result<(), io::Error> {
5035        self.features = features;
5036        Ok(())
5037    }
5038
5039    fn poll_event(&mut self, _timeout: Duration) -> Result<bool, io::Error> {
5040        Ok(false)
5041    }
5042
5043    fn read_event(&mut self) -> Result<Option<Event>, io::Error> {
5044        Ok(None)
5045    }
5046}
5047
5048// =============================================================================
5049// Program
5050// =============================================================================
5051
5052/// The program runtime that manages the update/view loop.
5053pub struct Program<M: Model, E: BackendEventSource<Error = io::Error>, W: Write + Send = Stdout> {
5054    /// The application model.
5055    model: M,
5056    /// Terminal output coordinator.
5057    writer: TerminalWriter<W>,
5058    /// Event source (terminal input, size queries, feature toggles).
5059    events: E,
5060    /// Currently active backend feature toggles.
5061    backend_features: BackendFeatures,
5062    /// Whether the program is running.
5063    running: bool,
5064    /// Whether the model shutdown hook and runtime teardown have completed.
5065    shutdown_complete: bool,
5066    /// Current tick rate (if any).
5067    tick_rate: Option<Duration>,
5068    /// Total commands actually executed by the runtime.
5069    executed_cmd_count: usize,
5070    /// Last tick time.
5071    last_tick: Instant,
5072    /// Whether the UI needs to be redrawn.
5073    dirty: bool,
5074    /// Monotonic frame index for evidence logging.
5075    frame_idx: u64,
5076    /// Monotonic tick index for tick-strategy scheduling.
5077    tick_count: u64,
5078    /// Widget scheduling signals captured during the last render.
5079    widget_signals: Vec<WidgetSignal>,
5080    /// Widget refresh selection configuration.
5081    widget_refresh_config: WidgetRefreshConfig,
5082    /// Last computed widget refresh plan.
5083    widget_refresh_plan: WidgetRefreshPlan,
5084    /// Current terminal width.
5085    width: u16,
5086    /// Current terminal height.
5087    height: u16,
5088    /// Forced terminal size override (when set, resize events are ignored).
5089    forced_size: Option<(u16, u16)>,
5090    /// Poll timeout when no tick is scheduled.
5091    poll_timeout: Duration,
5092    /// Whether the runtime should observe process-level termination signals.
5093    intercept_signals: bool,
5094    /// Termination signal recorded for this program instance (0 = none).
5095    ///
5096    /// Interactive constructors additionally consult the process-global slot
5097    /// that the OS signal handler thread writes to (`global_signal_slot`);
5098    /// headless and simulator programs only ever see signals injected through
5099    /// [`Program::inject_termination_signal`], so parallel tests can never
5100    /// clear or observe each other's pending signal.
5101    pending_signal: Arc<std::sync::atomic::AtomicI32>,
5102    /// Whether `observed_termination_signal` also reads the process-global
5103    /// slot written by the installed OS signal handler.
5104    global_signal_slot: bool,
5105    /// Immediate drain policy for bursty input handling.
5106    immediate_drain_config: ImmediateDrainConfig,
5107    /// Runtime counters for immediate-drain behavior.
5108    immediate_drain_stats: ImmediateDrainStats,
5109    /// Frame budget configuration.
5110    budget: RenderBudget,
5111    /// Runtime load-governor state for mode and fallback evidence.
5112    load_governor: LoadGovernorState,
5113    /// Conformal predictor for frame-time risk gating.
5114    conformal_predictor: Option<ConformalPredictor>,
5115    /// Last observed frame time (microseconds), used as a baseline predictor.
5116    last_frame_time_us: Option<f64>,
5117    /// Last observed update duration (microseconds).
5118    last_update_us: Option<u64>,
5119    /// Optional frame timing sink for profiling.
5120    frame_timing: Option<FrameTimingConfig>,
5121    /// Locale context used for rendering.
5122    locale_context: LocaleContext,
5123    /// Last observed locale version.
5124    locale_version: u64,
5125    /// Resize coalescer for rapid resize events.
5126    resize_coalescer: ResizeCoalescer,
5127    /// Shared evidence sink for decision logs (optional).
5128    evidence_sink: Option<EvidenceSink>,
5129    /// Whether fairness config has been logged to evidence sink.
5130    fairness_config_logged: bool,
5131    /// Resize handling behavior.
5132    resize_behavior: ResizeBehavior,
5133    /// Input fairness guard for scheduler integration.
5134    fairness_guard: InputFairnessGuard,
5135    /// Optional event recorder for macro capture.
5136    event_recorder: Option<EventRecorder>,
5137    /// Subscription lifecycle manager.
5138    subscriptions: SubscriptionManager<M::Message>,
5139    /// Channel for receiving messages from background tasks.
5140    #[cfg(test)]
5141    task_sender: std::sync::mpsc::Sender<M::Message>,
5142    /// Channel for receiving messages from background tasks.
5143    task_receiver: std::sync::mpsc::Receiver<M::Message>,
5144    /// Internal task execution substrate behind `Cmd::Task`.
5145    task_executor: TaskExecutor<M::Message>,
5146    /// Optional state registry for widget persistence.
5147    state_registry: Option<std::sync::Arc<StateRegistry>>,
5148    /// Persistence configuration.
5149    persistence_config: PersistenceConfig,
5150    /// Last checkpoint save time.
5151    last_checkpoint: Instant,
5152    /// Inline auto UI height remeasurement state.
5153    inline_auto_remeasure: Option<InlineAutoRemeasureState>,
5154    /// Gesture recognizer fed by `handle_event` when
5155    /// `ProgramConfig::gestures` is set.
5156    gesture_recognizer: Option<ftui_core::gesture::GestureRecognizer>,
5157    /// Screen-reader policy when `ProgramConfig::accessibility` is set.
5158    a11y_policy: Option<ScreenReaderPolicy>,
5159    /// Explicit content capture policy for accessibility evidence only.
5160    a11y_evidence_text: bool,
5161    /// Accessibility tree built from the last rendered frame.
5162    a11y_tree: Option<A11yTree>,
5163    /// Reading order (node IDs, push order) of the last accessibility tree.
5164    a11y_order: Vec<u64>,
5165    /// Screen-reader announcements derived from the last frame's tree diff.
5166    a11y_announcements: Vec<ScreenReaderAnnouncement>,
5167    /// Tree and reading order collected during `render_buffer`, consumed by
5168    /// `process_a11y_frame` once the frame has been rendered.
5169    a11y_pending: Option<(A11yTree, Vec<u64>)>,
5170    /// Set by `process_a11y_frame` when the tree differed from the previous
5171    /// frame; `render_frame` then delivers [`Model::on_accessibility`].
5172    a11y_changed: bool,
5173    /// Announcements dropped by the policy cap in the last frame.
5174    a11y_dropped: usize,
5175    /// Input events recovered from bytes the startup capability probes read
5176    /// off the tty while waiting for terminal replies; delivered before the
5177    /// main loop so a key or click during startup is not lost.
5178    startup_events: Vec<Event>,
5179    /// Preserve sequence state across successive recovered byte chunks.
5180    startup_parser: ftui_core::input_parser::InputParser,
5181    /// Per-frame bump arena for temporary render-path allocations.
5182    frame_arena: FrameArena,
5183    /// Unified frame guardrails (memory/queue limits).
5184    guardrails: FrameGuardrails,
5185    /// Frame index of the last soft-tier capacity trim (`None` = never
5186    /// trimmed).
5187    ///
5188    /// Soft memory alerts fire on retained CAPACITY that only a rebuild can
5189    /// shed; trimming every alerting frame would thrash allocations when
5190    /// usage hovers near the limit, so trims are cooldown-gated
5191    /// (bd-1za0z: actuator must be able to move the sensor).
5192    last_soft_trim_frame: Option<u64>,
5193    /// Optional tick strategy for selective background screen ticking.
5194    tick_strategy: Option<Box<dyn crate::tick_strategy::TickStrategy>>,
5195    /// Last active screen observed by the tick strategy dispatch path.
5196    last_active_screen_for_strategy: Option<String>,
5197}
5198
5199#[cfg(feature = "crossterm-compat")]
5200impl<M: Model> Program<M, CrosstermEventSource, Stdout> {
5201    /// Create a new program with default configuration.
5202    pub fn new(model: M) -> io::Result<Self>
5203    where
5204        M::Message: Send + 'static,
5205    {
5206        Self::with_config(model, ProgramConfig::default())
5207    }
5208
5209    /// Create a new program with the specified configuration.
5210    pub fn with_config(model: M, config: ProgramConfig) -> io::Result<Self>
5211    where
5212        M::Message: Send + 'static,
5213    {
5214        let resolved_lane = config.runtime_lane.resolve();
5215        let effect_queue_config = config.resolved_effect_queue_config();
5216        let mut capabilities = TerminalCapabilities::with_overrides();
5217        let mouse_capture = config.resolved_mouse_capture();
5218        let requested_features = BackendFeatures {
5219            mouse_capture,
5220            bracketed_paste: config.bracketed_paste,
5221            focus_events: config.focus_reporting,
5222            kitty_keyboard: config.kitty_keyboard,
5223        };
5224        let initial_features =
5225            sanitize_backend_features_for_capabilities(requested_features, &capabilities);
5226        let session = TerminalSession::new(SessionOptions {
5227            alternate_screen: matches!(config.screen_mode, ScreenMode::AltScreen),
5228            mouse_capture: initial_features.mouse_capture,
5229            bracketed_paste: initial_features.bracketed_paste,
5230            focus_events: initial_features.focus_events,
5231            kitty_keyboard: initial_features.kitty_keyboard,
5232            intercept_signals: config.intercept_signals,
5233        })?;
5234        let events = CrosstermEventSource::new(session, initial_features);
5235
5236        // Raw mode is active now, so the terminal can answer probes; the
5237        // writer built below must see the refined capabilities.
5238        let capability_decisions = probe_live_terminal(&mut capabilities);
5239        let scroll_region =
5240            verify_scroll_region(&capabilities, config.screen_mode, events.size().ok());
5241
5242        let mut writer = TerminalWriter::with_diff_config(
5243            io::stdout(),
5244            config.screen_mode,
5245            config.ui_anchor,
5246            capabilities,
5247            config.diff_config.clone(),
5248        )
5249        .with_capability_decisions(capability_decisions);
5250        writer.set_scroll_region_verified(
5251            scroll_region.verdict,
5252            scroll_region.rows,
5253            scroll_region.region_bottom,
5254        );
5255
5256        let frame_timing = config.frame_timing.clone();
5257        writer.set_timing_enabled(frame_timing.is_some());
5258
5259        let evidence_sink = EvidenceSink::from_config(&config.evidence_sink)?;
5260        if let Some(ref sink) = evidence_sink {
5261            writer = writer.with_evidence_sink(sink.clone());
5262        }
5263
5264        let render_trace = crate::RenderTraceRecorder::from_config(
5265            &config.render_trace,
5266            crate::RenderTraceContext {
5267                capabilities: writer.capabilities(),
5268                diff_config: config.diff_config.clone(),
5269                resize_config: config.resize_coalescer.clone(),
5270                conformal_config: config.conformal_config.clone(),
5271            },
5272        )?;
5273        if let Some(recorder) = render_trace {
5274            writer = writer.with_render_trace(recorder);
5275        }
5276
5277        // Get terminal size for initial frame (or forced size override).
5278        let (w, h) = config
5279            .forced_size
5280            .unwrap_or_else(|| events.size().unwrap_or((80, 24)));
5281        let width = w.max(1);
5282        let height = h.max(1);
5283        writer.set_size(width, height);
5284
5285        let budget = render_budget_from_program_config(&config);
5286        let load_governor = LoadGovernorState::new(
5287            config.load_governor.clone(),
5288            effect_queue_config.max_queue_depth,
5289        );
5290        let conformal_predictor = config
5291            .conformal_config
5292            .clone()
5293            .map(ConformalPredictor::new)
5294            .transpose()
5295            .map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error))?;
5296        let locale_context = config.locale_context.clone();
5297        let locale_version = locale_context.version();
5298        let mut resize_coalescer =
5299            ResizeCoalescer::new(config.resize_coalescer.clone(), (width, height))
5300                .with_screen_mode(config.screen_mode);
5301        if let Some(ref sink) = evidence_sink {
5302            resize_coalescer = resize_coalescer.with_evidence_sink(sink.clone());
5303        }
5304        let subscriptions = SubscriptionManager::new();
5305        let (task_sender, task_receiver) = std::sync::mpsc::channel();
5306        let inline_auto_remeasure = config
5307            .inline_auto_remeasure
5308            .clone()
5309            .map(InlineAutoRemeasureState::new);
5310        let gesture_recognizer = config
5311            .gestures
5312            .clone()
5313            .map(ftui_core::gesture::GestureRecognizer::new);
5314        let task_executor = TaskExecutor::new(
5315            &effect_queue_config,
5316            task_sender.clone(),
5317            evidence_sink.clone(),
5318        )?;
5319        let guardrails = FrameGuardrails::new(config.guardrails);
5320
5321        // Log runtime lane and rollout policy at startup (bd-2crbt)
5322        tracing::info!(
5323            target: crate::telemetry_schema::TARGET_RUNTIME,
5324            requested_lane = config.runtime_lane.label(),
5325            resolved_lane = resolved_lane.label(),
5326            rollout_policy = config.rollout_policy.label(),
5327            "runtime startup: lane={}, rollout={}",
5328            resolved_lane.label(),
5329            config.rollout_policy.label(),
5330        );
5331
5332        Ok(Self {
5333            model,
5334            writer,
5335            events,
5336            backend_features: initial_features,
5337            running: true,
5338            shutdown_complete: false,
5339            tick_rate: None,
5340            executed_cmd_count: 0,
5341            last_tick: Instant::now(),
5342            dirty: true,
5343            frame_idx: 0,
5344            tick_count: 0,
5345            widget_signals: Vec::new(),
5346            a11y_policy: config.accessibility,
5347            a11y_evidence_text: config.accessibility_evidence_text,
5348            a11y_tree: None,
5349            a11y_order: Vec::new(),
5350            a11y_announcements: Vec::new(),
5351            a11y_pending: None,
5352            a11y_changed: false,
5353            a11y_dropped: 0,
5354            startup_events: Vec::new(),
5355            startup_parser: ftui_core::input_parser::InputParser::new(),
5356            widget_refresh_config: config.widget_refresh,
5357            widget_refresh_plan: WidgetRefreshPlan::new(),
5358            width,
5359            height,
5360            forced_size: config.forced_size,
5361            poll_timeout: config.poll_timeout,
5362            intercept_signals: config.intercept_signals,
5363            pending_signal: Arc::new(std::sync::atomic::AtomicI32::new(0)),
5364            global_signal_slot: true,
5365            immediate_drain_config: config.immediate_drain,
5366            immediate_drain_stats: ImmediateDrainStats::default(),
5367            budget,
5368            load_governor,
5369            conformal_predictor,
5370            last_frame_time_us: None,
5371            last_update_us: None,
5372            frame_timing,
5373            locale_context,
5374            locale_version,
5375            resize_coalescer,
5376            evidence_sink,
5377            fairness_config_logged: false,
5378            resize_behavior: config.resize_behavior,
5379            fairness_guard: InputFairnessGuard::new(),
5380            event_recorder: None,
5381            subscriptions,
5382            #[cfg(test)]
5383            task_sender,
5384            task_receiver,
5385            task_executor,
5386            state_registry: config.persistence.registry.clone(),
5387            persistence_config: config.persistence,
5388            last_checkpoint: Instant::now(),
5389            inline_auto_remeasure,
5390            gesture_recognizer,
5391            frame_arena: FrameArena::default(),
5392            guardrails,
5393            last_soft_trim_frame: None,
5394            tick_strategy: config
5395                .tick_strategy
5396                .map(|strategy| Box::new(strategy) as Box<dyn crate::tick_strategy::TickStrategy>),
5397            last_active_screen_for_strategy: None,
5398        })
5399    }
5400}
5401
5402impl<M: Model, E: BackendEventSource<Error = io::Error>, W: Write + Send> Program<M, E, W> {
5403    /// Create a program with an externally-constructed event source and writer.
5404    ///
5405    /// This is the generic entry point for alternative backends (native tty,
5406    /// WASM, headless testing). The caller is responsible for terminal
5407    /// lifecycle (raw mode, cleanup) — the event source should handle that
5408    /// via its `Drop` impl or an external RAII guard.
5409    pub fn with_event_source(
5410        model: M,
5411        events: E,
5412        backend_features: BackendFeatures,
5413        writer: TerminalWriter<W>,
5414        config: ProgramConfig,
5415    ) -> io::Result<Self>
5416    where
5417        M::Message: Send + 'static,
5418    {
5419        let effect_queue_config = config.resolved_effect_queue_config();
5420        let (width, height) = config
5421            .forced_size
5422            .unwrap_or_else(|| events.size().unwrap_or((80, 24)));
5423        let width = width.max(1);
5424        let height = height.max(1);
5425
5426        let mut writer = writer;
5427        writer.set_size(width, height);
5428
5429        let evidence_sink = EvidenceSink::from_config(&config.evidence_sink)?;
5430        if let Some(ref sink) = evidence_sink {
5431            writer = writer.with_evidence_sink(sink.clone());
5432        }
5433
5434        let render_trace = crate::RenderTraceRecorder::from_config(
5435            &config.render_trace,
5436            crate::RenderTraceContext {
5437                capabilities: writer.capabilities(),
5438                diff_config: config.diff_config.clone(),
5439                resize_config: config.resize_coalescer.clone(),
5440                conformal_config: config.conformal_config.clone(),
5441            },
5442        )?;
5443        if let Some(recorder) = render_trace {
5444            writer = writer.with_render_trace(recorder);
5445        }
5446
5447        let frame_timing = config.frame_timing.clone();
5448        writer.set_timing_enabled(frame_timing.is_some());
5449
5450        let budget = render_budget_from_program_config(&config);
5451        let load_governor = LoadGovernorState::new(
5452            config.load_governor.clone(),
5453            effect_queue_config.max_queue_depth,
5454        );
5455        let conformal_predictor = config
5456            .conformal_config
5457            .clone()
5458            .map(ConformalPredictor::new)
5459            .transpose()
5460            .map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error))?;
5461        let locale_context = config.locale_context.clone();
5462        let locale_version = locale_context.version();
5463        let mut resize_coalescer =
5464            ResizeCoalescer::new(config.resize_coalescer.clone(), (width, height))
5465                .with_screen_mode(config.screen_mode);
5466        if let Some(ref sink) = evidence_sink {
5467            resize_coalescer = resize_coalescer.with_evidence_sink(sink.clone());
5468        }
5469        let subscriptions = SubscriptionManager::new();
5470        let (task_sender, task_receiver) = std::sync::mpsc::channel();
5471        let inline_auto_remeasure = config
5472            .inline_auto_remeasure
5473            .clone()
5474            .map(InlineAutoRemeasureState::new);
5475        let gesture_recognizer = config
5476            .gestures
5477            .clone()
5478            .map(ftui_core::gesture::GestureRecognizer::new);
5479        let task_executor = TaskExecutor::new(
5480            &effect_queue_config,
5481            task_sender.clone(),
5482            evidence_sink.clone(),
5483        )?;
5484
5485        let guardrails = FrameGuardrails::new(config.guardrails);
5486
5487        Ok(Self {
5488            model,
5489            writer,
5490            events,
5491            backend_features,
5492            running: true,
5493            shutdown_complete: false,
5494            tick_rate: None,
5495            executed_cmd_count: 0,
5496            last_tick: Instant::now(),
5497            dirty: true,
5498            frame_idx: 0,
5499            tick_count: 0,
5500            widget_signals: Vec::new(),
5501            a11y_policy: config.accessibility,
5502            a11y_evidence_text: config.accessibility_evidence_text,
5503            a11y_tree: None,
5504            a11y_order: Vec::new(),
5505            a11y_announcements: Vec::new(),
5506            a11y_pending: None,
5507            a11y_changed: false,
5508            a11y_dropped: 0,
5509            startup_events: Vec::new(),
5510            startup_parser: ftui_core::input_parser::InputParser::new(),
5511            widget_refresh_config: config.widget_refresh,
5512            widget_refresh_plan: WidgetRefreshPlan::new(),
5513            width,
5514            height,
5515            forced_size: config.forced_size,
5516            poll_timeout: config.poll_timeout,
5517            intercept_signals: config.intercept_signals,
5518            pending_signal: Arc::new(std::sync::atomic::AtomicI32::new(0)),
5519            global_signal_slot: true,
5520            immediate_drain_config: config.immediate_drain,
5521            immediate_drain_stats: ImmediateDrainStats::default(),
5522            budget,
5523            load_governor,
5524            conformal_predictor,
5525            last_frame_time_us: None,
5526            last_update_us: None,
5527            frame_timing,
5528            locale_context,
5529            locale_version,
5530            resize_coalescer,
5531            evidence_sink,
5532            fairness_config_logged: false,
5533            resize_behavior: config.resize_behavior,
5534            fairness_guard: InputFairnessGuard::new(),
5535            event_recorder: None,
5536            subscriptions,
5537            #[cfg(test)]
5538            task_sender,
5539            task_receiver,
5540            task_executor,
5541            state_registry: config.persistence.registry.clone(),
5542            persistence_config: config.persistence,
5543            last_checkpoint: Instant::now(),
5544            inline_auto_remeasure,
5545            gesture_recognizer,
5546            frame_arena: FrameArena::default(),
5547            guardrails,
5548            last_soft_trim_frame: None,
5549            tick_strategy: config
5550                .tick_strategy
5551                .map(|strategy| Box::new(strategy) as Box<dyn crate::tick_strategy::TickStrategy>),
5552            last_active_screen_for_strategy: None,
5553        })
5554    }
5555}
5556
5557// =============================================================================
5558// Native TTY backend constructor (feature-gated)
5559// =============================================================================
5560
5561#[cfg(any(feature = "crossterm-compat", feature = "native-backend"))]
5562#[inline]
5563const fn sanitize_backend_features_for_capabilities(
5564    requested: BackendFeatures,
5565    capabilities: &ftui_core::terminal_capabilities::TerminalCapabilities,
5566) -> BackendFeatures {
5567    let focus_events_supported = capabilities.focus_events && !capabilities.in_any_mux();
5568    let kitty_keyboard_supported = capabilities.kitty_keyboard && !capabilities.in_any_mux();
5569
5570    BackendFeatures {
5571        mouse_capture: requested.mouse_capture && capabilities.mouse_sgr,
5572        bracketed_paste: requested.bracketed_paste && capabilities.bracketed_paste,
5573        focus_events: requested.focus_events && focus_events_supported,
5574        kitty_keyboard: requested.kitty_keyboard && kitty_keyboard_supported,
5575    }
5576}
5577
5578#[cfg(all(feature = "native-backend", unix))]
5579impl<M: Model> Program<M, ftui_tty::TtyBackend, Stdout> {
5580    /// Open the default backend for this build (the native TTY backend).
5581    ///
5582    /// See [`DEFAULT_BACKEND`] and [`DefaultProgram`]; on builds without
5583    /// `native-backend` (or on non-Unix targets) this resolves to the Crossterm
5584    /// backend instead, and it does not exist when no backend was compiled.
5585    pub fn open(model: M, config: ProgramConfig) -> io::Result<Self>
5586    where
5587        M::Message: Send + 'static,
5588    {
5589        Self::with_native_backend(model, config)
5590    }
5591
5592    /// Create a program backed by the native TTY backend (no Crossterm).
5593    ///
5594    /// This opens a live terminal session via `ftui-tty`, entering raw mode
5595    /// and enabling the requested features. When the program exits (or panics),
5596    /// `TtyBackend::drop()` restores the terminal to its original state.
5597    ///
5598    /// **Unix-only.** `ftui-tty` does not yet have a Windows-native backend.
5599    /// On non-Unix targets call [`Program::with_config`] (with `crossterm-compat`)
5600    /// instead — calling `with_native_backend` from Windows used to silently
5601    /// fall through to the headless 0×0 test backend and produce a single
5602    /// init-frame-then-silence pattern that looks like a hung TUI.
5603    #[cfg(unix)]
5604    pub fn with_native_backend(model: M, config: ProgramConfig) -> io::Result<Self>
5605    where
5606        M::Message: Send + 'static,
5607    {
5608        let mut capabilities =
5609            ftui_core::terminal_capabilities::TerminalCapabilities::with_overrides();
5610        let mouse_capture = config.resolved_mouse_capture();
5611        let requested_features = BackendFeatures {
5612            mouse_capture,
5613            bracketed_paste: config.bracketed_paste,
5614            focus_events: config.focus_reporting,
5615            kitty_keyboard: config.kitty_keyboard,
5616        };
5617        let features =
5618            sanitize_backend_features_for_capabilities(requested_features, &capabilities);
5619        let options = ftui_tty::TtySessionOptions {
5620            alternate_screen: matches!(config.screen_mode, ScreenMode::AltScreen),
5621            features,
5622            intercept_signals: config.intercept_signals,
5623        };
5624        let backend = ftui_tty::TtyBackend::open(0, 0, options)?;
5625
5626        // The native session is live (raw mode), so the terminal can be asked
5627        // directly what it supports; see `probe_live_terminal`.
5628        let capability_decisions = probe_live_terminal(&mut capabilities);
5629        let scroll_region =
5630            verify_scroll_region(&capabilities, config.screen_mode, backend.size().ok());
5631
5632        let mut writer = TerminalWriter::with_diff_config(
5633            io::stdout(),
5634            config.screen_mode,
5635            config.ui_anchor,
5636            capabilities,
5637            config.diff_config.clone(),
5638        )
5639        .with_capability_decisions(capability_decisions);
5640        writer.set_scroll_region_verified(
5641            scroll_region.verdict,
5642            scroll_region.rows,
5643            scroll_region.region_bottom,
5644        );
5645
5646        Self::with_event_source(model, backend, features, writer, config)
5647    }
5648}
5649
5650impl<M: Model, E: BackendEventSource<Error = io::Error>, W: Write + Send> Program<M, E, W> {
5651    /// Run the main event loop.
5652    ///
5653    /// This is the main entry point. It handles:
5654    /// 1. Initialization (terminal setup, raw mode)
5655    /// 2. Event polling and message dispatch
5656    /// 3. Frame rendering
5657    /// 4. Shutdown (terminal cleanup)
5658    pub fn run(&mut self) -> io::Result<()> {
5659        if self.shutdown_complete {
5660            return Err(io::Error::new(
5661                io::ErrorKind::InvalidInput,
5662                "program lifecycle has already completed",
5663            ));
5664        }
5665
5666        let run_result = self.run_event_loop();
5667        self.complete_lifecycle(run_result)
5668    }
5669
5670    #[inline]
5671    fn observed_termination_signal(&self) -> Option<i32> {
5672        if !self.intercept_signals {
5673            return None;
5674        }
5675        match self
5676            .pending_signal
5677            .load(std::sync::atomic::Ordering::SeqCst)
5678        {
5679            0 => {}
5680            signal => return Some(signal),
5681        }
5682        if self.global_signal_slot {
5683            check_termination_signal()
5684        } else {
5685            None
5686        }
5687    }
5688
5689    /// Record a termination signal for this program instance, as if the OS
5690    /// signal handler had delivered it. The first pending signal wins until
5691    /// the run loop consumes it. Intended for harnesses and tests; interactive
5692    /// programs receive real signals through the installed handler.
5693    pub fn inject_termination_signal(&self, signal: i32) {
5694        let _ = self.pending_signal.compare_exchange(
5695            0,
5696            signal,
5697            std::sync::atomic::Ordering::SeqCst,
5698            std::sync::atomic::Ordering::SeqCst,
5699        );
5700    }
5701
5702    /// The termination signal pending for this program instance, if any.
5703    #[must_use]
5704    pub fn pending_termination_signal(&self) -> Option<i32> {
5705        match self
5706            .pending_signal
5707            .load(std::sync::atomic::Ordering::SeqCst)
5708        {
5709            0 => None,
5710            signal => Some(signal),
5711        }
5712    }
5713
5714    /// Access widget scheduling signals captured on the last render.
5715    #[inline]
5716    pub fn last_widget_signals(&self) -> &[WidgetSignal] {
5717        &self.widget_signals
5718    }
5719
5720    /// Snapshot immediate-drain runtime counters.
5721    #[inline]
5722    pub fn immediate_drain_stats(&self) -> ImmediateDrainStats {
5723        self.immediate_drain_stats
5724    }
5725
5726    /// The inner event loop, separated for proper cleanup handling.
5727    /// Parse raw input bytes (as the tty would have delivered them) into
5728    /// events that the main loop delivers before it starts polling. Used for
5729    /// the bytes the startup capability probes read off the tty while
5730    /// waiting for terminal replies (`caps_probe::take_probe_leftover_input`).
5731    pub fn queue_startup_input(&mut self, bytes: &[u8]) {
5732        if bytes.is_empty() {
5733            return;
5734        }
5735        let events = self.startup_parser.parse(bytes);
5736        debug!(
5737            bytes = bytes.len(),
5738            events = events.len(),
5739            "queued startup input recovered from the capability probes"
5740        );
5741        self.startup_events.extend(events);
5742    }
5743
5744    /// Deliver the queued startup events in arrival order.
5745    fn drain_startup_events(&mut self) -> io::Result<()> {
5746        // The probe-read batch is complete. Resolve an ambiguous trailing key
5747        // before handing input ownership back to the live event source; dropping
5748        // the parser here used to silently lose a lone Escape.
5749        if let Some(event) = self.startup_parser.timeout() {
5750            self.startup_events.push(event);
5751        }
5752        let events = std::mem::take(&mut self.startup_events);
5753        for event in events {
5754            if !self.running {
5755                break;
5756            }
5757            self.handle_event(event)?;
5758        }
5759        Ok(())
5760    }
5761
5762    fn run_event_loop(&mut self) -> io::Result<Option<i32>> {
5763        // Auto-load state on start
5764        if self.persistence_config.auto_load {
5765            self.load_state();
5766        }
5767
5768        // Input the constructors' probes swallowed belongs to this program.
5769        let leftover = ftui_core::caps_probe::take_probe_leftover_input();
5770        self.queue_startup_input(&leftover);
5771
5772        // Initialize
5773        let cmd = {
5774            let _span = info_span!(crate::telemetry_schema::span::PROGRAM_INIT).entered();
5775            self.model.init()
5776        };
5777        self.execute_cmd(cmd)?;
5778
5779        let mut termination_signal = self.observed_termination_signal();
5780        if self.running && termination_signal.is_none() {
5781            // Reconcile initial subscriptions
5782            self.reconcile_subscriptions();
5783            self.process_subscription_failures(false)?;
5784
5785            // Initial render
5786            if self.running {
5787                self.render_frame()?;
5788            }
5789        }
5790
5791        // Deliver input that arrived during startup before polling for more.
5792        if self.running && termination_signal.is_none() {
5793            self.drain_startup_events()?;
5794        }
5795
5796        // Main loop
5797        let mut loop_count: u64 = 0;
5798        while self.running {
5799            termination_signal = termination_signal.or_else(|| self.observed_termination_signal());
5800            if termination_signal.is_some() {
5801                self.running = false;
5802                break;
5803            }
5804
5805            loop_count += 1;
5806            // Log heartbeat every 100 iterations to avoid flooding stderr
5807            if loop_count.is_multiple_of(100) {
5808                crate::debug_trace!("main loop heartbeat: iteration {}", loop_count);
5809            }
5810
5811            // Poll for input with tick timeout
5812            let timeout = self.effective_timeout();
5813
5814            // Poll for events with timeout
5815            let poll_result = self.events.poll_event(timeout)?;
5816            termination_signal = termination_signal.or_else(|| self.observed_termination_signal());
5817            if termination_signal.is_some() {
5818                self.running = false;
5819                break;
5820            }
5821            if poll_result {
5822                self.drain_ready_events()?;
5823            }
5824            if !self.running {
5825                break;
5826            }
5827            termination_signal = termination_signal.or_else(|| self.observed_termination_signal());
5828            if termination_signal.is_some() {
5829                self.running = false;
5830                break;
5831            }
5832
5833            // Process subscription messages
5834            self.process_subscription_messages()?;
5835            self.process_subscription_failures(false)?;
5836            if !self.running {
5837                break;
5838            }
5839
5840            // Process background task results
5841            self.process_task_results()?;
5842            self.reap_finished_tasks();
5843            if !self.running {
5844                break;
5845            }
5846
5847            self.process_resize_coalescer()?;
5848            if !self.running {
5849                break;
5850            }
5851            termination_signal = termination_signal.or_else(|| self.observed_termination_signal());
5852            if termination_signal.is_some() {
5853                self.running = false;
5854                break;
5855            }
5856
5857            // Detect screen transitions from any update() calls above.
5858            // A.2: notifies the tick strategy so predictive strategies learn.
5859            // D.3: force-ticks the newly active screen for immediate refresh.
5860            self.check_screen_transition();
5861
5862            // Check for tick - deliver to model so periodic logic can run
5863            if self.should_tick() {
5864                self.tick_count = self.tick_count.wrapping_add(1);
5865                let tick_count = self.tick_count;
5866
5867                let mut used_screen_dispatch = false;
5868
5869                // Per-screen tick dispatch: if the model supports multi-screen
5870                // dispatch and a tick strategy is configured, tick individual
5871                // screens selectively instead of calling monolithic
5872                // `update(Tick)`.
5873                if let Some(strategy) = self.tick_strategy.as_mut() {
5874                    // Snapshot screen topology first so the mutable borrow of the
5875                    // dispatch adapter does not overlap strategy decisions.
5876                    let dispatch_snapshot = self.model.as_screen_tick_dispatch().map(|dispatch| {
5877                        let active = dispatch.active_screen_id();
5878                        let all_screens = dispatch.screen_ids();
5879                        (active, all_screens)
5880                    });
5881
5882                    if let Some((active, all_screens)) = dispatch_snapshot {
5883                        used_screen_dispatch = true;
5884
5885                        // Feed active-screen transitions into the strategy so
5886                        // predictive strategies can learn from real navigation.
5887                        if let Some(previous_active) =
5888                            self.last_active_screen_for_strategy.as_deref()
5889                            && previous_active != active
5890                        {
5891                            strategy.on_screen_transition(previous_active, &active);
5892                        }
5893                        self.last_active_screen_for_strategy = Some(active.clone());
5894
5895                        let all_screens_count = all_screens.len();
5896                        let mut tick_targets = Vec::with_capacity(all_screens_count.max(1));
5897                        // Active screen is always ticked.
5898                        tick_targets.push(active.clone());
5899
5900                        // Tick inactive screens according to the strategy.
5901                        for screen_id in all_screens {
5902                            if screen_id != active
5903                                && strategy.should_tick(&screen_id, tick_count, &active)
5904                                    == crate::tick_strategy::TickDecision::Tick
5905                            {
5906                                tick_targets.push(screen_id);
5907                            }
5908                        }
5909
5910                        // Compute skipped screens for tracing.
5911                        let skipped_count = all_screens_count.saturating_sub(tick_targets.len());
5912
5913                        if let Some(dispatch) = self.model.as_screen_tick_dispatch() {
5914                            for screen_id in &tick_targets {
5915                                dispatch.tick_screen(screen_id, tick_count);
5916                            }
5917                        }
5918
5919                        trace!(
5920                            tick = tick_count,
5921                            active = %active,
5922                            ticked = tick_targets.len(),
5923                            skipped = skipped_count,
5924                            "tick_strategy.frame"
5925                        );
5926
5927                        // Maintenance tick for the strategy.
5928                        strategy.maintenance_tick(tick_count);
5929                        self.mark_dirty();
5930                    }
5931                }
5932
5933                if used_screen_dispatch && self.running {
5934                    self.reconcile_subscriptions();
5935                }
5936
5937                // A stationary mouse-down only becomes a long press with the
5938                // passage of time, so the recognizer is polled once per tick.
5939                if let Some(gesture) = self
5940                    .gesture_recognizer
5941                    .as_mut()
5942                    .and_then(|recognizer| recognizer.check_long_press(Instant::now()))
5943                {
5944                    self.deliver_gesture(gesture)?;
5945                }
5946
5947                if !used_screen_dispatch {
5948                    // Monolithic model path does not expose active-screen
5949                    // transitions, so clear dispatch-local transition state.
5950                    self.last_active_screen_for_strategy = None;
5951                    let msg = M::Message::from(Event::Tick);
5952                    let cmd = {
5953                        let _span = debug_span!(
5954                            crate::telemetry_schema::span::PROGRAM_UPDATE,
5955                            msg_type = "Tick",
5956                            duration_us = tracing::field::Empty,
5957                            cmd_type = tracing::field::Empty
5958                        )
5959                        .entered();
5960                        let start = Instant::now();
5961                        let cmd = self.model.update(msg);
5962                        tracing::Span::current()
5963                            .record("duration_us", start.elapsed().as_micros() as u64);
5964                        tracing::Span::current()
5965                            .record("cmd_type", format!("{:?}", std::mem::discriminant(&cmd)));
5966                        cmd
5967                    };
5968                    self.mark_dirty();
5969                    self.execute_cmd(cmd)?;
5970                    if self.running {
5971                        self.reconcile_subscriptions();
5972                    }
5973                }
5974            }
5975
5976            // Check for periodic checkpoint save
5977            self.check_checkpoint_save();
5978
5979            // Detect locale changes outside the event loop.
5980            self.check_locale_change();
5981            termination_signal = termination_signal.or_else(|| self.observed_termination_signal());
5982            if termination_signal.is_some() {
5983                self.running = false;
5984                break;
5985            }
5986
5987            // Render if dirty
5988            if self.dirty {
5989                self.render_frame()?;
5990            }
5991
5992            // Periodic grapheme pool GC
5993            if loop_count.is_multiple_of(1000) {
5994                self.writer.gc(None);
5995            }
5996        }
5997
5998        Ok(termination_signal)
5999    }
6000
6001    /// Complete the model/runtime lifecycle after every event-loop exit path.
6002    fn complete_lifecycle(&mut self, run_result: io::Result<Option<i32>>) -> io::Result<()> {
6003        let (loop_signal, primary_error) = match run_result {
6004            Ok(signal) => (signal, None),
6005            Err(error) => (None, Some(error)),
6006        };
6007        let termination_signal = loop_signal.or_else(|| self.observed_termination_signal());
6008
6009        // The event loop is over. Lifecycle commands may run model updates,
6010        // but they must never restart normal event processing.
6011        self.running = false;
6012
6013        let mut hook_error = None;
6014        if let Some(error) = primary_error.as_ref()
6015            && let Err(error) = self.invoke_error_hook(&error.to_string(), true)
6016        {
6017            hook_error = Some(error);
6018        }
6019
6020        if let Err(error) = self.process_subscription_failures(true) {
6021            hook_error.get_or_insert(error);
6022        }
6023
6024        let shutdown_error = self.shutdown_once().err();
6025
6026        // A pending termination signal takes precedence over lifecycle-step
6027        // errors: it is what ended the loop, and callers rely on the
6028        // SignalTerminationError contract for the 128+signal process exit.
6029        if let Some(signal) = termination_signal {
6030            self.pending_signal
6031                .store(0, std::sync::atomic::Ordering::SeqCst);
6032            if self.global_signal_slot {
6033                clear_termination_signal();
6034            }
6035            let error = io::Error::new(
6036                io::ErrorKind::Interrupted,
6037                SignalTerminationError { signal },
6038            );
6039            debug_assert_eq!(signal_termination_from_error(&error), Some(signal));
6040            return Err(error);
6041        }
6042
6043        if let Some(error) = primary_error {
6044            return Err(error);
6045        }
6046
6047        if let Some(error) = hook_error {
6048            return Err(error);
6049        }
6050
6051        if let Some(error) = shutdown_error {
6052            // A failing cleanup command is still a command error. Report it
6053            // after the one-shot shutdown hook without attempting teardown a
6054            // second time.
6055            let _ = self.invoke_error_hook(&error.to_string(), true);
6056            return Err(error);
6057        }
6058
6059        Ok(())
6060    }
6061
6062    /// Run model shutdown and runtime teardown at most once.
6063    fn shutdown_once(&mut self) -> io::Result<()> {
6064        if self.shutdown_complete {
6065            return Ok(());
6066        }
6067        self.shutdown_complete = true;
6068
6069        let shutdown_cmd = {
6070            let _span = info_span!(crate::telemetry_schema::span::PROGRAM_SHUTDOWN).entered();
6071            self.model.on_shutdown()
6072        };
6073        // The shutdown sequence is error-isolated: a failing shutdown command
6074        // must not skip auto-save, strategy/executor shutdown, or signal exit
6075        // mapping. The first error is captured and surfaced after cleanup.
6076        let mut shutdown_error = self.execute_lifecycle_cmd(shutdown_cmd).err();
6077
6078        if self.persistence_config.auto_save {
6079            self.save_state();
6080        }
6081
6082        if let Some(ref mut strategy) = self.tick_strategy {
6083            strategy.shutdown();
6084        }
6085
6086        self.subscriptions.stop_all();
6087        if let Err(error) = self.process_subscription_failures(true) {
6088            shutdown_error.get_or_insert(error);
6089        }
6090
6091        self.task_executor.shutdown();
6092        self.reap_finished_tasks();
6093        if let Err(error) = self.drain_shutdown_task_results() {
6094            shutdown_error.get_or_insert(error);
6095        }
6096
6097        match shutdown_error {
6098            Some(error) => Err(error),
6099            None => Ok(()),
6100        }
6101    }
6102
6103    /// Drain ready events while bounding zero-timeout polling work.
6104    ///
6105    /// The runtime preserves low-latency draining by polling with
6106    /// `Duration::ZERO`, but switches to a bounded backoff path when a burst
6107    /// exceeds configured immediate-drain budgets.
6108    fn drain_ready_events(&mut self) -> io::Result<()> {
6109        self.immediate_drain_stats.bursts = self.immediate_drain_stats.bursts.saturating_add(1);
6110
6111        let zero_poll_limit = self
6112            .immediate_drain_config
6113            .max_zero_timeout_polls_per_burst
6114            .max(1);
6115        let max_burst_duration = self.immediate_drain_config.max_burst_duration;
6116        let backoff_timeout = self.immediate_drain_config.backoff_timeout;
6117
6118        let mut burst_start = Instant::now();
6119        let mut zero_polls_in_burst_window: u64 = 0;
6120        let mut capped_this_burst = false;
6121
6122        loop {
6123            // `read_event` may return `Ok(None)` even though the preceding
6124            // poll reported readiness: the event may be unrepresentable in
6125            // ftui's canonical event types, and on Windows console readiness
6126            // can be spurious (discarded key-release/focus/menu records), in
6127            // which case the crossterm-backed source re-polls with a zero
6128            // timeout instead of parking in a blocking read (frankentui#95).
6129            // Either way we simply fall through to the bounded zero-timeout
6130            // poll below; when nothing is pending the burst ends and the
6131            // outer loop parks in its normal timed poll — no busy-spin.
6132            if let Some(event) = self.events.read_event()? {
6133                self.handle_event(event)?;
6134                if !self.running {
6135                    break;
6136                }
6137            }
6138
6139            let budget_exhausted = (zero_polls_in_burst_window as usize) >= zero_poll_limit
6140                || burst_start.elapsed() >= max_burst_duration;
6141
6142            if budget_exhausted {
6143                if !capped_this_burst {
6144                    capped_this_burst = true;
6145                    self.immediate_drain_stats.capped_bursts =
6146                        self.immediate_drain_stats.capped_bursts.saturating_add(1);
6147                }
6148
6149                self.immediate_drain_stats.max_zero_timeout_polls_in_burst = self
6150                    .immediate_drain_stats
6151                    .max_zero_timeout_polls_in_burst
6152                    .max(zero_polls_in_burst_window);
6153
6154                std::thread::yield_now();
6155                self.immediate_drain_stats.backoff_polls =
6156                    self.immediate_drain_stats.backoff_polls.saturating_add(1);
6157                if !self.events.poll_event(backoff_timeout)? {
6158                    break;
6159                }
6160                zero_polls_in_burst_window = 0;
6161                burst_start = Instant::now();
6162                continue;
6163            }
6164
6165            self.immediate_drain_stats.zero_timeout_polls = self
6166                .immediate_drain_stats
6167                .zero_timeout_polls
6168                .saturating_add(1);
6169            zero_polls_in_burst_window = zero_polls_in_burst_window.saturating_add(1);
6170            if !self.events.poll_event(Duration::ZERO)? {
6171                break;
6172            }
6173        }
6174
6175        self.immediate_drain_stats.max_zero_timeout_polls_in_burst = self
6176            .immediate_drain_stats
6177            .max_zero_timeout_polls_in_burst
6178            .max(zero_polls_in_burst_window);
6179
6180        Ok(())
6181    }
6182
6183    /// Load state from the persistence registry.
6184    fn load_state(&mut self) {
6185        if let Some(registry) = &self.state_registry {
6186            match registry.load() {
6187                Ok(count) => {
6188                    info!(count, "loaded widget state from persistence");
6189                }
6190                Err(e) => {
6191                    tracing::warn!(error = %e, "failed to load widget state");
6192                }
6193            }
6194        }
6195    }
6196
6197    /// Save state to the persistence registry.
6198    fn save_state(&mut self) {
6199        if let Some(registry) = &self.state_registry {
6200            match registry.flush() {
6201                Ok(true) => {
6202                    debug!("saved widget state to persistence");
6203                }
6204                Ok(false) => {
6205                    // No changes to save
6206                }
6207                Err(e) => {
6208                    tracing::warn!(error = %e, "failed to save widget state");
6209                }
6210            }
6211        }
6212    }
6213
6214    /// Check if it's time for a periodic checkpoint save.
6215    fn check_checkpoint_save(&mut self) {
6216        if let Some(interval) = self.persistence_config.checkpoint_interval
6217            && self.last_checkpoint.elapsed() >= interval
6218        {
6219            self.save_state();
6220            self.last_checkpoint = Instant::now();
6221        }
6222    }
6223
6224    /// Hand one recognized gesture to `Model::on_gesture` and run the
6225    /// resulting command like any update command.
6226    fn deliver_gesture(
6227        &mut self,
6228        gesture: ftui_core::semantic_event::SemanticEvent,
6229    ) -> io::Result<()> {
6230        let cmd = {
6231            let _span = debug_span!(
6232                crate::telemetry_schema::span::PROGRAM_UPDATE,
6233                msg_type = "gesture"
6234            )
6235            .entered();
6236            self.model.on_gesture(gesture)
6237        };
6238        self.mark_dirty();
6239        self.execute_cmd(cmd)?;
6240        if self.running {
6241            self.reconcile_subscriptions();
6242        }
6243        Ok(())
6244    }
6245
6246    fn handle_event(&mut self, event: Event) -> io::Result<()> {
6247        // Track event start time and type for fairness scheduling.
6248        let event_start = Instant::now();
6249        let fairness_event_type = Self::classify_event_for_fairness(&event);
6250        if fairness_event_type == FairnessEventType::Input {
6251            self.fairness_guard.input_arrived(event_start);
6252        }
6253
6254        // Record event before processing (no-op when recorder is None or idle).
6255        if let Some(recorder) = &mut self.event_recorder {
6256            recorder.record(&event);
6257        }
6258
6259        let event = match event {
6260            Event::Resize { width, height } => {
6261                debug!(
6262                    width,
6263                    height,
6264                    behavior = ?self.resize_behavior,
6265                    "Resize event received"
6266                );
6267                if let Some((forced_width, forced_height)) = self.forced_size {
6268                    debug!(
6269                        forced_width,
6270                        forced_height, "Resize ignored due to forced size override"
6271                    );
6272                    self.fairness_guard.event_processed(
6273                        fairness_event_type,
6274                        event_start.elapsed(),
6275                        Instant::now(),
6276                    );
6277                    return Ok(());
6278                }
6279                // Clamp to minimum 1 to prevent Buffer::new panic on zero dimensions
6280                let width = width.max(1);
6281                let height = height.max(1);
6282                match self.resize_behavior {
6283                    ResizeBehavior::Immediate => {
6284                        self.resize_coalescer
6285                            .record_external_apply(width, height, Instant::now());
6286                        let result = self.apply_resize(width, height, Duration::ZERO, false);
6287                        self.fairness_guard.event_processed(
6288                            fairness_event_type,
6289                            event_start.elapsed(),
6290                            Instant::now(),
6291                        );
6292                        return result;
6293                    }
6294                    ResizeBehavior::Throttled => {
6295                        let action = self.resize_coalescer.handle_resize(width, height);
6296                        if let CoalesceAction::ApplyResize {
6297                            width,
6298                            height,
6299                            coalesce_time,
6300                            forced_by_deadline,
6301                        } = action
6302                        {
6303                            let result =
6304                                self.apply_resize(width, height, coalesce_time, forced_by_deadline);
6305                            self.fairness_guard.event_processed(
6306                                fairness_event_type,
6307                                event_start.elapsed(),
6308                                Instant::now(),
6309                            );
6310                            return result;
6311                        }
6312
6313                        self.fairness_guard.event_processed(
6314                            fairness_event_type,
6315                            event_start.elapsed(),
6316                            Instant::now(),
6317                        );
6318                        return Ok(());
6319                    }
6320                }
6321            }
6322            other => other,
6323        };
6324
6325        // Gesture recognition runs beside the raw event, never instead of it:
6326        // the raw event still reaches `update()` below, and any gesture the
6327        // recognizer completes is delivered to `on_gesture` afterwards.
6328        let gestures = self
6329            .gesture_recognizer
6330            .as_mut()
6331            .map(|recognizer| recognizer.process(&event, Instant::now()))
6332            .unwrap_or_default();
6333
6334        let msg = M::Message::from(event);
6335        let cmd = {
6336            let _span = debug_span!(
6337                crate::telemetry_schema::span::PROGRAM_UPDATE,
6338                msg_type = "event",
6339                duration_us = tracing::field::Empty,
6340                cmd_type = tracing::field::Empty
6341            )
6342            .entered();
6343            let start = Instant::now();
6344            let cmd = self.model.update(msg);
6345            let elapsed_us = start.elapsed().as_micros() as u64;
6346            self.last_update_us = Some(elapsed_us);
6347            tracing::Span::current().record("duration_us", elapsed_us);
6348            tracing::Span::current()
6349                .record("cmd_type", format!("{:?}", std::mem::discriminant(&cmd)));
6350            cmd
6351        };
6352        self.mark_dirty();
6353        self.execute_cmd(cmd)?;
6354        if self.running {
6355            self.reconcile_subscriptions();
6356        }
6357        for gesture in gestures {
6358            self.deliver_gesture(gesture)?;
6359        }
6360
6361        // Track input event processing for fairness.
6362        self.fairness_guard.event_processed(
6363            fairness_event_type,
6364            event_start.elapsed(),
6365            Instant::now(),
6366        );
6367
6368        Ok(())
6369    }
6370
6371    /// Classify an event for fairness tracking.
6372    fn classify_event_for_fairness(event: &Event) -> FairnessEventType {
6373        match event {
6374            Event::Key(_)
6375            | Event::Mouse(_)
6376            | Event::Paste(_)
6377            | Event::Ime(_)
6378            | Event::Focus(_)
6379            | Event::Clipboard(_) => FairnessEventType::Input,
6380            Event::Resize { .. } => FairnessEventType::Resize,
6381            Event::Tick => FairnessEventType::Tick,
6382        }
6383    }
6384
6385    /// Reconcile the model's declared subscriptions with running ones.
6386    fn reconcile_subscriptions(&mut self) {
6387        let _span = debug_span!(
6388            crate::telemetry_schema::span::PROGRAM_SUBSCRIPTIONS,
6389            active_count = tracing::field::Empty,
6390            started = tracing::field::Empty,
6391            stopped = tracing::field::Empty
6392        )
6393        .entered();
6394        let subs = self.model.subscriptions();
6395        let before_count = self.subscriptions.active_count();
6396        self.subscriptions.reconcile(subs);
6397        let after_count = self.subscriptions.active_count();
6398        let started = after_count.saturating_sub(before_count);
6399        let stopped = before_count.saturating_sub(after_count);
6400        crate::debug_trace!(
6401            "subscriptions reconcile: before={}, after={}, started={}, stopped={}",
6402            before_count,
6403            after_count,
6404            started,
6405            stopped
6406        );
6407        if after_count == 0 {
6408            crate::debug_trace!("subscriptions reconcile: no active subscriptions");
6409        }
6410        let current = tracing::Span::current();
6411        current.record("active_count", after_count);
6412        // started/stopped would require tracking in SubscriptionManager
6413        current.record("started", started);
6414        current.record("stopped", stopped);
6415    }
6416
6417    /// Report newly observed subscription failures through `Model::on_error`.
6418    fn process_subscription_failures(&mut self, during_lifecycle: bool) -> io::Result<()> {
6419        let mut first_error = None;
6420        for failure in self.subscriptions.drain_failures() {
6421            let error = format!("subscription {} failed: {}", failure.id, failure.error);
6422            if let Err(error) = self.invoke_error_hook(&error, during_lifecycle) {
6423                first_error.get_or_insert(error);
6424            }
6425        }
6426
6427        match first_error {
6428            Some(error) => Err(error),
6429            None => Ok(()),
6430        }
6431    }
6432
6433    /// Invoke the model error hook and execute its recovery command.
6434    fn invoke_error_hook(&mut self, error: &str, during_lifecycle: bool) -> io::Result<()> {
6435        let cmd = {
6436            let _span = info_span!(crate::telemetry_schema::span::PROGRAM_ERROR, error).entered();
6437            self.model.on_error(error)
6438        };
6439        if during_lifecycle {
6440            self.execute_lifecycle_cmd(cmd)
6441        } else {
6442            self.execute_cmd(cmd)
6443        }
6444    }
6445
6446    /// Execute a lifecycle command even after the normal loop stopped.
6447    ///
6448    /// `Cmd::Batch` and `Cmd::Sequence` use the running flag as their halt
6449    /// boundary, so temporarily reopening dispatch is required for cleanup
6450    /// batches. An explicit `Cmd::Quit` inside the lifecycle command still
6451    /// halts the remaining commands.
6452    fn execute_lifecycle_cmd(&mut self, cmd: Cmd<M::Message>) -> io::Result<()> {
6453        let was_running = std::mem::replace(&mut self.running, true);
6454        let result = self.execute_cmd(cmd);
6455        self.running = was_running && self.running;
6456        result
6457    }
6458
6459    /// Process pending messages from subscriptions.
6460    fn process_subscription_messages(&mut self) -> io::Result<()> {
6461        let messages = self.subscriptions.drain_messages();
6462        let msg_count = messages.len();
6463        if msg_count > 0 {
6464            crate::debug_trace!("processing {} subscription message(s)", msg_count);
6465        }
6466        for msg in messages {
6467            let cmd = {
6468                let _span = debug_span!(
6469                    crate::telemetry_schema::span::PROGRAM_UPDATE,
6470                    msg_type = "subscription",
6471                    duration_us = tracing::field::Empty,
6472                    cmd_type = tracing::field::Empty
6473                )
6474                .entered();
6475                let start = Instant::now();
6476                let cmd = self.model.update(msg);
6477                let elapsed_us = start.elapsed().as_micros() as u64;
6478                self.last_update_us = Some(elapsed_us);
6479                tracing::Span::current().record("duration_us", elapsed_us);
6480                tracing::Span::current()
6481                    .record("cmd_type", format!("{:?}", std::mem::discriminant(&cmd)));
6482                cmd
6483            };
6484            self.mark_dirty();
6485            self.execute_cmd(cmd)?;
6486            if !self.running {
6487                break;
6488            }
6489        }
6490        if self.running && self.dirty {
6491            self.reconcile_subscriptions();
6492        }
6493        Ok(())
6494    }
6495
6496    /// Process results from background tasks.
6497    fn process_task_results(&mut self) -> io::Result<()> {
6498        while let Ok(msg) = self.task_receiver.try_recv() {
6499            let cmd = {
6500                let _span = debug_span!(
6501                    crate::telemetry_schema::span::PROGRAM_UPDATE,
6502                    msg_type = "task",
6503                    duration_us = tracing::field::Empty,
6504                    cmd_type = tracing::field::Empty
6505                )
6506                .entered();
6507                let start = Instant::now();
6508                let cmd = self.model.update(msg);
6509                let elapsed_us = start.elapsed().as_micros() as u64;
6510                self.last_update_us = Some(elapsed_us);
6511                tracing::Span::current().record("duration_us", elapsed_us);
6512                tracing::Span::current()
6513                    .record("cmd_type", format!("{:?}", std::mem::discriminant(&cmd)));
6514                cmd
6515            };
6516            self.mark_dirty();
6517            self.execute_cmd(cmd)?;
6518            if !self.running {
6519                break;
6520            }
6521        }
6522        if self.running && self.dirty {
6523            self.reconcile_subscriptions();
6524        }
6525        Ok(())
6526    }
6527
6528    /// Execute a command.
6529    fn execute_cmd(&mut self, cmd: Cmd<M::Message>) -> io::Result<()> {
6530        self.executed_cmd_count = self.executed_cmd_count.saturating_add(1);
6531        match cmd {
6532            Cmd::None => {}
6533            Cmd::Quit => self.running = false,
6534            Cmd::Msg(m) => {
6535                let start = Instant::now();
6536                let cmd = self.model.update(m);
6537                let elapsed_us = start.elapsed().as_micros() as u64;
6538                self.last_update_us = Some(elapsed_us);
6539                self.mark_dirty();
6540                self.execute_cmd(cmd)?;
6541            }
6542            Cmd::Batch(cmds) => {
6543                // Batch currently executes sequentially. This is intentional
6544                // until an async runtime or task scheduler is added.
6545                for c in cmds {
6546                    self.execute_cmd(c)?;
6547                    if !self.running {
6548                        break;
6549                    }
6550                }
6551            }
6552            Cmd::Sequence(cmds) => {
6553                for c in cmds {
6554                    self.execute_cmd(c)?;
6555                    if !self.running {
6556                        break;
6557                    }
6558                }
6559            }
6560            Cmd::Tick(duration) => {
6561                self.tick_rate = Some(duration);
6562                self.last_tick = Instant::now();
6563            }
6564            Cmd::Log(text) => {
6565                let sanitized = sanitize(&text);
6566                let mut text_crlf = if sanitized.contains('\n') {
6567                    sanitized.replace("\r\n", "\n").replace('\n', "\r\n")
6568                } else {
6569                    sanitized.into_owned()
6570                };
6571                if !text_crlf.ends_with("\r\n") {
6572                    if text_crlf.ends_with('\n') {
6573                        text_crlf.pop();
6574                    }
6575                    text_crlf.push_str("\r\n");
6576                }
6577                self.writer.write_log(&text_crlf)?;
6578            }
6579            Cmd::Task(spec, f) => {
6580                crate::effect_system::record_command_effect("task", 0);
6581                self.task_executor.submit(spec, f);
6582            }
6583            Cmd::SaveState => {
6584                self.save_state();
6585            }
6586            Cmd::RestoreState => {
6587                self.load_state();
6588            }
6589            Cmd::SetMouseCapture(enabled) => {
6590                self.backend_features.mouse_capture = enabled;
6591                self.events.set_features(self.backend_features)?;
6592            }
6593            Cmd::SetTickStrategy(strategy) => {
6594                let new_name = strategy.name().to_owned();
6595                if let Some(mut previous) = self.tick_strategy.replace(strategy) {
6596                    let old_name = previous.name().to_owned();
6597                    previous.shutdown();
6598                    info!(old = %old_name, new = %new_name, "tick strategy changed at runtime");
6599                } else {
6600                    info!(new = %new_name, "tick strategy changed at runtime");
6601                }
6602                self.last_active_screen_for_strategy = None;
6603            }
6604        }
6605        Ok(())
6606    }
6607
6608    /// Detect active-screen transitions after any `update()` call and react:
6609    ///
6610    /// - **A.2** — notify the tick strategy via `on_screen_transition()` so
6611    ///   predictive strategies can learn navigation patterns.
6612    /// - **D.3** — force-tick the newly active screen so it renders fresh
6613    ///   content immediately, without waiting for the next tick interval.
6614    ///
6615    /// This is a no-op when no tick strategy is configured or when the model
6616    /// does not implement [`ScreenTickDispatch`].
6617    fn check_screen_transition(&mut self) {
6618        if self.tick_strategy.is_none() {
6619            return;
6620        }
6621
6622        // Snapshot the current active screen (releases &mut self.model).
6623        let current_active = match self.model.as_screen_tick_dispatch() {
6624            Some(dispatch) => dispatch.active_screen_id(),
6625            None => return,
6626        };
6627
6628        // First observation: just record, no transition event.
6629        let previous = match self.last_active_screen_for_strategy.take() {
6630            Some(prev) => prev,
6631            None => {
6632                self.last_active_screen_for_strategy = Some(current_active);
6633                return;
6634            }
6635        };
6636
6637        if previous == current_active {
6638            self.last_active_screen_for_strategy = Some(current_active);
6639            return;
6640        }
6641
6642        // A.2: Notify strategy of the transition.
6643        if let Some(strategy) = self.tick_strategy.as_mut() {
6644            strategy.on_screen_transition(&previous, &current_active);
6645        }
6646
6647        // D.3: Force-tick the newly active screen immediately.
6648        let mut force_ticked = false;
6649        if let Some(dispatch) = self.model.as_screen_tick_dispatch() {
6650            dispatch.tick_screen(&current_active, self.tick_count);
6651            force_ticked = true;
6652        }
6653        if force_ticked && self.running {
6654            self.reconcile_subscriptions();
6655        }
6656
6657        self.last_active_screen_for_strategy = Some(current_active);
6658        self.mark_dirty();
6659    }
6660
6661    fn reap_finished_tasks(&mut self) {
6662        self.task_executor.reap_finished();
6663    }
6664
6665    fn drain_shutdown_task_results(&mut self) -> io::Result<()> {
6666        while let Ok(msg) = self.task_receiver.try_recv() {
6667            let cmd = {
6668                let _span = debug_span!(
6669                    crate::telemetry_schema::span::PROGRAM_UPDATE,
6670                    msg_type = "shutdown_task",
6671                    duration_us = tracing::field::Empty,
6672                    cmd_type = tracing::field::Empty
6673                )
6674                .entered();
6675                let start = Instant::now();
6676                let cmd = self.model.update(msg);
6677                let elapsed_us = start.elapsed().as_micros() as u64;
6678                self.last_update_us = Some(elapsed_us);
6679                tracing::Span::current().record("duration_us", elapsed_us);
6680                tracing::Span::current()
6681                    .record("cmd_type", format!("{:?}", std::mem::discriminant(&cmd)));
6682                cmd
6683            };
6684            self.mark_dirty();
6685            self.execute_lifecycle_cmd(cmd)?;
6686        }
6687        Ok(())
6688    }
6689
6690    /// Render a frame with budget tracking.
6691    fn render_frame(&mut self) -> io::Result<()> {
6692        crate::debug_trace!("render_frame: {}x{}", self.width, self.height);
6693
6694        self.frame_idx = self.frame_idx.wrapping_add(1);
6695        let frame_idx = self.frame_idx;
6696        let degradation_start = self.budget.degradation();
6697
6698        // Reset budget for new frame, potentially upgrading quality
6699        self.budget.next_frame();
6700
6701        // Check frame guardrails (memory/queue limits). The frame loop itself
6702        // is synchronous, so "queue depth" is the effect backlog: tasks this
6703        // program handed to its executor that have not produced their
6704        // message yet (`TaskExecutor::in_flight`). This is the value the
6705        // queue guardrail thresholds (warn/max/emergency) were designed
6706        // against; it used to be hard-coded to 0, which made the whole queue
6707        // guardrail dead in production (bd-1za0z item 3). It is measured per
6708        // program rather than from the process-global queue counters so a
6709        // second program in the same process (or a leaked counter) cannot
6710        // make this one shed frames.
6711        let memory_bytes = self.writer.estimate_memory_usage() + self.frame_arena.allocated_bytes();
6712        let queue_depth = u32::try_from(self.task_executor.in_flight()).unwrap_or(u32::MAX);
6713        let verdict = self.guardrails.check_frame(memory_bytes, queue_depth);
6714
6715        // F2 observability: export a guardrail snapshot whenever any
6716        // guardrail fires. Alerts are naturally rate-limited by the
6717        // degradation logic, so this stays quiet in healthy runs
6718        // (bd-1za0z: GuardrailSnapshot::to_jsonl was production-dead).
6719        if !verdict.alerts.is_empty()
6720            && let Some(ref sink) = self.evidence_sink
6721        {
6722            let line = format!(
6723                r#"{{"schema_version":"{}","event":"guardrail_snapshot","snapshot":{}}}"#,
6724                crate::evidence_sink::EVIDENCE_SCHEMA_VERSION,
6725                self.guardrails.snapshot().to_jsonl(),
6726            );
6727            let _ = sink.write_jsonl(&line);
6728        }
6729
6730        if verdict.should_drop_frame() {
6731            // Emergency shed: skip this frame entirely to prevent OOM.
6732            // CRUCIALLY, remediate: two of the sensor's components are
6733            // retained CAPACITY that never shrinks on its own (bumpalo keeps
6734            // its largest chunk across reset(); the grapheme pool's Vec never
6735            // shrinks). Without releasing them the verdict is permanent and
6736            // the UI freezes forever — dropping frames cannot move the
6737            // sensor. Rebuilding the arena frees the retained chunk so the
6738            // next frame re-measures honestly.
6739            self.frame_arena = FrameArena::default();
6740            self.writer.gc(None);
6741            tracing::warn!(
6742                target: crate::telemetry_schema::TARGET_GUARDRAILS,
6743                memory_bytes,
6744                "emergency frame drop: memory guardrail tripped; arena rebuilt"
6745            );
6746            return Ok(());
6747        }
6748
6749        if verdict.should_degrade() {
6750            // Apply guardrail-recommended degradation if it's stricter than budget's
6751            let current = self.budget.degradation();
6752            if verdict.recommended_level > current {
6753                self.budget.set_degradation(verdict.recommended_level);
6754            }
6755
6756            // Soft-tier early trim (bd-1za0z): the memory sensor measures
6757            // retained CAPACITY, so once past the soft limit nothing the
6758            // degradation actuator does can lower it again — only releasing
6759            // capacity can. Trim early (same remediation as the emergency
6760            // shed, but non-fatal) instead of waiting for the emergency
6761            // tier; cooldown-gated so hovering near the limit cannot thrash
6762            // allocations.
6763            let soft_alert = verdict.alerts.iter().any(|alert| {
6764                alert.kind == GuardrailKind::Memory && alert.severity == AlertSeverity::Warning
6765            });
6766            let cooldown_elapsed = match self.last_soft_trim_frame {
6767                None => true,
6768                Some(last) => self.frame_idx.saturating_sub(last) >= SOFT_TRIM_COOLDOWN_FRAMES,
6769            };
6770            if soft_alert && cooldown_elapsed {
6771                self.frame_arena = FrameArena::default();
6772                self.writer.gc(None);
6773                self.last_soft_trim_frame = Some(self.frame_idx);
6774                tracing::debug!(
6775                    target: crate::telemetry_schema::TARGET_GUARDRAILS,
6776                    memory_bytes,
6777                    "soft memory alert: arena rebuilt to release retained capacity"
6778                );
6779            }
6780        }
6781
6782        // Apply conformal risk gate before rendering (if enabled)
6783        let mut conformal_prediction = None;
6784        if let Some(predictor) = self.conformal_predictor.as_ref() {
6785            let baseline_us = self
6786                .last_frame_time_us
6787                .unwrap_or_else(|| self.budget.total().as_secs_f64() * 1_000_000.0);
6788            let diff_strategy = self
6789                .writer
6790                .last_diff_strategy()
6791                .unwrap_or(DiffStrategy::Full);
6792            let frame_height_hint = self.writer.render_height_hint().max(1);
6793            let key = BucketKey::from_context(
6794                self.writer.screen_mode(),
6795                diff_strategy,
6796                self.width,
6797                frame_height_hint,
6798            );
6799            let budget_us = self.budget.total().as_secs_f64() * 1_000_000.0;
6800            let prediction = predictor.predict(key, baseline_us, budget_us);
6801            // An unavailable bound supplies no confidence-based action. Defer
6802            // explicitly to the independent measured-budget controller, which
6803            // already ran in next_frame(); do not erase its degradation or
6804            // stop collecting measurements by repeatedly degrading to SkipFrame.
6805            if !predictor.is_calibrated(&prediction) {
6806                debug!(
6807                    bucket = %prediction.bucket,
6808                    sample_count = prediction.sample_count,
6809                    fallback_level = prediction.fallback_level,
6810                    status = prediction.status.as_str(),
6811                    required_rank = prediction.required_rank,
6812                    action = "defer_to_budget_controller",
6813                    "conformal bound unavailable"
6814                );
6815            } else if prediction.risk {
6816                self.budget.degrade();
6817                info!(
6818                    bucket = %prediction.bucket,
6819                    upper_us = ?prediction.upper_us,
6820                    budget_us = prediction.budget_us,
6821                    fallback_level = prediction.fallback_level,
6822                    degradation = self.budget.degradation().as_str(),
6823                    "conformal gate triggered strategy downgrade"
6824                );
6825                debug!(
6826                    monotonic.counter.conformal_gate_triggers_total = 1_u64,
6827                    bucket = %prediction.bucket,
6828                    "conformal gate trigger"
6829                );
6830            }
6831            debug!(
6832                bucket = %prediction.bucket,
6833                upper_us = ?prediction.upper_us,
6834                budget_us = prediction.budget_us,
6835                fallback = prediction.fallback_level,
6836                risk = prediction.risk,
6837                "conformal risk gate"
6838            );
6839            if predictor.is_calibrated(&prediction)
6840                && let Some(quantile) = prediction.quantile
6841            {
6842                debug!(
6843                    monotonic.histogram.conformal_prediction_interval_width_us = quantile.max(0.0),
6844                    bucket = %prediction.bucket,
6845                    "conformal prediction interval width"
6846                );
6847            }
6848            conformal_prediction = Some(prediction);
6849        }
6850
6851        // Early skip if budget says to skip this frame entirely
6852        if self.budget.exhausted() {
6853            self.budget.record_frame_time(Duration::ZERO);
6854            let load_snapshot =
6855                self.update_load_governor_snapshot(frame_idx, 0.0, conformal_prediction.as_ref());
6856            self.emit_budget_evidence(
6857                frame_idx,
6858                degradation_start,
6859                0.0,
6860                conformal_prediction.as_ref(),
6861                &load_snapshot,
6862            );
6863            crate::debug_trace!(
6864                "frame skipped: budget exhausted (degradation={})",
6865                self.budget.degradation().as_str()
6866            );
6867            debug!(
6868                degradation = self.budget.degradation().as_str(),
6869                "frame skipped: budget exhausted before render"
6870            );
6871            // Keep dirty=true: the UI update was never presented, so a
6872            // future frame must still pick it up.
6873            return Ok(());
6874        }
6875
6876        let auto_bounds = self.writer.inline_auto_bounds();
6877        let needs_measure = auto_bounds.is_some() && self.writer.auto_ui_height().is_none();
6878        let mut should_measure = needs_measure;
6879        if auto_bounds.is_some()
6880            && let Some(state) = self.inline_auto_remeasure.as_mut()
6881        {
6882            let decision = state.sampler.decide(Instant::now());
6883            // The VOI decision is an evidence event like diff and budget
6884            // decisions: without this line the sampler's reasoning was only
6885            // visible through the in-process telemetry snapshot.
6886            if let Some(ref sink) = self.evidence_sink {
6887                let _ = sink.write_jsonl(&decision.to_jsonl());
6888            }
6889            if decision.should_sample {
6890                should_measure = true;
6891            }
6892        } else {
6893            crate::voi_telemetry::clear_inline_auto_voi_snapshot();
6894        }
6895
6896        // --- Render phase ---
6897        let render_start = Instant::now();
6898        if let (Some((min_height, max_height)), true) = (auto_bounds, should_measure) {
6899            let measure_height = if needs_measure {
6900                self.writer.render_height_hint().max(1)
6901            } else {
6902                max_height.max(1)
6903            };
6904            let (measure_buffer, _) = self.render_measure_buffer(measure_height);
6905            let measured_height = measure_buffer.content_height();
6906            let clamped = measured_height.clamp(min_height, max_height);
6907            let previous_height = self.writer.auto_ui_height();
6908            self.writer.set_auto_ui_height(clamped);
6909            if let Some(state) = self.inline_auto_remeasure.as_mut() {
6910                let threshold = state.config.change_threshold_rows;
6911                let violated = previous_height
6912                    .map(|prev| prev.abs_diff(clamped) >= threshold)
6913                    .unwrap_or(false);
6914                state.sampler.observe(violated);
6915            }
6916        }
6917        if auto_bounds.is_some()
6918            && let Some(state) = self.inline_auto_remeasure.as_ref()
6919        {
6920            let snapshot = state.sampler.snapshot(8, crate::debug_trace::elapsed_ms());
6921            crate::voi_telemetry::set_inline_auto_voi_snapshot(Some(snapshot));
6922        }
6923
6924        let frame_height = self.writer.render_height_hint().max(1);
6925        let _frame_span = info_span!(
6926            crate::telemetry_schema::span::RENDER_FRAME,
6927            width = self.width,
6928            height = frame_height,
6929            duration_us = tracing::field::Empty
6930        )
6931        .entered();
6932        let (buffer, cursor, cursor_visible) = self.render_buffer(frame_height);
6933        self.process_a11y_frame();
6934        self.update_widget_refresh_plan(frame_idx);
6935        let render_elapsed = render_start.elapsed();
6936        let mut present_elapsed = Duration::ZERO;
6937        let mut presented = false;
6938
6939        // Check if render phase overspent its budget
6940        let render_budget = self.budget.phase_budgets().render;
6941        if render_elapsed > render_budget {
6942            debug!(
6943                render_ms = render_elapsed.as_millis() as u32,
6944                budget_ms = render_budget.as_millis() as u32,
6945                "render phase exceeded budget"
6946            );
6947            // With the load governor active, the controller decides degradation
6948            // from measured frame history at the next frame boundary. The
6949            // legacy path keeps its immediate threshold fallback.
6950            if self.budget.controller().is_none() && self.budget.should_degrade(render_budget) {
6951                self.budget.degrade();
6952            }
6953        }
6954
6955        // --- Present phase ---
6956        if !self.budget.exhausted() {
6957            let present_start = Instant::now();
6958            {
6959                let _present_span =
6960                    debug_span!(crate::telemetry_schema::span::RENDER_PRESENT).entered();
6961                self.writer
6962                    .present_ui_owned(buffer, cursor, cursor_visible)?;
6963            }
6964            presented = true;
6965            present_elapsed = present_start.elapsed();
6966
6967            let present_budget = self.budget.phase_budgets().present;
6968            if present_elapsed > present_budget {
6969                debug!(
6970                    present_ms = present_elapsed.as_millis() as u32,
6971                    budget_ms = present_budget.as_millis() as u32,
6972                    "present phase exceeded budget"
6973                );
6974            }
6975        } else {
6976            debug!(
6977                degradation = self.budget.degradation().as_str(),
6978                elapsed_ms = self.budget.elapsed().as_millis() as u32,
6979                "frame present skipped: budget exhausted after render"
6980            );
6981        }
6982
6983        if let Some(ref frame_timing) = self.frame_timing {
6984            let update_us = self.last_update_us.unwrap_or(0);
6985            let render_us = render_elapsed.as_micros() as u64;
6986            let present_us = present_elapsed.as_micros() as u64;
6987            let diff_us = if presented {
6988                self.writer
6989                    .take_last_present_timings()
6990                    .map(|timings| timings.diff_us)
6991                    .unwrap_or(0)
6992            } else {
6993                let _ = self.writer.take_last_present_timings();
6994                0
6995            };
6996            let total_us = update_us
6997                .saturating_add(render_us)
6998                .saturating_add(present_us);
6999            let timing = FrameTiming {
7000                frame_idx,
7001                update_us,
7002                render_us,
7003                diff_us,
7004                present_us,
7005                total_us,
7006            };
7007            frame_timing.sink.record_frame(&timing);
7008        }
7009
7010        let frame_time = render_elapsed.saturating_add(present_elapsed);
7011        self.budget.record_frame_time(frame_time);
7012        let frame_time_us = frame_time.as_secs_f64() * 1_000_000.0;
7013
7014        if let (Some(predictor), Some(prediction)) = (
7015            self.conformal_predictor.as_mut(),
7016            conformal_prediction.as_ref(),
7017        ) {
7018            let diff_strategy = self
7019                .writer
7020                .last_diff_strategy()
7021                .unwrap_or(DiffStrategy::Full);
7022            let key = BucketKey::from_context(
7023                self.writer.screen_mode(),
7024                diff_strategy,
7025                self.width,
7026                frame_height,
7027            );
7028            predictor.observe(key, prediction.y_hat, frame_time_us);
7029        }
7030        self.last_frame_time_us = Some(frame_time_us);
7031        let load_snapshot = self.update_load_governor_snapshot(
7032            frame_idx,
7033            frame_time_us,
7034            conformal_prediction.as_ref(),
7035        );
7036        self.emit_budget_evidence(
7037            frame_idx,
7038            degradation_start,
7039            frame_time_us,
7040            conformal_prediction.as_ref(),
7041            &load_snapshot,
7042        );
7043
7044        // Only clear dirty when the frame was actually presented.
7045        // If present was skipped (budget exhausted after render), the UI
7046        // update was never shown and must be retried on the next frame.
7047        if presented {
7048            self.dirty = false;
7049        }
7050
7051        // Deliver the accessibility hook after the dirty reset so a model
7052        // that changes state in response gets one more frame.
7053        if self.a11y_changed {
7054            self.a11y_changed = false;
7055            self.deliver_a11y_frame()?;
7056        }
7057
7058        Ok(())
7059    }
7060
7061    fn update_load_governor_snapshot(
7062        &mut self,
7063        _frame_idx: u64,
7064        frame_time_us: f64,
7065        conformal_prediction: Option<&ConformalPrediction>,
7066    ) -> LoadGovernorSnapshot {
7067        let budget_us = conformal_prediction
7068            .map(|prediction| prediction.budget_us)
7069            .unwrap_or_else(|| self.budget.total().as_secs_f64() * 1_000_000.0);
7070        let resize_stats = self.resize_coalescer.stats();
7071        self.load_governor.observe(LoadGovernorObservation {
7072            frame_time_us,
7073            budget_us,
7074            degradation: self.budget.degradation(),
7075            queue: crate::effect_system::queue_telemetry(),
7076            // Only meaningful when the coalescer actually runs: in legacy
7077            // Immediate mode `tick_at` never fires, so a single Burst entry
7078            // would otherwise pin the governor at SoftOverload forever.
7079            resize_coalescing_active: self.resize_behavior.uses_coalescer()
7080                && (resize_stats.has_pending
7081                    || !matches!(resize_stats.regime, crate::resize_coalescer::Regime::Steady)),
7082            strict_semantics_violation: false,
7083        })
7084    }
7085
7086    fn emit_budget_evidence(
7087        &self,
7088        frame_idx: u64,
7089        degradation_start: DegradationLevel,
7090        frame_time_us: f64,
7091        conformal_prediction: Option<&ConformalPrediction>,
7092        load_snapshot: &LoadGovernorSnapshot,
7093    ) {
7094        let Some(telemetry) = self.budget.telemetry() else {
7095            set_budget_snapshot(None);
7096            return;
7097        };
7098
7099        let budget_us = conformal_prediction
7100            .map(|prediction| prediction.budget_us)
7101            .unwrap_or_else(|| self.budget.total().as_secs_f64() * 1_000_000.0);
7102        let conformal = conformal_prediction.map(ConformalEvidence::from_prediction);
7103        let degradation_after = self.budget.degradation();
7104
7105        let evidence = BudgetDecisionEvidence {
7106            frame_idx,
7107            decision: BudgetDecisionEvidence::decision_from_levels(
7108                degradation_start,
7109                degradation_after,
7110            ),
7111            controller_decision: telemetry.last_decision,
7112            degradation_before: degradation_start,
7113            degradation_after,
7114            frame_time_us,
7115            budget_us,
7116            pid_output: telemetry.pid_output,
7117            pid_p: telemetry.pid_p,
7118            pid_i: telemetry.pid_i,
7119            pid_d: telemetry.pid_d,
7120            e_value: telemetry.e_value,
7121            frames_observed: telemetry.frames_observed,
7122            frames_since_change: telemetry.frames_since_change,
7123            in_warmup: telemetry.in_warmup,
7124            controller_reason: telemetry.decision_reason,
7125            load_governor: *load_snapshot,
7126            resize_detector: self.resize_coalescer.last_detector().as_str(),
7127            conformal,
7128        };
7129
7130        let conformal_snapshot = evidence
7131            .conformal
7132            .as_ref()
7133            .map(|snapshot| ConformalSnapshot {
7134                bucket_key: snapshot.bucket_key.clone(),
7135                sample_count: snapshot.n_b,
7136                upper_us: snapshot.upper_us,
7137                risk: snapshot.risk,
7138                status: snapshot.status,
7139                required_rank: snapshot.required_rank,
7140            });
7141        set_budget_snapshot(Some(BudgetDecisionSnapshot {
7142            frame_idx: evidence.frame_idx,
7143            decision: evidence.decision,
7144            controller_decision: evidence.controller_decision,
7145            degradation_before: evidence.degradation_before,
7146            degradation_after: evidence.degradation_after,
7147            frame_time_us: evidence.frame_time_us,
7148            budget_us: evidence.budget_us,
7149            pid_output: evidence.pid_output,
7150            e_value: evidence.e_value,
7151            frames_observed: evidence.frames_observed,
7152            frames_since_change: evidence.frames_since_change,
7153            in_warmup: evidence.in_warmup,
7154            conformal: conformal_snapshot,
7155        }));
7156
7157        if let Some(ref sink) = self.evidence_sink {
7158            let _ = sink.write_jsonl(&evidence.to_jsonl());
7159        }
7160    }
7161
7162    fn update_widget_refresh_plan(&mut self, frame_idx: u64) {
7163        if !self.widget_refresh_config.enabled {
7164            self.widget_refresh_plan.clear();
7165            return;
7166        }
7167
7168        let budget_us = self.budget.phase_budgets().render.as_secs_f64() * 1_000_000.0;
7169        let degradation = self.budget.degradation();
7170        self.widget_refresh_plan.recompute(
7171            frame_idx,
7172            budget_us,
7173            degradation,
7174            &self.widget_signals,
7175            &self.widget_refresh_config,
7176        );
7177
7178        if let Some(ref sink) = self.evidence_sink {
7179            let _ = sink.write_jsonl(&self.widget_refresh_plan.to_jsonl());
7180        }
7181    }
7182
7183    fn render_buffer(&mut self, frame_height: u16) -> (Buffer, Option<(u16, u16)>, bool) {
7184        // Reset the per-frame arena so widgets get fresh scratch space.
7185        self.frame_arena.reset();
7186
7187        // Note: Frame borrows the pool and links from writer.
7188        // We scope it so it drops before we call present_ui (which needs exclusive writer access).
7189        let buffer = self.writer.take_render_buffer(self.width, frame_height);
7190        let mut a11y_builder = self.a11y_policy.map(|_| A11yTreeBuilder::new());
7191        let (pool, links) = self.writer.pool_and_links_mut();
7192        let mut frame = Frame::from_buffer(buffer, pool);
7193        frame.set_degradation(self.budget.degradation());
7194        frame.set_links(links);
7195        frame.set_widget_budget(self.widget_refresh_plan.as_budget());
7196        frame.set_arena(&self.frame_arena);
7197        if let Some(builder) = a11y_builder.as_mut() {
7198            frame.set_a11y(builder);
7199        }
7200
7201        let view_start = Instant::now();
7202        let _view_span = debug_span!(
7203            crate::telemetry_schema::span::PROGRAM_VIEW,
7204            duration_us = tracing::field::Empty,
7205            widget_count = tracing::field::Empty
7206        )
7207        .entered();
7208        self.model.view(&mut frame);
7209        self.widget_signals = frame.take_widget_signals();
7210        frame.finish_a11y();
7211        let a11y_order = frame.take_a11y_order();
7212        tracing::Span::current().record("duration_us", view_start.elapsed().as_micros() as u64);
7213        // widget_count would require tracking in Frame
7214
7215        let output = (frame.buffer, frame.cursor_position, frame.cursor_visible);
7216        // `frame` is not used past this point, which releases its borrow of
7217        // the builder so the tree can be built.
7218        self.a11y_pending = a11y_builder.map(|builder| (builder.build(), a11y_order));
7219        output
7220    }
7221
7222    /// Diff the accessibility tree collected by the last `render_buffer`
7223    /// against the previous frame's tree, derive screen-reader
7224    /// announcements, and export their metadata. Full text stays local unless
7225    /// explicitly included in the evidence sink; tracing never contains it.
7226    ///
7227    /// No-op unless `ProgramConfig::accessibility` is set.
7228    fn process_a11y_frame(&mut self) {
7229        let Some(policy) = self.a11y_policy else {
7230            return;
7231        };
7232        let Some((tree, order)) = self.a11y_pending.take() else {
7233            return;
7234        };
7235        let previous = self
7236            .a11y_tree
7237            .take()
7238            .unwrap_or_else(|| A11yTreeBuilder::new().build());
7239        let diff = tree.diff(&previous);
7240        let announcements = diff.screen_reader_announcements(&tree, policy);
7241
7242        if !diff.is_empty() {
7243            tracing::debug!(
7244                target: crate::telemetry_schema::TARGET_A11Y,
7245                frame_idx = self.frame_idx,
7246                nodes = tree.node_count(),
7247                added = diff.added.len(),
7248                removed = diff.removed.len(),
7249                changed = diff.changed.len(),
7250                focus_changed = diff.focus_changed.is_some(),
7251                announcements = announcements.announcements.len(),
7252                dropped = announcements.dropped_count,
7253                "a11y tree changed"
7254            );
7255            if let Some(ref sink) = self.evidence_sink {
7256                let focus = match diff.focus_changed {
7257                    Some((_, Some(id))) => id.to_string(),
7258                    Some((_, None)) | None => "null".to_string(),
7259                };
7260                let _ = sink.write_jsonl(&format!(
7261                    r#"{{"event":"a11y_tree","frame_idx":{},"nodes":{},"added":{},"removed":{},"changed":{},"focus":{},"announcements":{},"dropped":{}}}"#,
7262                    self.frame_idx,
7263                    tree.node_count(),
7264                    diff.added.len(),
7265                    diff.removed.len(),
7266                    diff.changed.len(),
7267                    focus,
7268                    announcements.announcements.len(),
7269                    announcements.dropped_count,
7270                ));
7271                for announcement in &announcements.announcements {
7272                    let node_id = announcement
7273                        .node_id
7274                        .map_or_else(|| "null".to_string(), |id| id.to_string());
7275                    let text = if self.a11y_evidence_text {
7276                        format!(
7277                            "\"{}\"",
7278                            crate::queueing_scheduler::escape_json(&announcement.text)
7279                        )
7280                    } else {
7281                        "null".to_string()
7282                    };
7283                    let _ = sink.write_jsonl(&format!(
7284                        r#"{{"event":"a11y_announcement","frame_idx":{},"node_id":{},"urgency":"{}","reason":"{:?}","text":{},"text_chars":{}}}"#,
7285                        self.frame_idx,
7286                        node_id,
7287                        announcement.urgency,
7288                        announcement.reason,
7289                        text,
7290                        announcement.text.chars().count(),
7291                    ));
7292                }
7293            }
7294        }
7295        for announcement in &announcements.announcements {
7296            tracing::info!(
7297                target: crate::telemetry_schema::TARGET_A11Y,
7298                frame_idx = self.frame_idx,
7299                node_id = announcement.node_id,
7300                urgency = %announcement.urgency,
7301                reason = ?announcement.reason,
7302                text_chars = announcement.text.chars().count(),
7303                "screen reader announcement"
7304            );
7305        }
7306
7307        self.a11y_changed = !diff.is_empty();
7308        self.a11y_dropped = announcements.dropped_count;
7309        self.a11y_announcements = announcements.announcements;
7310        self.a11y_tree = Some(tree);
7311        self.a11y_order = order;
7312    }
7313
7314    /// Hand the last frame's tree to [`Model::on_accessibility`] (called by
7315    /// `render_frame` when `process_a11y_frame` saw a change) and schedule
7316    /// one more frame so state the hook changed gets rendered.
7317    fn deliver_a11y_frame(&mut self) -> io::Result<()> {
7318        let Some(tree) = self.a11y_tree.as_ref() else {
7319            return Ok(());
7320        };
7321        let cmd = {
7322            let _span = debug_span!(
7323                crate::telemetry_schema::span::PROGRAM_UPDATE,
7324                msg_type = "accessibility"
7325            )
7326            .entered();
7327            self.model.on_accessibility(AccessibilityFrame {
7328                frame_idx: self.frame_idx,
7329                tree,
7330                order: &self.a11y_order,
7331                announcements: &self.a11y_announcements,
7332                dropped: self.a11y_dropped,
7333            })
7334        };
7335        self.mark_dirty();
7336        self.execute_cmd(cmd)?;
7337        if self.running {
7338            self.reconcile_subscriptions();
7339        }
7340        Ok(())
7341    }
7342
7343    /// The accessibility tree built from the last rendered frame, or `None`
7344    /// when [`ProgramConfig::accessibility`] is unset or nothing has been
7345    /// rendered yet.
7346    #[must_use]
7347    pub fn accessibility_tree(&self) -> Option<&A11yTree> {
7348        self.a11y_tree.as_ref()
7349    }
7350
7351    /// Reading order (node IDs in widget push order) of the last
7352    /// accessibility tree; empty when accessibility is off.
7353    #[must_use]
7354    pub fn accessibility_order(&self) -> &[u64] {
7355        &self.a11y_order
7356    }
7357
7358    /// Screen-reader announcements derived from the last frame's tree diff
7359    /// (bounded by the configured [`ScreenReaderPolicy`]); empty when the
7360    /// tree did not change in an announceable way.
7361    #[must_use]
7362    pub fn accessibility_announcements(&self) -> &[ScreenReaderAnnouncement] {
7363        &self.a11y_announcements
7364    }
7365
7366    /// Indented, one-node-per-line dump of the last accessibility tree in
7367    /// reading order (see [`A11yTree::dump_text`]); `None` when off.
7368    #[must_use]
7369    pub fn accessibility_dump(&self) -> Option<String> {
7370        self.a11y_tree
7371            .as_ref()
7372            .map(|tree| tree.dump_text(&self.a11y_order))
7373    }
7374
7375    fn emit_fairness_evidence(&mut self, decision: &FairnessDecision, dominance_count: u32) {
7376        let Some(ref sink) = self.evidence_sink else {
7377            return;
7378        };
7379
7380        let config = self.fairness_guard.config();
7381        if !self.fairness_config_logged {
7382            let config_entry = FairnessConfigEvidence {
7383                enabled: config.enabled,
7384                input_priority_threshold_ms: config.input_priority_threshold.as_millis() as u64,
7385                dominance_threshold: config.dominance_threshold,
7386                fairness_threshold: config.fairness_threshold,
7387            };
7388            let _ = sink.write_jsonl(&config_entry.to_jsonl());
7389            self.fairness_config_logged = true;
7390        }
7391
7392        let evidence = FairnessDecisionEvidence {
7393            frame_idx: self.frame_idx,
7394            decision: if decision.should_process {
7395                "allow"
7396            } else {
7397                "yield"
7398            },
7399            reason: decision.reason.as_str(),
7400            pending_input_latency_ms: decision
7401                .pending_input_latency
7402                .map(|latency| latency.as_millis() as u64),
7403            jain_index: decision.jain_index,
7404            resize_dominance_count: dominance_count,
7405            dominance_threshold: config.dominance_threshold,
7406            fairness_threshold: config.fairness_threshold,
7407            input_priority_threshold_ms: config.input_priority_threshold.as_millis() as u64,
7408        };
7409
7410        let _ = sink.write_jsonl(&evidence.to_jsonl());
7411    }
7412
7413    fn render_measure_buffer(&mut self, frame_height: u16) -> (Buffer, Option<(u16, u16)>) {
7414        // Reset the per-frame arena for measurement pass.
7415        self.frame_arena.reset();
7416
7417        let pool = self.writer.pool_mut();
7418        let mut frame = Frame::new(self.width, frame_height, pool);
7419        frame.set_degradation(self.budget.degradation());
7420        frame.set_arena(&self.frame_arena);
7421
7422        let view_start = Instant::now();
7423        let _view_span = debug_span!(
7424            crate::telemetry_schema::span::PROGRAM_VIEW,
7425            duration_us = tracing::field::Empty,
7426            widget_count = tracing::field::Empty
7427        )
7428        .entered();
7429        self.model.view(&mut frame);
7430        tracing::Span::current().record("duration_us", view_start.elapsed().as_micros() as u64);
7431
7432        (frame.buffer, frame.cursor_position)
7433    }
7434
7435    /// Calculate the effective poll timeout.
7436    fn effective_timeout(&self) -> Duration {
7437        if let Some(tick_rate) = self.tick_rate {
7438            let elapsed = self.last_tick.elapsed();
7439            let mut timeout = tick_rate.saturating_sub(elapsed);
7440            if self.resize_behavior.uses_coalescer()
7441                && let Some(resize_timeout) = self.resize_coalescer.time_until_apply(Instant::now())
7442            {
7443                timeout = timeout.min(resize_timeout);
7444            }
7445            timeout
7446        } else {
7447            let mut timeout = self.poll_timeout;
7448            if self.resize_behavior.uses_coalescer()
7449                && let Some(resize_timeout) = self.resize_coalescer.time_until_apply(Instant::now())
7450            {
7451                timeout = timeout.min(resize_timeout);
7452            }
7453            timeout
7454        }
7455    }
7456
7457    /// Check if we should send a tick.
7458    fn should_tick(&mut self) -> bool {
7459        if let Some(tick_rate) = self.tick_rate
7460            && self.last_tick.elapsed() >= tick_rate
7461        {
7462            self.last_tick = Instant::now();
7463            return true;
7464        }
7465        false
7466    }
7467
7468    fn process_resize_coalescer(&mut self) -> io::Result<()> {
7469        if !self.resize_behavior.uses_coalescer() {
7470            return Ok(());
7471        }
7472
7473        // Check fairness: if input is starving, skip resize application this cycle.
7474        // This ensures input events are processed before resize is finalized.
7475        let dominance_count = self.fairness_guard.resize_dominance_count();
7476        let fairness_decision = self.fairness_guard.check_fairness(Instant::now());
7477        self.emit_fairness_evidence(&fairness_decision, dominance_count);
7478        if !fairness_decision.should_process {
7479            debug!(
7480                reason = ?fairness_decision.reason,
7481                pending_latency_ms = fairness_decision.pending_input_latency.map(|d| d.as_millis() as u64),
7482                "Resize yielding to input for fairness"
7483            );
7484            // Skip resize application this cycle to allow input processing.
7485            return Ok(());
7486        }
7487
7488        let action = self.resize_coalescer.tick();
7489        let resize_snapshot =
7490            self.resize_coalescer
7491                .logs()
7492                .last()
7493                .map(|entry| ResizeDecisionSnapshot {
7494                    event_idx: entry.event_idx,
7495                    action: entry.action,
7496                    dt_ms: entry.dt_ms,
7497                    event_rate: entry.event_rate,
7498                    regime: entry.regime,
7499                    pending_size: entry.pending_size,
7500                    applied_size: entry.applied_size,
7501                    time_since_render_ms: entry.time_since_render_ms,
7502                    bocpd: self
7503                        .resize_coalescer
7504                        .bocpd()
7505                        .and_then(|detector| detector.last_evidence().cloned()),
7506                });
7507        set_resize_snapshot(resize_snapshot);
7508
7509        match action {
7510            CoalesceAction::ApplyResize {
7511                width,
7512                height,
7513                coalesce_time,
7514                forced_by_deadline,
7515            } => self.apply_resize(width, height, coalesce_time, forced_by_deadline),
7516            _ => Ok(()),
7517        }
7518    }
7519
7520    fn apply_resize(
7521        &mut self,
7522        width: u16,
7523        height: u16,
7524        coalesce_time: Duration,
7525        forced_by_deadline: bool,
7526    ) -> io::Result<()> {
7527        // Clamp to minimum 1 to prevent Buffer::new panic on zero dimensions
7528        let width = width.max(1);
7529        let height = height.max(1);
7530        self.width = width;
7531        self.height = height;
7532        self.writer.set_size(width, height);
7533        info!(
7534            width = width,
7535            height = height,
7536            coalesce_ms = coalesce_time.as_millis() as u64,
7537            forced = forced_by_deadline,
7538            "Resize applied"
7539        );
7540
7541        let msg = M::Message::from(Event::Resize { width, height });
7542        let start = Instant::now();
7543        let cmd = self.model.update(msg);
7544        let elapsed_us = start.elapsed().as_micros() as u64;
7545        self.last_update_us = Some(elapsed_us);
7546        self.mark_dirty();
7547        self.execute_cmd(cmd)?;
7548        if self.running && self.dirty {
7549            self.reconcile_subscriptions();
7550        }
7551        Ok(())
7552    }
7553
7554    // removed: resize placeholder rendering (continuous reflow preferred)
7555
7556    /// Get a reference to the model.
7557    pub fn model(&self) -> &M {
7558        &self.model
7559    }
7560
7561    /// Get a mutable reference to the model.
7562    pub fn model_mut(&mut self) -> &mut M {
7563        &mut self.model
7564    }
7565
7566    /// Check if the program is running.
7567    pub fn is_running(&self) -> bool {
7568        self.running
7569    }
7570
7571    /// Get the current tick rate, if one has been installed.
7572    #[must_use]
7573    pub const fn tick_rate(&self) -> Option<Duration> {
7574        self.tick_rate
7575    }
7576
7577    /// Get the number of commands actually executed by the runtime.
7578    #[must_use]
7579    pub const fn executed_cmd_count(&self) -> usize {
7580        self.executed_cmd_count
7581    }
7582
7583    /// Request a quit.
7584    pub fn quit(&mut self) {
7585        self.running = false;
7586    }
7587
7588    /// Get a reference to the state registry, if configured.
7589    pub fn state_registry(&self) -> Option<&std::sync::Arc<StateRegistry>> {
7590        self.state_registry.as_ref()
7591    }
7592
7593    /// Check if state persistence is enabled.
7594    pub fn has_persistence(&self) -> bool {
7595        self.state_registry.is_some()
7596    }
7597
7598    /// Query the current tick strategy's debug statistics.
7599    ///
7600    /// Returns key-value pairs describing the strategy's internal state
7601    /// (e.g. strategy name, divisors, confidence, transition counts).
7602    /// Returns an empty vec if no tick strategy is configured.
7603    #[must_use]
7604    pub fn tick_strategy_stats(&self) -> Vec<(String, String)> {
7605        self.tick_strategy
7606            .as_ref()
7607            .map(|s| s.debug_stats())
7608            .unwrap_or_default()
7609    }
7610
7611    /// Trigger a manual save of widget state.
7612    ///
7613    /// Returns the result of the flush operation, or `Ok(false)` if
7614    /// persistence is not configured.
7615    pub fn trigger_save(&mut self) -> StorageResult<bool> {
7616        if let Some(registry) = &self.state_registry {
7617            registry.flush()
7618        } else {
7619            Ok(false)
7620        }
7621    }
7622
7623    /// Trigger a manual load of widget state.
7624    ///
7625    /// Returns the number of entries loaded, or `Ok(0)` if persistence
7626    /// is not configured.
7627    pub fn trigger_load(&mut self) -> StorageResult<usize> {
7628        if let Some(registry) = &self.state_registry {
7629            registry.load()
7630        } else {
7631            Ok(0)
7632        }
7633    }
7634
7635    fn mark_dirty(&mut self) {
7636        self.dirty = true;
7637    }
7638
7639    fn check_locale_change(&mut self) {
7640        let version = self.locale_context.version();
7641        if version != self.locale_version {
7642            self.locale_version = version;
7643            self.mark_dirty();
7644        }
7645    }
7646
7647    /// Mark the UI as needing redraw.
7648    pub fn request_redraw(&mut self) {
7649        self.mark_dirty();
7650    }
7651
7652    /// Request a re-measure of inline auto UI height on next render.
7653    pub fn request_ui_height_remeasure(&mut self) {
7654        if self.writer.inline_auto_bounds().is_some() {
7655            self.writer.clear_auto_ui_height();
7656            if let Some(state) = self.inline_auto_remeasure.as_mut() {
7657                state.reset();
7658            }
7659            crate::voi_telemetry::clear_inline_auto_voi_snapshot();
7660            self.mark_dirty();
7661        }
7662    }
7663
7664    /// Start recording events into a macro.
7665    ///
7666    /// If already recording, the current recording is discarded and a new one starts.
7667    /// The current terminal size is captured as metadata.
7668    pub fn start_recording(&mut self, name: impl Into<String>) {
7669        let mut recorder = EventRecorder::new(name).with_terminal_size(self.width, self.height);
7670        recorder.start();
7671        self.event_recorder = Some(recorder);
7672    }
7673
7674    /// Stop recording and return the recorded macro, if any.
7675    ///
7676    /// Returns `None` if not currently recording.
7677    pub fn stop_recording(&mut self) -> Option<InputMacro> {
7678        self.event_recorder.take().map(EventRecorder::finish)
7679    }
7680
7681    /// Check if event recording is active.
7682    pub fn is_recording(&self) -> bool {
7683        self.event_recorder
7684            .as_ref()
7685            .is_some_and(EventRecorder::is_recording)
7686    }
7687}
7688
7689/// Builder for creating and running programs.
7690pub struct App;
7691
7692impl App {
7693    /// Create a new app builder with the given model.
7694    #[allow(clippy::new_ret_no_self)] // App is a namespace for builder methods
7695    pub fn new<M: Model>(model: M) -> AppBuilder<M> {
7696        AppBuilder {
7697            model,
7698            config: ProgramConfig::default(),
7699        }
7700    }
7701
7702    /// Create a fullscreen app.
7703    pub fn fullscreen<M: Model>(model: M) -> AppBuilder<M> {
7704        AppBuilder {
7705            model,
7706            config: ProgramConfig::fullscreen(),
7707        }
7708    }
7709
7710    /// Create an inline app with the given height.
7711    pub fn inline<M: Model>(model: M, height: u16) -> AppBuilder<M> {
7712        AppBuilder {
7713            model,
7714            config: ProgramConfig::inline(height),
7715        }
7716    }
7717
7718    /// Create an inline app with automatic UI height.
7719    pub fn inline_auto<M: Model>(model: M, min_height: u16, max_height: u16) -> AppBuilder<M> {
7720        AppBuilder {
7721            model,
7722            config: ProgramConfig::inline_auto(min_height, max_height),
7723        }
7724    }
7725
7726    /// Create a fullscreen app from a [`StringModel`](crate::string_model::StringModel).
7727    ///
7728    /// This wraps the string model in a [`StringModelAdapter`](crate::string_model::StringModelAdapter)
7729    /// so that `view_string()` output is rendered through the standard kernel pipeline.
7730    pub fn string_model<S: crate::string_model::StringModel>(
7731        model: S,
7732    ) -> AppBuilder<crate::string_model::StringModelAdapter<S>> {
7733        AppBuilder {
7734            model: crate::string_model::StringModelAdapter::new(model),
7735            config: ProgramConfig::fullscreen(),
7736        }
7737    }
7738}
7739
7740/// Builder for configuring and running programs.
7741#[must_use]
7742pub struct AppBuilder<M: Model> {
7743    model: M,
7744    config: ProgramConfig,
7745}
7746
7747impl<M: Model> AppBuilder<M> {
7748    /// Set the screen mode.
7749    pub fn screen_mode(mut self, mode: ScreenMode) -> Self {
7750        self.config.screen_mode = mode;
7751        self
7752    }
7753
7754    /// Set the UI anchor.
7755    pub fn anchor(mut self, anchor: UiAnchor) -> Self {
7756        self.config.ui_anchor = anchor;
7757        self
7758    }
7759
7760    /// Force mouse capture on.
7761    pub fn with_mouse(mut self) -> Self {
7762        self.config.mouse_capture_policy = MouseCapturePolicy::On;
7763        self
7764    }
7765
7766    /// Set mouse capture policy for this app.
7767    pub fn with_mouse_capture_policy(mut self, policy: MouseCapturePolicy) -> Self {
7768        self.config.mouse_capture_policy = policy;
7769        self
7770    }
7771
7772    /// Force mouse capture enabled/disabled for this app.
7773    pub fn with_mouse_enabled(mut self, enabled: bool) -> Self {
7774        self.config.mouse_capture_policy = if enabled {
7775            MouseCapturePolicy::On
7776        } else {
7777            MouseCapturePolicy::Off
7778        };
7779        self
7780    }
7781
7782    /// Set the frame budget configuration.
7783    pub fn with_budget(mut self, budget: FrameBudgetConfig) -> Self {
7784        self.config.budget = budget;
7785        self
7786    }
7787
7788    /// Set the runtime load-governor configuration.
7789    pub fn with_load_governor(mut self, config: LoadGovernorConfig) -> Self {
7790        self.config.load_governor = config;
7791        self
7792    }
7793
7794    /// Disable the adaptive load governor for this app.
7795    pub fn without_load_governor(mut self) -> Self {
7796        self.config.load_governor = LoadGovernorConfig::disabled();
7797        self
7798    }
7799
7800    /// Set the evidence JSONL sink configuration.
7801    pub fn with_evidence_sink(mut self, config: EvidenceSinkConfig) -> Self {
7802        self.config.evidence_sink = config;
7803        self
7804    }
7805
7806    /// Set the render-trace recorder configuration.
7807    pub fn with_render_trace(mut self, config: RenderTraceConfig) -> Self {
7808        self.config.render_trace = config;
7809        self
7810    }
7811
7812    /// Set the widget refresh selection configuration.
7813    pub fn with_widget_refresh(mut self, config: WidgetRefreshConfig) -> Self {
7814        self.config.widget_refresh = config;
7815        self
7816    }
7817
7818    /// Set the effect queue scheduling configuration.
7819    pub fn with_effect_queue(mut self, config: EffectQueueConfig) -> Self {
7820        self.config.effect_queue = config;
7821        self
7822    }
7823
7824    /// Enable inline auto UI height remeasurement.
7825    pub fn with_inline_auto_remeasure(mut self, config: InlineAutoRemeasureConfig) -> Self {
7826        self.config.inline_auto_remeasure = Some(config);
7827        self
7828    }
7829
7830    /// Disable inline auto UI height remeasurement.
7831    pub fn without_inline_auto_remeasure(mut self) -> Self {
7832        self.config.inline_auto_remeasure = None;
7833        self
7834    }
7835
7836    /// Set the locale context used for rendering.
7837    pub fn with_locale_context(mut self, locale_context: LocaleContext) -> Self {
7838        self.config.locale_context = locale_context;
7839        self
7840    }
7841
7842    /// Set the base locale used for rendering.
7843    pub fn with_locale(mut self, locale: impl Into<crate::locale::Locale>) -> Self {
7844        self.config.locale_context = LocaleContext::new(locale);
7845        self
7846    }
7847
7848    /// Set the resize coalescer configuration.
7849    pub fn resize_coalescer(mut self, config: CoalescerConfig) -> Self {
7850        self.config.resize_coalescer = config;
7851        self
7852    }
7853
7854    /// Set the resize handling behavior.
7855    pub fn resize_behavior(mut self, behavior: ResizeBehavior) -> Self {
7856        self.config.resize_behavior = behavior;
7857        self
7858    }
7859
7860    /// Toggle legacy immediate-resize behavior for migration.
7861    pub fn legacy_resize(mut self, enabled: bool) -> Self {
7862        if enabled {
7863            self.config.resize_behavior = ResizeBehavior::Immediate;
7864        }
7865        self
7866    }
7867
7868    /// Set the tick strategy for selective background screen ticking.
7869    pub fn tick_strategy(mut self, strategy: crate::tick_strategy::TickStrategyKind) -> Self {
7870        self.config.tick_strategy = Some(strategy);
7871        self
7872    }
7873
7874    /// Run the application on the default backend for this build.
7875    ///
7876    /// Selects the native TTY backend on Unix when `native-backend` is
7877    /// compiled, otherwise the Crossterm backend when `crossterm-compat` is
7878    /// compiled (see [`DEFAULT_BACKEND`]). When neither backend feature was
7879    /// compiled this returns an [`io::ErrorKind::Unsupported`] error whose
7880    /// message names the feature to enable ([`NO_BACKEND_MESSAGE`]).
7881    ///
7882    /// A termination signal that ends the run exits the process with
7883    /// `128 + signal` after the terminal has been restored, matching the
7884    /// behavior of [`AppBuilder::run_native`] and [`AppBuilder::run_crossterm`].
7885    pub fn run(self) -> io::Result<()>
7886    where
7887        M::Message: Send + 'static,
7888    {
7889        self.run_default_backend()
7890    }
7891
7892    #[cfg(all(feature = "native-backend", unix))]
7893    fn run_default_backend(self) -> io::Result<()>
7894    where
7895        M::Message: Send + 'static,
7896    {
7897        self.run_native()
7898    }
7899
7900    #[cfg(all(
7901        feature = "crossterm-compat",
7902        not(all(feature = "native-backend", unix))
7903    ))]
7904    fn run_default_backend(self) -> io::Result<()>
7905    where
7906        M::Message: Send + 'static,
7907    {
7908        self.run_crossterm()
7909    }
7910
7911    #[cfg(not(any(all(feature = "native-backend", unix), feature = "crossterm-compat")))]
7912    fn run_default_backend(self) -> io::Result<()>
7913    where
7914        M::Message: Send + 'static,
7915    {
7916        let _ = (self.model, self.config);
7917        Err(io::Error::new(
7918            io::ErrorKind::Unsupported,
7919            NO_BACKEND_MESSAGE,
7920        ))
7921    }
7922
7923    /// Run the application using the Crossterm backend.
7924    #[cfg(feature = "crossterm-compat")]
7925    pub fn run_crossterm(self) -> io::Result<()>
7926    where
7927        M::Message: Send + 'static,
7928    {
7929        finish_run(Program::with_config(self.model, self.config)?)
7930    }
7931
7932    /// Run the application using the Crossterm backend.
7933    ///
7934    /// This build did not enable `crossterm-compat`; use [`AppBuilder::run`]
7935    /// for the default backend.
7936    #[cfg(not(feature = "crossterm-compat"))]
7937    pub fn run_crossterm(self) -> io::Result<()>
7938    where
7939        M::Message: Send + 'static,
7940    {
7941        let _ = (self.model, self.config);
7942        Err(io::Error::new(
7943            io::ErrorKind::Unsupported,
7944            "enable `crossterm-compat` feature to use AppBuilder::run_crossterm()",
7945        ))
7946    }
7947
7948    /// Run the application using the native TTY backend.
7949    #[cfg(all(feature = "native-backend", unix))]
7950    pub fn run_native(self) -> io::Result<()>
7951    where
7952        M::Message: Send + 'static,
7953    {
7954        finish_run(Program::with_native_backend(self.model, self.config)?)
7955    }
7956
7957    /// Run the application using the native TTY backend.
7958    ///
7959    /// On non-Unix targets the native backend is unavailable; call
7960    /// [`AppBuilder::run`] (which selects Crossterm there) instead.
7961    #[cfg(any(not(feature = "native-backend"), not(unix)))]
7962    pub fn run_native(self) -> io::Result<()>
7963    where
7964        M::Message: Send + 'static,
7965    {
7966        let _ = (self.model, self.config);
7967        // Prefer the platform-level message: a Windows user without
7968        // `native-backend` enabled would otherwise be told to enable the
7969        // feature, only to discover after rebuilding that it's still
7970        // Unix-only. Pointing them at run() up front avoids the two-step debug.
7971        #[cfg(not(unix))]
7972        let msg = "AppBuilder::run_native() is Unix-only; use AppBuilder::run() on this platform";
7973        #[cfg(all(unix, not(feature = "native-backend")))]
7974        let msg = "enable `native-backend` feature to use AppBuilder::run_native()";
7975        Err(io::Error::new(io::ErrorKind::Unsupported, msg))
7976    }
7977}
7978
7979// =============================================================================
7980// Adaptive Batch Window: Queueing Model (bd-4kq0.8.1)
7981// =============================================================================
7982//
7983// # M/G/1 Queueing Model for Event Batching
7984//
7985// ## Problem
7986//
7987// The event loop must balance two objectives:
7988// 1. **Low latency**: Process events quickly (small batch window τ).
7989// 2. **Efficiency**: Batch multiple events to amortize render cost (large τ).
7990//
7991// ## Model
7992//
7993// We model the event loop as an M/G/1 queue:
7994// - Events arrive at rate λ (Poisson process, reasonable for human input).
7995// - Service time S has mean E[S] and variance Var[S] (render + present).
7996// - Utilization ρ = λ·E[S] must be < 1 for stability.
7997//
7998// ## Pollaczek–Khinchine Mean Waiting Time
7999//
8000// For M/G/1: E[W] = (λ·E[S²]) / (2·(1 − ρ))
8001// where E[S²] = Var[S] + E[S]².
8002//
8003// ## Optimal Batch Window τ
8004//
8005// With batching window τ, we collect ~(λ·τ) events per batch, amortizing
8006// the per-frame render cost. The effective per-event latency is:
8007//
8008//   L(τ) = τ/2 + E[S]
8009//         (waiting in batch)  (service)
8010//
8011// The batch reduces arrival rate to λ_eff = 1/τ (one batch per window),
8012// giving utilization ρ_eff = E[S]/τ.
8013//
8014// Minimizing L(τ) subject to ρ_eff < 1:
8015//   L(τ) = τ/2 + E[S]
8016//   dL/dτ = 1/2  (always positive, so smaller τ is always better for latency)
8017//
8018// But we need ρ_eff < 1, so τ > E[S].
8019//
8020// The practical rule: τ = max(E[S] · headroom_factor, τ_min)
8021// where headroom_factor provides margin (typically 1.5–2.0).
8022//
8023// For high arrival rates: τ = max(E[S] · headroom, 1/λ_target)
8024// where λ_target is the max frame rate we want to sustain.
8025//
8026// ## Failure Modes
8027//
8028// 1. **Overload (ρ ≥ 1)**: Queue grows unbounded. Mitigation: increase τ
8029//    (degrade to lower frame rate), or drop stale events.
8030// 2. **Bursty arrivals**: Real input is bursty (typing, mouse drag). The
8031//    exponential moving average of λ smooths this; high burst periods
8032//    temporarily increase τ.
8033// 3. **Variable service time**: Render complexity varies per frame. Using
8034//    EMA of E[S] tracks this adaptively.
8035//
8036// ## Observable Telemetry
8037//
8038// - λ_est: Exponential moving average of inter-arrival times.
8039// - es_est: Exponential moving average of service (render) times.
8040// - ρ_est: λ_est × es_est (estimated utilization).
8041
8042/// Adaptive batch window controller based on M/G/1 queueing model.
8043///
8044/// Estimates arrival rate λ and service time `E[S]` from observations,
8045/// then computes the optimal batch window τ to maintain stability
8046/// (ρ < 1) while minimizing latency.
8047#[derive(Debug, Clone)]
8048pub struct BatchController {
8049    /// Exponential moving average of inter-arrival time (seconds).
8050    ema_inter_arrival_s: f64,
8051    /// Exponential moving average of service time (seconds).
8052    ema_service_s: f64,
8053    /// EMA smoothing factor (0..1). Higher = more responsive.
8054    alpha: f64,
8055    /// Minimum batch window (floor).
8056    tau_min_s: f64,
8057    /// Maximum batch window (cap for responsiveness).
8058    tau_max_s: f64,
8059    /// Headroom factor: τ >= E[S] × headroom to keep ρ < 1.
8060    headroom: f64,
8061    /// Last event arrival timestamp.
8062    last_arrival: Option<Instant>,
8063    /// Number of observations.
8064    observations: u64,
8065}
8066
8067impl BatchController {
8068    /// Create a new controller with sensible defaults.
8069    ///
8070    /// - `alpha`: EMA smoothing (default 0.2)
8071    /// - `tau_min`: minimum batch window (default 1ms)
8072    /// - `tau_max`: maximum batch window (default 50ms)
8073    /// - `headroom`: stability margin (default 2.0, keeps ρ ≤ 0.5)
8074    pub fn new() -> Self {
8075        Self {
8076            ema_inter_arrival_s: 0.1, // assume 10 events/sec initially
8077            ema_service_s: 0.002,     // assume 2ms render initially
8078            alpha: 0.2,
8079            tau_min_s: 0.001, // 1ms floor
8080            tau_max_s: 0.050, // 50ms cap
8081            headroom: 2.0,
8082            last_arrival: None,
8083            observations: 0,
8084        }
8085    }
8086
8087    /// Record an event arrival, updating the inter-arrival estimate.
8088    pub fn observe_arrival(&mut self, now: Instant) {
8089        if let Some(last) = self.last_arrival {
8090            let dt = now.saturating_duration_since(last).as_secs_f64();
8091            if dt > 0.0 && dt < 10.0 {
8092                // Guard against stale gaps (e.g., app was suspended)
8093                self.ema_inter_arrival_s =
8094                    self.alpha * dt + (1.0 - self.alpha) * self.ema_inter_arrival_s;
8095                self.observations += 1;
8096            }
8097        }
8098        self.last_arrival = Some(now);
8099    }
8100
8101    /// Record a service (render) time observation.
8102    pub fn observe_service(&mut self, duration: Duration) {
8103        let dt = duration.as_secs_f64();
8104        if (0.0..10.0).contains(&dt) {
8105            self.ema_service_s = self.alpha * dt + (1.0 - self.alpha) * self.ema_service_s;
8106        }
8107    }
8108
8109    /// Estimated arrival rate λ (events/second).
8110    #[inline]
8111    pub fn lambda_est(&self) -> f64 {
8112        if self.ema_inter_arrival_s > 0.0 {
8113            1.0 / self.ema_inter_arrival_s
8114        } else {
8115            0.0
8116        }
8117    }
8118
8119    /// Estimated service time `E[S]` (seconds).
8120    #[inline]
8121    pub fn service_est_s(&self) -> f64 {
8122        self.ema_service_s
8123    }
8124
8125    /// Estimated utilization ρ = λ × `E[S]`.
8126    #[inline]
8127    pub fn rho_est(&self) -> f64 {
8128        self.lambda_est() * self.ema_service_s
8129    }
8130
8131    /// Compute the optimal batch window τ (seconds).
8132    ///
8133    /// τ = clamp(`E[S]` × headroom, τ_min, τ_max)
8134    ///
8135    /// When ρ approaches 1, τ increases to maintain stability.
8136    pub fn tau_s(&self) -> f64 {
8137        let base = self.ema_service_s * self.headroom;
8138        base.clamp(self.tau_min_s, self.tau_max_s)
8139    }
8140
8141    /// Compute the optimal batch window as a Duration.
8142    pub fn tau(&self) -> Duration {
8143        Duration::from_secs_f64(self.tau_s())
8144    }
8145
8146    /// Check if the system is stable (ρ < 1).
8147    #[inline]
8148    pub fn is_stable(&self) -> bool {
8149        self.rho_est() < 1.0
8150    }
8151
8152    /// Number of observations recorded.
8153    #[inline]
8154    pub fn observations(&self) -> u64 {
8155        self.observations
8156    }
8157}
8158
8159impl Default for BatchController {
8160    fn default() -> Self {
8161        Self::new()
8162    }
8163}
8164
8165#[cfg(test)]
8166mod tests {
8167    use super::*;
8168    use ftui_core::terminal_capabilities::TerminalCapabilities;
8169    use ftui_layout::PaneDragResizeEffect;
8170    use ftui_render::buffer::Buffer;
8171    use ftui_render::cell::Cell;
8172    use ftui_render::diff_strategy::DiffStrategy;
8173    use ftui_render::frame::CostEstimateSource;
8174    use ftui_render::frame_guardrails::{MemoryBudgetConfig, QueueConfig};
8175    use serde_json::Value;
8176    use std::collections::{HashMap, VecDeque};
8177    use std::path::PathBuf;
8178    use std::sync::mpsc;
8179    use std::sync::{
8180        Arc,
8181        atomic::{AtomicUsize, Ordering},
8182    };
8183
8184    // Simple test model
8185    struct TestModel {
8186        value: i32,
8187    }
8188
8189    #[derive(Debug)]
8190    enum TestMsg {
8191        Increment,
8192        Decrement,
8193        Quit,
8194    }
8195
8196    impl From<Event> for TestMsg {
8197        fn from(_event: Event) -> Self {
8198            TestMsg::Increment
8199        }
8200    }
8201
8202    impl Model for TestModel {
8203        type Message = TestMsg;
8204
8205        fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
8206            match msg {
8207                TestMsg::Increment => {
8208                    self.value += 1;
8209                    Cmd::none()
8210                }
8211                TestMsg::Decrement => {
8212                    self.value -= 1;
8213                    Cmd::none()
8214                }
8215                TestMsg::Quit => Cmd::quit(),
8216            }
8217        }
8218
8219        fn view(&self, _frame: &mut Frame) {
8220            // No-op for tests
8221        }
8222    }
8223
8224    #[test]
8225    fn cmd_none() {
8226        let cmd: Cmd<TestMsg> = Cmd::none();
8227        assert!(matches!(cmd, Cmd::None));
8228    }
8229
8230    #[test]
8231    fn cmd_quit() {
8232        let cmd: Cmd<TestMsg> = Cmd::quit();
8233        assert!(matches!(cmd, Cmd::Quit));
8234    }
8235
8236    #[test]
8237    fn cmd_msg() {
8238        let cmd: Cmd<TestMsg> = Cmd::msg(TestMsg::Increment);
8239        assert!(matches!(cmd, Cmd::Msg(TestMsg::Increment)));
8240    }
8241
8242    #[test]
8243    fn cmd_batch_empty() {
8244        let cmd: Cmd<TestMsg> = Cmd::batch(vec![]);
8245        assert!(matches!(cmd, Cmd::None));
8246    }
8247
8248    #[test]
8249    fn cmd_batch_single() {
8250        let cmd: Cmd<TestMsg> = Cmd::batch(vec![Cmd::quit()]);
8251        assert!(matches!(cmd, Cmd::Quit));
8252    }
8253
8254    #[test]
8255    fn cmd_batch_multiple() {
8256        let cmd: Cmd<TestMsg> = Cmd::batch(vec![Cmd::none(), Cmd::quit()]);
8257        assert!(matches!(cmd, Cmd::Batch(_)));
8258    }
8259
8260    #[test]
8261    fn cmd_sequence_empty() {
8262        let cmd: Cmd<TestMsg> = Cmd::sequence(vec![]);
8263        assert!(matches!(cmd, Cmd::None));
8264    }
8265
8266    #[test]
8267    fn cmd_tick() {
8268        let cmd: Cmd<TestMsg> = Cmd::tick(Duration::from_millis(100));
8269        assert!(matches!(cmd, Cmd::Tick(_)));
8270    }
8271
8272    #[test]
8273    fn cmd_task() {
8274        let cmd: Cmd<TestMsg> = Cmd::task(|| TestMsg::Increment);
8275        assert!(matches!(cmd, Cmd::Task(..)));
8276    }
8277
8278    #[test]
8279    fn cmd_debug_format() {
8280        let cmd: Cmd<TestMsg> = Cmd::task(|| TestMsg::Increment);
8281        let debug = format!("{cmd:?}");
8282        assert_eq!(
8283            debug,
8284            "Task { spec: TaskSpec { weight: 1.0, estimate_ms: 10.0, name: None } }"
8285        );
8286    }
8287
8288    #[test]
8289    fn model_subscriptions_default_empty() {
8290        let model = TestModel { value: 0 };
8291        let subs = model.subscriptions();
8292        assert!(subs.is_empty());
8293    }
8294
8295    #[test]
8296    fn program_config_default() {
8297        let config = ProgramConfig::default();
8298        assert!(matches!(config.screen_mode, ScreenMode::Inline { .. }));
8299        assert_eq!(config.mouse_capture_policy, MouseCapturePolicy::Auto);
8300        assert!(!config.resolved_mouse_capture());
8301        assert!(config.bracketed_paste);
8302        assert_eq!(config.resize_behavior, ResizeBehavior::Throttled);
8303        assert!(config.inline_auto_remeasure.is_none());
8304        let conformal = config
8305            .conformal_config
8306            .as_ref()
8307            .expect("conformal frame-time gating is on by default");
8308        assert_eq!(conformal.min_samples, 20, "warm-up before any gating");
8309        assert!(
8310            ProgramConfig::default()
8311                .without_conformal()
8312                .conformal_config
8313                .is_none()
8314        );
8315        assert!(config.diff_config.bayesian_enabled);
8316        assert!(config.diff_config.dirty_rows_enabled);
8317        assert!(config.resize_coalescer.enable_bocpd);
8318        assert!(config.resize_coalescer.heuristic_fallback);
8319        assert!(!config.effect_queue.enabled);
8320        assert_eq!(config.immediate_drain.max_zero_timeout_polls_per_burst, 64);
8321        assert_eq!(
8322            config.immediate_drain.max_burst_duration,
8323            Duration::from_millis(2)
8324        );
8325        assert_eq!(
8326            config.immediate_drain.backoff_timeout,
8327            Duration::from_millis(1)
8328        );
8329        assert_eq!(
8330            config.resize_coalescer.steady_delay_ms,
8331            CoalescerConfig::default().steady_delay_ms
8332        );
8333    }
8334
8335    #[test]
8336    fn program_config_with_immediate_drain() {
8337        let custom = ImmediateDrainConfig {
8338            max_zero_timeout_polls_per_burst: 7,
8339            max_burst_duration: Duration::from_millis(9),
8340            backoff_timeout: Duration::from_millis(3),
8341        };
8342        let config = ProgramConfig::default().with_immediate_drain(custom.clone());
8343        assert_eq!(
8344            config.immediate_drain.max_zero_timeout_polls_per_burst,
8345            custom.max_zero_timeout_polls_per_burst
8346        );
8347        assert_eq!(
8348            config.immediate_drain.max_burst_duration,
8349            custom.max_burst_duration
8350        );
8351        assert_eq!(
8352            config.immediate_drain.backoff_timeout,
8353            custom.backoff_timeout
8354        );
8355    }
8356
8357    #[test]
8358    fn program_config_fullscreen() {
8359        let config = ProgramConfig::fullscreen();
8360        assert!(matches!(config.screen_mode, ScreenMode::AltScreen));
8361    }
8362
8363    #[test]
8364    fn program_config_inline() {
8365        let config = ProgramConfig::inline(10);
8366        assert!(matches!(
8367            config.screen_mode,
8368            ScreenMode::Inline { ui_height: 10 }
8369        ));
8370    }
8371
8372    #[test]
8373    fn program_config_inline_auto() {
8374        let config = ProgramConfig::inline_auto(3, 9);
8375        assert!(matches!(
8376            config.screen_mode,
8377            ScreenMode::InlineAuto {
8378                min_height: 3,
8379                max_height: 9
8380            }
8381        ));
8382        assert!(config.inline_auto_remeasure.is_some());
8383    }
8384
8385    #[test]
8386    fn program_config_with_mouse() {
8387        let config = ProgramConfig::default().with_mouse();
8388        assert_eq!(config.mouse_capture_policy, MouseCapturePolicy::On);
8389        assert!(config.resolved_mouse_capture());
8390    }
8391
8392    #[cfg(feature = "native-backend")]
8393    #[test]
8394    fn sanitize_backend_features_disables_unsupported_features() {
8395        let requested = BackendFeatures {
8396            mouse_capture: true,
8397            bracketed_paste: true,
8398            focus_events: true,
8399            kitty_keyboard: true,
8400        };
8401        let sanitized =
8402            sanitize_backend_features_for_capabilities(requested, &TerminalCapabilities::basic());
8403        assert_eq!(sanitized, BackendFeatures::default());
8404    }
8405
8406    #[cfg(feature = "native-backend")]
8407    #[test]
8408    fn sanitize_backend_features_is_conservative_in_wezterm_mux() {
8409        let requested = BackendFeatures {
8410            mouse_capture: true,
8411            bracketed_paste: true,
8412            focus_events: true,
8413            kitty_keyboard: true,
8414        };
8415        let caps = TerminalCapabilities::builder()
8416            .mouse_sgr(true)
8417            .bracketed_paste(true)
8418            .focus_events(true)
8419            .kitty_keyboard(true)
8420            .in_wezterm_mux(true)
8421            .build();
8422        let sanitized = sanitize_backend_features_for_capabilities(requested, &caps);
8423
8424        assert!(sanitized.mouse_capture);
8425        assert!(sanitized.bracketed_paste);
8426        assert!(!sanitized.focus_events);
8427        assert!(!sanitized.kitty_keyboard);
8428    }
8429
8430    #[cfg(feature = "native-backend")]
8431    #[test]
8432    fn sanitize_backend_features_is_conservative_in_tmux() {
8433        let requested = BackendFeatures {
8434            mouse_capture: true,
8435            bracketed_paste: true,
8436            focus_events: true,
8437            kitty_keyboard: true,
8438        };
8439        let caps = TerminalCapabilities::builder()
8440            .mouse_sgr(true)
8441            .bracketed_paste(true)
8442            .focus_events(true)
8443            .kitty_keyboard(true)
8444            .in_tmux(true)
8445            .build();
8446        let sanitized = sanitize_backend_features_for_capabilities(requested, &caps);
8447
8448        assert!(sanitized.mouse_capture);
8449        assert!(sanitized.bracketed_paste);
8450        assert!(!sanitized.focus_events);
8451        assert!(!sanitized.kitty_keyboard);
8452    }
8453
8454    #[test]
8455    fn program_config_mouse_policy_auto_altscreen() {
8456        let config = ProgramConfig::fullscreen();
8457        assert_eq!(config.mouse_capture_policy, MouseCapturePolicy::Auto);
8458        assert!(config.resolved_mouse_capture());
8459    }
8460
8461    #[test]
8462    fn program_config_mouse_policy_force_off() {
8463        let config = ProgramConfig::fullscreen().with_mouse_capture_policy(MouseCapturePolicy::Off);
8464        assert_eq!(config.mouse_capture_policy, MouseCapturePolicy::Off);
8465        assert!(!config.resolved_mouse_capture());
8466    }
8467
8468    #[test]
8469    fn program_config_mouse_policy_force_on_inline() {
8470        let config = ProgramConfig::inline(6).with_mouse_enabled(true);
8471        assert_eq!(config.mouse_capture_policy, MouseCapturePolicy::On);
8472        assert!(config.resolved_mouse_capture());
8473    }
8474
8475    fn pane_target(axis: SplitAxis) -> PaneResizeTarget {
8476        PaneResizeTarget {
8477            split_id: ftui_layout::PaneId::MIN,
8478            axis,
8479        }
8480    }
8481
8482    fn pane_id(raw: u64) -> ftui_layout::PaneId {
8483        ftui_layout::PaneId::new(raw).expect("test pane id must be non-zero")
8484    }
8485
8486    fn nested_pane_tree() -> ftui_layout::PaneTree {
8487        let root = pane_id(1);
8488        let left = pane_id(2);
8489        let right_split = pane_id(3);
8490        let right_top = pane_id(4);
8491        let right_bottom = pane_id(5);
8492        let snapshot = ftui_layout::PaneTreeSnapshot {
8493            schema_version: ftui_layout::PANE_TREE_SCHEMA_VERSION,
8494            root,
8495            next_id: pane_id(6),
8496            nodes: vec![
8497                ftui_layout::PaneNodeRecord::split(
8498                    root,
8499                    None,
8500                    ftui_layout::PaneSplit {
8501                        axis: SplitAxis::Horizontal,
8502                        ratio: ftui_layout::PaneSplitRatio::new(1, 1).expect("valid ratio"),
8503                        first: left,
8504                        second: right_split,
8505                    },
8506                ),
8507                ftui_layout::PaneNodeRecord::leaf(
8508                    left,
8509                    Some(root),
8510                    ftui_layout::PaneLeaf::new("left"),
8511                ),
8512                ftui_layout::PaneNodeRecord::split(
8513                    right_split,
8514                    Some(root),
8515                    ftui_layout::PaneSplit {
8516                        axis: SplitAxis::Vertical,
8517                        ratio: ftui_layout::PaneSplitRatio::new(1, 1).expect("valid ratio"),
8518                        first: right_top,
8519                        second: right_bottom,
8520                    },
8521                ),
8522                ftui_layout::PaneNodeRecord::leaf(
8523                    right_top,
8524                    Some(right_split),
8525                    ftui_layout::PaneLeaf::new("right_top"),
8526                ),
8527                ftui_layout::PaneNodeRecord::leaf(
8528                    right_bottom,
8529                    Some(right_split),
8530                    ftui_layout::PaneLeaf::new("right_bottom"),
8531                ),
8532            ],
8533            extensions: std::collections::BTreeMap::new(),
8534        };
8535        ftui_layout::PaneTree::from_snapshot(snapshot).expect("valid nested pane tree")
8536    }
8537
8538    /// First-child share (in basis points) of a split node's ratio.
8539    fn root_first_share_bps(tree: &ftui_layout::PaneTree, split: ftui_layout::PaneId) -> u32 {
8540        match &tree.node(split).expect("split node present").kind {
8541            PaneNodeKind::Split(node) => {
8542                node.ratio.numerator() * 10_000
8543                    / (node.ratio.numerator() + node.ratio.denominator())
8544            }
8545            other => panic!("expected split node, got {other:?}"),
8546        }
8547    }
8548
8549    /// A fixed, timing-independent pressure-snap profile for deterministic tests.
8550    fn fixed_neutral_pressure() -> PanePressureSnapProfile {
8551        PanePressureSnapProfile {
8552            strength_bps: 5_000,
8553            hysteresis_bps: 100,
8554        }
8555    }
8556
8557    /// Apply a terminal dispatch's geometry-bearing transition to the live tree
8558    /// using a fixed, caller-supplied pressure profile.
8559    ///
8560    /// Unlike the realistic path (which derives pressure from pointer motion and
8561    /// therefore from wall-clock `speed`), this helper always uses `pressure`, so
8562    /// repeated runs of the same scripted event sequence are byte-for-byte
8563    /// deterministic. Returns the number of operations applied.
8564    fn apply_dispatch_fixed(
8565        tree: &mut ftui_layout::PaneTree,
8566        layout: &ftui_layout::PaneLayout,
8567        dispatch: &PaneTerminalDispatch,
8568        pressure: PanePressureSnapProfile,
8569        seed: &mut u64,
8570    ) -> usize {
8571        let Some(transition) = dispatch.primary_transition.as_ref() else {
8572            return 0;
8573        };
8574        let ops = tree.operations_for_transition(transition, layout, pressure);
8575        let applied = ops.len();
8576        for op in ops {
8577            tree.apply_operation(*seed, op).expect("operation applies");
8578            *seed += 1;
8579        }
8580        applied
8581    }
8582
8583    /// Drive a full scripted horizontal splitter drag through the live
8584    /// adapter -> bridge -> tree path with a fixed pressure profile. Press at
8585    /// `down_x`, then send Drag events for every position in `drag_xs` except the
8586    /// last, which is sent as the release (Up). Pointer x must increase across
8587    /// samples (the adapter tracks magnitude via saturating deltas). Returns the
8588    /// number of operations applied.
8589    #[allow(clippy::too_many_arguments)]
8590    fn drive_horizontal_drag_fixed(
8591        adapter: &mut PaneTerminalAdapter,
8592        tree: &mut ftui_layout::PaneTree,
8593        layout: &ftui_layout::PaneLayout,
8594        target: PaneResizeTarget,
8595        down_x: u16,
8596        y: u16,
8597        drag_xs: &[u16],
8598        pressure: PanePressureSnapProfile,
8599        seed: &mut u64,
8600    ) -> usize {
8601        let down = Event::Mouse(MouseEvent::new(
8602            MouseEventKind::Down(MouseButton::Left),
8603            down_x,
8604            y,
8605        ));
8606        let mut applied = apply_dispatch_fixed(
8607            tree,
8608            layout,
8609            &adapter.translate(&down, Some(target)),
8610            pressure,
8611            seed,
8612        );
8613
8614        let last = drag_xs.len().saturating_sub(1);
8615        for (idx, &x) in drag_xs.iter().enumerate() {
8616            let kind = if idx == last {
8617                MouseEventKind::Up(MouseButton::Left)
8618            } else {
8619                MouseEventKind::Drag(MouseButton::Left)
8620            };
8621            let event = Event::Mouse(MouseEvent::new(kind, x, y));
8622            applied += apply_dispatch_fixed(
8623                tree,
8624                layout,
8625                &adapter.translate(&event, None),
8626                pressure,
8627                seed,
8628            );
8629        }
8630        applied
8631    }
8632
8633    #[test]
8634    fn pane_terminal_splitter_resolution_is_deterministic() {
8635        let tree = nested_pane_tree();
8636        let layout = tree
8637            .solve_layout(Rect::new(0, 0, 50, 20))
8638            .expect("layout should solve");
8639        let handles = pane_terminal_splitter_handles(&tree, &layout, 3);
8640        assert_eq!(handles.len(), 2);
8641
8642        // Intersection between root vertical splitter and right-side horizontal
8643        // splitter deterministically resolves to smaller split ID.
8644        let overlap = pane_terminal_resolve_splitter_target(&handles, 25, 10)
8645            .expect("overlap cell should resolve");
8646        assert_eq!(overlap.split_id, pane_id(1));
8647        assert_eq!(overlap.axis, SplitAxis::Horizontal);
8648
8649        let right_only = pane_terminal_resolve_splitter_target(&handles, 40, 10)
8650            .expect("right split should resolve");
8651        assert_eq!(right_only.split_id, pane_id(3));
8652        assert_eq!(right_only.axis, SplitAxis::Vertical);
8653    }
8654
8655    #[test]
8656    fn pane_terminal_splitter_hits_register_and_decode_target() {
8657        let tree = nested_pane_tree();
8658        let layout = tree
8659            .solve_layout(Rect::new(0, 0, 50, 20))
8660            .expect("layout should solve");
8661        let handles = pane_terminal_splitter_handles(&tree, &layout, 3);
8662
8663        let mut pool = ftui_render::grapheme_pool::GraphemePool::new();
8664        let mut frame = Frame::with_hit_grid(50, 20, &mut pool);
8665        let registered = register_pane_terminal_splitter_hits(&mut frame, &handles, 9_000);
8666        assert_eq!(registered, handles.len());
8667
8668        let root_hit = frame
8669            .hit_test(25, 2)
8670            .expect("root splitter should be hittable");
8671        assert_eq!(root_hit.1, HitRegion::Handle);
8672        let root_target = pane_terminal_target_from_hit(root_hit).expect("target from hit");
8673        assert_eq!(root_target.split_id, pane_id(1));
8674        assert_eq!(root_target.axis, SplitAxis::Horizontal);
8675
8676        let right_hit = frame
8677            .hit_test(40, 10)
8678            .expect("right splitter should be hittable");
8679        assert_eq!(right_hit.1, HitRegion::Handle);
8680        let right_target = pane_terminal_target_from_hit(right_hit).expect("target from hit");
8681        assert_eq!(right_target.split_id, pane_id(3));
8682        assert_eq!(right_target.axis, SplitAxis::Vertical);
8683    }
8684
8685    #[test]
8686    fn pane_terminal_adapter_maps_basic_drag_lifecycle() {
8687        let mut adapter =
8688            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
8689        let target = pane_target(SplitAxis::Horizontal);
8690
8691        let down = Event::Mouse(MouseEvent::new(
8692            MouseEventKind::Down(MouseButton::Left),
8693            10,
8694            4,
8695        ));
8696        let down_dispatch = adapter.translate(&down, Some(target));
8697        let down_event = down_dispatch
8698            .primary_event
8699            .as_ref()
8700            .expect("pointer down semantic event");
8701        assert_eq!(down_event.sequence, 1);
8702        assert!(matches!(
8703            down_event.kind,
8704            PaneSemanticInputEventKind::PointerDown {
8705                target: actual_target,
8706                pointer_id: 1,
8707                button: PanePointerButton::Primary,
8708                position
8709            } if actual_target == target && position == PanePointerPosition::new(10, 4)
8710        ));
8711        assert!(down_event.validate().is_ok());
8712
8713        let drag = Event::Mouse(MouseEvent::new(
8714            MouseEventKind::Drag(MouseButton::Left),
8715            14,
8716            4,
8717        ));
8718        let drag_dispatch = adapter.translate(&drag, None);
8719        let drag_event = drag_dispatch
8720            .primary_event
8721            .as_ref()
8722            .expect("pointer move semantic event");
8723        assert_eq!(drag_event.sequence, 2);
8724        assert!(matches!(
8725            drag_event.kind,
8726            PaneSemanticInputEventKind::PointerMove {
8727                target: actual_target,
8728                pointer_id: 1,
8729                position,
8730                delta_x: 4,
8731                delta_y: 0
8732            } if actual_target == target && position == PanePointerPosition::new(14, 4)
8733        ));
8734        let drag_motion = drag_dispatch
8735            .motion
8736            .expect("drag should emit motion metadata");
8737        assert_eq!(drag_motion.delta_x, 4);
8738        assert_eq!(drag_motion.delta_y, 0);
8739        assert_eq!(drag_motion.direction_changes, 0);
8740        assert!(drag_motion.speed > 0.0);
8741        assert!(drag_dispatch.pressure_snap_profile().is_some());
8742
8743        let up = Event::Mouse(MouseEvent::new(
8744            MouseEventKind::Up(MouseButton::Left),
8745            14,
8746            4,
8747        ));
8748        let up_dispatch = adapter.translate(&up, None);
8749        let up_event = up_dispatch
8750            .primary_event
8751            .as_ref()
8752            .expect("pointer up semantic event");
8753        assert_eq!(up_event.sequence, 3);
8754        assert!(matches!(
8755            up_event.kind,
8756            PaneSemanticInputEventKind::PointerUp {
8757                target: actual_target,
8758                pointer_id: 1,
8759                button: PanePointerButton::Primary,
8760                position
8761            } if actual_target == target && position == PanePointerPosition::new(14, 4)
8762        ));
8763        let up_motion = up_dispatch
8764            .motion
8765            .expect("up should emit final motion metadata");
8766        assert_eq!(up_motion.delta_x, 4);
8767        assert_eq!(up_motion.delta_y, 0);
8768        assert_eq!(up_motion.direction_changes, 0);
8769        let inertial_throw = up_dispatch
8770            .inertial_throw
8771            .expect("up should emit inertial throw metadata");
8772        assert_eq!(
8773            up_dispatch.projected_position,
8774            Some(inertial_throw.projected_pointer(PanePointerPosition::new(14, 4)))
8775        );
8776        assert_eq!(adapter.active_pointer_id(), None);
8777        assert!(matches!(adapter.machine_state(), PaneDragResizeState::Idle));
8778    }
8779
8780    #[test]
8781    fn pane_terminal_adapter_drives_live_tree_mutation() {
8782        // End-to-end proof that the terminal adapter actually mutates the live
8783        // pane tree. Raw crossterm events flow through PaneTerminalAdapter into
8784        // PaneDragResizeTransition values, the layout bridge
8785        // (PaneTree::operations_for_transition) turns each geometry-bearing
8786        // transition into PaneOperation values, and apply_operation moves the
8787        // live root split ratio. This closes the historical gap where the
8788        // adapter emitted transitions that no production path consumed.
8789        fn apply_dispatch(
8790            tree: &mut ftui_layout::PaneTree,
8791            layout: &ftui_layout::PaneLayout,
8792            dispatch: &PaneTerminalDispatch,
8793            neutral: PanePressureSnapProfile,
8794            seed: &mut u64,
8795        ) -> usize {
8796            let Some(transition) = dispatch.primary_transition.as_ref() else {
8797                return 0;
8798            };
8799            let pressure = dispatch.pressure_snap_profile().unwrap_or(neutral);
8800            let ops = tree.operations_for_transition(transition, layout, pressure);
8801            let applied = ops.len();
8802            for op in ops {
8803                tree.apply_operation(*seed, op).expect("operation applies");
8804                *seed += 1;
8805            }
8806            applied
8807        }
8808
8809        let mut tree = nested_pane_tree();
8810        // The root split's own rectangle spans the whole viewport regardless of
8811        // its ratio, so a single solve is sufficient for targeting it.
8812        let layout = tree
8813            .solve_layout(Rect::new(0, 0, 50, 20))
8814            .expect("layout should solve");
8815        let root_split = pane_id(1);
8816        let target = PaneResizeTarget {
8817            split_id: root_split,
8818            axis: SplitAxis::Horizontal,
8819        };
8820        let neutral = PanePressureSnapProfile {
8821            strength_bps: 5_000,
8822            hysteresis_bps: 100,
8823        };
8824
8825        let before_share = root_first_share_bps(&tree, root_split);
8826
8827        let mut adapter =
8828            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
8829        let mut op_seed = 7_000u64;
8830        let mut geometry_transitions = 0usize;
8831
8832        // Press on the splitter (arms the machine; no geometry yet).
8833        let down = Event::Mouse(MouseEvent::new(
8834            MouseEventKind::Down(MouseButton::Left),
8835            25,
8836            10,
8837        ));
8838        let down_dispatch = adapter.translate(&down, Some(target));
8839        geometry_transitions +=
8840            apply_dispatch(&mut tree, &layout, &down_dispatch, neutral, &mut op_seed);
8841
8842        // Drag rightward across cells, applying each transition to the tree.
8843        for x in [30u16, 36, 42] {
8844            let drag = Event::Mouse(MouseEvent::new(
8845                MouseEventKind::Drag(MouseButton::Left),
8846                x,
8847                10,
8848            ));
8849            let dispatch = adapter.translate(&drag, None);
8850            geometry_transitions +=
8851                apply_dispatch(&mut tree, &layout, &dispatch, neutral, &mut op_seed);
8852        }
8853
8854        // Release.
8855        let up = Event::Mouse(MouseEvent::new(
8856            MouseEventKind::Up(MouseButton::Left),
8857            42,
8858            10,
8859        ));
8860        let up_dispatch = adapter.translate(&up, None);
8861        geometry_transitions +=
8862            apply_dispatch(&mut tree, &layout, &up_dispatch, neutral, &mut op_seed);
8863
8864        assert!(
8865            geometry_transitions > 0,
8866            "drag lifecycle should yield at least one geometry-bearing transition"
8867        );
8868        let after_share = root_first_share_bps(&tree, root_split);
8869        assert!(
8870            after_share > before_share,
8871            "rightward splitter drag should grow the first child: after={after_share} before={before_share}"
8872        );
8873        assert!(matches!(adapter.machine_state(), PaneDragResizeState::Idle));
8874    }
8875
8876    #[test]
8877    fn pane_terminal_adapter_resize_interrupt_cancels_drag_and_preserves_tree() {
8878        // Edge interruption: a terminal resize (SIGWINCH) arrives mid-drag. With
8879        // the default config (cancel_on_resize = true) the adapter must cancel the
8880        // in-flight gesture cleanly, leave the live tree valid and unmutated by the
8881        // interrupt itself, and remain reusable for a fresh gesture afterwards.
8882        let mut tree = nested_pane_tree();
8883        let layout = tree
8884            .solve_layout(Rect::new(0, 0, 50, 20))
8885            .expect("layout should solve");
8886        let root_split = pane_id(1);
8887        let target = PaneResizeTarget {
8888            split_id: root_split,
8889            axis: SplitAxis::Horizontal,
8890        };
8891        let pressure = fixed_neutral_pressure();
8892        let mut seed = 4_100u64;
8893
8894        let initial_hash = tree.state_hash();
8895
8896        let mut adapter =
8897            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
8898
8899        // Arm + drag (without releasing) so a gesture is genuinely in flight.
8900        let _ = apply_dispatch_fixed(
8901            &mut tree,
8902            &layout,
8903            &adapter.translate(
8904                &Event::Mouse(MouseEvent::new(
8905                    MouseEventKind::Down(MouseButton::Left),
8906                    25,
8907                    10,
8908                )),
8909                Some(target),
8910            ),
8911            pressure,
8912            &mut seed,
8913        );
8914        for x in [30u16, 36] {
8915            let _ = apply_dispatch_fixed(
8916                &mut tree,
8917                &layout,
8918                &adapter.translate(
8919                    &Event::Mouse(MouseEvent::new(
8920                        MouseEventKind::Drag(MouseButton::Left),
8921                        x,
8922                        10,
8923                    )),
8924                    None,
8925                ),
8926                pressure,
8927                &mut seed,
8928            );
8929        }
8930        let mid_drag_hash = tree.state_hash();
8931        assert_ne!(
8932            mid_drag_hash, initial_hash,
8933            "drag should have mutated the tree before the interrupt"
8934        );
8935        assert!(tree.validate().is_ok());
8936        assert_eq!(adapter.active_pointer_id(), Some(1));
8937
8938        // Resize interrupt mid-drag.
8939        let resize_dispatch = adapter.translate(
8940            &Event::Resize {
8941                width: 60,
8942                height: 24,
8943            },
8944            None,
8945        );
8946        let cancel = resize_dispatch
8947            .primary_event
8948            .as_ref()
8949            .expect("resize interrupt should emit a cancel semantic event");
8950        assert!(matches!(
8951            cancel.kind,
8952            PaneSemanticInputEventKind::Cancel {
8953                target: Some(actual),
8954                reason: PaneCancelReason::Programmatic
8955            } if actual == target
8956        ));
8957        assert_eq!(
8958            resize_dispatch.log.phase,
8959            PaneTerminalLifecyclePhase::ResizeInterrupt
8960        );
8961        assert_eq!(
8962            resize_dispatch.log.outcome,
8963            PaneTerminalLogOutcome::SemanticForwarded
8964        );
8965
8966        // The cancel transition carries no geometry, so the bridge yields no ops
8967        // and the tree is left exactly as the last drag sample left it.
8968        let cancel_transition = resize_dispatch
8969            .primary_transition
8970            .as_ref()
8971            .expect("cancel transition present");
8972        let cancel_ops = tree.operations_for_transition(cancel_transition, &layout, pressure);
8973        assert!(
8974            cancel_ops.is_empty(),
8975            "cancel transition must not mutate the live tree"
8976        );
8977        assert_eq!(tree.state_hash(), mid_drag_hash);
8978        assert!(tree.validate().is_ok());
8979
8980        // Adapter is back to idle with no active pointer.
8981        assert_eq!(adapter.active_pointer_id(), None);
8982        assert!(matches!(adapter.machine_state(), PaneDragResizeState::Idle));
8983
8984        // Reusable: a fresh gesture at the new viewport mutates the tree again.
8985        let new_layout = tree
8986            .solve_layout(Rect::new(0, 0, 60, 24))
8987            .expect("layout should solve at new size");
8988        let before_reuse = tree.state_hash();
8989        let applied = drive_horizontal_drag_fixed(
8990            &mut adapter,
8991            &mut tree,
8992            &new_layout,
8993            target,
8994            30,
8995            12,
8996            &[36, 42, 48],
8997            pressure,
8998            &mut seed,
8999        );
9000        assert!(applied > 0, "fresh gesture should apply operations");
9001        assert_ne!(
9002            tree.state_hash(),
9003            before_reuse,
9004            "adapter must remain usable after a resize interrupt"
9005        );
9006        assert!(tree.validate().is_ok());
9007        assert!(matches!(adapter.machine_state(), PaneDragResizeState::Idle));
9008    }
9009
9010    #[test]
9011    fn pane_terminal_adapter_survives_resize_storm_and_is_deterministic() {
9012        // Resize-storm stability at the live-tree level. The default config
9013        // cancels in-flight gestures on resize (matching real SIGWINCH behavior),
9014        // so a storm rapidly re-grabs the splitter and re-drags across many
9015        // viewport sizes. After every step the tree must stay structurally valid
9016        // and within ratio bounds, and the whole scripted storm must be
9017        // byte-for-byte deterministic across repeated runs.
9018        fn run_storm() -> u64 {
9019            let mut adapter = PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default())
9020                .expect("valid adapter");
9021            let mut tree = nested_pane_tree();
9022            let root_split = pane_id(1);
9023            let target = PaneResizeTarget {
9024                split_id: root_split,
9025                axis: SplitAxis::Horizontal,
9026            };
9027            let pressure = fixed_neutral_pressure();
9028            let mut seed = 5_200u64;
9029
9030            // Sizes the "window manager" cycles through during the storm.
9031            let sizes: [(u16, u16); 6] =
9032                [(50, 20), (80, 24), (40, 16), (120, 40), (30, 12), (100, 30)];
9033
9034            for (idx, &(w, h)) in sizes.iter().enumerate() {
9035                let layout = tree
9036                    .solve_layout(Rect::new(0, 0, w, h))
9037                    .expect("layout should solve under storm");
9038
9039                // Re-grab near 1/5 width and drag rightward to 3/5 width (always
9040                // increasing x, comfortably mid-rail to avoid child minimums).
9041                let down_x = (w / 5).max(2);
9042                let drag_x = (3 * w / 5).max(down_x + 2);
9043                let _ = apply_dispatch_fixed(
9044                    &mut tree,
9045                    &layout,
9046                    &adapter.translate(
9047                        &Event::Mouse(MouseEvent::new(
9048                            MouseEventKind::Down(MouseButton::Left),
9049                            down_x,
9050                            h / 2,
9051                        )),
9052                        Some(target),
9053                    ),
9054                    pressure,
9055                    &mut seed,
9056                );
9057                let _ = apply_dispatch_fixed(
9058                    &mut tree,
9059                    &layout,
9060                    &adapter.translate(
9061                        &Event::Mouse(MouseEvent::new(
9062                            MouseEventKind::Drag(MouseButton::Left),
9063                            drag_x,
9064                            h / 2,
9065                        )),
9066                        None,
9067                    ),
9068                    pressure,
9069                    &mut seed,
9070                );
9071                assert!(
9072                    tree.validate().is_ok(),
9073                    "tree invalid after drag at step {idx}"
9074                );
9075                let share = root_first_share_bps(&tree, root_split);
9076                assert!(
9077                    share > 0 && share < 10_000,
9078                    "split ratio escaped bounds at step {idx}: {share}"
9079                );
9080
9081                // Storm: a resize arrives mid-gesture and cancels it cleanly.
9082                let resize = adapter.translate(
9083                    &Event::Resize {
9084                        width: w,
9085                        height: h,
9086                    },
9087                    None,
9088                );
9089                if let Some(cancel_transition) = resize.primary_transition.as_ref() {
9090                    let cancel_ops =
9091                        tree.operations_for_transition(cancel_transition, &layout, pressure);
9092                    assert!(
9093                        cancel_ops.is_empty(),
9094                        "resize cancel must not mutate the tree at step {idx}"
9095                    );
9096                }
9097                assert!(matches!(adapter.machine_state(), PaneDragResizeState::Idle));
9098                assert_eq!(adapter.active_pointer_id(), None);
9099                assert!(
9100                    tree.validate().is_ok(),
9101                    "tree invalid after resize at step {idx}"
9102                );
9103            }
9104
9105            // A final complete gesture (with a real release) settles the tree.
9106            let (w, h) = (90u16, 30u16);
9107            let layout = tree
9108                .solve_layout(Rect::new(0, 0, w, h))
9109                .expect("final layout should solve");
9110            let _ = drive_horizontal_drag_fixed(
9111                &mut adapter,
9112                &mut tree,
9113                &layout,
9114                target,
9115                (w / 5).max(2),
9116                h / 2,
9117                &[w / 2, 3 * w / 5],
9118                pressure,
9119                &mut seed,
9120            );
9121            assert!(matches!(adapter.machine_state(), PaneDragResizeState::Idle));
9122            assert!(tree.validate().is_ok());
9123
9124            tree.state_hash()
9125        }
9126
9127        let first = run_storm();
9128        let second = run_storm();
9129        assert_eq!(
9130            first, second,
9131            "resize storm with repeated re-grabs must be deterministic"
9132        );
9133    }
9134
9135    #[test]
9136    fn pane_terminal_adapter_geometry_is_capability_invariant() {
9137        // Capability variance: the terminal adapter consumes already-parsed
9138        // `Event` values and makes no terminal-capability queries, so the same
9139        // logical drag must produce identical live-tree geometry whether the host
9140        // is a dumb terminal, a modern emulator, or tmux. We assert both halves:
9141        // (1) the capability profiles genuinely differ (non-vacuous), and (2) the
9142        // resulting tree state is identical across all three. This locks the
9143        // invariant that pane resize is capability-independent and would catch any
9144        // future regression that silently couples geometry to terminal caps.
9145        fn drag_under(
9146            over: ftui_core::capability_override::CapabilityOverride,
9147        ) -> (bool, bool, bool, u64) {
9148            ftui_core::capability_override::with_capability_override(over, || {
9149                let caps = ftui_core::capability_override::current_capabilities();
9150                let mut tree = nested_pane_tree();
9151                let layout = tree
9152                    .solve_layout(Rect::new(0, 0, 50, 20))
9153                    .expect("layout should solve");
9154                let target = PaneResizeTarget {
9155                    split_id: pane_id(1),
9156                    axis: SplitAxis::Horizontal,
9157                };
9158                let pressure = fixed_neutral_pressure();
9159                let mut seed = 6_300u64;
9160                let mut adapter = PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default())
9161                    .expect("valid adapter");
9162                let applied = drive_horizontal_drag_fixed(
9163                    &mut adapter,
9164                    &mut tree,
9165                    &layout,
9166                    target,
9167                    25,
9168                    10,
9169                    &[30, 36, 42],
9170                    pressure,
9171                    &mut seed,
9172                );
9173                assert!(
9174                    applied > 0,
9175                    "drag should apply operations under every profile"
9176                );
9177                (
9178                    caps.mouse_sgr,
9179                    caps.supports_true_color(),
9180                    caps.in_tmux,
9181                    tree.state_hash(),
9182                )
9183            })
9184        }
9185
9186        let (dumb_sgr, dumb_truecolor, _dumb_tmux, dumb_hash) =
9187            drag_under(ftui_core::capability_override::CapabilityOverride::dumb());
9188        let (modern_sgr, modern_truecolor, modern_tmux, modern_hash) =
9189            drag_under(ftui_core::capability_override::CapabilityOverride::modern());
9190        let (_tmux_sgr, _tmux_truecolor, tmux_tmux, tmux_hash) =
9191            drag_under(ftui_core::capability_override::CapabilityOverride::tmux());
9192
9193        // Non-vacuous: the three profiles really do present different caps.
9194        assert!(
9195            dumb_sgr != modern_sgr || dumb_truecolor != modern_truecolor,
9196            "dumb and modern profiles must differ in capabilities"
9197        );
9198        assert!(
9199            modern_tmux != tmux_tmux,
9200            "modern and tmux profiles must differ in the in_tmux flag"
9201        );
9202
9203        // Invariant: identical geometry regardless of terminal capabilities.
9204        assert_eq!(
9205            dumb_hash, modern_hash,
9206            "geometry must not depend on terminal capabilities"
9207        );
9208        assert_eq!(
9209            modern_hash, tmux_hash,
9210            "geometry must not depend on terminal capabilities"
9211        );
9212    }
9213
9214    #[test]
9215    fn pane_terminal_adapter_dispatch_log_traces_routing_and_failures() {
9216        // Diagnostic logs must capture event routing (the lifecycle phase of each
9217        // translated event) and failure context (deterministic ignore reasons), so
9218        // operators can reconstruct what the adapter did from the dispatch log
9219        // alone. This exercises both the happy routing path and two failure paths.
9220        let mut adapter =
9221            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
9222        let target = pane_target(SplitAxis::Horizontal);
9223
9224        // Failure path 1: wrong activation button is ignored with a precise reason.
9225        let wrong_button = adapter.translate(
9226            &Event::Mouse(MouseEvent::new(
9227                MouseEventKind::Down(MouseButton::Right),
9228                5,
9229                5,
9230            )),
9231            Some(target),
9232        );
9233        assert_eq!(
9234            wrong_button.log.phase,
9235            PaneTerminalLifecyclePhase::MouseDown
9236        );
9237        assert_eq!(
9238            wrong_button.log.outcome,
9239            PaneTerminalLogOutcome::Ignored(PaneTerminalIgnoredReason::ActivationButtonRequired)
9240        );
9241        assert!(wrong_button.primary_event.is_none());
9242        assert_eq!(adapter.active_pointer_id(), None);
9243
9244        // Routing: a real gesture progresses MouseDown -> MouseDrag -> MouseUp,
9245        // each forwarded with a monotonically increasing sequence number.
9246        let down = adapter.translate(
9247            &Event::Mouse(MouseEvent::new(
9248                MouseEventKind::Down(MouseButton::Left),
9249                25,
9250                10,
9251            )),
9252            Some(target),
9253        );
9254        assert_eq!(down.log.phase, PaneTerminalLifecyclePhase::MouseDown);
9255        assert_eq!(down.log.outcome, PaneTerminalLogOutcome::SemanticForwarded);
9256        assert_eq!(down.log.target, Some(target));
9257        assert_eq!(down.log.pointer_id, Some(1));
9258        let down_seq = down.log.sequence.expect("down sequence");
9259
9260        let drag = adapter.translate(
9261            &Event::Mouse(MouseEvent::new(
9262                MouseEventKind::Drag(MouseButton::Left),
9263                31,
9264                10,
9265            )),
9266            None,
9267        );
9268        assert_eq!(drag.log.phase, PaneTerminalLifecyclePhase::MouseDrag);
9269        assert_eq!(drag.log.outcome, PaneTerminalLogOutcome::SemanticForwarded);
9270        let drag_seq = drag.log.sequence.expect("drag sequence");
9271        assert!(drag_seq > down_seq, "sequence numbers must be monotonic");
9272
9273        let up = adapter.translate(
9274            &Event::Mouse(MouseEvent::new(
9275                MouseEventKind::Up(MouseButton::Left),
9276                31,
9277                10,
9278            )),
9279            None,
9280        );
9281        assert_eq!(up.log.phase, PaneTerminalLifecyclePhase::MouseUp);
9282        assert_eq!(up.log.outcome, PaneTerminalLogOutcome::SemanticForwarded);
9283        assert!(up.log.sequence.expect("up sequence") > drag_seq);
9284
9285        // Failure path 2: a resize with no active gesture is a clean no-op with a
9286        // precise reason rather than a spurious cancel.
9287        let idle_resize = adapter.translate(
9288            &Event::Resize {
9289                width: 80,
9290                height: 24,
9291            },
9292            None,
9293        );
9294        assert_eq!(
9295            idle_resize.log.phase,
9296            PaneTerminalLifecyclePhase::ResizeInterrupt
9297        );
9298        assert_eq!(
9299            idle_resize.log.outcome,
9300            PaneTerminalLogOutcome::Ignored(PaneTerminalIgnoredReason::ResizeNoop)
9301        );
9302        assert!(idle_resize.primary_event.is_none());
9303    }
9304
9305    #[test]
9306    fn pane_terminal_adapter_resize_preserves_gesture_when_cancel_disabled() {
9307        // Edge interruption, opposite branch: with cancel_on_resize disabled a
9308        // resize event is a deterministic no-op that leaves the active gesture
9309        // intact, so the drag can continue to completion afterwards.
9310        let config = PaneTerminalAdapterConfig {
9311            cancel_on_resize: false,
9312            ..PaneTerminalAdapterConfig::default()
9313        };
9314        let mut adapter = PaneTerminalAdapter::new(config).expect("valid adapter");
9315        let mut tree = nested_pane_tree();
9316        let layout = tree
9317            .solve_layout(Rect::new(0, 0, 50, 20))
9318            .expect("layout should solve");
9319        let root_split = pane_id(1);
9320        let target = PaneResizeTarget {
9321            split_id: root_split,
9322            axis: SplitAxis::Horizontal,
9323        };
9324        let pressure = fixed_neutral_pressure();
9325        let mut seed = 7_700u64;
9326
9327        // Arm + first drag sample.
9328        let _ = apply_dispatch_fixed(
9329            &mut tree,
9330            &layout,
9331            &adapter.translate(
9332                &Event::Mouse(MouseEvent::new(
9333                    MouseEventKind::Down(MouseButton::Left),
9334                    20,
9335                    10,
9336                )),
9337                Some(target),
9338            ),
9339            pressure,
9340            &mut seed,
9341        );
9342        let _ = apply_dispatch_fixed(
9343            &mut tree,
9344            &layout,
9345            &adapter.translate(
9346                &Event::Mouse(MouseEvent::new(
9347                    MouseEventKind::Drag(MouseButton::Left),
9348                    26,
9349                    10,
9350                )),
9351                None,
9352            ),
9353            pressure,
9354            &mut seed,
9355        );
9356        assert_eq!(adapter.active_pointer_id(), Some(1));
9357
9358        // Resize arrives mid-drag: ignored as a no-op, gesture survives.
9359        let resize = adapter.translate(
9360            &Event::Resize {
9361                width: 50,
9362                height: 20,
9363            },
9364            None,
9365        );
9366        assert!(resize.primary_event.is_none());
9367        assert!(resize.primary_transition.is_none());
9368        assert_eq!(
9369            resize.log.outcome,
9370            PaneTerminalLogOutcome::Ignored(PaneTerminalIgnoredReason::ResizeNoop)
9371        );
9372        assert_eq!(
9373            adapter.active_pointer_id(),
9374            Some(1),
9375            "gesture must survive the resize when cancel_on_resize is disabled"
9376        );
9377
9378        // The drag continues and a release commits cleanly.
9379        let before_finish = tree.state_hash();
9380        for x in [32u16, 38] {
9381            let _ = apply_dispatch_fixed(
9382                &mut tree,
9383                &layout,
9384                &adapter.translate(
9385                    &Event::Mouse(MouseEvent::new(
9386                        MouseEventKind::Drag(MouseButton::Left),
9387                        x,
9388                        10,
9389                    )),
9390                    None,
9391                ),
9392                pressure,
9393                &mut seed,
9394            );
9395        }
9396        let _ = apply_dispatch_fixed(
9397            &mut tree,
9398            &layout,
9399            &adapter.translate(
9400                &Event::Mouse(MouseEvent::new(
9401                    MouseEventKind::Up(MouseButton::Left),
9402                    38,
9403                    10,
9404                )),
9405                None,
9406            ),
9407            pressure,
9408            &mut seed,
9409        );
9410        assert_ne!(
9411            tree.state_hash(),
9412            before_finish,
9413            "the surviving gesture should keep mutating the tree"
9414        );
9415        assert!(matches!(adapter.machine_state(), PaneDragResizeState::Idle));
9416        assert!(tree.validate().is_ok());
9417    }
9418
9419    #[test]
9420    fn pane_terminal_adapter_focus_loss_emits_cancel() {
9421        let mut adapter =
9422            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
9423        let target = pane_target(SplitAxis::Vertical);
9424
9425        let down = Event::Mouse(MouseEvent::new(
9426            MouseEventKind::Down(MouseButton::Left),
9427            3,
9428            9,
9429        ));
9430        let _ = adapter.translate(&down, Some(target));
9431        assert_eq!(adapter.active_pointer_id(), Some(1));
9432
9433        let cancel_dispatch = adapter.translate(&Event::Focus(false), None);
9434        let cancel_event = cancel_dispatch
9435            .primary_event
9436            .as_ref()
9437            .expect("focus-loss cancel event");
9438        assert!(matches!(
9439            cancel_event.kind,
9440            PaneSemanticInputEventKind::Cancel {
9441                target: Some(actual_target),
9442                reason: PaneCancelReason::FocusLost
9443            } if actual_target == target
9444        ));
9445        assert_eq!(adapter.active_pointer_id(), None);
9446        assert!(matches!(adapter.machine_state(), PaneDragResizeState::Idle));
9447    }
9448
9449    #[test]
9450    fn pane_terminal_adapter_recovers_missing_mouse_up() {
9451        let mut adapter =
9452            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
9453        let first_target = pane_target(SplitAxis::Horizontal);
9454        let second_target = pane_target(SplitAxis::Vertical);
9455
9456        let first_down = Event::Mouse(MouseEvent::new(
9457            MouseEventKind::Down(MouseButton::Left),
9458            5,
9459            5,
9460        ));
9461        let _ = adapter.translate(&first_down, Some(first_target));
9462
9463        let second_down = Event::Mouse(MouseEvent::new(
9464            MouseEventKind::Down(MouseButton::Left),
9465            8,
9466            11,
9467        ));
9468        let dispatch = adapter.translate(&second_down, Some(second_target));
9469        let recovery = dispatch
9470            .recovery_event
9471            .as_ref()
9472            .expect("recovery cancel expected");
9473        assert!(matches!(
9474            recovery.kind,
9475            PaneSemanticInputEventKind::Cancel {
9476                target: Some(actual_target),
9477                reason: PaneCancelReason::PointerCancel
9478            } if actual_target == first_target
9479        ));
9480        let primary = dispatch
9481            .primary_event
9482            .as_ref()
9483            .expect("second pointer down expected");
9484        assert!(matches!(
9485            primary.kind,
9486            PaneSemanticInputEventKind::PointerDown {
9487                target: actual_target,
9488                pointer_id: 1,
9489                button: PanePointerButton::Primary,
9490                position
9491            } if actual_target == second_target && position == PanePointerPosition::new(8, 11)
9492        ));
9493        assert_eq!(recovery.sequence, 2);
9494        assert_eq!(primary.sequence, 3);
9495        assert!(matches!(
9496            dispatch.log.outcome,
9497            PaneTerminalLogOutcome::SemanticForwardedAfterRecovery
9498        ));
9499        assert_eq!(dispatch.log.recovery_cancel_sequence, Some(2));
9500    }
9501
9502    #[test]
9503    fn pane_terminal_adapter_modifier_parity() {
9504        let mut adapter =
9505            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
9506        let target = pane_target(SplitAxis::Horizontal);
9507
9508        let mouse = MouseEvent::new(MouseEventKind::Down(MouseButton::Left), 1, 2)
9509            .with_modifiers(Modifiers::SHIFT | Modifiers::ALT | Modifiers::CTRL | Modifiers::SUPER);
9510        let dispatch = adapter.translate(&Event::Mouse(mouse), Some(target));
9511        let event = dispatch.primary_event.expect("semantic event");
9512        assert!(event.modifiers.shift);
9513        assert!(event.modifiers.alt);
9514        assert!(event.modifiers.ctrl);
9515        assert!(event.modifiers.meta);
9516    }
9517
9518    #[test]
9519    fn pane_terminal_adapter_keyboard_resize_mapping() {
9520        let mut adapter =
9521            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
9522        let target = pane_target(SplitAxis::Horizontal);
9523
9524        let key = KeyEvent::new(KeyCode::Right);
9525        let dispatch = adapter.translate(&Event::Key(key), Some(target));
9526        let event = dispatch.primary_event.expect("keyboard resize event");
9527        assert!(matches!(
9528            event.kind,
9529            PaneSemanticInputEventKind::KeyboardResize {
9530                target: actual_target,
9531                direction: PaneResizeDirection::Increase,
9532                units: 1
9533            } if actual_target == target
9534        ));
9535
9536        let shifted = KeyEvent::new(KeyCode::Right).with_modifiers(Modifiers::SHIFT);
9537        let shifted_dispatch = adapter.translate(&Event::Key(shifted), Some(target));
9538        let shifted_event = shifted_dispatch
9539            .primary_event
9540            .expect("shifted resize event");
9541        assert!(matches!(
9542            shifted_event.kind,
9543            PaneSemanticInputEventKind::KeyboardResize {
9544                direction: PaneResizeDirection::Increase,
9545                units: 5,
9546                ..
9547            }
9548        ));
9549        assert!(shifted_event.modifiers.shift);
9550    }
9551
9552    #[test]
9553    fn pane_terminal_adapter_keyboard_resize_requires_focus() {
9554        let mut adapter =
9555            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
9556        let target = pane_target(SplitAxis::Horizontal);
9557
9558        let _ = adapter.translate(&Event::Focus(false), None);
9559        assert!(!adapter.window_focused());
9560
9561        let unfocused = adapter.translate(&Event::Key(KeyEvent::new(KeyCode::Right)), Some(target));
9562        assert!(unfocused.primary_event.is_none());
9563        assert!(matches!(
9564            unfocused.log.outcome,
9565            PaneTerminalLogOutcome::Ignored(PaneTerminalIgnoredReason::WindowNotFocused)
9566        ));
9567
9568        let _ = adapter.translate(&Event::Focus(true), None);
9569        assert!(adapter.window_focused());
9570
9571        let focused = adapter.translate(&Event::Key(KeyEvent::new(KeyCode::Right)), Some(target));
9572        assert!(focused.primary_event.is_some());
9573    }
9574
9575    #[test]
9576    fn pane_terminal_adapter_drag_updates_are_coalesced() {
9577        let mut adapter = PaneTerminalAdapter::new(PaneTerminalAdapterConfig {
9578            drag_update_coalesce_distance: 2,
9579            ..PaneTerminalAdapterConfig::default()
9580        })
9581        .expect("valid adapter");
9582        let target = pane_target(SplitAxis::Horizontal);
9583
9584        let down = Event::Mouse(MouseEvent::new(
9585            MouseEventKind::Down(MouseButton::Left),
9586            10,
9587            4,
9588        ));
9589        let _ = adapter.translate(&down, Some(target));
9590
9591        let drag_start = Event::Mouse(MouseEvent::new(
9592            MouseEventKind::Drag(MouseButton::Left),
9593            14,
9594            4,
9595        ));
9596        let started = adapter.translate(&drag_start, None);
9597        assert!(started.primary_event.is_some());
9598        assert!(matches!(
9599            adapter.machine_state(),
9600            PaneDragResizeState::Dragging { .. }
9601        ));
9602
9603        let coalesced = Event::Mouse(MouseEvent::new(
9604            MouseEventKind::Drag(MouseButton::Left),
9605            15,
9606            4,
9607        ));
9608        let coalesced_dispatch = adapter.translate(&coalesced, None);
9609        assert!(coalesced_dispatch.primary_event.is_none());
9610        assert!(matches!(
9611            coalesced_dispatch.log.outcome,
9612            PaneTerminalLogOutcome::Ignored(PaneTerminalIgnoredReason::DragCoalesced)
9613        ));
9614
9615        let forwarded = Event::Mouse(MouseEvent::new(
9616            MouseEventKind::Drag(MouseButton::Left),
9617            16,
9618            4,
9619        ));
9620        let forwarded_dispatch = adapter.translate(&forwarded, None);
9621        let forwarded_event = forwarded_dispatch
9622            .primary_event
9623            .as_ref()
9624            .expect("coalesced movement should flush once threshold reached");
9625        assert!(matches!(
9626            forwarded_event.kind,
9627            PaneSemanticInputEventKind::PointerMove {
9628                delta_x: 2,
9629                delta_y: 0,
9630                ..
9631            }
9632        ));
9633    }
9634
9635    #[test]
9636    fn pane_terminal_adapter_motion_tracks_direction_changes() {
9637        let mut adapter =
9638            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
9639        let target = pane_target(SplitAxis::Horizontal);
9640
9641        let down = Event::Mouse(MouseEvent::new(
9642            MouseEventKind::Down(MouseButton::Left),
9643            10,
9644            4,
9645        ));
9646        let _ = adapter.translate(&down, Some(target));
9647
9648        let drag_forward = Event::Mouse(MouseEvent::new(
9649            MouseEventKind::Drag(MouseButton::Left),
9650            14,
9651            4,
9652        ));
9653        let forward_dispatch = adapter.translate(&drag_forward, None);
9654        let forward_motion = forward_dispatch
9655            .motion
9656            .expect("forward drag should emit motion metadata");
9657        assert_eq!(forward_motion.direction_changes, 0);
9658
9659        let drag_reverse = Event::Mouse(MouseEvent::new(
9660            MouseEventKind::Drag(MouseButton::Left),
9661            12,
9662            4,
9663        ));
9664        let reverse_dispatch = adapter.translate(&drag_reverse, None);
9665        let reverse_motion = reverse_dispatch
9666            .motion
9667            .expect("reverse drag should emit motion metadata");
9668        assert_eq!(reverse_motion.direction_changes, 1);
9669
9670        let up = Event::Mouse(MouseEvent::new(
9671            MouseEventKind::Up(MouseButton::Left),
9672            12,
9673            4,
9674        ));
9675        let up_dispatch = adapter.translate(&up, None);
9676        let up_motion = up_dispatch
9677            .motion
9678            .expect("release should include cumulative motion metadata");
9679        assert_eq!(up_motion.direction_changes, 1);
9680    }
9681
9682    #[test]
9683    fn pane_terminal_adapter_drag_and_moved_share_motion_bookkeeping() {
9684        // `Drag` and `Moved` forward identical `PointerMove` semantics through
9685        // the same `apply_pointer_motion` path; only the lifecycle phase differs.
9686        // Driving the identical motion sequence through each arm must therefore
9687        // produce identical motion metadata at every step (the extraction's
9688        // equivalence guarantee).
9689        let run = |moved: bool| {
9690            let mut adapter = PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default())
9691                .expect("valid adapter");
9692            let target = pane_target(SplitAxis::Horizontal);
9693            let down = Event::Mouse(MouseEvent::new(
9694                MouseEventKind::Down(MouseButton::Left),
9695                10,
9696                4,
9697            ));
9698            let _ = adapter.translate(&down, Some(target));
9699            let mut motions = Vec::new();
9700            for (x, y) in [(14u16, 4u16), (12, 4), (16, 4)] {
9701                let kind = if moved {
9702                    MouseEventKind::Moved
9703                } else {
9704                    MouseEventKind::Drag(MouseButton::Left)
9705                };
9706                let dispatch = adapter.translate(&Event::Mouse(MouseEvent::new(kind, x, y)), None);
9707                assert!(dispatch.primary_event.is_some());
9708                motions.push(dispatch.motion.expect("motion metadata present"));
9709            }
9710            motions
9711        };
9712
9713        let via_drag = run(false);
9714        let via_moved = run(true);
9715        assert_eq!(via_drag, via_moved);
9716        // Sanity: the reverse step (14->12) registered a direction change in both.
9717        assert_eq!(via_drag[1].direction_changes, 1);
9718    }
9719
9720    #[test]
9721    fn pane_terminal_adapter_translate_with_handles_resolves_target() {
9722        let tree = nested_pane_tree();
9723        let layout = tree
9724            .solve_layout(Rect::new(0, 0, 50, 20))
9725            .expect("layout should solve");
9726        let handles =
9727            pane_terminal_splitter_handles(&tree, &layout, PANE_TERMINAL_DEFAULT_HIT_THICKNESS);
9728        let mut adapter =
9729            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
9730
9731        let down = Event::Mouse(MouseEvent::new(
9732            MouseEventKind::Down(MouseButton::Left),
9733            25,
9734            10,
9735        ));
9736        let dispatch = adapter.translate_with_handles(&down, &handles);
9737        let event = dispatch
9738            .primary_event
9739            .as_ref()
9740            .expect("pointer down should be routed from handles");
9741        assert!(matches!(
9742            event.kind,
9743            PaneSemanticInputEventKind::PointerDown {
9744                target:
9745                    PaneResizeTarget {
9746                        split_id,
9747                        axis: SplitAxis::Horizontal
9748                    },
9749                ..
9750            } if split_id == pane_id(1)
9751        ));
9752    }
9753
9754    #[test]
9755    fn model_update() {
9756        let mut model = TestModel { value: 0 };
9757        model.update(TestMsg::Increment);
9758        assert_eq!(model.value, 1);
9759        model.update(TestMsg::Decrement);
9760        assert_eq!(model.value, 0);
9761        assert!(matches!(model.update(TestMsg::Quit), Cmd::Quit));
9762    }
9763
9764    #[test]
9765    fn model_init_default() {
9766        let mut model = TestModel { value: 0 };
9767        let cmd = model.init();
9768        assert!(matches!(cmd, Cmd::None));
9769    }
9770
9771    // Resize coalescer behavior is covered by resize_coalescer.rs tests.
9772
9773    // =========================================================================
9774    // DETERMINISM TESTS - Program loop determinism (bd-2nu8.10.1)
9775    // =========================================================================
9776
9777    #[test]
9778    fn cmd_sequence_executes_in_order() {
9779        // Verify that Cmd::Sequence executes commands in declared order
9780        use crate::simulator::ProgramSimulator;
9781
9782        struct SeqModel {
9783            trace: Vec<i32>,
9784        }
9785
9786        #[derive(Debug)]
9787        enum SeqMsg {
9788            Append(i32),
9789            TriggerSequence,
9790        }
9791
9792        impl From<Event> for SeqMsg {
9793            fn from(_: Event) -> Self {
9794                SeqMsg::Append(0)
9795            }
9796        }
9797
9798        impl Model for SeqModel {
9799            type Message = SeqMsg;
9800
9801            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
9802                match msg {
9803                    SeqMsg::Append(n) => {
9804                        self.trace.push(n);
9805                        Cmd::none()
9806                    }
9807                    SeqMsg::TriggerSequence => Cmd::sequence(vec![
9808                        Cmd::msg(SeqMsg::Append(1)),
9809                        Cmd::msg(SeqMsg::Append(2)),
9810                        Cmd::msg(SeqMsg::Append(3)),
9811                    ]),
9812                }
9813            }
9814
9815            fn view(&self, _frame: &mut Frame) {}
9816        }
9817
9818        let mut sim = ProgramSimulator::new(SeqModel { trace: vec![] });
9819        sim.init();
9820        sim.send(SeqMsg::TriggerSequence);
9821
9822        assert_eq!(sim.model().trace, vec![1, 2, 3]);
9823    }
9824
9825    #[test]
9826    fn cmd_batch_executes_all_regardless_of_order() {
9827        // Verify that Cmd::Batch executes all commands
9828        use crate::simulator::ProgramSimulator;
9829
9830        struct BatchModel {
9831            values: Vec<i32>,
9832        }
9833
9834        #[derive(Debug)]
9835        enum BatchMsg {
9836            Add(i32),
9837            TriggerBatch,
9838        }
9839
9840        impl From<Event> for BatchMsg {
9841            fn from(_: Event) -> Self {
9842                BatchMsg::Add(0)
9843            }
9844        }
9845
9846        impl Model for BatchModel {
9847            type Message = BatchMsg;
9848
9849            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
9850                match msg {
9851                    BatchMsg::Add(n) => {
9852                        self.values.push(n);
9853                        Cmd::none()
9854                    }
9855                    BatchMsg::TriggerBatch => Cmd::batch(vec![
9856                        Cmd::msg(BatchMsg::Add(10)),
9857                        Cmd::msg(BatchMsg::Add(20)),
9858                        Cmd::msg(BatchMsg::Add(30)),
9859                    ]),
9860                }
9861            }
9862
9863            fn view(&self, _frame: &mut Frame) {}
9864        }
9865
9866        let mut sim = ProgramSimulator::new(BatchModel { values: vec![] });
9867        sim.init();
9868        sim.send(BatchMsg::TriggerBatch);
9869
9870        // All values should be present
9871        assert_eq!(sim.model().values.len(), 3);
9872        assert!(sim.model().values.contains(&10));
9873        assert!(sim.model().values.contains(&20));
9874        assert!(sim.model().values.contains(&30));
9875    }
9876
9877    #[test]
9878    fn cmd_sequence_stops_on_quit() {
9879        // Verify that Cmd::Sequence stops processing after Quit
9880        use crate::simulator::ProgramSimulator;
9881
9882        struct SeqQuitModel {
9883            trace: Vec<i32>,
9884        }
9885
9886        #[derive(Debug)]
9887        enum SeqQuitMsg {
9888            Append(i32),
9889            TriggerSequenceWithQuit,
9890        }
9891
9892        impl From<Event> for SeqQuitMsg {
9893            fn from(_: Event) -> Self {
9894                SeqQuitMsg::Append(0)
9895            }
9896        }
9897
9898        impl Model for SeqQuitModel {
9899            type Message = SeqQuitMsg;
9900
9901            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
9902                match msg {
9903                    SeqQuitMsg::Append(n) => {
9904                        self.trace.push(n);
9905                        Cmd::none()
9906                    }
9907                    SeqQuitMsg::TriggerSequenceWithQuit => Cmd::sequence(vec![
9908                        Cmd::msg(SeqQuitMsg::Append(1)),
9909                        Cmd::quit(),
9910                        Cmd::msg(SeqQuitMsg::Append(2)), // Should not execute
9911                    ]),
9912                }
9913            }
9914
9915            fn view(&self, _frame: &mut Frame) {}
9916        }
9917
9918        let mut sim = ProgramSimulator::new(SeqQuitModel { trace: vec![] });
9919        sim.init();
9920        sim.send(SeqQuitMsg::TriggerSequenceWithQuit);
9921
9922        assert_eq!(sim.model().trace, vec![1]);
9923        assert!(!sim.is_running());
9924    }
9925
9926    #[test]
9927    fn identical_input_produces_identical_state() {
9928        // Verify deterministic state transitions
9929        use crate::simulator::ProgramSimulator;
9930
9931        fn run_scenario() -> Vec<i32> {
9932            struct DetModel {
9933                values: Vec<i32>,
9934            }
9935
9936            #[derive(Debug, Clone)]
9937            enum DetMsg {
9938                Add(i32),
9939                Double,
9940            }
9941
9942            impl From<Event> for DetMsg {
9943                fn from(_: Event) -> Self {
9944                    DetMsg::Add(1)
9945                }
9946            }
9947
9948            impl Model for DetModel {
9949                type Message = DetMsg;
9950
9951                fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
9952                    match msg {
9953                        DetMsg::Add(n) => {
9954                            self.values.push(n);
9955                            Cmd::none()
9956                        }
9957                        DetMsg::Double => {
9958                            if let Some(&last) = self.values.last() {
9959                                self.values.push(last * 2);
9960                            }
9961                            Cmd::none()
9962                        }
9963                    }
9964                }
9965
9966                fn view(&self, _frame: &mut Frame) {}
9967            }
9968
9969            let mut sim = ProgramSimulator::new(DetModel { values: vec![] });
9970            sim.init();
9971            sim.send(DetMsg::Add(5));
9972            sim.send(DetMsg::Double);
9973            sim.send(DetMsg::Add(3));
9974            sim.send(DetMsg::Double);
9975
9976            sim.model().values.clone()
9977        }
9978
9979        // Run the same scenario multiple times
9980        let run1 = run_scenario();
9981        let run2 = run_scenario();
9982        let run3 = run_scenario();
9983
9984        assert_eq!(run1, run2);
9985        assert_eq!(run2, run3);
9986        assert_eq!(run1, vec![5, 10, 3, 6]);
9987    }
9988
9989    #[test]
9990    fn identical_state_produces_identical_render() {
9991        // Verify consistent render outputs for identical inputs
9992        use crate::simulator::ProgramSimulator;
9993
9994        struct RenderModel {
9995            counter: i32,
9996        }
9997
9998        #[derive(Debug)]
9999        enum RenderMsg {
10000            Set(i32),
10001        }
10002
10003        impl From<Event> for RenderMsg {
10004            fn from(_: Event) -> Self {
10005                RenderMsg::Set(0)
10006            }
10007        }
10008
10009        impl Model for RenderModel {
10010            type Message = RenderMsg;
10011
10012            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
10013                match msg {
10014                    RenderMsg::Set(n) => {
10015                        self.counter = n;
10016                        Cmd::none()
10017                    }
10018                }
10019            }
10020
10021            fn view(&self, frame: &mut Frame) {
10022                let text = format!("Value: {}", self.counter);
10023                for (i, c) in text.chars().enumerate() {
10024                    if (i as u16) < frame.width() {
10025                        use ftui_render::cell::Cell;
10026                        frame.buffer.set_raw(i as u16, 0, Cell::from_char(c));
10027                    }
10028                }
10029            }
10030        }
10031
10032        // Create two simulators with the same state
10033        let mut sim1 = ProgramSimulator::new(RenderModel { counter: 42 });
10034        let mut sim2 = ProgramSimulator::new(RenderModel { counter: 42 });
10035
10036        let buf1 = sim1.capture_frame(80, 24);
10037        let buf2 = sim2.capture_frame(80, 24);
10038
10039        // Compare buffer contents
10040        for y in 0..24 {
10041            for x in 0..80 {
10042                let cell1 = buf1.get(x, y).unwrap();
10043                let cell2 = buf2.get(x, y).unwrap();
10044                assert_eq!(
10045                    cell1.content.as_char(),
10046                    cell2.content.as_char(),
10047                    "Mismatch at ({}, {})",
10048                    x,
10049                    y
10050                );
10051            }
10052        }
10053    }
10054
10055    // Resize coalescer timing invariants are covered in resize_coalescer.rs tests.
10056
10057    #[test]
10058    fn cmd_log_creates_log_command() {
10059        let cmd: Cmd<TestMsg> = Cmd::log("test message");
10060        assert!(matches!(cmd, Cmd::Log(s) if s == "test message"));
10061    }
10062
10063    #[test]
10064    fn cmd_log_from_string() {
10065        let msg = String::from("dynamic message");
10066        let cmd: Cmd<TestMsg> = Cmd::log(msg);
10067        assert!(matches!(cmd, Cmd::Log(s) if s == "dynamic message"));
10068    }
10069
10070    #[test]
10071    fn program_simulator_logs_jsonl_with_seed_and_run_id() {
10072        // Ensure ProgramSimulator captures JSONL log lines with run_id/seed.
10073        use crate::simulator::ProgramSimulator;
10074
10075        struct LogModel {
10076            run_id: &'static str,
10077            seed: u64,
10078        }
10079
10080        #[derive(Debug)]
10081        enum LogMsg {
10082            Emit,
10083        }
10084
10085        impl From<Event> for LogMsg {
10086            fn from(_: Event) -> Self {
10087                LogMsg::Emit
10088            }
10089        }
10090
10091        impl Model for LogModel {
10092            type Message = LogMsg;
10093
10094            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
10095                let line = format!(
10096                    r#"{{"event":"test","run_id":"{}","seed":{}}}"#,
10097                    self.run_id, self.seed
10098                );
10099                Cmd::log(line)
10100            }
10101
10102            fn view(&self, _frame: &mut Frame) {}
10103        }
10104
10105        let mut sim = ProgramSimulator::new(LogModel {
10106            run_id: "test-run-001",
10107            seed: 4242,
10108        });
10109        sim.init();
10110        sim.send(LogMsg::Emit);
10111
10112        let logs = sim.logs();
10113        assert_eq!(logs.len(), 1);
10114        assert!(logs[0].contains(r#""run_id":"test-run-001""#));
10115        assert!(logs[0].contains(r#""seed":4242"#));
10116    }
10117
10118    #[test]
10119    fn cmd_sequence_single_unwraps() {
10120        let cmd: Cmd<TestMsg> = Cmd::sequence(vec![Cmd::quit()]);
10121        // Single element sequence should unwrap to the inner command
10122        assert!(matches!(cmd, Cmd::Quit));
10123    }
10124
10125    #[test]
10126    fn cmd_sequence_multiple() {
10127        let cmd: Cmd<TestMsg> = Cmd::sequence(vec![Cmd::none(), Cmd::quit()]);
10128        assert!(matches!(cmd, Cmd::Sequence(_)));
10129    }
10130
10131    #[test]
10132    fn cmd_default_is_none() {
10133        let cmd: Cmd<TestMsg> = Cmd::default();
10134        assert!(matches!(cmd, Cmd::None));
10135    }
10136
10137    #[test]
10138    fn cmd_debug_all_variants() {
10139        // Test Debug impl for all variants
10140        let none: Cmd<TestMsg> = Cmd::none();
10141        assert_eq!(format!("{none:?}"), "None");
10142
10143        let quit: Cmd<TestMsg> = Cmd::quit();
10144        assert_eq!(format!("{quit:?}"), "Quit");
10145
10146        let msg: Cmd<TestMsg> = Cmd::msg(TestMsg::Increment);
10147        assert!(format!("{msg:?}").starts_with("Msg("));
10148
10149        let batch: Cmd<TestMsg> = Cmd::batch(vec![Cmd::none(), Cmd::none()]);
10150        assert!(format!("{batch:?}").starts_with("Batch("));
10151
10152        let seq: Cmd<TestMsg> = Cmd::sequence(vec![Cmd::none(), Cmd::none()]);
10153        assert!(format!("{seq:?}").starts_with("Sequence("));
10154
10155        let tick: Cmd<TestMsg> = Cmd::tick(Duration::from_secs(1));
10156        assert!(format!("{tick:?}").starts_with("Tick("));
10157
10158        let log: Cmd<TestMsg> = Cmd::log("test");
10159        assert!(format!("{log:?}").starts_with("Log("));
10160    }
10161
10162    #[test]
10163    fn program_config_with_budget() {
10164        let budget = FrameBudgetConfig {
10165            total: Duration::from_millis(50),
10166            ..Default::default()
10167        };
10168        let config = ProgramConfig::default().with_budget(budget);
10169        assert_eq!(config.budget.total, Duration::from_millis(50));
10170    }
10171
10172    #[test]
10173    fn load_governor_default_is_enabled() {
10174        let config = LoadGovernorConfig::default();
10175        assert!(config.enabled);
10176        assert_eq!(
10177            config.budget_controller.degradation_floor,
10178            DegradationLevel::SimpleBorders
10179        );
10180    }
10181
10182    #[test]
10183    fn program_config_load_governor_builders() {
10184        let governor = LoadGovernorConfig::disabled().with_enabled(true);
10185        let config = ProgramConfig::default().with_load_governor(governor);
10186        assert!(config.load_governor.enabled);
10187
10188        let config = config.without_load_governor();
10189        assert!(!config.load_governor.enabled);
10190    }
10191
10192    fn governor_observation(
10193        frame_time_ms: f64,
10194        in_flight: u64,
10195        dropped: u64,
10196        degradation: DegradationLevel,
10197        resize_coalescing_active: bool,
10198        strict_semantics_violation: bool,
10199    ) -> LoadGovernorObservation {
10200        LoadGovernorObservation {
10201            frame_time_us: frame_time_ms * 1_000.0,
10202            budget_us: 16_000.0,
10203            degradation,
10204            queue: crate::effect_system::QueueTelemetry {
10205                // Invariant: in_flight = enqueued - processed (drops are
10206                // rejected before ever being counted as enqueued).
10207                enqueued: in_flight,
10208                processed: 0,
10209                dropped,
10210                high_water: in_flight,
10211                in_flight,
10212            },
10213            resize_coalescing_active,
10214            strict_semantics_violation,
10215        }
10216    }
10217
10218    fn test_load_governor(max_queue_depth: usize, recovery_intervals: u8) -> LoadGovernorState {
10219        let policy = LoadGovernorPolicy {
10220            recovery_intervals,
10221            ..Default::default()
10222        };
10223        LoadGovernorState::new(
10224            LoadGovernorConfig::enabled().with_policy(policy),
10225            max_queue_depth,
10226        )
10227    }
10228
10229    #[test]
10230    fn load_governor_policy_defaults_match_runtime_contract() {
10231        let policy = LoadGovernorPolicy::default().normalized();
10232
10233        assert_eq!(policy.stressed_queue_watermark, 0.5);
10234        assert_eq!(policy.degraded_queue_watermark, 0.8);
10235        assert_eq!(policy.recovery_queue_watermark, 0.25);
10236        assert_eq!(policy.recovery_intervals, 3);
10237        assert_eq!(policy.budget_overrun_soft_ratio, 1.0);
10238    }
10239
10240    #[test]
10241    fn load_governor_classifies_queue_watermarks_and_recovery() {
10242        let mut governor = test_load_governor(100, 2);
10243
10244        let steady = governor.observe(governor_observation(
10245            8.0,
10246            0,
10247            0,
10248            DegradationLevel::Full,
10249            false,
10250            false,
10251        ));
10252        assert_eq!(steady.mode, RuntimeLoadMode::Healthy);
10253        assert_eq!(steady.pressure_class, RuntimePressureClass::SteadyState);
10254        assert_eq!(steady.disposition, RuntimeWorkDisposition::AdmitAll);
10255
10256        let stressed = governor.observe(governor_observation(
10257            8.0,
10258            50,
10259            0,
10260            DegradationLevel::Full,
10261            false,
10262            false,
10263        ));
10264        assert_eq!(stressed.mode, RuntimeLoadMode::Stressed);
10265        assert_eq!(stressed.pressure_class, RuntimePressureClass::SoftOverload);
10266        assert_eq!(
10267            stressed.disposition,
10268            RuntimeWorkDisposition::CoalesceVisibleDeferBackground
10269        );
10270        assert_eq!(stressed.reason_code, "queue_stressed_watermark");
10271
10272        let degraded = governor.observe(governor_observation(
10273            8.0,
10274            80,
10275            0,
10276            DegradationLevel::Full,
10277            false,
10278            false,
10279        ));
10280        assert_eq!(degraded.mode, RuntimeLoadMode::Degraded);
10281        assert_eq!(degraded.pressure_class, RuntimePressureClass::HardOverload);
10282        assert_eq!(
10283            degraded.disposition,
10284            RuntimeWorkDisposition::DeferBackgroundDropBestEffort
10285        );
10286        assert_eq!(degraded.reason_code, "queue_degraded_watermark");
10287
10288        let recovery_pending = governor.observe(governor_observation(
10289            8.0,
10290            10,
10291            0,
10292            DegradationLevel::Full,
10293            false,
10294            false,
10295        ));
10296        assert_eq!(recovery_pending.mode, RuntimeLoadMode::Degraded);
10297        assert_eq!(recovery_pending.reason_code, "recovery_hysteresis_pending");
10298        assert_eq!(recovery_pending.recovery_intervals_observed, 1);
10299
10300        let recovered = governor.observe(governor_observation(
10301            8.0,
10302            10,
10303            0,
10304            DegradationLevel::Full,
10305            false,
10306            false,
10307        ));
10308        assert_eq!(recovered.mode, RuntimeLoadMode::Recovered);
10309        assert_eq!(recovered.reason_code, "recovery_hysteresis_satisfied");
10310        assert_eq!(
10311            recovered.disposition,
10312            RuntimeWorkDisposition::ReadmitAfterHysteresis
10313        );
10314
10315        let healthy = governor.observe(governor_observation(
10316            8.0,
10317            10,
10318            0,
10319            DegradationLevel::Full,
10320            false,
10321            false,
10322        ));
10323        assert_eq!(healthy.mode, RuntimeLoadMode::Healthy);
10324        assert_eq!(healthy.reason_code, "recovered_interval_closed");
10325    }
10326
10327    #[test]
10328    fn load_governor_uses_uncapped_budget_pressure_fallback() {
10329        let mut governor = test_load_governor(0, 2);
10330
10331        let stressed = governor.observe(governor_observation(
10332            20.0,
10333            0,
10334            0,
10335            DegradationLevel::Full,
10336            false,
10337            false,
10338        ));
10339        assert_eq!(stressed.mode, RuntimeLoadMode::Stressed);
10340        assert_eq!(stressed.reason_code, "frame_budget_overrun");
10341        assert_eq!(stressed.queue_max_depth, None);
10342
10343        let degraded = governor.observe(governor_observation(
10344            8.0,
10345            0,
10346            0,
10347            DegradationLevel::SimpleBorders,
10348            false,
10349            false,
10350        ));
10351        assert_eq!(degraded.mode, RuntimeLoadMode::Degraded);
10352        assert_eq!(degraded.reason_code, "budget_degradation_active");
10353    }
10354
10355    #[test]
10356    fn load_governor_strict_semantics_failure_is_terminal() {
10357        let mut governor = test_load_governor(100, 2);
10358
10359        let unsafe_snapshot = governor.observe(governor_observation(
10360            8.0,
10361            0,
10362            0,
10363            DegradationLevel::Full,
10364            false,
10365            true,
10366        ));
10367
10368        assert_eq!(unsafe_snapshot.mode, RuntimeLoadMode::Unsafe);
10369        assert_eq!(unsafe_snapshot.pressure_class, RuntimePressureClass::Unsafe);
10370        assert_eq!(
10371            unsafe_snapshot.disposition,
10372            RuntimeWorkDisposition::FailFastStrictGuarantee
10373        );
10374        assert!(!unsafe_snapshot.strict_semantics_preserved);
10375        assert_eq!(unsafe_snapshot.reason_code, "strict_semantics_violation");
10376    }
10377
10378    #[test]
10379    fn load_governor_unsafe_latches_through_later_pressure() {
10380        let mut governor = test_load_governor(100, 2);
10381
10382        // Enter Unsafe via a strict-semantics violation.
10383        let entered = governor.observe(governor_observation(
10384            8.0,
10385            0,
10386            0,
10387            DegradationLevel::Full,
10388            false,
10389            true,
10390        ));
10391        assert_eq!(entered.mode, RuntimeLoadMode::Unsafe);
10392
10393        // A later hard-overload interval (queue ratio >= degraded watermark) with
10394        // NO fresh violation must not downgrade the terminal Unsafe state.
10395        let hard = governor.observe(governor_observation(
10396            8.0,
10397            90,
10398            0,
10399            DegradationLevel::SimpleBorders,
10400            false,
10401            false,
10402        ));
10403        assert_eq!(hard.mode, RuntimeLoadMode::Unsafe);
10404        assert_eq!(
10405            hard.disposition,
10406            RuntimeWorkDisposition::FailFastStrictGuarantee
10407        );
10408        assert!(!hard.strict_semantics_preserved);
10409        assert_eq!(hard.reason_code, "strict_semantics_violation");
10410
10411        // A soft-overload interval (would otherwise classify as Stressed) must
10412        // also keep Unsafe latched rather than escaping downward.
10413        let soft = governor.observe(governor_observation(
10414            8.0,
10415            60,
10416            0,
10417            DegradationLevel::Full,
10418            true,
10419            false,
10420        ));
10421        assert_eq!(soft.mode, RuntimeLoadMode::Unsafe);
10422
10423        // And a fully steady interval never recovers out of Unsafe.
10424        let steady = governor.observe(governor_observation(
10425            8.0,
10426            0,
10427            0,
10428            DegradationLevel::Full,
10429            false,
10430            false,
10431        ));
10432        assert_eq!(steady.mode, RuntimeLoadMode::Unsafe);
10433        assert!(!steady.strict_semantics_preserved);
10434    }
10435
10436    #[test]
10437    fn load_governor_hysteresis_prevents_single_sample_recovery() {
10438        let mut governor = test_load_governor(100, 3);
10439
10440        governor.observe(governor_observation(
10441            8.0,
10442            90,
10443            0,
10444            DegradationLevel::Full,
10445            false,
10446            false,
10447        ));
10448
10449        for expected in 1..=2 {
10450            let snapshot = governor.observe(governor_observation(
10451                8.0,
10452                0,
10453                0,
10454                DegradationLevel::Full,
10455                false,
10456                false,
10457            ));
10458            assert_eq!(snapshot.mode, RuntimeLoadMode::Degraded);
10459            assert_eq!(snapshot.recovery_intervals_observed, expected);
10460            assert_eq!(snapshot.reason_code, "recovery_hysteresis_pending");
10461        }
10462
10463        let recovered = governor.observe(governor_observation(
10464            8.0,
10465            0,
10466            0,
10467            DegradationLevel::Full,
10468            false,
10469            false,
10470        ));
10471        assert_eq!(recovered.mode, RuntimeLoadMode::Recovered);
10472    }
10473
10474    #[test]
10475    fn load_governor_stress_e2e_evidence_shows_degraded_and_recovery() {
10476        let mut governor = test_load_governor(50, 2);
10477        let scenario = [
10478            governor_observation(8.0, 0, 0, DegradationLevel::Full, false, false),
10479            governor_observation(18.0, 25, 0, DegradationLevel::Full, true, false),
10480            governor_observation(22.0, 45, 1, DegradationLevel::SimpleBorders, true, false),
10481            governor_observation(8.0, 5, 1, DegradationLevel::Full, false, false),
10482            governor_observation(8.0, 5, 1, DegradationLevel::Full, false, false),
10483            governor_observation(8.0, 5, 1, DegradationLevel::Full, false, false),
10484        ];
10485
10486        let mut modes = Vec::new();
10487        for observation in scenario {
10488            let snapshot = governor.observe(observation);
10489            modes.push(snapshot.mode);
10490            println!(
10491                "{{\"test\":\"load_governor_stress_e2e\",\"mode\":\"{}\",\"pressure_class\":\"{}\",\"work_disposition\":\"{}\",\"reason\":\"{}\",\"transition\":{},\"deferred\":{},\"coalesced\":{},\"dropped\":{}}}",
10492                snapshot.mode.as_str(),
10493                snapshot.pressure_class.as_str(),
10494                snapshot.disposition.as_str(),
10495                snapshot.reason_code,
10496                snapshot.transition,
10497                snapshot.deferred_work_total,
10498                snapshot.coalesced_work_total,
10499                snapshot.dropped_work_total
10500            );
10501        }
10502
10503        assert!(modes.contains(&RuntimeLoadMode::Stressed));
10504        assert!(modes.contains(&RuntimeLoadMode::Degraded));
10505        assert!(modes.contains(&RuntimeLoadMode::Recovered));
10506        assert_eq!(modes.last(), Some(&RuntimeLoadMode::Healthy));
10507    }
10508
10509    #[test]
10510    fn headless_program_default_load_governor_attaches_controller() {
10511        let program =
10512            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
10513        assert!(program.budget.controller().is_some());
10514    }
10515
10516    #[test]
10517    fn headless_program_load_governor_target_tracks_frame_budget() {
10518        let config = ProgramConfig::default().with_budget(FrameBudgetConfig {
10519            total: Duration::from_millis(50),
10520            ..Default::default()
10521        });
10522        let program = headless_program_with_config(TestModel { value: 0 }, config);
10523        assert_eq!(
10524            program.budget.controller().unwrap().config().target,
10525            Duration::from_millis(50)
10526        );
10527    }
10528
10529    #[test]
10530    fn headless_program_without_load_governor_uses_legacy_budget() {
10531        let program = headless_program_with_config(
10532            TestModel { value: 0 },
10533            ProgramConfig::default().without_load_governor(),
10534        );
10535        assert!(program.budget.controller().is_none());
10536    }
10537
10538    #[test]
10539    fn app_builder_without_load_governor_sets_config() {
10540        let builder = App::new(TestModel { value: 0 }).without_load_governor();
10541        assert!(!builder.config.load_governor.enabled);
10542    }
10543
10544    #[test]
10545    fn program_config_with_conformal() {
10546        let config = ProgramConfig::default().with_conformal_config(ConformalConfig {
10547            alpha: 0.2,
10548            ..Default::default()
10549        });
10550        assert!(config.conformal_config.is_some());
10551        assert!((config.conformal_config.as_ref().unwrap().alpha - 0.2).abs() < 1e-6);
10552    }
10553
10554    #[test]
10555    fn program_rejects_invalid_conformal_configuration() {
10556        let features = BackendFeatures::default();
10557        let events = HeadlessEventSource::new(80, 24, features);
10558        let writer = TerminalWriter::new(
10559            Vec::<u8>::new(),
10560            ScreenMode::AltScreen,
10561            UiAnchor::Bottom,
10562            TerminalCapabilities::default(),
10563        );
10564        let result = Program::with_event_source(
10565            TestModel { value: 0 },
10566            events,
10567            features,
10568            writer,
10569            ProgramConfig::default()
10570                .with_signal_interception(false)
10571                .with_conformal_config(ConformalConfig {
10572                    alpha: f64::NAN,
10573                    ..Default::default()
10574                }),
10575        );
10576        let error = result.err().expect("invalid configuration must fail");
10577        assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
10578        assert!(error.to_string().contains("alpha"));
10579    }
10580
10581    #[test]
10582    fn program_config_forced_size_clamps_minimums() {
10583        let config = ProgramConfig::default().with_forced_size(0, 0);
10584        assert_eq!(config.forced_size, Some((1, 1)));
10585
10586        let cleared = config.without_forced_size();
10587        assert!(cleared.forced_size.is_none());
10588    }
10589
10590    #[test]
10591    fn effect_queue_config_defaults_are_safe() {
10592        let config = EffectQueueConfig::default();
10593        assert!(!config.enabled);
10594        assert_eq!(config.backend, TaskExecutorBackend::Spawned);
10595        assert!(config.scheduler.smith_enabled);
10596        assert!(!config.scheduler.preemptive);
10597        assert_eq!(config.scheduler.aging_factor, 0.0);
10598        assert_eq!(config.scheduler.wait_starve_ms, 0.0);
10599    }
10600
10601    #[test]
10602    fn handle_effect_command_enqueues_or_executes_inline() {
10603        let (result_tx, result_rx) = mpsc::channel::<u32>();
10604        let mut scheduler = QueueingScheduler::new(EffectQueueConfig::default().scheduler);
10605        let mut tasks: HashMap<u64, Box<dyn FnOnce() -> u32 + Send>> = HashMap::new();
10606
10607        let ran = Arc::new(AtomicUsize::new(0));
10608        let ran_task = ran.clone();
10609        let cmd = EffectCommand::Enqueue(
10610            TaskSpec::default(),
10611            Box::new(move || {
10612                ran_task.fetch_add(1, Ordering::SeqCst);
10613                7
10614            }),
10615        );
10616
10617        let shutdown = handle_effect_command(cmd, &mut scheduler, &mut tasks, &result_tx, None, 0);
10618        assert_eq!(shutdown, EffectLoopControl::Continue);
10619        assert_eq!(ran.load(Ordering::SeqCst), 0);
10620        assert_eq!(tasks.len(), 1);
10621        assert!(result_rx.try_recv().is_err());
10622
10623        let mut full_scheduler = QueueingScheduler::new(SchedulerConfig {
10624            max_queue_size: 0,
10625            ..Default::default()
10626        });
10627        let mut full_tasks: HashMap<u64, Box<dyn FnOnce() -> u32 + Send>> = HashMap::new();
10628        let ran_full = Arc::new(AtomicUsize::new(0));
10629        let ran_full_task = ran_full.clone();
10630        let cmd_full = EffectCommand::Enqueue(
10631            TaskSpec::default(),
10632            Box::new(move || {
10633                ran_full_task.fetch_add(1, Ordering::SeqCst);
10634                42
10635            }),
10636        );
10637
10638        let shutdown_full = handle_effect_command(
10639            cmd_full,
10640            &mut full_scheduler,
10641            &mut full_tasks,
10642            &result_tx,
10643            None,
10644            0,
10645        );
10646        assert_eq!(shutdown_full, EffectLoopControl::Continue);
10647        assert!(full_tasks.is_empty());
10648        assert_eq!(ran_full.load(Ordering::SeqCst), 1);
10649        assert_eq!(
10650            result_rx.recv_timeout(Duration::from_millis(200)).unwrap(),
10651            42
10652        );
10653
10654        let shutdown = handle_effect_command(
10655            EffectCommand::Shutdown,
10656            &mut full_scheduler,
10657            &mut full_tasks,
10658            &result_tx,
10659            None,
10660            0,
10661        );
10662        assert_eq!(shutdown, EffectLoopControl::ShutdownRequested);
10663    }
10664
10665    #[test]
10666    fn handle_effect_command_inline_fallback_writes_backpressure_evidence() {
10667        let evidence_path = temp_evidence_path("task_executor_backpressure");
10668        let sink_config = EvidenceSinkConfig::enabled_file(&evidence_path);
10669        let sink = EvidenceSink::from_config(&sink_config)
10670            .expect("evidence sink config")
10671            .expect("evidence sink enabled");
10672        let (result_tx, result_rx) = mpsc::channel::<u32>();
10673        let mut scheduler = QueueingScheduler::new(SchedulerConfig {
10674            max_queue_size: 0,
10675            ..Default::default()
10676        });
10677        let mut tasks: HashMap<u64, Box<dyn FnOnce() -> u32 + Send>> = HashMap::new();
10678
10679        let shutdown = handle_effect_command(
10680            EffectCommand::Enqueue(TaskSpec::default(), Box::new(|| 7)),
10681            &mut scheduler,
10682            &mut tasks,
10683            &result_tx,
10684            Some(&sink),
10685            0,
10686        );
10687
10688        assert_eq!(shutdown, EffectLoopControl::Continue);
10689        assert!(tasks.is_empty());
10690        assert_eq!(
10691            result_rx.recv_timeout(Duration::from_millis(200)).unwrap(),
10692            7
10693        );
10694
10695        let backpressure_line = read_evidence_event(&evidence_path, "task_executor_backpressure");
10696        assert_eq!(backpressure_line["backend"], "queued");
10697        assert_eq!(backpressure_line["action"], "inline_fallback");
10698        assert_eq!(backpressure_line["max_queue_size"], 0);
10699        assert_eq!(backpressure_line["total_rejected"], 1);
10700
10701        let completion_line = read_evidence_event(&evidence_path, "task_executor_complete");
10702        assert_eq!(completion_line["backend"], "queued-inline-fallback");
10703        assert!(completion_line["duration_us"].is_number());
10704    }
10705
10706    #[test]
10707    fn effect_queue_loop_executes_tasks_and_shutdowns() {
10708        let (cmd_tx, cmd_rx) = mpsc::channel::<EffectCommand<u32>>();
10709        let (result_tx, result_rx) = mpsc::channel::<u32>();
10710        let config = EffectQueueConfig {
10711            enabled: true,
10712            backend: TaskExecutorBackend::EffectQueue,
10713            scheduler: SchedulerConfig {
10714                preemptive: false,
10715                ..Default::default()
10716            },
10717            explicit_backend: true,
10718            ..Default::default()
10719        };
10720
10721        let handle = std::thread::spawn(move || {
10722            effect_queue_loop(
10723                config,
10724                cmd_rx,
10725                result_tx,
10726                None,
10727                &std::sync::atomic::AtomicUsize::new(0),
10728            );
10729        });
10730
10731        cmd_tx
10732            .send(EffectCommand::Enqueue(TaskSpec::default(), Box::new(|| 10)))
10733            .unwrap();
10734        cmd_tx
10735            .send(EffectCommand::Enqueue(
10736                TaskSpec::new(2.0, 5.0).with_name("second"),
10737                Box::new(|| 20),
10738            ))
10739            .unwrap();
10740
10741        let mut results = vec![
10742            result_rx.recv_timeout(Duration::from_millis(500)).unwrap(),
10743            result_rx.recv_timeout(Duration::from_millis(500)).unwrap(),
10744        ];
10745        results.sort_unstable();
10746        assert_eq!(results, vec![10, 20]);
10747
10748        cmd_tx.send(EffectCommand::Shutdown).unwrap();
10749        let _ = handle.join();
10750    }
10751
10752    #[test]
10753    fn effect_queue_loop_drains_queued_tasks_after_shutdown_request() {
10754        let (cmd_tx, cmd_rx) = mpsc::channel::<EffectCommand<u32>>();
10755        let (result_tx, result_rx) = mpsc::channel::<u32>();
10756        let config = EffectQueueConfig {
10757            enabled: true,
10758            backend: TaskExecutorBackend::EffectQueue,
10759            scheduler: SchedulerConfig {
10760                preemptive: false,
10761                ..Default::default()
10762            },
10763            explicit_backend: true,
10764            ..Default::default()
10765        };
10766
10767        let handle = std::thread::spawn(move || {
10768            effect_queue_loop(
10769                config,
10770                cmd_rx,
10771                result_tx,
10772                None,
10773                &std::sync::atomic::AtomicUsize::new(0),
10774            );
10775        });
10776
10777        cmd_tx
10778            .send(EffectCommand::Enqueue(
10779                TaskSpec::default().with_name("slow"),
10780                Box::new(|| {
10781                    std::thread::sleep(Duration::from_millis(20));
10782                    10
10783                }),
10784            ))
10785            .unwrap();
10786        cmd_tx
10787            .send(EffectCommand::Enqueue(
10788                TaskSpec::new(2.0, 5.0).with_name("fast"),
10789                Box::new(|| 20),
10790            ))
10791            .unwrap();
10792        cmd_tx.send(EffectCommand::Shutdown).unwrap();
10793
10794        let mut results = vec![
10795            result_rx.recv_timeout(Duration::from_millis(500)).unwrap(),
10796            result_rx.recv_timeout(Duration::from_millis(500)).unwrap(),
10797        ];
10798        results.sort_unstable();
10799        assert_eq!(results, vec![10, 20]);
10800
10801        handle
10802            .join()
10803            .expect("effect queue thread joins after draining");
10804    }
10805
10806    #[test]
10807    fn effect_queue_loop_survives_panicking_task_and_runs_later_work() {
10808        let (cmd_tx, cmd_rx) = mpsc::channel::<EffectCommand<u32>>();
10809        let (result_tx, result_rx) = mpsc::channel::<u32>();
10810        let config = EffectQueueConfig {
10811            enabled: true,
10812            backend: TaskExecutorBackend::EffectQueue,
10813            scheduler: SchedulerConfig {
10814                preemptive: false,
10815                ..Default::default()
10816            },
10817            explicit_backend: true,
10818            ..Default::default()
10819        };
10820
10821        let handle = std::thread::spawn(move || {
10822            effect_queue_loop(
10823                config,
10824                cmd_rx,
10825                result_tx,
10826                None,
10827                &std::sync::atomic::AtomicUsize::new(0),
10828            );
10829        });
10830
10831        cmd_tx
10832            .send(EffectCommand::Enqueue(
10833                TaskSpec::new(3.0, 1.0).with_name("panic"),
10834                Box::new(|| panic!("queued panic")),
10835            ))
10836            .unwrap();
10837        cmd_tx
10838            .send(EffectCommand::Enqueue(
10839                TaskSpec::new(1.0, 5.0).with_name("after"),
10840                Box::new(|| 99),
10841            ))
10842            .unwrap();
10843
10844        assert_eq!(
10845            result_rx.recv_timeout(Duration::from_millis(500)).unwrap(),
10846            99
10847        );
10848
10849        cmd_tx.send(EffectCommand::Shutdown).unwrap();
10850        handle
10851            .join()
10852            .expect("effect queue thread survives task panic");
10853    }
10854
10855    #[test]
10856    fn effect_queue_loop_rejects_tasks_submitted_after_shutdown_request() {
10857        let (cmd_tx, cmd_rx) = mpsc::channel::<EffectCommand<u32>>();
10858        let (result_tx, result_rx) = mpsc::channel::<u32>();
10859        let config = EffectQueueConfig {
10860            enabled: true,
10861            backend: TaskExecutorBackend::EffectQueue,
10862            scheduler: SchedulerConfig {
10863                preemptive: false,
10864                ..Default::default()
10865            },
10866            explicit_backend: true,
10867            ..Default::default()
10868        };
10869
10870        let handle = std::thread::spawn(move || {
10871            effect_queue_loop(
10872                config,
10873                cmd_rx,
10874                result_tx,
10875                None,
10876                &std::sync::atomic::AtomicUsize::new(0),
10877            );
10878        });
10879
10880        cmd_tx
10881            .send(EffectCommand::Enqueue(
10882                TaskSpec::default().with_name("slow"),
10883                Box::new(|| {
10884                    std::thread::sleep(Duration::from_millis(20));
10885                    10
10886                }),
10887            ))
10888            .unwrap();
10889        cmd_tx.send(EffectCommand::Shutdown).unwrap();
10890        cmd_tx
10891            .send(EffectCommand::Enqueue(
10892                TaskSpec::new(1.0, 1.0).with_name("late"),
10893                Box::new(|| 99),
10894            ))
10895            .unwrap();
10896
10897        assert_eq!(
10898            result_rx.recv_timeout(Duration::from_millis(500)).unwrap(),
10899            10
10900        );
10901        assert!(
10902            result_rx.recv_timeout(Duration::from_millis(100)).is_err(),
10903            "post-shutdown enqueue should not execute"
10904        );
10905
10906        handle
10907            .join()
10908            .expect("effect queue thread joins after rejecting post-shutdown work");
10909    }
10910
10911    #[test]
10912    fn effect_queue_enqueue_after_shutdown_records_drop() {
10913        let (tx, rx) = mpsc::channel::<EffectCommand<u32>>();
10914        drop(rx);
10915
10916        let queue = EffectQueue {
10917            sender: tx,
10918            handle: None,
10919            closed: true,
10920            depth: Arc::new(AtomicUsize::new(0)),
10921        };
10922        let runs = Arc::new(AtomicUsize::new(0));
10923        let before = crate::effect_system::effects_queue_dropped();
10924
10925        queue.enqueue(
10926            TaskSpec::default(),
10927            Box::new({
10928                let runs = Arc::clone(&runs);
10929                move || {
10930                    runs.fetch_add(1, Ordering::SeqCst);
10931                    7
10932                }
10933            }),
10934        );
10935
10936        let after = crate::effect_system::effects_queue_dropped();
10937        assert_eq!(runs.load(Ordering::SeqCst), 0);
10938        assert!(
10939            after > before,
10940            "enqueue after shutdown should increment dropped counter"
10941        );
10942    }
10943
10944    #[test]
10945    fn effect_queue_enqueue_with_closed_channel_records_drop() {
10946        let (tx, rx) = mpsc::channel::<EffectCommand<u32>>();
10947        drop(rx);
10948
10949        let queue = EffectQueue {
10950            sender: tx,
10951            handle: None,
10952            closed: false,
10953            depth: Arc::new(AtomicUsize::new(0)),
10954        };
10955        let runs = Arc::new(AtomicUsize::new(0));
10956        let before = crate::effect_system::effects_queue_dropped();
10957
10958        queue.enqueue(
10959            TaskSpec::default(),
10960            Box::new({
10961                let runs = Arc::clone(&runs);
10962                move || {
10963                    runs.fetch_add(1, Ordering::SeqCst);
10964                    9
10965                }
10966            }),
10967        );
10968
10969        let after = crate::effect_system::effects_queue_dropped();
10970        assert_eq!(runs.load(Ordering::SeqCst), 0);
10971        assert!(
10972            after > before,
10973            "enqueue into a closed queue channel should increment dropped counter"
10974        );
10975    }
10976
10977    // =========================================================================
10978    // Backpressure tests (bd-2zd0a)
10979    // =========================================================================
10980
10981    #[test]
10982    fn backpressure_drops_tasks_beyond_max_depth() {
10983        let (result_tx, _result_rx) = mpsc::channel::<u32>();
10984        let mut scheduler = QueueingScheduler::new(SchedulerConfig::default());
10985        let mut tasks: HashMap<u64, Box<dyn FnOnce() -> u32 + Send>> = HashMap::new();
10986        let in_flight_before = crate::effect_system::queue_telemetry().in_flight;
10987
10988        // Enqueue 2 tasks with max_depth=2 — should succeed
10989        let r1 = handle_effect_command(
10990            EffectCommand::Enqueue(TaskSpec::default(), Box::new(|| 1)),
10991            &mut scheduler,
10992            &mut tasks,
10993            &result_tx,
10994            None,
10995            2,
10996        );
10997        assert_eq!(r1, EffectLoopControl::Continue);
10998        assert_eq!(tasks.len(), 1);
10999
11000        let r2 = handle_effect_command(
11001            EffectCommand::Enqueue(TaskSpec::default(), Box::new(|| 2)),
11002            &mut scheduler,
11003            &mut tasks,
11004            &result_tx,
11005            None,
11006            2,
11007        );
11008        assert_eq!(r2, EffectLoopControl::Continue);
11009        assert_eq!(tasks.len(), 2);
11010
11011        // 3rd task should be dropped (depth=2 >= max_depth=2)
11012        let dropped_before = crate::effect_system::effects_queue_dropped();
11013        let r3 = handle_effect_command(
11014            EffectCommand::Enqueue(TaskSpec::default(), Box::new(|| 3)),
11015            &mut scheduler,
11016            &mut tasks,
11017            &result_tx,
11018            None,
11019            2,
11020        );
11021        assert_eq!(r3, EffectLoopControl::Continue);
11022        assert_eq!(
11023            tasks.len(),
11024            2,
11025            "task should have been dropped, not enqueued"
11026        );
11027        assert!(
11028            crate::effect_system::effects_queue_dropped() > dropped_before,
11029            "dropped counter should increment"
11030        );
11031        release_unrun_queued_tasks(in_flight_before);
11032    }
11033
11034    #[test]
11035    fn backpressure_zero_depth_means_unbounded() {
11036        let (result_tx, _result_rx) = mpsc::channel::<u32>();
11037        let mut scheduler = QueueingScheduler::new(SchedulerConfig::default());
11038        let mut tasks: HashMap<u64, Box<dyn FnOnce() -> u32 + Send>> = HashMap::new();
11039
11040        // With max_depth=0, can enqueue many tasks
11041        let in_flight_before = crate::effect_system::queue_telemetry().in_flight;
11042        for i in 0..20 {
11043            let r = handle_effect_command(
11044                EffectCommand::Enqueue(TaskSpec::default(), Box::new(move || i)),
11045                &mut scheduler,
11046                &mut tasks,
11047                &result_tx,
11048                None,
11049                0,
11050            );
11051            assert_eq!(r, EffectLoopControl::Continue);
11052        }
11053        // All should be enqueued (some may have been inlined by scheduler, but none dropped)
11054        release_unrun_queued_tasks(in_flight_before);
11055    }
11056
11057    /// The enqueue counters are process-global and `in_flight` feeds the
11058    /// frame guardrail of every `Program` in this process. A unit test that
11059    /// queues tasks into a bare task map never runs them, so it must hand the
11060    /// accounting back or later headless render tests see a phantom backlog
11061    /// and drop their frames.
11062    fn release_unrun_queued_tasks(in_flight_before: u64) {
11063        let leaked = crate::effect_system::queue_telemetry()
11064            .in_flight
11065            .saturating_sub(in_flight_before);
11066        for _ in 0..leaked {
11067            crate::effect_system::record_queue_processed();
11068        }
11069    }
11070
11071    #[test]
11072    fn inline_auto_remeasure_reset_clears_decision() {
11073        let mut state = InlineAutoRemeasureState::new(InlineAutoRemeasureConfig::default());
11074        state.sampler.decide(Instant::now());
11075        assert!(state.sampler.last_decision().is_some());
11076
11077        state.reset();
11078        assert!(state.sampler.last_decision().is_none());
11079    }
11080
11081    #[test]
11082    fn budget_decision_jsonl_contains_required_fields() {
11083        let evidence = BudgetDecisionEvidence {
11084            frame_idx: 7,
11085            decision: BudgetDecision::Degrade,
11086            controller_decision: BudgetDecision::Hold,
11087            degradation_before: DegradationLevel::Full,
11088            degradation_after: DegradationLevel::NoStyling,
11089            frame_time_us: 12_345.678,
11090            budget_us: 16_000.0,
11091            pid_output: 1.25,
11092            pid_p: 0.5,
11093            pid_i: 0.25,
11094            pid_d: 0.5,
11095            e_value: 2.0,
11096            frames_observed: 42,
11097            frames_since_change: 3,
11098            in_warmup: false,
11099            controller_reason: BudgetDecisionReason::OverloadEvidencePassed,
11100            resize_detector: "bocpd",
11101            load_governor: LoadGovernorSnapshot {
11102                mode: RuntimeLoadMode::Degraded,
11103                mode_before: RuntimeLoadMode::Stressed,
11104                pressure_class: RuntimePressureClass::HardOverload,
11105                disposition: RuntimeWorkDisposition::DeferBackgroundDropBestEffort,
11106                reason_code: "budget_degradation_active",
11107                transition: true,
11108                strict_semantics_preserved: true,
11109                queue_in_flight: 8,
11110                queue_max_depth: Some(10),
11111                queue_dropped_delta: 0,
11112                resize_coalescing_active: false,
11113                recovery_intervals_observed: 0,
11114                recovery_intervals_required: 3,
11115                deferred_work_total: 2,
11116                coalesced_work_total: 1,
11117                dropped_work_total: 0,
11118            },
11119            conformal: Some(ConformalEvidence {
11120                bucket_key: "inline:dirty:10".to_string(),
11121                n_b: 32,
11122                alpha: 0.05,
11123                q_b: Some(1000.0),
11124                y_hat: 12_000.0,
11125                upper_us: Some(13_000.0),
11126                risk: true,
11127                status: ConformalStatus::Calibrated,
11128                required_rank: 32,
11129                fallback_level: 1,
11130                window_size: 256,
11131                reset_count: 2,
11132            }),
11133        };
11134
11135        let jsonl = evidence.to_jsonl();
11136        assert!(jsonl.contains("\"event\":\"budget_decision\""));
11137        assert!(jsonl.contains("\"decision\":\"degrade\""));
11138        assert!(jsonl.contains("\"decision_controller\":\"stay\""));
11139        assert!(jsonl.contains("\"decision_controller_reason\":\"overload_evidence_passed\""));
11140        assert!(jsonl.contains("\"degradation_before\":\"Full\""));
11141        assert!(jsonl.contains("\"degradation_after\":\"NoStyling\""));
11142        assert!(jsonl.contains("\"frame_time_us\":12345.678000"));
11143        assert!(jsonl.contains("\"budget_us\":16000.000000"));
11144        assert!(jsonl.contains("\"pid_output\":1.250000"));
11145        assert!(jsonl.contains("\"e_value\":2.000000"));
11146        assert!(jsonl.contains("\"runtime_mode\":\"degraded\""));
11147        assert!(jsonl.contains("\"runtime_mode_before\":\"stressed\""));
11148        assert!(jsonl.contains("\"pressure_class\":\"hard_overload\""));
11149        assert!(jsonl.contains("\"work_disposition\":\"defer_background_drop_best_effort\""));
11150        assert!(jsonl.contains("\"governor_reason\":\"budget_degradation_active\""));
11151        assert!(jsonl.contains("\"governor_transition\":true"));
11152        assert!(jsonl.contains("\"strict_semantics_preserved\":true"));
11153        assert!(jsonl.contains("\"queue_in_flight\":8"));
11154        assert!(jsonl.contains("\"queue_max_depth\":10"));
11155        assert!(jsonl.contains("\"resize_detector\":\"bocpd\""));
11156        assert!(jsonl.contains("\"deferred_work_total\":2"));
11157        assert!(jsonl.contains("\"bucket_key\":\"inline:dirty:10\""));
11158        assert!(jsonl.contains("\"n_b\":32"));
11159        assert!(jsonl.contains("\"alpha\":0.050000"));
11160        assert!(jsonl.contains("\"q_b\":1000.000000"));
11161        assert!(jsonl.contains("\"y_hat\":12000.000000"));
11162        assert!(jsonl.contains("\"upper_us\":13000.000000"));
11163        assert!(jsonl.contains("\"risk\":true"));
11164        assert!(jsonl.contains("\"fallback_level\":1"));
11165        assert!(jsonl.contains("\"window_size\":256"));
11166        assert!(jsonl.contains("\"reset_count\":2"));
11167    }
11168
11169    fn make_signal(
11170        widget_id: u64,
11171        essential: bool,
11172        priority: f32,
11173        staleness_ms: u64,
11174        cost_us: f32,
11175    ) -> WidgetSignal {
11176        WidgetSignal {
11177            widget_id,
11178            essential,
11179            priority,
11180            staleness_ms,
11181            focus_boost: 0.0,
11182            interaction_boost: 0.0,
11183            area_cells: 1,
11184            cost_estimate_us: cost_us,
11185            recent_cost_us: 0.0,
11186            estimate_source: CostEstimateSource::FixedDefault,
11187        }
11188    }
11189
11190    fn signal_value_cost(signal: &WidgetSignal, config: &WidgetRefreshConfig) -> (f32, f32, bool) {
11191        let starved = config.starve_ms > 0 && signal.staleness_ms >= config.starve_ms;
11192        let staleness_window = config.staleness_window_ms.max(1) as f32;
11193        let staleness_score = (signal.staleness_ms as f32 / staleness_window).min(1.0);
11194        let mut value = config.weight_priority * signal.priority
11195            + config.weight_staleness * staleness_score
11196            + config.weight_focus * signal.focus_boost
11197            + config.weight_interaction * signal.interaction_boost;
11198        if starved {
11199            value += config.starve_boost;
11200        }
11201        let raw_cost = if signal.recent_cost_us > 0.0 {
11202            signal.recent_cost_us
11203        } else {
11204            signal.cost_estimate_us
11205        };
11206        let cost_us = raw_cost.max(config.min_cost_us);
11207        (value, cost_us, starved)
11208    }
11209
11210    fn fifo_select(
11211        signals: &[WidgetSignal],
11212        budget_us: f64,
11213        config: &WidgetRefreshConfig,
11214    ) -> (Vec<u64>, f64, usize) {
11215        let mut selected = Vec::new();
11216        let mut total_value = 0.0f64;
11217        let mut starved_selected = 0usize;
11218        let mut remaining = budget_us;
11219
11220        for signal in signals {
11221            if !signal.essential {
11222                continue;
11223            }
11224            let (value, cost_us, starved) = signal_value_cost(signal, config);
11225            remaining -= cost_us as f64;
11226            total_value += value as f64;
11227            if starved {
11228                starved_selected = starved_selected.saturating_add(1);
11229            }
11230            selected.push(signal.widget_id);
11231        }
11232        for signal in signals {
11233            if signal.essential {
11234                continue;
11235            }
11236            let (value, cost_us, starved) = signal_value_cost(signal, config);
11237            if remaining >= cost_us as f64 {
11238                remaining -= cost_us as f64;
11239                total_value += value as f64;
11240                if starved {
11241                    starved_selected = starved_selected.saturating_add(1);
11242                }
11243                selected.push(signal.widget_id);
11244            }
11245        }
11246
11247        (selected, total_value, starved_selected)
11248    }
11249
11250    fn rotate_signals(signals: &[WidgetSignal], offset: usize) -> Vec<WidgetSignal> {
11251        if signals.is_empty() {
11252            return Vec::new();
11253        }
11254        let mut rotated = Vec::with_capacity(signals.len());
11255        for idx in 0..signals.len() {
11256            rotated.push(signals[(idx + offset) % signals.len()].clone());
11257        }
11258        rotated
11259    }
11260
11261    #[test]
11262    fn widget_refresh_selects_essentials_first() {
11263        let signals = vec![
11264            make_signal(1, true, 0.6, 0, 5.0),
11265            make_signal(2, false, 0.9, 0, 4.0),
11266        ];
11267        let mut plan = WidgetRefreshPlan::new();
11268        let config = WidgetRefreshConfig::default();
11269        plan.recompute(1, 6.0, DegradationLevel::Full, &signals, &config);
11270        let selected: Vec<u64> = plan.selected.iter().map(|e| e.widget_id).collect();
11271        assert_eq!(selected, vec![1]);
11272        assert!(!plan.over_budget);
11273    }
11274
11275    #[test]
11276    fn widget_refresh_degradation_essential_only_skips_nonessential() {
11277        let signals = vec![
11278            make_signal(1, true, 0.5, 0, 2.0),
11279            make_signal(2, false, 1.0, 0, 1.0),
11280        ];
11281        let mut plan = WidgetRefreshPlan::new();
11282        let config = WidgetRefreshConfig::default();
11283        plan.recompute(3, 10.0, DegradationLevel::EssentialOnly, &signals, &config);
11284        let selected: Vec<u64> = plan.selected.iter().map(|e| e.widget_id).collect();
11285        assert_eq!(selected, vec![1]);
11286        assert_eq!(plan.skipped_count, 1);
11287    }
11288
11289    #[test]
11290    fn widget_refresh_starvation_guard_forces_one_starved() {
11291        let signals = vec![make_signal(7, false, 0.1, 10_000, 8.0)];
11292        let mut plan = WidgetRefreshPlan::new();
11293        let config = WidgetRefreshConfig {
11294            starve_ms: 1_000,
11295            max_starved_per_frame: 1,
11296            ..Default::default()
11297        };
11298        plan.recompute(5, 0.0, DegradationLevel::Full, &signals, &config);
11299        assert_eq!(plan.selected.len(), 1);
11300        assert!(plan.selected[0].starved);
11301        assert!(plan.over_budget);
11302    }
11303
11304    #[test]
11305    fn widget_refresh_budget_blocks_when_no_selection() {
11306        let signals = vec![make_signal(42, false, 0.2, 0, 10.0)];
11307        let mut plan = WidgetRefreshPlan::new();
11308        let config = WidgetRefreshConfig {
11309            starve_ms: 0,
11310            max_starved_per_frame: 0,
11311            ..Default::default()
11312        };
11313        plan.recompute(8, 0.0, DegradationLevel::Full, &signals, &config);
11314        let budget = plan.as_budget();
11315        assert!(!budget.allows(42, false));
11316    }
11317
11318    #[test]
11319    fn widget_refresh_max_drop_fraction_forces_minimum_refresh() {
11320        let signals = vec![
11321            make_signal(1, false, 0.4, 0, 10.0),
11322            make_signal(2, false, 0.4, 0, 10.0),
11323            make_signal(3, false, 0.4, 0, 10.0),
11324            make_signal(4, false, 0.4, 0, 10.0),
11325        ];
11326        let mut plan = WidgetRefreshPlan::new();
11327        let config = WidgetRefreshConfig {
11328            starve_ms: 0,
11329            max_starved_per_frame: 0,
11330            max_drop_fraction: 0.5,
11331            ..Default::default()
11332        };
11333        plan.recompute(12, 0.0, DegradationLevel::Full, &signals, &config);
11334        let selected: Vec<u64> = plan.selected.iter().map(|e| e.widget_id).collect();
11335        assert_eq!(selected, vec![1, 2]);
11336    }
11337
11338    #[test]
11339    fn widget_refresh_greedy_beats_fifo_and_round_robin() {
11340        let signals = vec![
11341            make_signal(1, false, 0.1, 0, 6.0),
11342            make_signal(2, false, 0.2, 0, 6.0),
11343            make_signal(3, false, 1.0, 0, 4.0),
11344            make_signal(4, false, 0.9, 0, 3.0),
11345            make_signal(5, false, 0.8, 0, 3.0),
11346            make_signal(6, false, 0.1, 4_000, 2.0),
11347        ];
11348        let budget_us = 10.0;
11349        let config = WidgetRefreshConfig::default();
11350
11351        let mut plan = WidgetRefreshPlan::new();
11352        plan.recompute(21, budget_us, DegradationLevel::Full, &signals, &config);
11353        let greedy_value = plan.selected_value;
11354        let greedy_selected: Vec<u64> = plan.selected.iter().map(|e| e.widget_id).collect();
11355
11356        let (fifo_selected, fifo_value, _fifo_starved) = fifo_select(&signals, budget_us, &config);
11357        let rotated = rotate_signals(&signals, 2);
11358        let (rr_selected, rr_value, _rr_starved) = fifo_select(&rotated, budget_us, &config);
11359
11360        assert!(
11361            greedy_value > fifo_value,
11362            "greedy_value={greedy_value:.3} <= fifo_value={fifo_value:.3}; greedy={:?}, fifo={:?}",
11363            greedy_selected,
11364            fifo_selected
11365        );
11366        assert!(
11367            greedy_value > rr_value,
11368            "greedy_value={greedy_value:.3} <= rr_value={rr_value:.3}; greedy={:?}, rr={:?}",
11369            greedy_selected,
11370            rr_selected
11371        );
11372        assert!(
11373            plan.starved_selected > 0,
11374            "greedy did not select starved widget; greedy={:?}",
11375            greedy_selected
11376        );
11377    }
11378
11379    #[test]
11380    fn widget_refresh_jsonl_contains_required_fields() {
11381        let signals = vec![make_signal(7, true, 0.2, 0, 2.0)];
11382        let mut plan = WidgetRefreshPlan::new();
11383        let config = WidgetRefreshConfig::default();
11384        plan.recompute(9, 4.0, DegradationLevel::Full, &signals, &config);
11385        let jsonl = plan.to_jsonl();
11386        assert!(jsonl.contains("\"event\":\"widget_refresh\""));
11387        assert!(jsonl.contains("\"frame_idx\":9"));
11388        assert!(jsonl.contains("\"selected_count\":1"));
11389        assert!(jsonl.contains("\"id\":7"));
11390    }
11391
11392    #[test]
11393    fn program_config_with_resize_coalescer() {
11394        let config = ProgramConfig::default().with_resize_coalescer(CoalescerConfig {
11395            steady_delay_ms: 8,
11396            burst_delay_ms: 20,
11397            hard_deadline_ms: 80,
11398            burst_enter_rate: 12.0,
11399            burst_exit_rate: 6.0,
11400            cooldown_frames: 2,
11401            rate_window_size: 6,
11402            enable_logging: true,
11403            enable_bocpd: false,
11404            heuristic_fallback: true,
11405            bocpd_config: None,
11406        });
11407        assert_eq!(config.resize_coalescer.steady_delay_ms, 8);
11408        assert!(config.resize_coalescer.enable_logging);
11409    }
11410
11411    #[test]
11412    fn program_config_with_resize_behavior() {
11413        let config = ProgramConfig::default().with_resize_behavior(ResizeBehavior::Immediate);
11414        assert_eq!(config.resize_behavior, ResizeBehavior::Immediate);
11415    }
11416
11417    #[test]
11418    fn program_config_with_legacy_resize_enabled() {
11419        let config = ProgramConfig::default().with_legacy_resize(true);
11420        assert_eq!(config.resize_behavior, ResizeBehavior::Immediate);
11421    }
11422
11423    #[test]
11424    fn program_config_with_legacy_resize_disabled_keeps_default() {
11425        let config = ProgramConfig::default().with_legacy_resize(false);
11426        assert_eq!(config.resize_behavior, ResizeBehavior::Throttled);
11427    }
11428
11429    fn diff_strategy_trace(bayesian_enabled: bool) -> Vec<DiffStrategy> {
11430        let config = RuntimeDiffConfig::default().with_bayesian_enabled(bayesian_enabled);
11431        let mut writer = TerminalWriter::with_diff_config(
11432            Vec::<u8>::new(),
11433            ScreenMode::AltScreen,
11434            UiAnchor::Bottom,
11435            TerminalCapabilities::basic(),
11436            config,
11437        );
11438        writer.set_size(8, 4);
11439
11440        let mut buffer = Buffer::new(8, 4);
11441        let mut trace = Vec::new();
11442
11443        writer.present_ui(&buffer, None, false).unwrap();
11444        trace.push(
11445            writer
11446                .last_diff_strategy()
11447                .unwrap_or(DiffStrategy::FullRedraw),
11448        );
11449
11450        buffer.set_raw(0, 0, Cell::from_char('A'));
11451        writer.present_ui(&buffer, None, false).unwrap();
11452        trace.push(
11453            writer
11454                .last_diff_strategy()
11455                .unwrap_or(DiffStrategy::FullRedraw),
11456        );
11457
11458        buffer.set_raw(1, 1, Cell::from_char('B'));
11459        writer.present_ui(&buffer, None, false).unwrap();
11460        trace.push(
11461            writer
11462                .last_diff_strategy()
11463                .unwrap_or(DiffStrategy::FullRedraw),
11464        );
11465
11466        trace
11467    }
11468
11469    fn coalescer_checksum(enable_bocpd: bool) -> String {
11470        let mut config = CoalescerConfig::default().with_logging(true);
11471        config = if enable_bocpd {
11472            config.with_bocpd()
11473        } else {
11474            config.without_bocpd()
11475        };
11476
11477        let base = Instant::now();
11478        let mut coalescer = ResizeCoalescer::new(config, (80, 24)).with_last_render(base);
11479
11480        let events = [
11481            (0_u64, (82_u16, 24_u16)),
11482            (10, (83, 25)),
11483            (20, (84, 26)),
11484            (35, (90, 28)),
11485            (55, (92, 30)),
11486        ];
11487
11488        let mut idx = 0usize;
11489        for t_ms in (0_u64..=160).step_by(8) {
11490            let now = base + Duration::from_millis(t_ms);
11491            while idx < events.len() && events[idx].0 == t_ms {
11492                let (w, h) = events[idx].1;
11493                coalescer.handle_resize_at(w, h, now);
11494                idx += 1;
11495            }
11496            coalescer.tick_at(now);
11497        }
11498
11499        coalescer.decision_checksum_hex()
11500    }
11501
11502    fn conformal_trace(enabled: bool) -> Vec<(Option<f64>, bool)> {
11503        if !enabled {
11504            return Vec::new();
11505        }
11506
11507        let mut predictor =
11508            ConformalPredictor::new(ConformalConfig::default()).expect("valid config");
11509        let key = BucketKey::from_context(ScreenMode::AltScreen, DiffStrategy::Full, 80, 24);
11510        let mut trace = Vec::new();
11511
11512        for i in 0..30 {
11513            let y_hat = 16_000.0 + (i as f64) * 15.0;
11514            let observed = y_hat + (i % 7) as f64 * 120.0;
11515            predictor.observe(key, y_hat, observed);
11516            let prediction = predictor.predict(key, y_hat, 20_000.0);
11517            trace.push((prediction.upper_us, prediction.risk));
11518        }
11519
11520        trace
11521    }
11522
11523    #[test]
11524    fn policy_toggle_matrix_determinism() {
11525        for &bayesian in &[false, true] {
11526            for &bocpd in &[false, true] {
11527                for &conformal in &[false, true] {
11528                    let diff_a = diff_strategy_trace(bayesian);
11529                    let diff_b = diff_strategy_trace(bayesian);
11530                    assert_eq!(diff_a, diff_b, "diff strategy not deterministic");
11531
11532                    let checksum_a = coalescer_checksum(bocpd);
11533                    let checksum_b = coalescer_checksum(bocpd);
11534                    assert_eq!(checksum_a, checksum_b, "coalescer checksum mismatch");
11535
11536                    let conf_a = conformal_trace(conformal);
11537                    let conf_b = conformal_trace(conformal);
11538                    assert_eq!(conf_a, conf_b, "conformal predictor not deterministic");
11539
11540                    if conformal {
11541                        assert!(!conf_a.is_empty(), "conformal trace should be populated");
11542                    } else {
11543                        assert!(conf_a.is_empty(), "conformal trace should be empty");
11544                    }
11545                }
11546            }
11547        }
11548    }
11549
11550    #[test]
11551    fn resize_behavior_uses_coalescer_flag() {
11552        assert!(ResizeBehavior::Throttled.uses_coalescer());
11553        assert!(!ResizeBehavior::Immediate.uses_coalescer());
11554    }
11555
11556    #[test]
11557    fn nested_cmd_msg_executes_recursively() {
11558        // Verify that Cmd::Msg triggers recursive update
11559        use crate::simulator::ProgramSimulator;
11560
11561        struct NestedModel {
11562            depth: usize,
11563        }
11564
11565        #[derive(Debug)]
11566        enum NestedMsg {
11567            Nest(usize),
11568        }
11569
11570        impl From<Event> for NestedMsg {
11571            fn from(_: Event) -> Self {
11572                NestedMsg::Nest(0)
11573            }
11574        }
11575
11576        impl Model for NestedModel {
11577            type Message = NestedMsg;
11578
11579            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
11580                match msg {
11581                    NestedMsg::Nest(n) => {
11582                        self.depth += 1;
11583                        if n > 0 {
11584                            Cmd::msg(NestedMsg::Nest(n - 1))
11585                        } else {
11586                            Cmd::none()
11587                        }
11588                    }
11589                }
11590            }
11591
11592            fn view(&self, _frame: &mut Frame) {}
11593        }
11594
11595        let mut sim = ProgramSimulator::new(NestedModel { depth: 0 });
11596        sim.init();
11597        sim.send(NestedMsg::Nest(3));
11598
11599        // Should have recursed 4 times (3, 2, 1, 0)
11600        assert_eq!(sim.model().depth, 4);
11601    }
11602
11603    #[test]
11604    fn task_executes_synchronously_in_simulator() {
11605        // In simulator, tasks execute synchronously
11606        use crate::simulator::ProgramSimulator;
11607
11608        struct TaskModel {
11609            completed: bool,
11610        }
11611
11612        #[derive(Debug)]
11613        enum TaskMsg {
11614            Complete,
11615            SpawnTask,
11616        }
11617
11618        impl From<Event> for TaskMsg {
11619            fn from(_: Event) -> Self {
11620                TaskMsg::Complete
11621            }
11622        }
11623
11624        impl Model for TaskModel {
11625            type Message = TaskMsg;
11626
11627            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
11628                match msg {
11629                    TaskMsg::Complete => {
11630                        self.completed = true;
11631                        Cmd::none()
11632                    }
11633                    TaskMsg::SpawnTask => Cmd::task(|| TaskMsg::Complete),
11634                }
11635            }
11636
11637            fn view(&self, _frame: &mut Frame) {}
11638        }
11639
11640        let mut sim = ProgramSimulator::new(TaskModel { completed: false });
11641        sim.init();
11642        sim.send(TaskMsg::SpawnTask);
11643
11644        // Task should have completed synchronously
11645        assert!(sim.model().completed);
11646    }
11647
11648    #[test]
11649    fn multiple_updates_accumulate_correctly() {
11650        // Verify state accumulates correctly across multiple updates
11651        use crate::simulator::ProgramSimulator;
11652
11653        struct AccumModel {
11654            sum: i32,
11655        }
11656
11657        #[derive(Debug)]
11658        enum AccumMsg {
11659            Add(i32),
11660            Multiply(i32),
11661        }
11662
11663        impl From<Event> for AccumMsg {
11664            fn from(_: Event) -> Self {
11665                AccumMsg::Add(1)
11666            }
11667        }
11668
11669        impl Model for AccumModel {
11670            type Message = AccumMsg;
11671
11672            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
11673                match msg {
11674                    AccumMsg::Add(n) => {
11675                        self.sum += n;
11676                        Cmd::none()
11677                    }
11678                    AccumMsg::Multiply(n) => {
11679                        self.sum *= n;
11680                        Cmd::none()
11681                    }
11682                }
11683            }
11684
11685            fn view(&self, _frame: &mut Frame) {}
11686        }
11687
11688        let mut sim = ProgramSimulator::new(AccumModel { sum: 0 });
11689        sim.init();
11690
11691        // (0 + 5) * 2 + 3 = 13
11692        sim.send(AccumMsg::Add(5));
11693        sim.send(AccumMsg::Multiply(2));
11694        sim.send(AccumMsg::Add(3));
11695
11696        assert_eq!(sim.model().sum, 13);
11697    }
11698
11699    #[test]
11700    fn init_command_executes_before_first_update() {
11701        // Verify init() command executes before any update
11702        use crate::simulator::ProgramSimulator;
11703
11704        struct InitModel {
11705            initialized: bool,
11706            updates: usize,
11707        }
11708
11709        #[derive(Debug)]
11710        enum InitMsg {
11711            Update,
11712            MarkInit,
11713        }
11714
11715        impl From<Event> for InitMsg {
11716            fn from(_: Event) -> Self {
11717                InitMsg::Update
11718            }
11719        }
11720
11721        impl Model for InitModel {
11722            type Message = InitMsg;
11723
11724            fn init(&mut self) -> Cmd<Self::Message> {
11725                Cmd::msg(InitMsg::MarkInit)
11726            }
11727
11728            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
11729                match msg {
11730                    InitMsg::MarkInit => {
11731                        self.initialized = true;
11732                        Cmd::none()
11733                    }
11734                    InitMsg::Update => {
11735                        self.updates += 1;
11736                        Cmd::none()
11737                    }
11738                }
11739            }
11740
11741            fn view(&self, _frame: &mut Frame) {}
11742        }
11743
11744        let mut sim = ProgramSimulator::new(InitModel {
11745            initialized: false,
11746            updates: 0,
11747        });
11748        sim.init();
11749
11750        assert!(sim.model().initialized);
11751        sim.send(InitMsg::Update);
11752        assert_eq!(sim.model().updates, 1);
11753    }
11754
11755    // =========================================================================
11756    // INLINE MODE FRAME SIZING TESTS (bd-20vg)
11757    // =========================================================================
11758
11759    #[test]
11760    fn ui_height_returns_correct_value_inline_mode() {
11761        // Verify TerminalWriter.ui_height() returns ui_height in inline mode
11762        use crate::terminal_writer::{ScreenMode, TerminalWriter, UiAnchor};
11763        use ftui_core::terminal_capabilities::TerminalCapabilities;
11764
11765        let output = Vec::new();
11766        let writer = TerminalWriter::new(
11767            output,
11768            ScreenMode::Inline { ui_height: 10 },
11769            UiAnchor::Bottom,
11770            TerminalCapabilities::basic(),
11771        );
11772        assert_eq!(writer.ui_height(), 10);
11773    }
11774
11775    #[test]
11776    fn ui_height_returns_term_height_altscreen_mode() {
11777        // Verify TerminalWriter.ui_height() returns full terminal height in alt-screen mode
11778        use crate::terminal_writer::{ScreenMode, TerminalWriter, UiAnchor};
11779        use ftui_core::terminal_capabilities::TerminalCapabilities;
11780
11781        let output = Vec::new();
11782        let mut writer = TerminalWriter::new(
11783            output,
11784            ScreenMode::AltScreen,
11785            UiAnchor::Bottom,
11786            TerminalCapabilities::basic(),
11787        );
11788        writer.set_size(80, 24);
11789        assert_eq!(writer.ui_height(), 24);
11790    }
11791
11792    #[test]
11793    fn inline_mode_frame_uses_ui_height_not_terminal_height() {
11794        // Verify that in inline mode, the model receives a frame with ui_height,
11795        // not the full terminal height. This is the core fix for bd-20vg.
11796        use crate::simulator::ProgramSimulator;
11797        use std::cell::Cell as StdCell;
11798
11799        thread_local! {
11800            static CAPTURED_HEIGHT: StdCell<u16> = const { StdCell::new(0) };
11801        }
11802
11803        struct FrameSizeTracker;
11804
11805        #[derive(Debug)]
11806        enum SizeMsg {
11807            Check,
11808        }
11809
11810        impl From<Event> for SizeMsg {
11811            fn from(_: Event) -> Self {
11812                SizeMsg::Check
11813            }
11814        }
11815
11816        impl Model for FrameSizeTracker {
11817            type Message = SizeMsg;
11818
11819            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
11820                Cmd::none()
11821            }
11822
11823            fn view(&self, frame: &mut Frame) {
11824                // Capture the frame height we receive
11825                CAPTURED_HEIGHT.with(|h| h.set(frame.height()));
11826            }
11827        }
11828
11829        // Use simulator to verify frame dimension handling
11830        let mut sim = ProgramSimulator::new(FrameSizeTracker);
11831        sim.init();
11832
11833        // Capture with specific dimensions (simulates inline mode ui_height=10)
11834        let buf = sim.capture_frame(80, 10);
11835        assert_eq!(buf.height(), 10);
11836        assert_eq!(buf.width(), 80);
11837
11838        // Verify the frame has the correct dimensions
11839        // In inline mode with ui_height=10, the frame should be 10 rows tall,
11840        // NOT the full terminal height (e.g., 24).
11841    }
11842
11843    #[test]
11844    fn altscreen_frame_uses_full_terminal_height() {
11845        // Regression test: in alt-screen mode, frame should use full terminal height.
11846        use crate::terminal_writer::{ScreenMode, TerminalWriter, UiAnchor};
11847        use ftui_core::terminal_capabilities::TerminalCapabilities;
11848
11849        let output = Vec::new();
11850        let mut writer = TerminalWriter::new(
11851            output,
11852            ScreenMode::AltScreen,
11853            UiAnchor::Bottom,
11854            TerminalCapabilities::basic(),
11855        );
11856        writer.set_size(80, 40);
11857
11858        // In alt-screen, ui_height equals terminal height
11859        assert_eq!(writer.ui_height(), 40);
11860    }
11861
11862    #[test]
11863    fn ui_height_clamped_to_terminal_height() {
11864        // Verify ui_height doesn't exceed terminal height
11865        // (This is handled in present_inline, but ui_height() returns the configured value)
11866        use crate::terminal_writer::{ScreenMode, TerminalWriter, UiAnchor};
11867        use ftui_core::terminal_capabilities::TerminalCapabilities;
11868
11869        let output = Vec::new();
11870        let mut writer = TerminalWriter::new(
11871            output,
11872            ScreenMode::Inline { ui_height: 100 },
11873            UiAnchor::Bottom,
11874            TerminalCapabilities::basic(),
11875        );
11876        writer.set_size(80, 10);
11877
11878        // ui_height() returns configured value, but present_inline clamps
11879        // The Frame should be created with ui_height (100), which is later
11880        // clamped during presentation. For safety, we should use the min.
11881        // Note: This documents current behavior. A stricter fix might
11882        // have ui_height() return min(ui_height, term_height).
11883        assert_eq!(writer.ui_height(), 100);
11884    }
11885
11886    // =========================================================================
11887    // TICK DELIVERY TESTS (bd-3ufh)
11888    // =========================================================================
11889
11890    #[test]
11891    fn tick_event_delivered_to_model_update() {
11892        // Verify that Event::Tick is delivered to model.update()
11893        // This is the core fix: ticks now flow through the update pipeline.
11894        use crate::simulator::ProgramSimulator;
11895
11896        struct TickTracker {
11897            tick_count: usize,
11898        }
11899
11900        #[derive(Debug)]
11901        enum TickMsg {
11902            Tick,
11903            Other,
11904        }
11905
11906        impl From<Event> for TickMsg {
11907            fn from(event: Event) -> Self {
11908                match event {
11909                    Event::Tick => TickMsg::Tick,
11910                    _ => TickMsg::Other,
11911                }
11912            }
11913        }
11914
11915        impl Model for TickTracker {
11916            type Message = TickMsg;
11917
11918            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
11919                match msg {
11920                    TickMsg::Tick => {
11921                        self.tick_count += 1;
11922                        Cmd::none()
11923                    }
11924                    TickMsg::Other => Cmd::none(),
11925                }
11926            }
11927
11928            fn view(&self, _frame: &mut Frame) {}
11929        }
11930
11931        let mut sim = ProgramSimulator::new(TickTracker { tick_count: 0 });
11932        sim.init();
11933
11934        // Manually inject tick event to simulate what the runtime does
11935        sim.inject_event(Event::Tick);
11936        assert_eq!(sim.model().tick_count, 1);
11937
11938        sim.inject_event(Event::Tick);
11939        sim.inject_event(Event::Tick);
11940        assert_eq!(sim.model().tick_count, 3);
11941    }
11942
11943    #[test]
11944    fn tick_command_sets_tick_rate() {
11945        // Verify Cmd::tick() sets the tick rate in the simulator
11946        use crate::simulator::{CmdRecord, ProgramSimulator};
11947
11948        struct TickModel;
11949
11950        #[derive(Debug)]
11951        enum Msg {
11952            SetTick,
11953            Noop,
11954        }
11955
11956        impl From<Event> for Msg {
11957            fn from(_: Event) -> Self {
11958                Msg::Noop
11959            }
11960        }
11961
11962        impl Model for TickModel {
11963            type Message = Msg;
11964
11965            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
11966                match msg {
11967                    Msg::SetTick => Cmd::tick(Duration::from_millis(100)),
11968                    Msg::Noop => Cmd::none(),
11969                }
11970            }
11971
11972            fn view(&self, _frame: &mut Frame) {}
11973        }
11974
11975        let mut sim = ProgramSimulator::new(TickModel);
11976        sim.init();
11977        sim.send(Msg::SetTick);
11978
11979        // Check that tick was recorded
11980        let commands = sim.command_log();
11981        assert!(
11982            commands
11983                .iter()
11984                .any(|c| matches!(c, CmdRecord::Tick(d) if *d == Duration::from_millis(100)))
11985        );
11986    }
11987
11988    #[test]
11989    fn tick_can_trigger_further_commands() {
11990        // Verify that tick handling can return commands that are executed
11991        use crate::simulator::ProgramSimulator;
11992
11993        struct ChainModel {
11994            stage: usize,
11995        }
11996
11997        #[derive(Debug)]
11998        enum ChainMsg {
11999            Tick,
12000            Advance,
12001            Noop,
12002        }
12003
12004        impl From<Event> for ChainMsg {
12005            fn from(event: Event) -> Self {
12006                match event {
12007                    Event::Tick => ChainMsg::Tick,
12008                    _ => ChainMsg::Noop,
12009                }
12010            }
12011        }
12012
12013        impl Model for ChainModel {
12014            type Message = ChainMsg;
12015
12016            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
12017                match msg {
12018                    ChainMsg::Tick => {
12019                        self.stage += 1;
12020                        // Return another message to be processed
12021                        Cmd::msg(ChainMsg::Advance)
12022                    }
12023                    ChainMsg::Advance => {
12024                        self.stage += 10;
12025                        Cmd::none()
12026                    }
12027                    ChainMsg::Noop => Cmd::none(),
12028                }
12029            }
12030
12031            fn view(&self, _frame: &mut Frame) {}
12032        }
12033
12034        let mut sim = ProgramSimulator::new(ChainModel { stage: 0 });
12035        sim.init();
12036        sim.inject_event(Event::Tick);
12037
12038        // Tick increments by 1, then Advance increments by 10
12039        assert_eq!(sim.model().stage, 11);
12040    }
12041
12042    #[test]
12043    fn tick_disabled_with_zero_duration() {
12044        // Verify that Duration::ZERO disables ticks (no busy loop)
12045        use crate::simulator::ProgramSimulator;
12046
12047        struct ZeroTickModel {
12048            disabled: bool,
12049        }
12050
12051        #[derive(Debug)]
12052        enum ZeroMsg {
12053            DisableTick,
12054            Noop,
12055        }
12056
12057        impl From<Event> for ZeroMsg {
12058            fn from(_: Event) -> Self {
12059                ZeroMsg::Noop
12060            }
12061        }
12062
12063        impl Model for ZeroTickModel {
12064            type Message = ZeroMsg;
12065
12066            fn init(&mut self) -> Cmd<Self::Message> {
12067                // Start with a tick enabled
12068                Cmd::tick(Duration::from_millis(100))
12069            }
12070
12071            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
12072                match msg {
12073                    ZeroMsg::DisableTick => {
12074                        self.disabled = true;
12075                        // Setting tick to ZERO should effectively disable
12076                        Cmd::tick(Duration::ZERO)
12077                    }
12078                    ZeroMsg::Noop => Cmd::none(),
12079                }
12080            }
12081
12082            fn view(&self, _frame: &mut Frame) {}
12083        }
12084
12085        let mut sim = ProgramSimulator::new(ZeroTickModel { disabled: false });
12086        sim.init();
12087
12088        // Verify initial tick rate is set
12089        assert!(sim.tick_rate().is_some());
12090        assert_eq!(sim.tick_rate(), Some(Duration::from_millis(100)));
12091
12092        // Disable ticks
12093        sim.send(ZeroMsg::DisableTick);
12094        assert!(sim.model().disabled);
12095
12096        // Note: The simulator still records the ZERO tick, but the runtime's
12097        // should_tick() handles ZERO duration appropriately
12098        assert_eq!(sim.tick_rate(), Some(Duration::ZERO));
12099    }
12100
12101    #[test]
12102    fn tick_event_distinguishable_from_other_events() {
12103        // Verify Event::Tick can be distinguished in pattern matching
12104        let tick = Event::Tick;
12105        let key = Event::Key(ftui_core::event::KeyEvent::new(
12106            ftui_core::event::KeyCode::Char('a'),
12107        ));
12108
12109        assert!(matches!(tick, Event::Tick));
12110        assert!(!matches!(key, Event::Tick));
12111    }
12112
12113    #[test]
12114    fn tick_event_clone_and_eq() {
12115        // Verify Event::Tick implements Clone and Eq correctly
12116        let tick1 = Event::Tick;
12117        let tick2 = tick1.clone();
12118        assert_eq!(tick1, tick2);
12119    }
12120
12121    #[test]
12122    fn model_receives_tick_and_input_events() {
12123        // Verify model can handle both tick and input events correctly
12124        use crate::simulator::ProgramSimulator;
12125
12126        struct MixedModel {
12127            ticks: usize,
12128            keys: usize,
12129        }
12130
12131        #[derive(Debug)]
12132        enum MixedMsg {
12133            Tick,
12134            Key,
12135        }
12136
12137        impl From<Event> for MixedMsg {
12138            fn from(event: Event) -> Self {
12139                match event {
12140                    Event::Tick => MixedMsg::Tick,
12141                    _ => MixedMsg::Key,
12142                }
12143            }
12144        }
12145
12146        impl Model for MixedModel {
12147            type Message = MixedMsg;
12148
12149            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
12150                match msg {
12151                    MixedMsg::Tick => {
12152                        self.ticks += 1;
12153                        Cmd::none()
12154                    }
12155                    MixedMsg::Key => {
12156                        self.keys += 1;
12157                        Cmd::none()
12158                    }
12159                }
12160            }
12161
12162            fn view(&self, _frame: &mut Frame) {}
12163        }
12164
12165        let mut sim = ProgramSimulator::new(MixedModel { ticks: 0, keys: 0 });
12166        sim.init();
12167
12168        // Interleave tick and input events
12169        sim.inject_event(Event::Tick);
12170        sim.inject_event(Event::Key(ftui_core::event::KeyEvent::new(
12171            ftui_core::event::KeyCode::Char('a'),
12172        )));
12173        sim.inject_event(Event::Tick);
12174        sim.inject_event(Event::Key(ftui_core::event::KeyEvent::new(
12175            ftui_core::event::KeyCode::Char('b'),
12176        )));
12177        sim.inject_event(Event::Tick);
12178
12179        assert_eq!(sim.model().ticks, 3);
12180        assert_eq!(sim.model().keys, 2);
12181    }
12182
12183    // =========================================================================
12184    // HEADLESS PROGRAM TESTS (bd-1av4o.2)
12185    // =========================================================================
12186
12187    fn headless_program_with_resolved_config<M: Model>(
12188        model: M,
12189        config: ProgramConfig,
12190    ) -> Program<M, HeadlessEventSource, Vec<u8>>
12191    where
12192        M::Message: Send + 'static,
12193    {
12194        let effect_queue_config = config.resolved_effect_queue_config();
12195        let capabilities = TerminalCapabilities::basic();
12196        let mut writer = TerminalWriter::with_diff_config(
12197            Vec::new(),
12198            config.screen_mode,
12199            config.ui_anchor,
12200            capabilities,
12201            config.diff_config.clone(),
12202        );
12203        let frame_timing = config.frame_timing.clone();
12204        writer.set_timing_enabled(frame_timing.is_some());
12205
12206        let (width, height) = config.forced_size.unwrap_or((80, 24));
12207        let width = width.max(1);
12208        let height = height.max(1);
12209        writer.set_size(width, height);
12210
12211        let mouse_capture = config.resolved_mouse_capture();
12212        let initial_features = BackendFeatures {
12213            mouse_capture,
12214            bracketed_paste: config.bracketed_paste,
12215            focus_events: config.focus_reporting,
12216            kitty_keyboard: config.kitty_keyboard,
12217        };
12218        let events = HeadlessEventSource::new(width, height, initial_features);
12219        let evidence_sink = EvidenceSink::from_config(&config.evidence_sink)
12220            .expect("headless evidence sink config");
12221
12222        let budget = render_budget_from_program_config(&config);
12223        let load_governor = LoadGovernorState::new(
12224            config.load_governor.clone(),
12225            effect_queue_config.max_queue_depth,
12226        );
12227        let conformal_predictor = config
12228            .conformal_config
12229            .clone()
12230            .map(ConformalPredictor::new)
12231            .transpose()
12232            .expect("valid headless conformal config");
12233        let locale_context = config.locale_context.clone();
12234        let locale_version = locale_context.version();
12235        let mut resize_coalescer =
12236            ResizeCoalescer::new(config.resize_coalescer.clone(), (width, height));
12237        if let Some(ref sink) = evidence_sink {
12238            resize_coalescer = resize_coalescer.with_evidence_sink(sink.clone());
12239        }
12240        let subscriptions = SubscriptionManager::new();
12241        let (task_sender, task_receiver) = std::sync::mpsc::channel();
12242        let inline_auto_remeasure = config
12243            .inline_auto_remeasure
12244            .clone()
12245            .map(InlineAutoRemeasureState::new);
12246        let gesture_recognizer = config
12247            .gestures
12248            .clone()
12249            .map(ftui_core::gesture::GestureRecognizer::new);
12250        let guardrails = FrameGuardrails::new(config.guardrails);
12251        let task_executor = TaskExecutor::new(
12252            &effect_queue_config,
12253            task_sender.clone(),
12254            evidence_sink.clone(),
12255        )
12256        .expect("task executor");
12257
12258        Program {
12259            model,
12260            writer,
12261            events,
12262            backend_features: initial_features,
12263            running: true,
12264            shutdown_complete: false,
12265            tick_rate: None,
12266            executed_cmd_count: 0,
12267            last_tick: Instant::now(),
12268            dirty: true,
12269            frame_idx: 0,
12270            tick_count: 0,
12271            widget_signals: Vec::new(),
12272            a11y_policy: config.accessibility,
12273            a11y_evidence_text: config.accessibility_evidence_text,
12274            a11y_tree: None,
12275            a11y_order: Vec::new(),
12276            a11y_announcements: Vec::new(),
12277            a11y_pending: None,
12278            a11y_changed: false,
12279            a11y_dropped: 0,
12280            startup_events: Vec::new(),
12281            startup_parser: ftui_core::input_parser::InputParser::new(),
12282            widget_refresh_config: config.widget_refresh,
12283            widget_refresh_plan: WidgetRefreshPlan::new(),
12284            width,
12285            height,
12286            forced_size: config.forced_size,
12287            poll_timeout: config.poll_timeout,
12288            intercept_signals: config.intercept_signals,
12289            pending_signal: Arc::new(std::sync::atomic::AtomicI32::new(0)),
12290            // Headless test programs never install an OS signal handler, so
12291            // they must not read (or clear) the process-global slot: that is
12292            // exactly the cross-test race that used to hang this binary.
12293            global_signal_slot: false,
12294            immediate_drain_config: config.immediate_drain,
12295            immediate_drain_stats: ImmediateDrainStats::default(),
12296            budget,
12297            load_governor,
12298            conformal_predictor,
12299            last_frame_time_us: None,
12300            last_update_us: None,
12301            frame_timing,
12302            locale_context,
12303            locale_version,
12304            resize_coalescer,
12305            evidence_sink,
12306            fairness_config_logged: false,
12307            resize_behavior: config.resize_behavior,
12308            fairness_guard: InputFairnessGuard::new(),
12309            event_recorder: None,
12310            subscriptions,
12311            #[cfg(test)]
12312            task_sender,
12313            task_receiver,
12314            task_executor,
12315            state_registry: config.persistence.registry.clone(),
12316            persistence_config: config.persistence,
12317            last_checkpoint: Instant::now(),
12318            inline_auto_remeasure,
12319            gesture_recognizer,
12320            frame_arena: FrameArena::default(),
12321            guardrails,
12322            last_soft_trim_frame: None,
12323            tick_strategy: config
12324                .tick_strategy
12325                .map(|strategy| Box::new(strategy) as Box<dyn crate::tick_strategy::TickStrategy>),
12326            last_active_screen_for_strategy: None,
12327        }
12328    }
12329
12330    fn headless_program_with_config<M: Model>(
12331        model: M,
12332        config: ProgramConfig,
12333    ) -> Program<M, HeadlessEventSource, Vec<u8>>
12334    where
12335        M::Message: Send + 'static,
12336    {
12337        // Headless unit tests should not observe process-global shutdown state
12338        // unless they explicitly opt into signal interception.
12339        headless_program_with_resolved_config(model, config.with_signal_interception(false))
12340    }
12341
12342    fn headless_signal_program_with_config<M: Model>(
12343        model: M,
12344        config: ProgramConfig,
12345    ) -> Program<M, HeadlessEventSource, Vec<u8>>
12346    where
12347        M::Message: Send + 'static,
12348    {
12349        headless_program_with_resolved_config(model, config)
12350    }
12351
12352    fn temp_evidence_path(label: &str) -> PathBuf {
12353        static COUNTER: AtomicUsize = AtomicUsize::new(0);
12354        let seq = COUNTER.fetch_add(1, Ordering::Relaxed);
12355        let pid = std::process::id();
12356        let mut path = std::env::temp_dir();
12357        path.push(format!("ftui_evidence_{label}_{pid}_{seq}.jsonl"));
12358        path
12359    }
12360
12361    fn read_evidence_event(path: &PathBuf, event: &str) -> Value {
12362        let jsonl = std::fs::read_to_string(path).expect("read evidence jsonl");
12363        let needle = format!("\"event\":\"{event}\"");
12364        let missing_msg = format!("missing {event} line");
12365        let line = jsonl
12366            .lines()
12367            .find(|line| line.contains(&needle))
12368            .expect(&missing_msg);
12369        serde_json::from_str(line).expect("valid evidence json")
12370    }
12371
12372    #[test]
12373    fn headless_apply_resize_updates_model_and_dimensions() {
12374        struct ResizeModel {
12375            last_size: Option<(u16, u16)>,
12376        }
12377
12378        #[derive(Debug)]
12379        enum ResizeMsg {
12380            Resize(u16, u16),
12381            Other,
12382        }
12383
12384        impl From<Event> for ResizeMsg {
12385            fn from(event: Event) -> Self {
12386                match event {
12387                    Event::Resize { width, height } => ResizeMsg::Resize(width, height),
12388                    _ => ResizeMsg::Other,
12389                }
12390            }
12391        }
12392
12393        impl Model for ResizeModel {
12394            type Message = ResizeMsg;
12395
12396            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
12397                if let ResizeMsg::Resize(w, h) = msg {
12398                    self.last_size = Some((w, h));
12399                }
12400                Cmd::none()
12401            }
12402
12403            fn view(&self, _frame: &mut Frame) {}
12404        }
12405
12406        let mut program =
12407            headless_program_with_config(ResizeModel { last_size: None }, ProgramConfig::default());
12408        program.dirty = false;
12409
12410        program
12411            .apply_resize(0, 0, Duration::ZERO, false)
12412            .expect("resize");
12413
12414        assert_eq!(program.width, 1);
12415        assert_eq!(program.height, 1);
12416        assert_eq!(program.model().last_size, Some((1, 1)));
12417        assert!(program.dirty);
12418    }
12419
12420    #[test]
12421    fn headless_apply_resize_reconciles_subscriptions() {
12422        use crate::subscription::{StopSignal, SubId, Subscription};
12423
12424        struct ResizeSubModel {
12425            subscribed: bool,
12426        }
12427
12428        #[derive(Debug)]
12429        enum ResizeSubMsg {
12430            Resize,
12431            Other,
12432        }
12433
12434        impl From<Event> for ResizeSubMsg {
12435            fn from(event: Event) -> Self {
12436                match event {
12437                    Event::Resize { .. } => Self::Resize,
12438                    _ => Self::Other,
12439                }
12440            }
12441        }
12442
12443        impl Model for ResizeSubModel {
12444            type Message = ResizeSubMsg;
12445
12446            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
12447                if matches!(msg, ResizeSubMsg::Resize) {
12448                    self.subscribed = true;
12449                }
12450                Cmd::none()
12451            }
12452
12453            fn view(&self, _frame: &mut Frame) {}
12454
12455            fn subscriptions(&self) -> Vec<Box<dyn Subscription<Self::Message>>> {
12456                if self.subscribed {
12457                    vec![Box::new(ResizeSubscription)]
12458                } else {
12459                    vec![]
12460                }
12461            }
12462        }
12463
12464        struct ResizeSubscription;
12465
12466        impl Subscription<ResizeSubMsg> for ResizeSubscription {
12467            fn id(&self) -> SubId {
12468                1
12469            }
12470
12471            fn run(&self, _sender: mpsc::Sender<ResizeSubMsg>, _stop: StopSignal) {}
12472        }
12473
12474        let mut program = headless_program_with_config(
12475            ResizeSubModel { subscribed: false },
12476            ProgramConfig::default(),
12477        );
12478
12479        assert_eq!(program.subscriptions.active_count(), 0);
12480        program
12481            .apply_resize(120, 40, Duration::ZERO, false)
12482            .expect("resize");
12483
12484        assert!(program.model().subscribed);
12485        assert_eq!(program.subscriptions.active_count(), 1);
12486    }
12487
12488    #[test]
12489    fn headless_execute_cmd_log_writes_output() {
12490        let mut program =
12491            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
12492        program.execute_cmd(Cmd::log("hello world")).expect("log");
12493
12494        let bytes = program.writer.into_inner().expect("writer output");
12495        let output = String::from_utf8_lossy(&bytes);
12496        assert!(output.contains("hello world"));
12497    }
12498
12499    #[test]
12500    fn headless_process_task_results_updates_model() {
12501        struct TaskModel {
12502            updates: usize,
12503        }
12504
12505        #[derive(Debug)]
12506        enum TaskMsg {
12507            Done,
12508        }
12509
12510        impl From<Event> for TaskMsg {
12511            fn from(_: Event) -> Self {
12512                TaskMsg::Done
12513            }
12514        }
12515
12516        impl Model for TaskModel {
12517            type Message = TaskMsg;
12518
12519            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
12520                self.updates += 1;
12521                Cmd::none()
12522            }
12523
12524            fn view(&self, _frame: &mut Frame) {}
12525        }
12526
12527        let mut program =
12528            headless_program_with_config(TaskModel { updates: 0 }, ProgramConfig::default());
12529        program.dirty = false;
12530        program.task_sender.send(TaskMsg::Done).unwrap();
12531
12532        program
12533            .process_task_results()
12534            .expect("process task results");
12535        assert_eq!(program.model().updates, 1);
12536        assert!(program.dirty);
12537    }
12538
12539    #[test]
12540    fn run_invokes_on_shutdown_after_quit() {
12541        use std::sync::{
12542            Arc,
12543            atomic::{AtomicUsize, Ordering},
12544        };
12545
12546        struct ShutdownModel {
12547            shutdowns: Arc<AtomicUsize>,
12548        }
12549
12550        #[derive(Debug, Clone, Copy)]
12551        enum ShutdownMsg {
12552            Quit,
12553            ShutdownRan,
12554        }
12555
12556        impl From<Event> for ShutdownMsg {
12557            fn from(_: Event) -> Self {
12558                ShutdownMsg::Quit
12559            }
12560        }
12561
12562        impl Model for ShutdownModel {
12563            type Message = ShutdownMsg;
12564
12565            fn init(&mut self) -> Cmd<Self::Message> {
12566                Cmd::quit()
12567            }
12568
12569            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
12570                match msg {
12571                    ShutdownMsg::Quit => Cmd::quit(),
12572                    ShutdownMsg::ShutdownRan => {
12573                        self.shutdowns.fetch_add(1, Ordering::SeqCst);
12574                        Cmd::none()
12575                    }
12576                }
12577            }
12578
12579            fn view(&self, _frame: &mut Frame) {}
12580
12581            fn on_shutdown(&mut self) -> Cmd<Self::Message> {
12582                Cmd::msg(ShutdownMsg::ShutdownRan)
12583            }
12584        }
12585
12586        let shutdowns = Arc::new(AtomicUsize::new(0));
12587        let mut program = headless_program_with_config(
12588            ShutdownModel {
12589                shutdowns: Arc::clone(&shutdowns),
12590            },
12591            ProgramConfig::default(),
12592        );
12593
12594        program.run().expect("program run");
12595
12596        assert_eq!(shutdowns.load(Ordering::SeqCst), 1);
12597    }
12598
12599    #[test]
12600    fn run_processes_shutdown_task_results_before_exit() {
12601        use std::sync::{
12602            Arc,
12603            atomic::{AtomicUsize, Ordering},
12604        };
12605
12606        struct ShutdownTaskModel {
12607            shutdowns: Arc<AtomicUsize>,
12608        }
12609
12610        #[derive(Debug, Clone, Copy)]
12611        enum ShutdownTaskMsg {
12612            Quit,
12613            ShutdownRan,
12614        }
12615
12616        impl From<Event> for ShutdownTaskMsg {
12617            fn from(_: Event) -> Self {
12618                ShutdownTaskMsg::Quit
12619            }
12620        }
12621
12622        impl Model for ShutdownTaskModel {
12623            type Message = ShutdownTaskMsg;
12624
12625            fn init(&mut self) -> Cmd<Self::Message> {
12626                Cmd::quit()
12627            }
12628
12629            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
12630                match msg {
12631                    ShutdownTaskMsg::Quit => Cmd::quit(),
12632                    ShutdownTaskMsg::ShutdownRan => {
12633                        self.shutdowns.fetch_add(1, Ordering::SeqCst);
12634                        Cmd::none()
12635                    }
12636                }
12637            }
12638
12639            fn view(&self, _frame: &mut Frame) {}
12640
12641            fn on_shutdown(&mut self) -> Cmd<Self::Message> {
12642                Cmd::task(|| ShutdownTaskMsg::ShutdownRan)
12643            }
12644        }
12645
12646        let shutdowns = Arc::new(AtomicUsize::new(0));
12647        let mut program = headless_program_with_config(
12648            ShutdownTaskModel {
12649                shutdowns: Arc::clone(&shutdowns),
12650            },
12651            ProgramConfig::default(),
12652        );
12653
12654        program.run().expect("program run");
12655
12656        assert_eq!(shutdowns.load(Ordering::SeqCst), 1);
12657    }
12658
12659    #[test]
12660    fn run_processes_shutdown_task_results_with_effect_queue_backend() {
12661        use std::sync::{
12662            Arc,
12663            atomic::{AtomicUsize, Ordering},
12664        };
12665
12666        struct ShutdownTaskModel {
12667            shutdowns: Arc<AtomicUsize>,
12668        }
12669
12670        #[derive(Debug, Clone, Copy)]
12671        enum ShutdownTaskMsg {
12672            Quit,
12673            ShutdownRan,
12674        }
12675
12676        impl From<Event> for ShutdownTaskMsg {
12677            fn from(_: Event) -> Self {
12678                ShutdownTaskMsg::Quit
12679            }
12680        }
12681
12682        impl Model for ShutdownTaskModel {
12683            type Message = ShutdownTaskMsg;
12684
12685            fn init(&mut self) -> Cmd<Self::Message> {
12686                Cmd::quit()
12687            }
12688
12689            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
12690                match msg {
12691                    ShutdownTaskMsg::Quit => Cmd::quit(),
12692                    ShutdownTaskMsg::ShutdownRan => {
12693                        self.shutdowns.fetch_add(1, Ordering::SeqCst);
12694                        Cmd::none()
12695                    }
12696                }
12697            }
12698
12699            fn view(&self, _frame: &mut Frame) {}
12700
12701            fn on_shutdown(&mut self) -> Cmd<Self::Message> {
12702                Cmd::task(|| ShutdownTaskMsg::ShutdownRan)
12703            }
12704        }
12705
12706        let shutdowns = Arc::new(AtomicUsize::new(0));
12707        let mut program = headless_program_with_config(
12708            ShutdownTaskModel {
12709                shutdowns: Arc::clone(&shutdowns),
12710            },
12711            ProgramConfig::default().with_effect_queue(
12712                EffectQueueConfig::default().with_backend(TaskExecutorBackend::EffectQueue),
12713            ),
12714        );
12715
12716        program.run().expect("program run");
12717
12718        assert_eq!(shutdowns.load(Ordering::SeqCst), 1);
12719    }
12720
12721    #[test]
12722    fn shutdown_task_results_do_not_spawn_follow_up_tasks_after_executor_shutdown() {
12723        use std::sync::{
12724            Arc,
12725            atomic::{AtomicUsize, Ordering},
12726        };
12727
12728        struct ShutdownTaskModel {
12729            shutdowns: Arc<AtomicUsize>,
12730            follow_up_runs: Arc<AtomicUsize>,
12731        }
12732
12733        #[derive(Debug, Clone, Copy)]
12734        enum ShutdownTaskMsg {
12735            Quit,
12736            ShutdownRan,
12737            FollowUp,
12738        }
12739
12740        impl From<Event> for ShutdownTaskMsg {
12741            fn from(_: Event) -> Self {
12742                ShutdownTaskMsg::Quit
12743            }
12744        }
12745
12746        impl Model for ShutdownTaskModel {
12747            type Message = ShutdownTaskMsg;
12748
12749            fn init(&mut self) -> Cmd<Self::Message> {
12750                Cmd::quit()
12751            }
12752
12753            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
12754                match msg {
12755                    ShutdownTaskMsg::Quit => Cmd::quit(),
12756                    ShutdownTaskMsg::ShutdownRan => {
12757                        self.shutdowns.fetch_add(1, Ordering::SeqCst);
12758                        let follow_up_runs = Arc::clone(&self.follow_up_runs);
12759                        Cmd::task(move || {
12760                            follow_up_runs.fetch_add(1, Ordering::SeqCst);
12761                            ShutdownTaskMsg::FollowUp
12762                        })
12763                    }
12764                    ShutdownTaskMsg::FollowUp => {
12765                        self.follow_up_runs.fetch_add(1, Ordering::SeqCst);
12766                        Cmd::none()
12767                    }
12768                }
12769            }
12770
12771            fn view(&self, _frame: &mut Frame) {}
12772
12773            fn on_shutdown(&mut self) -> Cmd<Self::Message> {
12774                Cmd::task(|| ShutdownTaskMsg::ShutdownRan)
12775            }
12776        }
12777
12778        let shutdowns = Arc::new(AtomicUsize::new(0));
12779        let follow_up_runs = Arc::new(AtomicUsize::new(0));
12780        let mut program = headless_program_with_config(
12781            ShutdownTaskModel {
12782                shutdowns: Arc::clone(&shutdowns),
12783                follow_up_runs: Arc::clone(&follow_up_runs),
12784            },
12785            ProgramConfig::default(),
12786        );
12787
12788        program.run().expect("program run");
12789
12790        assert_eq!(shutdowns.load(Ordering::SeqCst), 1);
12791        assert_eq!(follow_up_runs.load(Ordering::SeqCst), 0);
12792    }
12793
12794    #[test]
12795    fn run_quit_from_init_skips_initial_render_and_subscription_start() {
12796        use crate::subscription::{StopSignal, SubId, Subscription};
12797
12798        struct InitQuitModel {
12799            render_calls: Arc<AtomicUsize>,
12800            subscription_starts: Arc<AtomicUsize>,
12801        }
12802
12803        #[derive(Debug, Clone, Copy)]
12804        enum InitQuitMsg {
12805            Noop,
12806        }
12807
12808        impl From<Event> for InitQuitMsg {
12809            fn from(_: Event) -> Self {
12810                Self::Noop
12811            }
12812        }
12813
12814        impl Model for InitQuitModel {
12815            type Message = InitQuitMsg;
12816
12817            fn init(&mut self) -> Cmd<Self::Message> {
12818                Cmd::quit()
12819            }
12820
12821            fn update(&mut self, _: Self::Message) -> Cmd<Self::Message> {
12822                Cmd::none()
12823            }
12824
12825            fn view(&self, _frame: &mut Frame) {
12826                self.render_calls.fetch_add(1, Ordering::SeqCst);
12827            }
12828
12829            fn subscriptions(&self) -> Vec<Box<dyn Subscription<Self::Message>>> {
12830                vec![Box::new(InitQuitSubscription {
12831                    starts: Arc::clone(&self.subscription_starts),
12832                })]
12833            }
12834        }
12835
12836        struct InitQuitSubscription {
12837            starts: Arc<AtomicUsize>,
12838        }
12839
12840        impl Subscription<InitQuitMsg> for InitQuitSubscription {
12841            fn id(&self) -> SubId {
12842                1
12843            }
12844
12845            fn run(&self, _sender: mpsc::Sender<InitQuitMsg>, stop: StopSignal) {
12846                self.starts.fetch_add(1, Ordering::SeqCst);
12847                let _ = stop.wait_timeout(Duration::from_millis(10));
12848            }
12849        }
12850
12851        let render_calls = Arc::new(AtomicUsize::new(0));
12852        let subscription_starts = Arc::new(AtomicUsize::new(0));
12853        let mut program = headless_program_with_config(
12854            InitQuitModel {
12855                render_calls: Arc::clone(&render_calls),
12856                subscription_starts: Arc::clone(&subscription_starts),
12857            },
12858            ProgramConfig::default(),
12859        );
12860
12861        program.run().expect("program run");
12862
12863        assert_eq!(render_calls.load(Ordering::SeqCst), 0);
12864        assert_eq!(subscription_starts.load(Ordering::SeqCst), 0);
12865    }
12866
12867    #[test]
12868    fn run_invokes_on_shutdown_before_returning_signal_error() {
12869        use std::sync::{
12870            Arc,
12871            atomic::{AtomicUsize, Ordering},
12872        };
12873
12874        struct ShutdownModel {
12875            shutdowns: Arc<AtomicUsize>,
12876        }
12877
12878        #[derive(Debug, Clone, Copy)]
12879        enum ShutdownMsg {
12880            Noop,
12881            ShutdownRan,
12882        }
12883
12884        impl From<Event> for ShutdownMsg {
12885            fn from(_: Event) -> Self {
12886                ShutdownMsg::Noop
12887            }
12888        }
12889
12890        impl Model for ShutdownModel {
12891            type Message = ShutdownMsg;
12892
12893            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
12894                match msg {
12895                    ShutdownMsg::Noop => Cmd::none(),
12896                    ShutdownMsg::ShutdownRan => {
12897                        self.shutdowns.fetch_add(1, Ordering::SeqCst);
12898                        Cmd::none()
12899                    }
12900                }
12901            }
12902
12903            fn view(&self, _frame: &mut Frame) {}
12904
12905            fn on_shutdown(&mut self) -> Cmd<Self::Message> {
12906                Cmd::msg(ShutdownMsg::ShutdownRan)
12907            }
12908        }
12909
12910        let shutdowns = Arc::new(AtomicUsize::new(0));
12911        let mut program = headless_signal_program_with_config(
12912            ShutdownModel {
12913                shutdowns: Arc::clone(&shutdowns),
12914            },
12915            ProgramConfig::default().with_signal_interception(true),
12916        );
12917
12918        program.inject_termination_signal(2);
12919        let err = program.run().expect_err("signal should stop runtime");
12920
12921        assert_eq!(shutdowns.load(Ordering::SeqCst), 1);
12922        assert_eq!(signal_termination_from_error(&err), Some(2));
12923        assert_eq!(program.pending_termination_signal(), None);
12924    }
12925
12926    /// Regression test for the cross-test signal race: two headless programs
12927    /// running concurrently, each with its own injected signal, must both
12928    /// terminate with their own signal. Before the per-program slot existed,
12929    /// any other test constructing or finishing a headless program cleared
12930    /// the process-global slot and left the loop waiting forever.
12931    #[test]
12932    fn two_concurrent_headless_programs_with_independent_pending_signals_both_terminate() {
12933        fn run_with_signal(signal: i32) -> Option<i32> {
12934            let mut program = headless_signal_program_with_config(
12935                TestModel { value: 0 },
12936                ProgramConfig::default().with_signal_interception(true),
12937            );
12938            program.inject_termination_signal(signal);
12939            let err = program.run().expect_err("signal should stop runtime");
12940            assert_eq!(program.pending_termination_signal(), None);
12941            signal_termination_from_error(&err)
12942        }
12943
12944        let sigint = std::thread::spawn(|| run_with_signal(2));
12945        let sigterm = std::thread::spawn(|| run_with_signal(15));
12946        // A third program without a pending signal must not observe either.
12947        let clean = std::thread::spawn(|| {
12948            let program = headless_signal_program_with_config(
12949                TestModel { value: 0 },
12950                ProgramConfig::default().with_signal_interception(true),
12951            );
12952            program.observed_termination_signal()
12953        });
12954
12955        assert_eq!(sigint.join().expect("sigint thread"), Some(2));
12956        assert_eq!(sigterm.join().expect("sigterm thread"), Some(15));
12957        assert_eq!(clean.join().expect("clean thread"), None);
12958    }
12959
12960    /// `DEFAULT_BACKEND` must agree with the cfg predicates that select the
12961    /// `AppBuilder::run` dispatch, so consumers can trust it to describe what
12962    /// `run()` will do in their build.
12963    #[test]
12964    fn default_backend_constant_matches_cfg() {
12965        let expected = if cfg!(all(feature = "native-backend", unix)) {
12966            "native"
12967        } else if cfg!(feature = "crossterm-compat") {
12968            "crossterm"
12969        } else {
12970            "none"
12971        };
12972        assert_eq!(DEFAULT_BACKEND, expected);
12973        assert!(NO_BACKEND_MESSAGE.contains("native-backend"));
12974        assert!(NO_BACKEND_MESSAGE.contains("crossterm-compat"));
12975    }
12976
12977    /// Without a compiled backend, `run()` must fail up front with an error
12978    /// that names the features to enable instead of pretending to run.
12979    #[cfg(not(any(all(feature = "native-backend", unix), feature = "crossterm-compat")))]
12980    #[test]
12981    fn run_without_backend_reports_missing_features() {
12982        let err = App::new(TestModel { value: 0 })
12983            .run()
12984            .expect_err("no backend compiled");
12985        assert_eq!(err.kind(), io::ErrorKind::Unsupported);
12986        assert_eq!(err.to_string(), NO_BACKEND_MESSAGE);
12987        let err = App::new(TestModel { value: 0 })
12988            .run_crossterm()
12989            .expect_err("crossterm not compiled");
12990        assert_eq!(err.kind(), io::ErrorKind::Unsupported);
12991        assert!(err.to_string().contains("crossterm-compat"));
12992    }
12993
12994    #[test]
12995    fn inject_termination_signal_first_signal_wins() {
12996        let program = headless_signal_program_with_config(
12997            TestModel { value: 0 },
12998            ProgramConfig::default().with_signal_interception(true),
12999        );
13000        assert_eq!(program.pending_termination_signal(), None);
13001        program.inject_termination_signal(15);
13002        program.inject_termination_signal(2);
13003        assert_eq!(program.pending_termination_signal(), Some(15));
13004        assert_eq!(program.observed_termination_signal(), Some(15));
13005
13006        // Interception disabled: the slot is still recorded but not observed.
13007        let quiet = headless_signal_program_with_config(
13008            TestModel { value: 0 },
13009            ProgramConfig::default().with_signal_interception(false),
13010        );
13011        quiet.inject_termination_signal(2);
13012        assert_eq!(quiet.pending_termination_signal(), Some(2));
13013        assert_eq!(quiet.observed_termination_signal(), None);
13014    }
13015
13016    #[test]
13017    fn run_pending_signal_skips_initial_render_and_subscription_start() {
13018        use crate::subscription::{StopSignal, SubId, Subscription};
13019
13020        struct SignalStopModel {
13021            render_calls: Arc<AtomicUsize>,
13022            subscription_starts: Arc<AtomicUsize>,
13023        }
13024
13025        #[derive(Debug, Clone, Copy)]
13026        enum SignalStopMsg {
13027            Noop,
13028        }
13029
13030        impl From<Event> for SignalStopMsg {
13031            fn from(_: Event) -> Self {
13032                Self::Noop
13033            }
13034        }
13035
13036        impl Model for SignalStopModel {
13037            type Message = SignalStopMsg;
13038
13039            fn update(&mut self, _: Self::Message) -> Cmd<Self::Message> {
13040                Cmd::none()
13041            }
13042
13043            fn view(&self, _frame: &mut Frame) {
13044                self.render_calls.fetch_add(1, Ordering::SeqCst);
13045            }
13046
13047            fn subscriptions(&self) -> Vec<Box<dyn Subscription<Self::Message>>> {
13048                vec![Box::new(SignalStopSubscription {
13049                    starts: Arc::clone(&self.subscription_starts),
13050                })]
13051            }
13052        }
13053
13054        struct SignalStopSubscription {
13055            starts: Arc<AtomicUsize>,
13056        }
13057
13058        impl Subscription<SignalStopMsg> for SignalStopSubscription {
13059            fn id(&self) -> SubId {
13060                11
13061            }
13062
13063            fn run(&self, _sender: mpsc::Sender<SignalStopMsg>, stop: StopSignal) {
13064                self.starts.fetch_add(1, Ordering::SeqCst);
13065                let _ = stop.wait_timeout(Duration::from_millis(10));
13066            }
13067        }
13068
13069        let render_calls = Arc::new(AtomicUsize::new(0));
13070        let subscription_starts = Arc::new(AtomicUsize::new(0));
13071        let mut program = headless_signal_program_with_config(
13072            SignalStopModel {
13073                render_calls: Arc::clone(&render_calls),
13074                subscription_starts: Arc::clone(&subscription_starts),
13075            },
13076            ProgramConfig::default().with_signal_interception(true),
13077        );
13078
13079        program.inject_termination_signal(15);
13080        let err = program.run().expect_err("signal should stop runtime");
13081
13082        assert_eq!(signal_termination_from_error(&err), Some(15));
13083        assert_eq!(render_calls.load(Ordering::SeqCst), 0);
13084        assert_eq!(subscription_starts.load(Ordering::SeqCst), 0);
13085        assert_eq!(program.pending_termination_signal(), None);
13086    }
13087
13088    #[test]
13089    fn headless_should_tick_and_timeout_behaviors() {
13090        let mut program =
13091            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
13092        program.tick_rate = Some(Duration::from_millis(5));
13093        program.last_tick = Instant::now() - Duration::from_millis(10);
13094
13095        assert!(program.should_tick());
13096        assert!(!program.should_tick());
13097
13098        let timeout = program.effective_timeout();
13099        assert!(timeout <= Duration::from_millis(5));
13100
13101        program.tick_rate = None;
13102        program.poll_timeout = Duration::from_millis(33);
13103        assert_eq!(program.effective_timeout(), Duration::from_millis(33));
13104    }
13105
13106    #[test]
13107    fn headless_effective_timeout_respects_resize_coalescer() {
13108        let mut config = ProgramConfig::default().with_resize_behavior(ResizeBehavior::Throttled);
13109        config.resize_coalescer.steady_delay_ms = 0;
13110        config.resize_coalescer.burst_delay_ms = 0;
13111
13112        let mut program = headless_program_with_config(TestModel { value: 0 }, config);
13113        program.tick_rate = Some(Duration::from_millis(50));
13114
13115        program.resize_coalescer.handle_resize(120, 40);
13116        assert!(program.resize_coalescer.has_pending());
13117
13118        let timeout = program.effective_timeout();
13119        assert_eq!(timeout, Duration::ZERO);
13120    }
13121
13122    #[test]
13123    fn headless_ui_height_remeasure_clears_auto_height() {
13124        let mut config = ProgramConfig::inline_auto(2, 6);
13125        config.inline_auto_remeasure = Some(InlineAutoRemeasureConfig::default());
13126
13127        let mut program = headless_program_with_config(TestModel { value: 0 }, config);
13128        program.dirty = false;
13129        program.writer.set_auto_ui_height(5);
13130
13131        assert_eq!(program.writer.auto_ui_height(), Some(5));
13132        program.request_ui_height_remeasure();
13133
13134        assert_eq!(program.writer.auto_ui_height(), None);
13135        assert!(program.dirty);
13136    }
13137
13138    #[test]
13139    fn headless_recording_lifecycle_and_locale_change() {
13140        let mut program =
13141            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
13142        program.dirty = false;
13143
13144        program.start_recording("demo");
13145        assert!(program.is_recording());
13146        let recorded = program.stop_recording();
13147        assert!(recorded.is_some());
13148        assert!(!program.is_recording());
13149
13150        let prev_dirty = program.dirty;
13151        program.locale_context.set_locale("fr");
13152        program.check_locale_change();
13153        assert!(program.dirty || prev_dirty);
13154    }
13155
13156    #[test]
13157    fn headless_render_frame_marks_clean_and_sets_diff() {
13158        struct RenderModel;
13159
13160        #[derive(Debug)]
13161        enum RenderMsg {
13162            Noop,
13163        }
13164
13165        impl From<Event> for RenderMsg {
13166            fn from(_: Event) -> Self {
13167                RenderMsg::Noop
13168            }
13169        }
13170
13171        impl Model for RenderModel {
13172            type Message = RenderMsg;
13173
13174            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
13175                Cmd::none()
13176            }
13177
13178            fn view(&self, frame: &mut Frame) {
13179                frame.buffer.set_raw(0, 0, Cell::from_char('X'));
13180            }
13181        }
13182
13183        let mut program = headless_program_with_config(RenderModel, ProgramConfig::default());
13184        program.render_frame().expect("render frame");
13185
13186        assert!(!program.dirty);
13187        assert!(program.writer.last_diff_strategy().is_some());
13188        assert_eq!(program.frame_idx, 1);
13189    }
13190
13191    /// CONTRACT (bd-1za0z F2): when a guardrail alert fires during
13192    /// render_frame, a `guardrail_snapshot` evidence row is exported through
13193    /// the configured sink — GuardrailSnapshot::to_jsonl is live production
13194    /// observability, not dead code.
13195    #[test]
13196    fn headless_render_frame_emits_guardrail_snapshot_evidence_on_alert() {
13197        struct AlertModel;
13198
13199        #[derive(Debug)]
13200        enum AlertMsg {
13201            Noop,
13202        }
13203
13204        impl From<Event> for AlertMsg {
13205            fn from(_: Event) -> Self {
13206                AlertMsg::Noop
13207            }
13208        }
13209
13210        impl Model for AlertModel {
13211            type Message = AlertMsg;
13212
13213            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
13214                Cmd::none()
13215            }
13216
13217            fn view(&self, frame: &mut Frame) {
13218                frame.buffer.set_raw(0, 0, Cell::from_char('X'));
13219            }
13220        }
13221
13222        let evidence_path = temp_evidence_path("guardrail_snapshot");
13223        let config = ProgramConfig {
13224            guardrails: GuardrailsConfig {
13225                // Soft limit of one byte: the very first frame alerts, so
13226                // no memory pressure needs to be manufactured.
13227                memory: MemoryBudgetConfig {
13228                    soft_limit_bytes: 1,
13229                    ..MemoryBudgetConfig::default()
13230                },
13231                queue: QueueConfig::default(),
13232            },
13233            evidence_sink: EvidenceSinkConfig::enabled_file(&evidence_path),
13234            ..Default::default()
13235        };
13236
13237        let mut program = headless_program_with_config(AlertModel, config);
13238        program.dirty = true;
13239        program.render_frame().expect("render frame with alert");
13240
13241        let contents =
13242            std::fs::read_to_string(&evidence_path).expect("guardrail evidence file written");
13243        let _ = std::fs::remove_file(&evidence_path);
13244        assert!(
13245            contents.contains(r#""event":"guardrail_snapshot""#),
13246            "alerting frame must export a guardrail_snapshot row; got: {contents}"
13247        );
13248        assert!(
13249            contents.contains(r#""mem_soft_violations":"#),
13250            "snapshot row must carry the violation counters"
13251        );
13252    }
13253
13254    /// The inline-auto VOI sampler's decision is exported through the evidence
13255    /// sink (`voi_decision`), not only through the in-process telemetry
13256    /// snapshot, so operators can grep why a remeasure did or did not happen.
13257    #[test]
13258    fn headless_inline_auto_exports_voi_decision_evidence() {
13259        struct TallModel;
13260
13261        #[derive(Debug)]
13262        enum TallMsg {
13263            Noop,
13264        }
13265
13266        impl From<Event> for TallMsg {
13267            fn from(_: Event) -> Self {
13268                TallMsg::Noop
13269            }
13270        }
13271
13272        impl Model for TallModel {
13273            type Message = TallMsg;
13274
13275            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
13276                Cmd::none()
13277            }
13278
13279            fn view(&self, frame: &mut Frame) {
13280                frame.buffer.set_raw(0, 0, Cell::from_char('V'));
13281            }
13282        }
13283
13284        let evidence_path = temp_evidence_path("voi_decision");
13285        let config = ProgramConfig::inline_auto(1, 6)
13286            .with_evidence_sink(EvidenceSinkConfig::enabled_file(&evidence_path));
13287        assert!(config.inline_auto_remeasure.is_some());
13288
13289        let mut program = headless_program_with_config(TallModel, config);
13290        for _ in 0..3 {
13291            program.dirty = true;
13292            program.render_frame().expect("render inline-auto frame");
13293        }
13294
13295        let contents = std::fs::read_to_string(&evidence_path).expect("evidence file written");
13296        let _ = std::fs::remove_file(&evidence_path);
13297        assert!(
13298            contents.contains(r#""event":"voi_decision""#),
13299            "inline-auto frames must export the VOI decision; got: {contents}"
13300        );
13301        assert!(
13302            contents.contains(r#""should_sample":"#) && contents.contains(r#""voi_gain":"#),
13303            "voi_decision row must carry the sampler reasoning"
13304        );
13305    }
13306
13307    /// Bytes the startup probes swallowed (a click and a key sent while the
13308    /// terminal was being probed) are parsed and delivered to the model in
13309    /// order before the main loop; draining twice delivers nothing more.
13310    #[test]
13311    fn startup_input_recovered_from_probes_reaches_the_model() {
13312        use ftui_core::event::{KeyCode, MouseEventKind};
13313
13314        #[derive(Default)]
13315        struct RecorderModel {
13316            seen: Vec<String>,
13317            keys: Vec<KeyEvent>,
13318        }
13319
13320        #[derive(Debug)]
13321        enum RecMsg {
13322            Event(Event),
13323        }
13324
13325        impl From<Event> for RecMsg {
13326            fn from(event: Event) -> Self {
13327                RecMsg::Event(event)
13328            }
13329        }
13330
13331        impl Model for RecorderModel {
13332            type Message = RecMsg;
13333
13334            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
13335                match msg {
13336                    RecMsg::Event(Event::Mouse(mouse)) => {
13337                        self.seen
13338                            .push(format!("mouse:{:?}@{},{}", mouse.kind, mouse.x, mouse.y));
13339                    }
13340                    RecMsg::Event(Event::Key(key)) => {
13341                        self.seen.push(format!("key:{:?}", key.code));
13342                        self.keys.push(key);
13343                    }
13344                    RecMsg::Event(_) => {}
13345                }
13346                Cmd::none()
13347            }
13348
13349            fn view(&self, frame: &mut Frame) {
13350                frame.buffer.set_raw(0, 0, Cell::from_char('R'));
13351            }
13352        }
13353
13354        let mut program =
13355            headless_program_with_config(RecorderModel::default(), ProgramConfig::default());
13356        // SGR mouse press + release at column 2 row 1, then a typed `q`.
13357        program.queue_startup_input(b"\x1b[<0;2;1M\x1b[<0;2;1mq");
13358        assert_eq!(program.startup_events.len(), 3);
13359        program
13360            .drain_startup_events()
13361            .expect("deliver startup events");
13362        assert!(program.startup_events.is_empty());
13363        let seen = program.model().seen.clone();
13364        assert_eq!(seen.len(), 3, "{seen:?}");
13365        assert!(
13366            seen[0].starts_with(&format!(
13367                "mouse:{:?}",
13368                MouseEventKind::Down(ftui_core::event::MouseButton::Left)
13369            )) && seen[0].ends_with("@1,0"),
13370            "{seen:?}"
13371        );
13372        assert!(seen[1].starts_with("mouse:Up"), "{seen:?}");
13373        assert_eq!(seen[2], format!("key:{:?}", KeyCode::Char('q')));
13374
13375        program.drain_startup_events().expect("nothing left");
13376        assert_eq!(program.model().seen.len(), 3);
13377        program.queue_startup_input(b"");
13378        assert!(program.startup_events.is_empty());
13379
13380        // A probe can consume the final lone Escape before timing out. The
13381        // startup handoff must deliver that key, even with no subsequent input.
13382        program.queue_startup_input(b"\x1b[<0;2;1M\x1b");
13383        program
13384            .drain_startup_events()
13385            .expect("deliver trailing ESC");
13386        assert_eq!(program.model().seen.len(), 5);
13387        assert_eq!(program.model().seen[4], "key:Escape");
13388        program.drain_startup_events().expect("no duplicate ESC");
13389        assert_eq!(program.model().seen.len(), 5);
13390
13391        // Recovery may arrive in chunks. A pending prefix is not a key until
13392        // the batch is drained, so arrows and Alt+UTF-8 keep their identity.
13393        program.queue_startup_input(b"\x1b");
13394        program.queue_startup_input(b"[C\x1b\xc3");
13395        program.queue_startup_input(b"\xa9");
13396        program.drain_startup_events().expect("fragmented recovery");
13397        assert_eq!(&program.model().seen[5..], &["key:Right", "key:Char('é')"]);
13398        assert_eq!(
13399            program.model().keys.last(),
13400            Some(
13401                &KeyEvent::new(KeyCode::Char('é')).with_modifiers(ftui_core::event::Modifiers::ALT)
13402            )
13403        );
13404    }
13405
13406    /// With `ProgramConfig::accessibility` set, every rendered frame builds
13407    /// an accessibility tree from the nodes the view pushes, diffs it against
13408    /// the previous frame and exports the resulting announcements as
13409    /// evidence rows; without it nothing is collected.
13410    #[test]
13411    fn headless_accessibility_builds_tree_and_exports_announcements() {
13412        use ftui_a11y::node::{A11yNodeInfo, A11yRole, A11yState, LiveRegion};
13413        use ftui_a11y::tree::AnnouncementReason;
13414        use ftui_core::geometry::Rect;
13415
13416        struct A11yModel {
13417            frames: std::cell::Cell<u32>,
13418            hook_calls: u32,
13419            last_dump: String,
13420        }
13421
13422        #[derive(Debug)]
13423        enum A11yMsg {
13424            Noop,
13425        }
13426
13427        impl From<Event> for A11yMsg {
13428            fn from(_: Event) -> Self {
13429                A11yMsg::Noop
13430            }
13431        }
13432
13433        impl Model for A11yModel {
13434            type Message = A11yMsg;
13435
13436            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
13437                Cmd::none()
13438            }
13439
13440            fn on_accessibility(&mut self, a11y: AccessibilityFrame<'_>) -> Cmd<Self::Message> {
13441                self.hook_calls += 1;
13442                self.last_dump = a11y.dump();
13443                Cmd::none()
13444            }
13445
13446            fn view(&self, frame: &mut Frame) {
13447                let n = self.frames.get();
13448                self.frames.set(n + 1);
13449                frame.buffer.set_raw(0, 0, Cell::from_char('A'));
13450                frame.push_a11y(
13451                    A11yNodeInfo::new(1, A11yRole::Button, Rect::new(0, 0, 10, 1))
13452                        .with_name("OK")
13453                        .with_state(A11yState {
13454                            focused: true,
13455                            ..A11yState::default()
13456                        }),
13457                );
13458                if let Some(builder) = frame.a11y.as_deref_mut() {
13459                    builder.set_focused(Some(1));
13460                }
13461                // The second frame adds a polite live region.
13462                if n >= 1 {
13463                    frame.push_a11y(
13464                        A11yNodeInfo::new(2, A11yRole::Label, Rect::new(0, 1, 10, 1))
13465                            .with_name("Saved")
13466                            .with_live_region(LiveRegion::Polite),
13467                    );
13468                }
13469            }
13470        }
13471
13472        // Off by default: nothing is collected even though the view pushes.
13473        let mut off = headless_program_with_config(
13474            A11yModel {
13475                frames: std::cell::Cell::new(0),
13476                hook_calls: 0,
13477                last_dump: String::new(),
13478            },
13479            ProgramConfig::default(),
13480        );
13481        off.dirty = true;
13482        off.render_frame().expect("render without accessibility");
13483        assert!(off.accessibility_tree().is_none());
13484        assert!(off.accessibility_order().is_empty());
13485        assert!(off.accessibility_announcements().is_empty());
13486        assert!(off.accessibility_dump().is_none());
13487        assert_eq!(off.model.hook_calls, 0);
13488
13489        let evidence_path = temp_evidence_path("a11y");
13490        let config = ProgramConfig::default()
13491            .with_accessibility(ScreenReaderPolicy::default())
13492            .with_evidence_sink(EvidenceSinkConfig::enabled_file(&evidence_path));
13493        let mut program = headless_program_with_config(
13494            A11yModel {
13495                frames: std::cell::Cell::new(0),
13496                hook_calls: 0,
13497                last_dump: String::new(),
13498            },
13499            config,
13500        );
13501
13502        program.dirty = true;
13503        program.render_frame().expect("render first a11y frame");
13504        let tree = program
13505            .accessibility_tree()
13506            .expect("tree after first frame");
13507        assert_eq!(tree.node_count(), 1);
13508        assert_eq!(tree.focused_id(), Some(1));
13509        assert_eq!(program.accessibility_order(), &[1]);
13510        let first: Vec<AnnouncementReason> = program
13511            .accessibility_announcements()
13512            .iter()
13513            .map(|a| a.reason)
13514            .collect();
13515        assert!(
13516            first.contains(&AnnouncementReason::FocusChanged),
13517            "first frame must announce the focused button; got {first:?}"
13518        );
13519
13520        program.dirty = true;
13521        program.render_frame().expect("render second a11y frame");
13522        let tree = program
13523            .accessibility_tree()
13524            .expect("tree after second frame");
13525        assert_eq!(tree.node_count(), 2);
13526        assert_eq!(program.accessibility_order(), &[1, 2]);
13527        let second: Vec<(AnnouncementReason, String)> = program
13528            .accessibility_announcements()
13529            .iter()
13530            .map(|a| (a.reason, a.text.clone()))
13531            .collect();
13532        assert!(
13533            second.iter().any(
13534                |(reason, text)| *reason == AnnouncementReason::LiveRegionAdded
13535                    && text.contains("Saved")
13536            ),
13537            "second frame must announce the new live region; got {second:?}"
13538        );
13539        let dump = program.accessibility_dump().expect("dump when enabled");
13540        assert!(
13541            dump.contains("OK") && dump.contains("Saved"),
13542            "dump: {dump}"
13543        );
13544
13545        // A frame with no tree change produces no announcements.
13546        program.dirty = true;
13547        program.render_frame().expect("render third a11y frame");
13548        assert!(program.accessibility_announcements().is_empty());
13549        // The hook fired for the two changing frames only, saw the dump, and
13550        // requested one more frame each time.
13551        assert_eq!(program.model.hook_calls, 2);
13552        assert!(program.model.last_dump.contains("Saved"));
13553        assert!(
13554            !program.dirty,
13555            "an unchanged frame must not request a redraw"
13556        );
13557
13558        let contents = std::fs::read_to_string(&evidence_path).expect("evidence file written");
13559        let _ = std::fs::remove_file(&evidence_path);
13560        assert!(
13561            contents.contains(r#""event":"a11y_tree""#),
13562            "tree changes must be exported; got: {contents}"
13563        );
13564        assert!(
13565            contents.contains(r#""event":"a11y_announcement""#)
13566                && contents.contains(r#""reason":"LiveRegionAdded""#)
13567                && contents.contains(r#""urgency":"polite""#),
13568            "announcements must be exported with reason and urgency; got: {contents}"
13569        );
13570        assert_eq!(
13571            contents.matches(r#""event":"a11y_tree""#).count(),
13572            2,
13573            "only the two changing frames export a11y_tree rows; got: {contents}"
13574        );
13575        assert!(
13576            !contents.contains("Saved"),
13577            "ordinary evidence must not contain accessibility content"
13578        );
13579    }
13580
13581    const A11Y_PRIVACY_CANARY: &str = "A11Y_SECRET_450512_\"é\\\n日";
13582    // Screen-reader text already normalizes whitespace before delivery.
13583    const A11Y_NORMALIZED_CANARY: &str = "A11Y_SECRET_450512_\"é\\ 日";
13584
13585    fn exercise_a11y_privacy(config: ProgramConfig) -> (Vec<String>, usize) {
13586        use ftui_a11y::node::{A11yNodeInfo, A11yRole, A11yState, LiveRegion};
13587        use ftui_core::geometry::Rect;
13588
13589        #[derive(Default)]
13590        struct ContentModel {
13591            received: Vec<String>,
13592            dropped: usize,
13593        }
13594
13595        impl Model for ContentModel {
13596            type Message = Event;
13597
13598            fn update(&mut self, _: Event) -> Cmd<Event> {
13599                Cmd::none()
13600            }
13601
13602            fn view(&self, frame: &mut Frame) {
13603                frame.buffer.set_raw(0, 0, Cell::from_char('A'));
13604                for (index, (role, source)) in [
13605                    (A11yRole::TextInput, "input"),
13606                    (A11yRole::TextInput, "textarea"),
13607                    (A11yRole::Label, "label"),
13608                    (A11yRole::Dialog, "modal"),
13609                    (A11yRole::Label, "live-region"),
13610                ]
13611                .into_iter()
13612                .enumerate()
13613                {
13614                    frame.push_a11y(
13615                        A11yNodeInfo::new(
13616                            index as u64 + 1,
13617                            role,
13618                            Rect::new(0, index as u16, 20, 1),
13619                        )
13620                        .with_name(format!("{source}: {A11Y_PRIVACY_CANARY}"))
13621                        .with_state(A11yState {
13622                            focused: index == 0,
13623                            ..A11yState::default()
13624                        })
13625                        .with_live_region(LiveRegion::Polite),
13626                    );
13627                }
13628            }
13629
13630            fn on_accessibility(&mut self, frame: AccessibilityFrame<'_>) -> Cmd<Event> {
13631                self.received
13632                    .extend(frame.announcements.iter().map(|a| a.text.clone()));
13633                self.dropped += frame.dropped;
13634                Cmd::none()
13635            }
13636        }
13637
13638        let mut program = headless_program_with_config(ContentModel::default(), config);
13639        program.render_frame().expect("render private a11y content");
13640        let received = program.model.received.clone();
13641        let dropped = program.model.dropped;
13642        program.render_frame().expect("render unchanged a11y tree");
13643        assert_eq!(
13644            program.model.received, received,
13645            "no duplicate announcements"
13646        );
13647        (received, dropped)
13648    }
13649
13650    #[derive(Clone, Default)]
13651    struct A11yTraceCapture(std::sync::Arc<std::sync::Mutex<String>>);
13652
13653    impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for A11yTraceCapture {
13654        fn on_event(
13655            &self,
13656            event: &tracing::Event<'_>,
13657            _: tracing_subscriber::layer::Context<'_, S>,
13658        ) {
13659            struct Fields<'a>(&'a mut String);
13660            impl tracing::field::Visit for Fields<'_> {
13661                fn record_debug(
13662                    &mut self,
13663                    field: &tracing::field::Field,
13664                    value: &dyn std::fmt::Debug,
13665                ) {
13666                    use std::fmt::Write as _;
13667                    write!(self.0, "{}={value:?};", field.name()).expect("write capture");
13668                }
13669            }
13670            let mut output = self.0.lock().expect("capture lock");
13671            output.push_str(event.metadata().target());
13672            event.record(&mut Fields(&mut output));
13673            output.push('\n');
13674        }
13675    }
13676
13677    #[test]
13678    fn headless_a11y_privacy_preserves_local_content_and_explicit_capture() {
13679        use tracing_subscriber::prelude::*;
13680
13681        for enabled in [false, true] {
13682            for include_text in [false, true] {
13683                for max_announcements in [2, 8] {
13684                    let path = temp_evidence_path("a11y_privacy");
13685                    let capture = A11yTraceCapture::default();
13686                    let subscriber = tracing_subscriber::registry().with(capture.clone());
13687                    let mut config = ProgramConfig::default()
13688                        .with_accessibility_evidence_text(include_text)
13689                        .with_evidence_sink(EvidenceSinkConfig::enabled_file(&path));
13690                    if enabled {
13691                        config = config.with_accessibility(ScreenReaderPolicy {
13692                            max_announcements,
13693                            ..ScreenReaderPolicy::default()
13694                        });
13695                    }
13696                    let (local, dropped) = tracing::subscriber::with_default(subscriber, || {
13697                        exercise_a11y_privacy(config)
13698                    });
13699                    let trace = capture.0.lock().expect("capture lock").clone();
13700                    assert!(
13701                        !trace.contains("A11Y_SECRET_450512"),
13702                        "content entered tracing"
13703                    );
13704                    let contents = std::fs::read_to_string(&path).expect("read evidence");
13705                    let rows: Vec<serde_json::Value> = contents
13706                        .lines()
13707                        .map(|line| serde_json::from_str(line).expect("valid JSONL"))
13708                        .filter(|row: &serde_json::Value| row["event"] == "a11y_announcement")
13709                        .collect();
13710                    assert_eq!(rows.len(), local.len());
13711                    if enabled {
13712                        assert!(!local.is_empty(), "local accessibility received nothing");
13713                        assert!(local.len() <= max_announcements);
13714                        assert!(
13715                            local
13716                                .iter()
13717                                .all(|text| text.contains(A11Y_NORMALIZED_CANARY))
13718                        );
13719                        assert!(trace.contains("screen reader announcement"));
13720                        assert_eq!(dropped > 0, max_announcements == 2);
13721                        for (row, text) in rows.iter().zip(&local) {
13722                            assert_eq!(row["text_chars"], text.chars().count());
13723                            if include_text {
13724                                assert_eq!(row["text"], *text, "explicit content round trip");
13725                            } else {
13726                                assert!(row["text"].is_null());
13727                            }
13728                        }
13729                    } else {
13730                        assert!(local.is_empty());
13731                        assert_eq!(dropped, 0);
13732                        assert!(!trace.contains("screen reader announcement"));
13733                    }
13734                    if !include_text {
13735                        assert!(!contents.contains("A11Y_SECRET_450512"));
13736                    }
13737                }
13738            }
13739        }
13740    }
13741
13742    #[cfg(target_os = "linux")]
13743    #[test]
13744    fn headless_a11y_privacy_preserves_callback_when_evidence_write_fails() {
13745        use tracing_subscriber::prelude::*;
13746
13747        let capture = A11yTraceCapture::default();
13748        let subscriber = tracing_subscriber::registry().with(capture.clone());
13749        let config = ProgramConfig::default()
13750            .with_accessibility(ScreenReaderPolicy::default())
13751            .with_evidence_sink(EvidenceSinkConfig::enabled_file("/dev/full"));
13752        let (local, _) =
13753            tracing::subscriber::with_default(subscriber, || exercise_a11y_privacy(config));
13754        assert!(!local.is_empty());
13755        assert!(
13756            local
13757                .iter()
13758                .all(|text| text.contains(A11Y_NORMALIZED_CANARY))
13759        );
13760        let trace = capture.0.lock().expect("capture lock");
13761        assert!(trace.contains("screen reader announcement"));
13762        assert!(!trace.contains("A11Y_SECRET_450512"));
13763    }
13764
13765    #[cfg(feature = "telemetry")]
13766    #[test]
13767    fn headless_a11y_privacy_through_real_otlp_http_exporter() {
13768        use std::io::{Read as _, Write as _};
13769        use std::net::TcpListener;
13770        use std::sync::Arc;
13771        use std::sync::atomic::{AtomicBool, Ordering};
13772        use tracing_subscriber::prelude::*;
13773
13774        let listener = TcpListener::bind("127.0.0.1:0").expect("bind local collector");
13775        listener.set_nonblocking(true).expect("bounded accept");
13776        let endpoint = format!("http://{}/v1/traces", listener.local_addr().unwrap());
13777        let stop = Arc::new(AtomicBool::new(false));
13778        let collector_stop = stop.clone();
13779        let collector = std::thread::spawn(move || {
13780            let start = std::time::Instant::now();
13781            let mut payloads = Vec::new();
13782            while !collector_stop.load(Ordering::Acquire)
13783                && start.elapsed() < std::time::Duration::from_secs(30)
13784            {
13785                let (mut stream, _) = match listener.accept() {
13786                    Ok(connection) => connection,
13787                    Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
13788                        std::thread::sleep(std::time::Duration::from_millis(5));
13789                        continue;
13790                    }
13791                    Err(error) => panic!("collector accept failed: {error}"),
13792                };
13793                stream
13794                    .set_read_timeout(Some(std::time::Duration::from_secs(3)))
13795                    .expect("bounded request read");
13796                let mut request = Vec::new();
13797                let (header_end, content_len) = loop {
13798                    let mut byte = [0];
13799                    stream.read_exact(&mut byte).expect("read HTTP headers");
13800                    request.push(byte[0]);
13801                    assert!(request.len() <= 32_768, "bounded HTTP headers");
13802                    if request.ends_with(b"\r\n\r\n") {
13803                        let headers = std::str::from_utf8(&request).expect("HTTP header text");
13804                        assert!(headers.starts_with("POST /v1/traces "));
13805                        let length: usize = headers
13806                            .lines()
13807                            .filter_map(|line| line.split_once(':'))
13808                            .find(|(name, _)| name.eq_ignore_ascii_case("content-length"))
13809                            .expect("OTLP request content length")
13810                            .1
13811                            .trim()
13812                            .parse()
13813                            .expect("numeric content length");
13814                        assert!(length <= 2 * 1024 * 1024, "bounded request body");
13815                        break (request.len(), length);
13816                    }
13817                };
13818                request.resize(header_end + content_len, 0);
13819                stream
13820                    .read_exact(&mut request[header_end..])
13821                    .expect("read actual OTLP protobuf");
13822                payloads.push(request[header_end..].to_vec());
13823                stream
13824                    .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")
13825                    .expect("acknowledge export");
13826            }
13827            payloads
13828        });
13829
13830        let mut telemetry = crate::telemetry::TelemetryConfig::from_env_with(|key| match key {
13831            "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT" => Some(endpoint.clone()),
13832            "OTEL_TRACES_EXPORTER" => Some("otlp".into()),
13833            _ => None,
13834        });
13835        telemetry.processor = crate::telemetry::SpanProcessorKind::Simple;
13836        telemetry.headers.push((
13837            "User-Agent".into(),
13838            "OpenAI File Downloader, XaiImageApiFetch/1.0".into(),
13839        ));
13840        let (layer, provider) = telemetry.build_layer().expect("real OTLP exporter");
13841        let subscriber = tracing_subscriber::registry().with(layer);
13842        let evidence_path = temp_evidence_path("a11y_otlp_private");
13843        let (local, _) = tracing::subscriber::with_default(subscriber, || {
13844            let _span = tracing::info_span!("a11y_privacy_live_export").entered();
13845            exercise_a11y_privacy(
13846                ProgramConfig::default()
13847                    .with_accessibility(ScreenReaderPolicy::default())
13848                    .with_accessibility_evidence_text(true)
13849                    .with_evidence_sink(EvidenceSinkConfig::enabled_file(&evidence_path)),
13850            )
13851        });
13852        provider.force_flush().expect("flush actual export");
13853        provider.shutdown().expect("shutdown exporter");
13854        stop.store(true, Ordering::Release);
13855        let payloads = collector.join().expect("local collector finished");
13856        assert!(
13857            !local.is_empty(),
13858            "accessibility callback must receive text"
13859        );
13860        assert!(
13861            local
13862                .iter()
13863                .all(|text| text.contains(A11Y_NORMALIZED_CANARY))
13864        );
13865        assert!(!payloads.is_empty(), "zero exports is not a privacy pass");
13866        let exported = payloads.concat();
13867        let exported_text = String::from_utf8_lossy(&exported);
13868        assert!(exported_text.contains("screen reader announcement"));
13869        assert!(!exported_text.contains("A11Y_SECRET_450512"));
13870        let evidence = std::fs::read_to_string(evidence_path).expect("explicit local evidence");
13871        assert!(evidence.contains("A11Y_SECRET_450512"));
13872    }
13873
13874    /// Conformal gating is on by default, so its warm-up must be harmless:
13875    /// until `min_samples` residuals exist the prediction rests on the
13876    /// `q_default` prior, which (10 ms on top of a 16 ms baseline against a
13877    /// 16 ms budget by default; made deliberately huge here) reports `risk`,
13878    /// yet an uncalibrated verdict must never lower the degradation level.
13879    /// The evidence rows must still show that risky, uncalibrated verdict so
13880    /// the warm-up is observable.
13881    #[test]
13882    fn headless_default_config_never_degrades_during_conformal_warmup() {
13883        use ftui_render::budget::DegradationLevel;
13884
13885        struct WarmModel;
13886
13887        #[derive(Debug)]
13888        enum WarmMsg {
13889            Noop,
13890        }
13891
13892        impl From<Event> for WarmMsg {
13893            fn from(_: Event) -> Self {
13894                WarmMsg::Noop
13895            }
13896        }
13897
13898        impl Model for WarmModel {
13899            type Message = WarmMsg;
13900
13901            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
13902                Cmd::none()
13903            }
13904
13905            fn view(&self, frame: &mut Frame) {
13906                frame.buffer.set_raw(0, 0, Cell::from_char('W'));
13907            }
13908        }
13909
13910        let evidence_path = temp_evidence_path("conformal_warmup");
13911        let defaults = ProgramConfig::default()
13912            .conformal_config
13913            .expect("conformal on by default");
13914        let min_samples = defaults.min_samples;
13915        // Load-independent setup: a 5 s frame budget keeps the PID path from
13916        // degrading when the test host is busy, while a 10 s `q_default`
13917        // prior makes every uncalibrated conformal verdict risky, so the only
13918        // thing that could degrade here is the warm-up gate letting the
13919        // prior through.
13920        let config = ProgramConfig::default()
13921            .with_budget(FrameBudgetConfig {
13922                total: Duration::from_secs(5),
13923                ..FrameBudgetConfig::default()
13924            })
13925            .with_conformal_config(ConformalConfig {
13926                q_default: 10_000_000.0,
13927                ..defaults
13928            })
13929            .with_evidence_sink(EvidenceSinkConfig::enabled_file(&evidence_path));
13930        let mut program = headless_program_with_config(WarmModel, config);
13931        assert!(program.conformal_predictor.is_some());
13932
13933        for frame in 0..min_samples + 5 {
13934            program.dirty = true;
13935            program.render_frame().expect("render frame");
13936            assert_eq!(
13937                program.budget.degradation(),
13938                DegradationLevel::Full,
13939                "frame {frame}: an uncalibrated or fast frame must not degrade"
13940            );
13941        }
13942
13943        let contents = std::fs::read_to_string(&evidence_path).expect("evidence written");
13944        let _ = std::fs::remove_file(&evidence_path);
13945        let rows: Vec<&str> = contents
13946            .lines()
13947            .filter(|l| l.contains(r#""event":"budget_decision""#))
13948            .collect();
13949        assert!(
13950            rows.len() >= min_samples,
13951            "one budget_decision row per frame: {contents}"
13952        );
13953        assert!(
13954            rows.iter()
13955                .any(|r| r.contains(r#""risk":true"#) && r.contains(r#""n_b":0"#)),
13956            "the cold-start prior must be visible as an uncalibrated risky verdict: {contents}"
13957        );
13958        assert!(
13959            rows.iter()
13960                .all(|r| r.contains(r#""degradation_after":"Full""#)),
13961            "no row may record a degradation: {contents}"
13962        );
13963    }
13964
13965    #[test]
13966    fn headless_unattainable_conformal_rank_keeps_rendering_and_measuring() {
13967        use ftui_render::budget::DegradationLevel;
13968        let path = temp_evidence_path("conformal_unattainable_rank");
13969        let config = ProgramConfig::default()
13970            .with_budget(FrameBudgetConfig::with_total(Duration::from_secs(5)))
13971            .with_conformal_config(ConformalConfig {
13972                alpha: 0.01,
13973                min_samples: 20,
13974                window_size: 128,
13975                q_default: 10_000_000.0,
13976            })
13977            .with_evidence_sink(EvidenceSinkConfig::enabled_file(&path));
13978        let mut program = headless_program_with_config(TestModel { value: 0 }, config);
13979        for _ in 0..105 {
13980            program.dirty = true;
13981            program
13982                .render_frame()
13983                .expect("render while calibration grows");
13984            assert_eq!(program.budget.degradation(), DegradationLevel::Full);
13985            assert!(
13986                !program.dirty,
13987                "unavailable rank must not strand rendering at SkipFrame"
13988            );
13989        }
13990        let contents = std::fs::read_to_string(path).expect("actual runtime evidence");
13991        let rows: Vec<serde_json::Value> = contents
13992            .lines()
13993            .map(|line| serde_json::from_str(line).expect("valid evidence JSON"))
13994            .filter(|row: &serde_json::Value| row["event"] == "budget_decision")
13995            .collect();
13996        let unavailable: Vec<_> = rows
13997            .iter()
13998            .filter(|row| row["conformal_status"] == "unattainable_rank")
13999            .collect();
14000        assert!(
14001            !unavailable.is_empty(),
14002            "must observe the post-warmup missing rank"
14003        );
14004        for row in unavailable {
14005            assert!(row["upper_us"].is_null());
14006            assert!(row["q_b"].is_null());
14007            assert_eq!(row["risk"], true);
14008            assert_eq!(row["degradation_after"], "Full");
14009        }
14010        assert!(
14011            rows.iter()
14012                .any(|row| row["conformal_status"] == "calibrated" && row["upper_us"].is_number()),
14013            "continued measurements must eventually yield an available bound"
14014        );
14015    }
14016
14017    #[test]
14018    fn headless_unavailable_conformal_bound_preserves_controller_degradation() {
14019        use ftui_render::budget::DegradationLevel;
14020        let config = ProgramConfig::default()
14021            .with_budget(FrameBudgetConfig::with_total(Duration::from_secs(5)))
14022            .with_conformal_config(ConformalConfig {
14023                alpha: 0.01,
14024                min_samples: 1,
14025                ..Default::default()
14026            });
14027        let mut program = headless_program_with_config(TestModel { value: 0 }, config);
14028        // Controlled observations exercise the actual budget controller and
14029        // runtime gate. These durations are not live performance measurements.
14030        for _ in 0..15 {
14031            program.budget.record_frame_time(Duration::from_secs(200));
14032            program.dirty = true;
14033            program
14034                .render_frame()
14035                .expect("real runtime/controller path");
14036        }
14037        assert_eq!(
14038            program.budget.degradation(),
14039            DegradationLevel::SimpleBorders
14040        );
14041        let predictor = program.conformal_predictor.as_ref().unwrap();
14042        let prediction = predictor.predict(
14043            BucketKey::from_context(ScreenMode::AltScreen, DiffStrategy::Full, 80, 24),
14044            0.0,
14045            5_000_000.0,
14046        );
14047        assert_eq!(prediction.upper_us, None);
14048        assert!(!predictor.is_calibrated(&prediction));
14049    }
14050
14051    /// With `ProgramConfig::gestures` set, raw mouse events still reach
14052    /// `update()` and every recognized gesture reaches `Model::on_gesture`;
14053    /// without it nothing is recognized.
14054    #[test]
14055    fn headless_program_delivers_recognized_gestures_to_on_gesture() {
14056        use ftui_core::event::{Modifiers, MouseButton, MouseEvent, MouseEventKind};
14057        use ftui_core::gesture::GestureConfig;
14058        use ftui_core::semantic_event::SemanticEvent;
14059        use std::sync::{Arc, Mutex};
14060
14061        struct GestureModel {
14062            raw: usize,
14063            gestures: Arc<Mutex<Vec<SemanticEvent>>>,
14064        }
14065
14066        #[derive(Debug)]
14067        enum GMsg {
14068            Raw,
14069        }
14070
14071        impl From<Event> for GMsg {
14072            fn from(_: Event) -> Self {
14073                GMsg::Raw
14074            }
14075        }
14076
14077        impl Model for GestureModel {
14078            type Message = GMsg;
14079
14080            fn update(&mut self, _msg: GMsg) -> Cmd<GMsg> {
14081                self.raw += 1;
14082                Cmd::none()
14083            }
14084
14085            fn view(&self, _frame: &mut Frame) {}
14086
14087            fn on_gesture(&mut self, gesture: SemanticEvent) -> Cmd<GMsg> {
14088                self.gestures.lock().unwrap().push(gesture);
14089                Cmd::none()
14090            }
14091        }
14092
14093        let mouse = |kind: MouseEventKind, x: u16, y: u16| {
14094            Event::Mouse(MouseEvent {
14095                kind,
14096                x,
14097                y,
14098                modifiers: Modifiers::NONE,
14099            })
14100        };
14101
14102        let log = Arc::new(Mutex::new(Vec::new()));
14103        let config = ProgramConfig::default().with_gestures(GestureConfig::default());
14104        let mut program = headless_program_with_config(
14105            GestureModel {
14106                raw: 0,
14107                gestures: Arc::clone(&log),
14108            },
14109            config,
14110        );
14111        // Click: down and up at the same cell.
14112        program
14113            .handle_event(mouse(MouseEventKind::Down(MouseButton::Left), 4, 2))
14114            .unwrap();
14115        program
14116            .handle_event(mouse(MouseEventKind::Up(MouseButton::Left), 4, 2))
14117            .unwrap();
14118        // Drag: down, move past the 3-cell dead zone, up.
14119        program
14120            .handle_event(mouse(MouseEventKind::Down(MouseButton::Left), 10, 5))
14121            .unwrap();
14122        program
14123            .handle_event(mouse(MouseEventKind::Drag(MouseButton::Left), 16, 5))
14124            .unwrap();
14125        program
14126            .handle_event(mouse(MouseEventKind::Up(MouseButton::Left), 16, 5))
14127            .unwrap();
14128        assert_eq!(program.model.raw, 5, "raw events keep flowing to update()");
14129
14130        let gestures = log.lock().unwrap();
14131        assert!(
14132            matches!(
14133                gestures.first(),
14134                Some(SemanticEvent::Click { pos, button: MouseButton::Left })
14135                    if pos.x == 4 && pos.y == 2
14136            ),
14137            "first gesture is the click: {gestures:?}"
14138        );
14139        assert!(
14140            gestures
14141                .iter()
14142                .any(|g| matches!(g, SemanticEvent::DragStart { .. })),
14143            "drag start recognized: {gestures:?}"
14144        );
14145        assert!(
14146            gestures
14147                .iter()
14148                .any(|g| matches!(g, SemanticEvent::DragEnd { .. })),
14149            "drag end recognized: {gestures:?}"
14150        );
14151        drop(gestures);
14152
14153        // Without the config nothing is recognized and update() is unaffected.
14154        let quiet = Arc::new(Mutex::new(Vec::new()));
14155        let mut program = headless_program_with_config(
14156            GestureModel {
14157                raw: 0,
14158                gestures: Arc::clone(&quiet),
14159            },
14160            ProgramConfig::default(),
14161        );
14162        program
14163            .handle_event(mouse(MouseEventKind::Down(MouseButton::Left), 1, 1))
14164            .unwrap();
14165        program
14166            .handle_event(mouse(MouseEventKind::Up(MouseButton::Left), 1, 1))
14167            .unwrap();
14168        assert!(quiet.lock().unwrap().is_empty());
14169        assert_eq!(program.model.raw, 2);
14170    }
14171
14172    /// CONTRACT (bd-1za0z item 3): the queue guardrail sees the live effect
14173    /// backlog (`TaskExecutor::in_flight`), not a hard-coded zero. With a
14174    /// warn depth of one and four tasks in flight, the very first frame must
14175    /// raise a queue alert and export a snapshot carrying that depth.
14176    #[test]
14177    fn headless_render_frame_feeds_live_effect_backlog_to_queue_guardrail() {
14178        struct QueueModel;
14179
14180        #[derive(Debug)]
14181        enum QueueMsg {
14182            Noop,
14183        }
14184
14185        impl From<Event> for QueueMsg {
14186            fn from(_: Event) -> Self {
14187                QueueMsg::Noop
14188            }
14189        }
14190
14191        impl Model for QueueModel {
14192            type Message = QueueMsg;
14193
14194            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
14195                Cmd::none()
14196            }
14197
14198            fn view(&self, frame: &mut Frame) {
14199                frame.buffer.set_raw(0, 0, Cell::from_char('Q'));
14200            }
14201        }
14202
14203        let evidence_path = temp_evidence_path("guardrail_queue_depth");
14204        let config = ProgramConfig {
14205            guardrails: GuardrailsConfig {
14206                memory: MemoryBudgetConfig::default(),
14207                queue: QueueConfig {
14208                    warn_depth: 1,
14209                    ..QueueConfig::default()
14210                },
14211            },
14212            evidence_sink: EvidenceSinkConfig::enabled_file(&evidence_path),
14213            ..Default::default()
14214        };
14215
14216        // Hand four real effects to this program's executor (the default
14217        // spawned lane) that are still running when the frame renders: the
14218        // guardrail must count them as the backlog. Drain them afterwards so
14219        // the test leaves no worker threads behind.
14220        const IN_FLIGHT: usize = 4;
14221        let mut program = headless_program_with_config(QueueModel, config);
14222        let release = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
14223        for _ in 0..IN_FLIGHT {
14224            let release = std::sync::Arc::clone(&release);
14225            program
14226                .execute_cmd(Cmd::task(move || {
14227                    while !release.load(std::sync::atomic::Ordering::Acquire) {
14228                        std::thread::sleep(Duration::from_millis(1));
14229                    }
14230                    QueueMsg::Noop
14231                }))
14232                .expect("submit in-flight task");
14233        }
14234        assert_eq!(program.task_executor.in_flight(), IN_FLIGHT);
14235        program.dirty = true;
14236        let rendered = program.render_frame();
14237        release.store(true, std::sync::atomic::Ordering::Release);
14238        let deadline = Instant::now() + Duration::from_secs(5);
14239        while program.task_executor.in_flight() > 0 && Instant::now() <= deadline {
14240            program
14241                .process_task_results()
14242                .expect("process task results");
14243            std::thread::sleep(Duration::from_millis(1));
14244        }
14245        assert_eq!(program.task_executor.in_flight(), 0, "tasks must drain");
14246        rendered.expect("render frame with queue alert");
14247
14248        let contents =
14249            std::fs::read_to_string(&evidence_path).expect("guardrail evidence file written");
14250        let _ = std::fs::remove_file(&evidence_path);
14251        assert!(
14252            contents.contains(r#""event":"guardrail_snapshot""#),
14253            "queue backlog above warn_depth must export a guardrail_snapshot row; got: {contents}"
14254        );
14255        let depth = contents
14256            .split(r#""queue_depth":"#)
14257            .nth(1)
14258            .and_then(|rest| rest.split(|c: char| !c.is_ascii_digit()).next())
14259            .and_then(|digits| digits.parse::<u64>().ok())
14260            .expect("snapshot row carries queue_depth");
14261        assert!(
14262            depth >= IN_FLIGHT as u64,
14263            "guardrail must observe the live backlog (>= {IN_FLIGHT}), saw {depth}: {contents}"
14264        );
14265    }
14266
14267    /// CONTRACT (bd-1za0z): a soft memory alert must trigger a capacity trim
14268    /// (arena rebuild + pool gc) so the degradation actuator can actually
14269    /// move the sensor — retained capacity alone must not pin alerts forever.
14270    #[test]
14271    fn headless_render_frame_soft_alert_trims_retained_capacity() {
14272        struct AlertModel;
14273
14274        #[derive(Debug)]
14275        enum AlertMsg {
14276            Noop,
14277        }
14278
14279        impl From<Event> for AlertMsg {
14280            fn from(_: Event) -> Self {
14281                AlertMsg::Noop
14282            }
14283        }
14284
14285        impl Model for AlertModel {
14286            type Message = AlertMsg;
14287
14288            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
14289                Cmd::none()
14290            }
14291
14292            fn view(&self, _frame: &mut Frame) {}
14293        }
14294
14295        let config = ProgramConfig {
14296            guardrails: GuardrailsConfig {
14297                memory: MemoryBudgetConfig {
14298                    soft_limit_bytes: 4096,
14299                    ..MemoryBudgetConfig::default()
14300                },
14301                queue: QueueConfig::default(),
14302            },
14303            ..Default::default()
14304        };
14305
14306        let mut program = headless_program_with_config(AlertModel, config.clone());
14307
14308        // Control: same config, same render, no injected capacity — its
14309        // post-frame arena size is the floor a successful trim must return
14310        // to (the render itself allocates a deterministic working set).
14311        let mut control = headless_program_with_config(AlertModel, config);
14312        control.dirty = true;
14313        control.render_frame().expect("control render");
14314        let control_bytes = control.frame_arena.allocated_bytes();
14315
14316        // Simulate retained capacity well above the soft limit: 256 KiB of
14317        // arena allocations that a reset-less sensor can never shed.
14318        let filler = vec![0u8; 256 * 1024];
14319        program.frame_arena.alloc_slice(&filler);
14320        assert!(program.frame_arena.allocated_bytes() >= 256 * 1024);
14321
14322        program.dirty = true;
14323        program
14324            .render_frame()
14325            .expect("render frame with soft alert");
14326        assert_eq!(
14327            program.last_soft_trim_frame,
14328            Some(program.frame_idx),
14329            "soft alert must trigger the capacity trim"
14330        );
14331
14332        // The trim released the injected chunk: the arena is back at the
14333        // control's size instead of carrying the extra 256 KiB.
14334        let after = program.frame_arena.allocated_bytes();
14335        assert!(
14336            after <= control_bytes + 1024,
14337            "soft alert must trim retained capacity: after={after}, control={control_bytes}"
14338        );
14339    }
14340
14341    #[test]
14342    fn headless_render_frame_skips_when_budget_exhausted() {
14343        let config = ProgramConfig {
14344            budget: FrameBudgetConfig::with_total(Duration::ZERO),
14345            ..Default::default()
14346        };
14347
14348        let mut program = headless_program_with_config(TestModel { value: 0 }, config);
14349        program.dirty = true;
14350        program.render_frame().expect("render frame");
14351
14352        // Dirty state is preserved when frame is skipped — the UI update
14353        // was never presented and must be retried.
14354        assert!(program.dirty);
14355        assert_eq!(program.frame_idx, 1);
14356    }
14357
14358    #[test]
14359    fn headless_render_frame_emits_budget_evidence_with_controller() {
14360        use ftui_render::budget::BudgetControllerConfig;
14361
14362        struct RenderModel;
14363
14364        #[derive(Debug)]
14365        enum RenderMsg {
14366            Noop,
14367        }
14368
14369        impl From<Event> for RenderMsg {
14370            fn from(_: Event) -> Self {
14371                RenderMsg::Noop
14372            }
14373        }
14374
14375        impl Model for RenderModel {
14376            type Message = RenderMsg;
14377
14378            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
14379                Cmd::none()
14380            }
14381
14382            fn view(&self, frame: &mut Frame) {
14383                frame.buffer.set_raw(0, 0, Cell::from_char('E'));
14384            }
14385        }
14386
14387        let config =
14388            ProgramConfig::default().with_evidence_sink(EvidenceSinkConfig::enabled_stdout());
14389        let mut program = headless_program_with_config(RenderModel, config);
14390        program.budget = program
14391            .budget
14392            .with_controller(BudgetControllerConfig::default());
14393
14394        program.render_frame().expect("render frame");
14395        assert!(program.budget.telemetry().is_some());
14396        assert_eq!(program.frame_idx, 1);
14397    }
14398
14399    #[test]
14400    fn headless_handle_event_updates_model() {
14401        struct EventModel {
14402            events: usize,
14403            last_resize: Option<(u16, u16)>,
14404        }
14405
14406        #[derive(Debug)]
14407        enum EventMsg {
14408            Resize(u16, u16),
14409            Other,
14410        }
14411
14412        impl From<Event> for EventMsg {
14413            fn from(event: Event) -> Self {
14414                match event {
14415                    Event::Resize { width, height } => EventMsg::Resize(width, height),
14416                    _ => EventMsg::Other,
14417                }
14418            }
14419        }
14420
14421        impl Model for EventModel {
14422            type Message = EventMsg;
14423
14424            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
14425                self.events += 1;
14426                if let EventMsg::Resize(w, h) = msg {
14427                    self.last_resize = Some((w, h));
14428                }
14429                Cmd::none()
14430            }
14431
14432            fn view(&self, _frame: &mut Frame) {}
14433        }
14434
14435        let mut program = headless_program_with_config(
14436            EventModel {
14437                events: 0,
14438                last_resize: None,
14439            },
14440            ProgramConfig::default().with_resize_behavior(ResizeBehavior::Immediate),
14441        );
14442
14443        program
14444            .handle_event(Event::Key(ftui_core::event::KeyEvent::new(
14445                ftui_core::event::KeyCode::Char('x'),
14446            )))
14447            .expect("handle key");
14448        assert_eq!(program.model().events, 1);
14449
14450        program
14451            .handle_event(Event::Resize {
14452                width: 10,
14453                height: 5,
14454            })
14455            .expect("handle resize");
14456        assert_eq!(program.model().events, 2);
14457        assert_eq!(program.model().last_resize, Some((10, 5)));
14458        assert_eq!(program.width, 10);
14459        assert_eq!(program.height, 5);
14460    }
14461
14462    #[test]
14463    fn headless_handle_event_quit_skips_subscription_reconcile() {
14464        use crate::subscription::{StopSignal, SubId, Subscription};
14465
14466        struct QuitSubModel {
14467            quitting: bool,
14468            subscription_starts: Arc<AtomicUsize>,
14469        }
14470
14471        #[derive(Debug)]
14472        enum QuitSubMsg {
14473            Quit,
14474            Other,
14475        }
14476
14477        impl From<Event> for QuitSubMsg {
14478            fn from(event: Event) -> Self {
14479                match event {
14480                    Event::Key(_) => Self::Quit,
14481                    _ => Self::Other,
14482                }
14483            }
14484        }
14485
14486        impl Model for QuitSubModel {
14487            type Message = QuitSubMsg;
14488
14489            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
14490                match msg {
14491                    QuitSubMsg::Quit => {
14492                        self.quitting = true;
14493                        Cmd::quit()
14494                    }
14495                    QuitSubMsg::Other => Cmd::none(),
14496                }
14497            }
14498
14499            fn view(&self, _frame: &mut Frame) {}
14500
14501            fn subscriptions(&self) -> Vec<Box<dyn Subscription<Self::Message>>> {
14502                if self.quitting {
14503                    vec![Box::new(QuitSubSubscription {
14504                        starts: Arc::clone(&self.subscription_starts),
14505                    })]
14506                } else {
14507                    vec![]
14508                }
14509            }
14510        }
14511
14512        struct QuitSubSubscription {
14513            starts: Arc<AtomicUsize>,
14514        }
14515
14516        impl Subscription<QuitSubMsg> for QuitSubSubscription {
14517            fn id(&self) -> SubId {
14518                7
14519            }
14520
14521            fn run(&self, _sender: mpsc::Sender<QuitSubMsg>, stop: StopSignal) {
14522                self.starts.fetch_add(1, Ordering::SeqCst);
14523                let _ = stop.wait_timeout(Duration::from_millis(10));
14524            }
14525        }
14526
14527        let subscription_starts = Arc::new(AtomicUsize::new(0));
14528        let mut program = headless_program_with_config(
14529            QuitSubModel {
14530                quitting: false,
14531                subscription_starts: Arc::clone(&subscription_starts),
14532            },
14533            ProgramConfig::default(),
14534        );
14535
14536        program
14537            .handle_event(Event::Key(ftui_core::event::KeyEvent::new(
14538                ftui_core::event::KeyCode::Char('q'),
14539            )))
14540            .expect("handle event");
14541
14542        assert!(!program.is_running());
14543        assert_eq!(program.subscriptions.active_count(), 0);
14544        assert_eq!(subscription_starts.load(Ordering::SeqCst), 0);
14545    }
14546
14547    #[test]
14548    fn headless_handle_resize_ignored_when_forced_size() {
14549        struct ResizeModel {
14550            resized: bool,
14551        }
14552
14553        #[derive(Debug)]
14554        enum ResizeMsg {
14555            Resize,
14556            Other,
14557        }
14558
14559        impl From<Event> for ResizeMsg {
14560            fn from(event: Event) -> Self {
14561                match event {
14562                    Event::Resize { .. } => ResizeMsg::Resize,
14563                    _ => ResizeMsg::Other,
14564                }
14565            }
14566        }
14567
14568        impl Model for ResizeModel {
14569            type Message = ResizeMsg;
14570
14571            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
14572                if matches!(msg, ResizeMsg::Resize) {
14573                    self.resized = true;
14574                }
14575                Cmd::none()
14576            }
14577
14578            fn view(&self, _frame: &mut Frame) {}
14579        }
14580
14581        let config = ProgramConfig::default().with_forced_size(80, 24);
14582        let mut program = headless_program_with_config(ResizeModel { resized: false }, config);
14583
14584        program
14585            .handle_event(Event::Resize {
14586                width: 120,
14587                height: 40,
14588            })
14589            .expect("handle resize");
14590
14591        assert_eq!(program.width, 80);
14592        assert_eq!(program.height, 24);
14593        assert!(!program.model().resized);
14594    }
14595
14596    #[test]
14597    fn headless_execute_cmd_batch_sequence_and_quit() {
14598        struct BatchModel {
14599            count: usize,
14600        }
14601
14602        #[derive(Debug)]
14603        enum BatchMsg {
14604            Inc,
14605        }
14606
14607        impl From<Event> for BatchMsg {
14608            fn from(_: Event) -> Self {
14609                BatchMsg::Inc
14610            }
14611        }
14612
14613        impl Model for BatchModel {
14614            type Message = BatchMsg;
14615
14616            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
14617                match msg {
14618                    BatchMsg::Inc => {
14619                        self.count += 1;
14620                        Cmd::none()
14621                    }
14622                }
14623            }
14624
14625            fn view(&self, _frame: &mut Frame) {}
14626        }
14627
14628        let mut program =
14629            headless_program_with_config(BatchModel { count: 0 }, ProgramConfig::default());
14630
14631        program
14632            .execute_cmd(Cmd::Batch(vec![
14633                Cmd::msg(BatchMsg::Inc),
14634                Cmd::Sequence(vec![
14635                    Cmd::msg(BatchMsg::Inc),
14636                    Cmd::quit(),
14637                    Cmd::msg(BatchMsg::Inc),
14638                ]),
14639            ]))
14640            .expect("batch cmd");
14641
14642        assert_eq!(program.model().count, 2);
14643        assert!(!program.running);
14644    }
14645
14646    #[test]
14647    fn headless_process_subscription_messages_updates_model() {
14648        use crate::subscription::{StopSignal, SubId, Subscription};
14649
14650        struct SubModel {
14651            pings: usize,
14652            ready_tx: mpsc::Sender<()>,
14653        }
14654
14655        #[derive(Debug)]
14656        enum SubMsg {
14657            Ping,
14658            Other,
14659        }
14660
14661        impl From<Event> for SubMsg {
14662            fn from(_: Event) -> Self {
14663                SubMsg::Other
14664            }
14665        }
14666
14667        impl Model for SubModel {
14668            type Message = SubMsg;
14669
14670            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
14671                if let SubMsg::Ping = msg {
14672                    self.pings += 1;
14673                }
14674                Cmd::none()
14675            }
14676
14677            fn view(&self, _frame: &mut Frame) {}
14678
14679            fn subscriptions(&self) -> Vec<Box<dyn Subscription<Self::Message>>> {
14680                vec![Box::new(TestSubscription {
14681                    ready_tx: self.ready_tx.clone(),
14682                })]
14683            }
14684        }
14685
14686        struct TestSubscription {
14687            ready_tx: mpsc::Sender<()>,
14688        }
14689
14690        impl Subscription<SubMsg> for TestSubscription {
14691            fn id(&self) -> SubId {
14692                1
14693            }
14694
14695            fn run(&self, sender: mpsc::Sender<SubMsg>, _stop: StopSignal) {
14696                let _ = sender.send(SubMsg::Ping);
14697                let _ = self.ready_tx.send(());
14698            }
14699        }
14700
14701        let (ready_tx, ready_rx) = mpsc::channel();
14702        let mut program =
14703            headless_program_with_config(SubModel { pings: 0, ready_tx }, ProgramConfig::default());
14704
14705        program.reconcile_subscriptions();
14706        ready_rx
14707            .recv_timeout(Duration::from_millis(200))
14708            .expect("subscription started");
14709        program
14710            .process_subscription_messages()
14711            .expect("process subscriptions");
14712
14713        assert_eq!(program.model().pings, 1);
14714    }
14715
14716    #[test]
14717    fn headless_execute_cmd_task_spawns_and_reaps() {
14718        struct TaskModel {
14719            done: bool,
14720        }
14721
14722        #[derive(Debug)]
14723        enum TaskMsg {
14724            Done,
14725        }
14726
14727        impl From<Event> for TaskMsg {
14728            fn from(_: Event) -> Self {
14729                TaskMsg::Done
14730            }
14731        }
14732
14733        impl Model for TaskModel {
14734            type Message = TaskMsg;
14735
14736            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
14737                match msg {
14738                    TaskMsg::Done => {
14739                        self.done = true;
14740                        Cmd::none()
14741                    }
14742                }
14743            }
14744
14745            fn view(&self, _frame: &mut Frame) {}
14746        }
14747
14748        let mut program =
14749            headless_program_with_config(TaskModel { done: false }, ProgramConfig::default());
14750        program
14751            .execute_cmd(Cmd::task(|| TaskMsg::Done))
14752            .expect("task cmd");
14753
14754        let deadline = Instant::now() + Duration::from_millis(200);
14755        while !program.model().done && Instant::now() <= deadline {
14756            program
14757                .process_task_results()
14758                .expect("process task results");
14759            program.reap_finished_tasks();
14760        }
14761
14762        assert!(program.model().done, "task result did not arrive in time");
14763    }
14764
14765    #[test]
14766    fn headless_default_task_executor_is_spawned_for_structured_lane() {
14767        // Input-lag regression fix (#78): the default Structured lane must use
14768        // per-task `Spawned` execution, NOT the single-worker effect queue.
14769        // Routing every `Cmd::Task` through one serialized `effect_queue_loop`
14770        // worker added per-keystroke head-of-line latency for apps that forward
14771        // PTY output via per-pane polling tasks. Structured cancellation does
14772        // not require the effect queue, so the default backend is `Spawned`
14773        // ("spawned") here, matching v0.2.1 task concurrency.
14774        let program =
14775            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
14776        assert_eq!(program.task_executor.kind_name(), "spawned");
14777    }
14778
14779    #[test]
14780    fn headless_structured_lane_task_executor_writes_spawned_backend_evidence() {
14781        // Input-lag regression fix (#78): the default Structured lane emits the
14782        // "spawned" backend in startup evidence (was "queued"), reflecting the
14783        // restored per-task-thread execution.
14784        let evidence_path = temp_evidence_path("task_executor_spawned_backend");
14785        let sink_config = EvidenceSinkConfig::enabled_file(&evidence_path);
14786        let config = ProgramConfig::default().with_evidence_sink(sink_config);
14787        let _program = headless_program_with_config(TestModel { value: 0 }, config);
14788
14789        let backend_line = read_evidence_event(&evidence_path, "task_executor_backend");
14790        assert_eq!(backend_line["backend"], "spawned");
14791    }
14792
14793    #[test]
14794    fn headless_legacy_lane_task_executor_is_spawned() {
14795        let config = ProgramConfig::default().with_lane(RuntimeLane::Legacy);
14796        let program = headless_program_with_config(TestModel { value: 0 }, config);
14797        assert_eq!(program.task_executor.kind_name(), "spawned");
14798    }
14799
14800    #[test]
14801    fn headless_explicit_spawned_backend_overrides_structured_lane_default() {
14802        let config = ProgramConfig::default().with_effect_queue(
14803            EffectQueueConfig::default().with_backend(TaskExecutorBackend::Spawned),
14804        );
14805        let program = headless_program_with_config(TestModel { value: 0 }, config);
14806        assert_eq!(program.task_executor.kind_name(), "spawned");
14807    }
14808
14809    #[cfg(feature = "asupersync-executor")]
14810    #[test]
14811    fn headless_asupersync_task_executor_is_selected() {
14812        let config = ProgramConfig::default().with_effect_queue(
14813            EffectQueueConfig::default().with_backend(TaskExecutorBackend::Asupersync),
14814        );
14815        let program = headless_program_with_config(TestModel { value: 0 }, config);
14816        assert_eq!(program.task_executor.kind_name(), "asupersync");
14817    }
14818
14819    #[test]
14820    fn headless_persistence_commands_with_registry() {
14821        use crate::state_persistence::{MemoryStorage, StateRegistry};
14822        use std::sync::Arc;
14823
14824        let registry = Arc::new(StateRegistry::new(Box::new(MemoryStorage::new())));
14825        let config = ProgramConfig::default().with_registry(registry.clone());
14826        let mut program = headless_program_with_config(TestModel { value: 0 }, config);
14827
14828        assert!(program.has_persistence());
14829        assert!(program.state_registry().is_some());
14830
14831        program.execute_cmd(Cmd::save_state()).expect("save");
14832        program.execute_cmd(Cmd::restore_state()).expect("restore");
14833
14834        let saved = program.trigger_save().expect("trigger save");
14835        let loaded = program.trigger_load().expect("trigger load");
14836        assert!(!saved);
14837        assert_eq!(loaded, 0);
14838    }
14839
14840    #[test]
14841    fn headless_process_resize_coalescer_applies_pending_resize() {
14842        struct ResizeModel {
14843            last_size: Option<(u16, u16)>,
14844        }
14845
14846        #[derive(Debug)]
14847        enum ResizeMsg {
14848            Resize(u16, u16),
14849            Other,
14850        }
14851
14852        impl From<Event> for ResizeMsg {
14853            fn from(event: Event) -> Self {
14854                match event {
14855                    Event::Resize { width, height } => ResizeMsg::Resize(width, height),
14856                    _ => ResizeMsg::Other,
14857                }
14858            }
14859        }
14860
14861        impl Model for ResizeModel {
14862            type Message = ResizeMsg;
14863
14864            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
14865                if let ResizeMsg::Resize(w, h) = msg {
14866                    self.last_size = Some((w, h));
14867                }
14868                Cmd::none()
14869            }
14870
14871            fn view(&self, _frame: &mut Frame) {}
14872        }
14873
14874        let evidence_path = temp_evidence_path("fairness_allow");
14875        let sink_config = EvidenceSinkConfig::enabled_file(&evidence_path);
14876        let mut config = ProgramConfig::default().with_resize_behavior(ResizeBehavior::Throttled);
14877        config.resize_coalescer.steady_delay_ms = 0;
14878        config.resize_coalescer.burst_delay_ms = 0;
14879        config.resize_coalescer.hard_deadline_ms = 1_000;
14880        config.evidence_sink = sink_config.clone();
14881
14882        let mut program = headless_program_with_config(ResizeModel { last_size: None }, config);
14883        let sink = EvidenceSink::from_config(&sink_config)
14884            .expect("evidence sink config")
14885            .expect("evidence sink enabled");
14886        program.evidence_sink = Some(sink);
14887
14888        program.resize_coalescer.handle_resize(120, 40);
14889        assert!(program.resize_coalescer.has_pending());
14890
14891        program
14892            .process_resize_coalescer()
14893            .expect("process resize coalescer");
14894
14895        assert_eq!(program.width, 120);
14896        assert_eq!(program.height, 40);
14897        assert_eq!(program.model().last_size, Some((120, 40)));
14898
14899        let config_line = read_evidence_event(&evidence_path, "fairness_config");
14900        assert_eq!(config_line["event"], "fairness_config");
14901        assert!(config_line["enabled"].is_boolean());
14902        assert!(config_line["input_priority_threshold_ms"].is_number());
14903        assert!(config_line["dominance_threshold"].is_number());
14904        assert!(config_line["fairness_threshold"].is_number());
14905
14906        let decision_line = read_evidence_event(&evidence_path, "fairness_decision");
14907        assert_eq!(decision_line["event"], "fairness_decision");
14908        assert_eq!(decision_line["decision"], "allow");
14909        assert_eq!(decision_line["reason"], "none");
14910        assert!(decision_line["pending_input_latency_ms"].is_null());
14911        assert!(decision_line["jain_index"].is_number());
14912        assert!(decision_line["resize_dominance_count"].is_number());
14913        assert!(decision_line["dominance_threshold"].is_number());
14914        assert!(decision_line["fairness_threshold"].is_number());
14915        assert!(decision_line["input_priority_threshold_ms"].is_number());
14916    }
14917
14918    #[test]
14919    fn headless_process_resize_coalescer_yields_to_input() {
14920        struct ResizeModel {
14921            last_size: Option<(u16, u16)>,
14922        }
14923
14924        #[derive(Debug)]
14925        enum ResizeMsg {
14926            Resize(u16, u16),
14927            Other,
14928        }
14929
14930        impl From<Event> for ResizeMsg {
14931            fn from(event: Event) -> Self {
14932                match event {
14933                    Event::Resize { width, height } => ResizeMsg::Resize(width, height),
14934                    _ => ResizeMsg::Other,
14935                }
14936            }
14937        }
14938
14939        impl Model for ResizeModel {
14940            type Message = ResizeMsg;
14941
14942            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
14943                if let ResizeMsg::Resize(w, h) = msg {
14944                    self.last_size = Some((w, h));
14945                }
14946                Cmd::none()
14947            }
14948
14949            fn view(&self, _frame: &mut Frame) {}
14950        }
14951
14952        let evidence_path = temp_evidence_path("fairness_yield");
14953        let sink_config = EvidenceSinkConfig::enabled_file(&evidence_path);
14954        let mut config = ProgramConfig::default().with_resize_behavior(ResizeBehavior::Throttled);
14955        config.resize_coalescer.steady_delay_ms = 0;
14956        config.resize_coalescer.burst_delay_ms = 0;
14957        // Use a large hard deadline so elapsed wall-clock time between coalescer
14958        // construction and `handle_resize` never triggers an immediate apply.
14959        config.resize_coalescer.hard_deadline_ms = 10_000;
14960        config.evidence_sink = sink_config.clone();
14961
14962        let mut program = headless_program_with_config(ResizeModel { last_size: None }, config);
14963        let sink = EvidenceSink::from_config(&sink_config)
14964            .expect("evidence sink config")
14965            .expect("evidence sink enabled");
14966        program.evidence_sink = Some(sink);
14967
14968        program.fairness_guard = InputFairnessGuard::with_config(
14969            crate::input_fairness::FairnessConfig::default().with_max_latency(Duration::ZERO),
14970        );
14971        program
14972            .fairness_guard
14973            .input_arrived(Instant::now() - Duration::from_millis(1));
14974
14975        program.resize_coalescer.handle_resize(120, 40);
14976        assert!(program.resize_coalescer.has_pending());
14977
14978        program
14979            .process_resize_coalescer()
14980            .expect("process resize coalescer");
14981
14982        assert_eq!(program.width, 80);
14983        assert_eq!(program.height, 24);
14984        assert_eq!(program.model().last_size, None);
14985        assert!(program.resize_coalescer.has_pending());
14986
14987        let decision_line = read_evidence_event(&evidence_path, "fairness_decision");
14988        assert_eq!(decision_line["event"], "fairness_decision");
14989        assert_eq!(decision_line["decision"], "yield");
14990        assert_eq!(decision_line["reason"], "input_latency");
14991        assert!(decision_line["pending_input_latency_ms"].is_number());
14992        assert!(decision_line["jain_index"].is_number());
14993        assert!(decision_line["resize_dominance_count"].is_number());
14994        assert!(decision_line["dominance_threshold"].is_number());
14995        assert!(decision_line["fairness_threshold"].is_number());
14996        assert!(decision_line["input_priority_threshold_ms"].is_number());
14997    }
14998
14999    #[test]
15000    fn headless_execute_cmd_task_with_effect_queue() {
15001        struct TaskModel {
15002            done: bool,
15003        }
15004
15005        #[derive(Debug)]
15006        enum TaskMsg {
15007            Done,
15008        }
15009
15010        impl From<Event> for TaskMsg {
15011            fn from(_: Event) -> Self {
15012                TaskMsg::Done
15013            }
15014        }
15015
15016        impl Model for TaskModel {
15017            type Message = TaskMsg;
15018
15019            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
15020                match msg {
15021                    TaskMsg::Done => {
15022                        self.done = true;
15023                        Cmd::none()
15024                    }
15025                }
15026            }
15027
15028            fn view(&self, _frame: &mut Frame) {}
15029        }
15030
15031        let effect_queue = EffectQueueConfig {
15032            enabled: true,
15033            backend: TaskExecutorBackend::EffectQueue,
15034            scheduler: SchedulerConfig {
15035                max_queue_size: 0,
15036                ..Default::default()
15037            },
15038            explicit_backend: true,
15039            ..Default::default()
15040        };
15041        let config = ProgramConfig::default().with_effect_queue(effect_queue);
15042        let mut program = headless_program_with_config(TaskModel { done: false }, config);
15043
15044        program
15045            .execute_cmd(Cmd::task(|| TaskMsg::Done))
15046            .expect("task cmd");
15047
15048        let deadline = Instant::now() + Duration::from_millis(200);
15049        while !program.model().done && Instant::now() <= deadline {
15050            program
15051                .process_task_results()
15052                .expect("process task results");
15053        }
15054
15055        assert!(
15056            program.model().done,
15057            "effect queue task result did not arrive in time"
15058        );
15059        assert_eq!(program.task_executor.kind_name(), "queued");
15060    }
15061
15062    #[test]
15063    fn headless_execute_cmd_task_with_spawned_backend_writes_completion_evidence() {
15064        struct TaskModel {
15065            done: bool,
15066        }
15067
15068        #[derive(Debug)]
15069        enum TaskMsg {
15070            Done,
15071        }
15072
15073        impl From<Event> for TaskMsg {
15074            fn from(_: Event) -> Self {
15075                TaskMsg::Done
15076            }
15077        }
15078
15079        impl Model for TaskModel {
15080            type Message = TaskMsg;
15081
15082            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
15083                match msg {
15084                    TaskMsg::Done => {
15085                        self.done = true;
15086                        Cmd::none()
15087                    }
15088                }
15089            }
15090
15091            fn view(&self, _frame: &mut Frame) {}
15092        }
15093
15094        let evidence_path = temp_evidence_path("task_executor_spawned_complete");
15095        let sink_config = EvidenceSinkConfig::enabled_file(&evidence_path);
15096        let config = ProgramConfig::default()
15097            .with_lane(RuntimeLane::Legacy)
15098            .with_evidence_sink(sink_config);
15099        let mut program = headless_program_with_config(TaskModel { done: false }, config);
15100
15101        program
15102            .execute_cmd(Cmd::task(|| TaskMsg::Done))
15103            .expect("task cmd");
15104
15105        let deadline = Instant::now() + Duration::from_millis(200);
15106        while !program.model().done && Instant::now() <= deadline {
15107            program
15108                .process_task_results()
15109                .expect("process task results");
15110            program.reap_finished_tasks();
15111        }
15112
15113        assert!(
15114            program.model().done,
15115            "spawned task result did not arrive in time"
15116        );
15117
15118        let completion_line = read_evidence_event(&evidence_path, "task_executor_complete");
15119        assert_eq!(completion_line["backend"], "spawned");
15120        assert!(completion_line["duration_us"].is_number());
15121    }
15122
15123    #[test]
15124    fn headless_effect_queue_task_panic_writes_panic_evidence_and_continues() {
15125        struct TaskModel {
15126            done: bool,
15127        }
15128
15129        #[derive(Debug)]
15130        enum TaskMsg {
15131            Done,
15132        }
15133
15134        impl From<Event> for TaskMsg {
15135            fn from(_: Event) -> Self {
15136                TaskMsg::Done
15137            }
15138        }
15139
15140        impl Model for TaskModel {
15141            type Message = TaskMsg;
15142
15143            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
15144                match msg {
15145                    TaskMsg::Done => {
15146                        self.done = true;
15147                        Cmd::none()
15148                    }
15149                }
15150            }
15151
15152            fn view(&self, _frame: &mut Frame) {}
15153        }
15154
15155        let evidence_path = temp_evidence_path("task_executor_queued_panic");
15156        let sink_config = EvidenceSinkConfig::enabled_file(&evidence_path);
15157        let config = ProgramConfig::default()
15158            .with_evidence_sink(sink_config)
15159            .with_effect_queue(
15160                EffectQueueConfig::default().with_backend(TaskExecutorBackend::EffectQueue),
15161            );
15162        let mut program = headless_program_with_config(TaskModel { done: false }, config);
15163
15164        program
15165            .execute_cmd(Cmd::task(|| -> TaskMsg { panic!("queued panic evidence") }))
15166            .expect("panic task cmd");
15167        program
15168            .execute_cmd(Cmd::task(|| TaskMsg::Done))
15169            .expect("follow-up task cmd");
15170
15171        let deadline = Instant::now() + Duration::from_millis(500);
15172        while !program.model().done && Instant::now() <= deadline {
15173            program
15174                .process_task_results()
15175                .expect("process task results");
15176        }
15177
15178        assert!(
15179            program.model().done,
15180            "effect queue should continue after a panicking task"
15181        );
15182
15183        let panic_line = read_evidence_event(&evidence_path, "task_executor_panic");
15184        assert_eq!(panic_line["backend"], "queued");
15185        assert_eq!(panic_line["panic_msg"], "queued panic evidence");
15186    }
15187
15188    #[cfg(feature = "asupersync-executor")]
15189    #[test]
15190    fn headless_execute_cmd_task_with_asupersync_backend() {
15191        struct TaskModel {
15192            done: bool,
15193        }
15194
15195        #[derive(Debug)]
15196        enum TaskMsg {
15197            Done,
15198        }
15199
15200        impl From<Event> for TaskMsg {
15201            fn from(_: Event) -> Self {
15202                TaskMsg::Done
15203            }
15204        }
15205
15206        impl Model for TaskModel {
15207            type Message = TaskMsg;
15208
15209            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
15210                match msg {
15211                    TaskMsg::Done => {
15212                        self.done = true;
15213                        Cmd::none()
15214                    }
15215                }
15216            }
15217
15218            fn view(&self, _frame: &mut Frame) {}
15219        }
15220
15221        let config = ProgramConfig::default().with_effect_queue(
15222            EffectQueueConfig::default().with_backend(TaskExecutorBackend::Asupersync),
15223        );
15224        let mut program = headless_program_with_config(TaskModel { done: false }, config);
15225
15226        program
15227            .execute_cmd(Cmd::task(|| TaskMsg::Done))
15228            .expect("task cmd");
15229
15230        let deadline = Instant::now() + Duration::from_millis(200);
15231        while !program.model().done && Instant::now() <= deadline {
15232            program
15233                .process_task_results()
15234                .expect("process task results");
15235            program.reap_finished_tasks();
15236        }
15237
15238        assert!(
15239            program.model().done,
15240            "asupersync task result did not arrive in time"
15241        );
15242        assert_eq!(program.task_executor.kind_name(), "asupersync");
15243    }
15244
15245    #[cfg(feature = "asupersync-executor")]
15246    #[test]
15247    fn headless_asupersync_task_executor_writes_backend_and_completion_evidence() {
15248        struct TaskModel {
15249            done: bool,
15250        }
15251
15252        #[derive(Debug)]
15253        enum TaskMsg {
15254            Done,
15255        }
15256
15257        impl From<Event> for TaskMsg {
15258            fn from(_: Event) -> Self {
15259                TaskMsg::Done
15260            }
15261        }
15262
15263        impl Model for TaskModel {
15264            type Message = TaskMsg;
15265
15266            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
15267                match msg {
15268                    TaskMsg::Done => {
15269                        self.done = true;
15270                        Cmd::none()
15271                    }
15272                }
15273            }
15274
15275            fn view(&self, _frame: &mut Frame) {}
15276        }
15277
15278        let evidence_path = temp_evidence_path("task_executor_asupersync_complete");
15279        let sink_config = EvidenceSinkConfig::enabled_file(&evidence_path);
15280        let config = ProgramConfig::default()
15281            .with_evidence_sink(sink_config)
15282            .with_effect_queue(
15283                EffectQueueConfig::default().with_backend(TaskExecutorBackend::Asupersync),
15284            );
15285        let mut program = headless_program_with_config(TaskModel { done: false }, config);
15286
15287        let backend_line = read_evidence_event(&evidence_path, "task_executor_backend");
15288        assert_eq!(backend_line["backend"], "asupersync");
15289
15290        program
15291            .execute_cmd(Cmd::task(|| TaskMsg::Done))
15292            .expect("task cmd");
15293
15294        let deadline = Instant::now() + Duration::from_millis(200);
15295        while !program.model().done && Instant::now() <= deadline {
15296            program
15297                .process_task_results()
15298                .expect("process task results");
15299            program.reap_finished_tasks();
15300        }
15301
15302        assert!(
15303            program.model().done,
15304            "asupersync task result did not arrive in time"
15305        );
15306
15307        let completion_line = read_evidence_event(&evidence_path, "task_executor_complete");
15308        assert_eq!(completion_line["backend"], "asupersync");
15309        assert!(completion_line["duration_us"].is_number());
15310    }
15311
15312    // =========================================================================
15313    // Asupersync executor: semantic parity, failure, stress, shutdown, and
15314    // backpressure coverage (bd-392ka).
15315    // =========================================================================
15316
15317    /// Run `count` tasks (each emitting its index) through `backend` headlessly
15318    /// and return the sorted multiset of delivered message payloads.
15319    #[cfg(feature = "asupersync-executor")]
15320    fn collect_task_batch(backend: TaskExecutorBackend, count: u32) -> Vec<u32> {
15321        struct CollectModel {
15322            got: Vec<u32>,
15323        }
15324        #[derive(Debug)]
15325        enum CollectMsg {
15326            Got(u32),
15327        }
15328        impl From<Event> for CollectMsg {
15329            fn from(_: Event) -> Self {
15330                CollectMsg::Got(u32::MAX)
15331            }
15332        }
15333        impl Model for CollectModel {
15334            type Message = CollectMsg;
15335            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
15336                match msg {
15337                    CollectMsg::Got(value) => self.got.push(value),
15338                }
15339                Cmd::none()
15340            }
15341            fn view(&self, _frame: &mut Frame) {}
15342        }
15343
15344        let config = ProgramConfig::default()
15345            .with_effect_queue(EffectQueueConfig::default().with_backend(backend));
15346        let mut program = headless_program_with_config(CollectModel { got: Vec::new() }, config);
15347        for index in 0..count {
15348            program
15349                .execute_cmd(Cmd::task(move || CollectMsg::Got(index)))
15350                .expect("task cmd");
15351        }
15352        let deadline = Instant::now() + Duration::from_secs(5);
15353        while program.model().got.len() < count as usize && Instant::now() <= deadline {
15354            program
15355                .process_task_results()
15356                .expect("process task results");
15357            program.reap_finished_tasks();
15358        }
15359        let mut got = program.model().got.clone();
15360        got.sort_unstable();
15361        got
15362    }
15363
15364    #[cfg(feature = "asupersync-executor")]
15365    #[test]
15366    fn asupersync_semantic_parity_with_spawned_backend() {
15367        // The same task batch must deliver an identical message multiset whether
15368        // run through the legacy Spawned backend or the Asupersync backend. This
15369        // is the evidence-backed semantic-parity check (a shadow-run in miniature).
15370        let expected: Vec<u32> = (0..16).collect();
15371        let spawned = collect_task_batch(TaskExecutorBackend::Spawned, 16);
15372        let asupersync = collect_task_batch(TaskExecutorBackend::Asupersync, 16);
15373        assert_eq!(
15374            spawned, expected,
15375            "spawned backend lost or reordered results"
15376        );
15377        assert_eq!(
15378            asupersync, expected,
15379            "asupersync backend diverged from the expected results"
15380        );
15381        assert_eq!(
15382            asupersync, spawned,
15383            "asupersync diverged from spawned (parity)"
15384        );
15385    }
15386
15387    #[cfg(feature = "asupersync-executor")]
15388    #[test]
15389    fn asupersync_stress_delivers_every_task() {
15390        // Under a large burst, every task result must arrive exactly once.
15391        let count: u32 = 200;
15392        let got = collect_task_batch(TaskExecutorBackend::Asupersync, count);
15393        assert_eq!(
15394            got.len(),
15395            count as usize,
15396            "asupersync dropped tasks under load"
15397        );
15398        assert_eq!(got, (0..count).collect::<Vec<_>>());
15399    }
15400
15401    #[cfg(feature = "asupersync-executor")]
15402    #[test]
15403    fn asupersync_task_panic_is_isolated() {
15404        struct PanicModel {
15405            survivor_seen: bool,
15406        }
15407        #[derive(Debug)]
15408        enum PanicMsg {
15409            Survivor,
15410        }
15411        impl From<Event> for PanicMsg {
15412            fn from(_: Event) -> Self {
15413                PanicMsg::Survivor
15414            }
15415        }
15416        impl Model for PanicModel {
15417            type Message = PanicMsg;
15418            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
15419                match msg {
15420                    PanicMsg::Survivor => self.survivor_seen = true,
15421                }
15422                Cmd::none()
15423            }
15424            fn view(&self, _frame: &mut Frame) {}
15425        }
15426
15427        let evidence_path = temp_evidence_path("asupersync_panic");
15428        let sink_config = EvidenceSinkConfig::enabled_file(&evidence_path);
15429        let config = ProgramConfig::default()
15430            .with_evidence_sink(sink_config)
15431            .with_effect_queue(
15432                EffectQueueConfig::default().with_backend(TaskExecutorBackend::Asupersync),
15433            );
15434        let mut program = headless_program_with_config(
15435            PanicModel {
15436                survivor_seen: false,
15437            },
15438            config,
15439        );
15440
15441        // A panicking task must neither crash the executor nor deliver a message...
15442        program
15443            .execute_cmd(Cmd::task(|| -> PanicMsg { panic!("asupersync boom") }))
15444            .expect("panic task cmd");
15445        // ...and a task submitted afterwards must still complete normally.
15446        program
15447            .execute_cmd(Cmd::task(|| PanicMsg::Survivor))
15448            .expect("survivor task cmd");
15449
15450        let deadline = Instant::now() + Duration::from_secs(5);
15451        // The survivor can finish before the other worker records its panic.
15452        // Completed handles also guarantee that their evidence writes finished.
15453        while (!program.model().survivor_seen || program.task_executor.in_flight() > 0)
15454            && Instant::now() <= deadline
15455        {
15456            program
15457                .process_task_results()
15458                .expect("process task results");
15459            program.reap_finished_tasks();
15460        }
15461        assert!(
15462            program.model().survivor_seen,
15463            "executor did not survive a panicking task"
15464        );
15465        assert_eq!(
15466            program.task_executor.in_flight(),
15467            0,
15468            "executor tasks did not finish before evidence was read"
15469        );
15470        let panic_line = read_evidence_event(&evidence_path, "task_executor_panic");
15471        assert_eq!(panic_line["backend"], "asupersync");
15472        assert_eq!(panic_line["panic_msg"], "asupersync boom");
15473    }
15474
15475    #[cfg(feature = "asupersync-executor")]
15476    #[test]
15477    fn asupersync_rejects_tasks_after_shutdown() {
15478        struct ShutdownModel {
15479            seen: bool,
15480        }
15481        #[derive(Debug)]
15482        enum ShutdownMsg {
15483            Seen,
15484        }
15485        impl From<Event> for ShutdownMsg {
15486            fn from(_: Event) -> Self {
15487                ShutdownMsg::Seen
15488            }
15489        }
15490        impl Model for ShutdownModel {
15491            type Message = ShutdownMsg;
15492            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
15493                match msg {
15494                    ShutdownMsg::Seen => self.seen = true,
15495                }
15496                Cmd::none()
15497            }
15498            fn view(&self, _frame: &mut Frame) {}
15499        }
15500
15501        let config = ProgramConfig::default().with_effect_queue(
15502            EffectQueueConfig::default().with_backend(TaskExecutorBackend::Asupersync),
15503        );
15504        let mut program = headless_program_with_config(ShutdownModel { seen: false }, config);
15505
15506        // After shutdown, new submissions are rejected (structured ownership):
15507        // the task never runs, so no message is delivered.
15508        program.task_executor.shutdown();
15509        program
15510            .execute_cmd(Cmd::task(|| ShutdownMsg::Seen))
15511            .expect("post-shutdown task cmd");
15512
15513        let deadline = Instant::now() + Duration::from_millis(200);
15514        while Instant::now() <= deadline {
15515            program
15516                .process_task_results()
15517                .expect("process task results");
15518            program.reap_finished_tasks();
15519        }
15520        assert!(
15521            !program.model().seen,
15522            "a task submitted after shutdown was executed"
15523        );
15524    }
15525
15526    #[test]
15527    fn spawned_executor_enforces_max_queue_depth_and_counts_drops() {
15528        let (result_tx, _result_rx) = mpsc::channel::<u32>();
15529        let (gate_tx, gate_rx) = mpsc::channel::<()>();
15530        let mut executor = SpawnTaskExecutor::new(result_tx, None, 1);
15531
15532        // First task occupies the single in-flight slot until gated.
15533        executor.submit(Box::new(move || {
15534            let _ = gate_rx.recv();
15535            1
15536        }));
15537        assert_eq!(executor.handles.len(), 1);
15538
15539        // Second submit exceeds the bound: shed + counted, no thread spawned.
15540        executor.submit(Box::new(|| 2));
15541        assert_eq!(executor.dropped, 1, "backpressure drop not counted");
15542        assert_eq!(executor.handles.len(), 1, "task spawned past the bound");
15543
15544        // Release the gate; post-shutdown submits are also counted drops.
15545        gate_tx.send(()).expect("release gate");
15546        executor.shutdown();
15547        executor.submit(Box::new(|| 3));
15548        assert_eq!(executor.dropped, 2, "post-shutdown drop not counted");
15549    }
15550
15551    #[cfg(feature = "asupersync-executor")]
15552    #[test]
15553    fn asupersync_backpressure_sheds_excess_in_flight_tasks() {
15554        struct SlowModel {
15555            done: u32,
15556        }
15557        #[derive(Debug)]
15558        enum SlowMsg {
15559            Done,
15560        }
15561        impl From<Event> for SlowMsg {
15562            fn from(_: Event) -> Self {
15563                SlowMsg::Done
15564            }
15565        }
15566        impl Model for SlowModel {
15567            type Message = SlowMsg;
15568            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
15569                match msg {
15570                    SlowMsg::Done => self.done += 1,
15571                }
15572                Cmd::none()
15573            }
15574            fn view(&self, _frame: &mut Frame) {}
15575        }
15576
15577        let evidence_path = temp_evidence_path("asupersync_backpressure");
15578        let sink_config = EvidenceSinkConfig::enabled_file(&evidence_path);
15579        let config = ProgramConfig::default()
15580            .with_evidence_sink(sink_config)
15581            .with_effect_queue(
15582                EffectQueueConfig::default()
15583                    .with_backend(TaskExecutorBackend::Asupersync)
15584                    .with_max_queue_depth(2),
15585            );
15586        let mut program = headless_program_with_config(SlowModel { done: 0 }, config);
15587
15588        // Submit more slow (still in-flight) tasks than the depth cap allows: the
15589        // first two occupy the in-flight slots, the rest are shed by backpressure.
15590        for _ in 0..6 {
15591            program
15592                .execute_cmd(Cmd::task(|| {
15593                    std::thread::sleep(Duration::from_millis(120));
15594                    SlowMsg::Done
15595                }))
15596                .expect("slow task cmd");
15597        }
15598
15599        // Backpressure must have fired with a recorded drop.
15600        let backpressure_line = read_evidence_event(&evidence_path, "task_executor_backpressure");
15601        assert_eq!(backpressure_line["backend"], "asupersync");
15602        assert_eq!(backpressure_line["action"], "drop");
15603
15604        // Drain the accepted tasks so teardown is prompt; no more than the depth
15605        // cap of tasks may complete.
15606        let deadline = Instant::now() + Duration::from_secs(5);
15607        while program.model().done < 2 && Instant::now() <= deadline {
15608            program
15609                .process_task_results()
15610                .expect("process task results");
15611            program.reap_finished_tasks();
15612        }
15613        assert!(
15614            program.model().done <= 2,
15615            "more tasks completed than the in-flight depth cap permits"
15616        );
15617    }
15618
15619    // =========================================================================
15620    // BatchController Tests (bd-4kq0.8.1)
15621    // =========================================================================
15622
15623    #[test]
15624    fn unit_tau_monotone() {
15625        // τ should decrease (or stay constant) as service time decreases,
15626        // since τ = E[S] × headroom.
15627        let mut bc = BatchController::new();
15628
15629        // High service time → high τ
15630        bc.observe_service(Duration::from_millis(20));
15631        bc.observe_service(Duration::from_millis(20));
15632        bc.observe_service(Duration::from_millis(20));
15633        let tau_high = bc.tau_s();
15634
15635        // Low service time → lower τ
15636        for _ in 0..20 {
15637            bc.observe_service(Duration::from_millis(1));
15638        }
15639        let tau_low = bc.tau_s();
15640
15641        assert!(
15642            tau_low <= tau_high,
15643            "τ should decrease with lower service time: tau_low={tau_low:.6}, tau_high={tau_high:.6}"
15644        );
15645    }
15646
15647    #[test]
15648    fn unit_tau_monotone_lambda() {
15649        // As arrival rate λ decreases (longer inter-arrival times),
15650        // τ should not increase (it's based on service time, not λ).
15651        // But ρ should decrease.
15652        let mut bc = BatchController::new();
15653        let base = Instant::now();
15654
15655        // Fast arrivals (λ high)
15656        for i in 0..10 {
15657            bc.observe_arrival(base + Duration::from_millis(i * 10));
15658        }
15659        let rho_fast = bc.rho_est();
15660
15661        // Slow arrivals (λ low)
15662        for i in 10..20 {
15663            bc.observe_arrival(base + Duration::from_millis(100 + i * 100));
15664        }
15665        let rho_slow = bc.rho_est();
15666
15667        assert!(
15668            rho_slow < rho_fast,
15669            "ρ should decrease with slower arrivals: rho_slow={rho_slow:.4}, rho_fast={rho_fast:.4}"
15670        );
15671    }
15672
15673    #[test]
15674    fn unit_stability() {
15675        // With reasonable service times, the controller should keep ρ < 1.
15676        let mut bc = BatchController::new();
15677        let base = Instant::now();
15678
15679        // Moderate arrival rate: 30 events/sec
15680        for i in 0..30 {
15681            bc.observe_arrival(base + Duration::from_millis(i * 33));
15682            bc.observe_service(Duration::from_millis(5)); // 5ms render
15683        }
15684
15685        assert!(
15686            bc.is_stable(),
15687            "should be stable at 30 events/sec with 5ms service: ρ={:.4}",
15688            bc.rho_est()
15689        );
15690        assert!(
15691            bc.rho_est() < 1.0,
15692            "utilization should be < 1: ρ={:.4}",
15693            bc.rho_est()
15694        );
15695
15696        // τ must be > E[S] (stability requirement)
15697        assert!(
15698            bc.tau_s() > bc.service_est_s(),
15699            "τ ({:.6}) must exceed E[S] ({:.6}) for stability",
15700            bc.tau_s(),
15701            bc.service_est_s()
15702        );
15703    }
15704
15705    #[test]
15706    fn unit_stability_high_load() {
15707        // Even under high load, τ keeps the system stable.
15708        let mut bc = BatchController::new();
15709        let base = Instant::now();
15710
15711        // 100 events/sec with 8ms render
15712        for i in 0..50 {
15713            bc.observe_arrival(base + Duration::from_millis(i * 10));
15714            bc.observe_service(Duration::from_millis(8));
15715        }
15716
15717        // τ × ρ_eff = E[S]/τ should be < 1
15718        let tau = bc.tau_s();
15719        let rho_eff = bc.service_est_s() / tau;
15720        assert!(
15721            rho_eff < 1.0,
15722            "effective utilization should be < 1: ρ_eff={rho_eff:.4}, τ={tau:.6}, E[S]={:.6}",
15723            bc.service_est_s()
15724        );
15725    }
15726
15727    #[test]
15728    fn batch_controller_defaults() {
15729        let bc = BatchController::new();
15730        assert!(bc.tau_s() >= bc.tau_min_s);
15731        assert!(bc.tau_s() <= bc.tau_max_s);
15732        assert_eq!(bc.observations(), 0);
15733        assert!(bc.is_stable());
15734    }
15735
15736    #[test]
15737    fn batch_controller_tau_clamped() {
15738        let mut bc = BatchController::new();
15739
15740        // Very fast service → τ clamped to tau_min
15741        for _ in 0..20 {
15742            bc.observe_service(Duration::from_micros(10));
15743        }
15744        assert!(
15745            bc.tau_s() >= bc.tau_min_s,
15746            "τ should be >= tau_min: τ={:.6}, min={:.6}",
15747            bc.tau_s(),
15748            bc.tau_min_s
15749        );
15750
15751        // Very slow service → τ clamped to tau_max
15752        for _ in 0..20 {
15753            bc.observe_service(Duration::from_millis(100));
15754        }
15755        assert!(
15756            bc.tau_s() <= bc.tau_max_s,
15757            "τ should be <= tau_max: τ={:.6}, max={:.6}",
15758            bc.tau_s(),
15759            bc.tau_max_s
15760        );
15761    }
15762
15763    #[test]
15764    fn batch_controller_duration_conversion() {
15765        let bc = BatchController::new();
15766        let tau = bc.tau();
15767        let tau_s = bc.tau_s();
15768        // Duration should match f64 representation
15769        let diff = (tau.as_secs_f64() - tau_s).abs();
15770        assert!(diff < 1e-9, "Duration conversion mismatch: {diff}");
15771    }
15772
15773    #[test]
15774    fn batch_controller_lambda_estimation() {
15775        let mut bc = BatchController::new();
15776        let base = Instant::now();
15777
15778        // 50 events/sec (20ms apart)
15779        for i in 0..20 {
15780            bc.observe_arrival(base + Duration::from_millis(i * 20));
15781        }
15782
15783        // λ should converge near 50
15784        let lambda = bc.lambda_est();
15785        assert!(
15786            lambda > 20.0 && lambda < 100.0,
15787            "λ should be near 50: got {lambda:.1}"
15788        );
15789    }
15790
15791    // ─────────────────────────────────────────────────────────────────────────────
15792    // Persistence Config Tests
15793    // ─────────────────────────────────────────────────────────────────────────────
15794
15795    #[test]
15796    fn cmd_save_state() {
15797        let cmd: Cmd<TestMsg> = Cmd::save_state();
15798        assert!(matches!(cmd, Cmd::SaveState));
15799    }
15800
15801    #[test]
15802    fn cmd_restore_state() {
15803        let cmd: Cmd<TestMsg> = Cmd::restore_state();
15804        assert!(matches!(cmd, Cmd::RestoreState));
15805    }
15806
15807    #[test]
15808    fn persistence_config_default() {
15809        let config = PersistenceConfig::default();
15810        assert!(config.registry.is_none());
15811        assert!(config.checkpoint_interval.is_none());
15812        assert!(config.auto_load);
15813        assert!(config.auto_save);
15814    }
15815
15816    #[test]
15817    fn persistence_config_disabled() {
15818        let config = PersistenceConfig::disabled();
15819        assert!(config.registry.is_none());
15820    }
15821
15822    #[test]
15823    fn persistence_config_with_registry() {
15824        use crate::state_persistence::{MemoryStorage, StateRegistry};
15825        use std::sync::Arc;
15826
15827        let registry = Arc::new(StateRegistry::new(Box::new(MemoryStorage::new())));
15828        let config = PersistenceConfig::with_registry(registry.clone());
15829
15830        assert!(config.registry.is_some());
15831        assert!(config.auto_load);
15832        assert!(config.auto_save);
15833    }
15834
15835    #[test]
15836    fn persistence_config_checkpoint_interval() {
15837        use crate::state_persistence::{MemoryStorage, StateRegistry};
15838        use std::sync::Arc;
15839
15840        let registry = Arc::new(StateRegistry::new(Box::new(MemoryStorage::new())));
15841        let config = PersistenceConfig::with_registry(registry)
15842            .checkpoint_every(Duration::from_secs(30))
15843            .auto_load(false)
15844            .auto_save(true);
15845
15846        assert!(config.checkpoint_interval.is_some());
15847        assert_eq!(config.checkpoint_interval.unwrap(), Duration::from_secs(30));
15848        assert!(!config.auto_load);
15849        assert!(config.auto_save);
15850    }
15851
15852    #[test]
15853    fn program_config_with_persistence() {
15854        use crate::state_persistence::{MemoryStorage, StateRegistry};
15855        use std::sync::Arc;
15856
15857        let registry = Arc::new(StateRegistry::new(Box::new(MemoryStorage::new())));
15858        let config = ProgramConfig::default().with_registry(registry);
15859
15860        assert!(config.persistence.registry.is_some());
15861    }
15862
15863    // =========================================================================
15864    // TaskSpec tests (bd-2yjus)
15865    // =========================================================================
15866
15867    #[test]
15868    fn task_spec_default() {
15869        let spec = TaskSpec::default();
15870        assert_eq!(spec.weight, DEFAULT_TASK_WEIGHT);
15871        assert_eq!(spec.estimate_ms, DEFAULT_TASK_ESTIMATE_MS);
15872        assert!(spec.name.is_none());
15873    }
15874
15875    #[test]
15876    fn task_spec_new() {
15877        let spec = TaskSpec::new(5.0, 20.0);
15878        assert_eq!(spec.weight, 5.0);
15879        assert_eq!(spec.estimate_ms, 20.0);
15880        assert!(spec.name.is_none());
15881    }
15882
15883    #[test]
15884    fn task_spec_with_name() {
15885        let spec = TaskSpec::default().with_name("fetch_data");
15886        assert_eq!(spec.name.as_deref(), Some("fetch_data"));
15887    }
15888
15889    #[test]
15890    fn task_spec_debug() {
15891        let spec = TaskSpec::new(2.0, 15.0).with_name("test");
15892        let debug = format!("{spec:?}");
15893        assert!(debug.contains("2.0"));
15894        assert!(debug.contains("15.0"));
15895        assert!(debug.contains("test"));
15896    }
15897
15898    // =========================================================================
15899    // Cmd::count() tests (bd-2yjus)
15900    // =========================================================================
15901
15902    #[test]
15903    fn cmd_count_none() {
15904        let cmd: Cmd<TestMsg> = Cmd::none();
15905        assert_eq!(cmd.count(), 0);
15906    }
15907
15908    #[test]
15909    fn cmd_count_atomic() {
15910        assert_eq!(Cmd::<TestMsg>::quit().count(), 1);
15911        assert_eq!(Cmd::<TestMsg>::msg(TestMsg::Increment).count(), 1);
15912        assert_eq!(Cmd::<TestMsg>::tick(Duration::from_millis(100)).count(), 1);
15913        assert_eq!(Cmd::<TestMsg>::log("hello").count(), 1);
15914        assert_eq!(Cmd::<TestMsg>::save_state().count(), 1);
15915        assert_eq!(Cmd::<TestMsg>::restore_state().count(), 1);
15916        assert_eq!(Cmd::<TestMsg>::set_mouse_capture(true).count(), 1);
15917    }
15918
15919    #[test]
15920    fn cmd_count_batch() {
15921        let cmd: Cmd<TestMsg> =
15922            Cmd::Batch(vec![Cmd::quit(), Cmd::msg(TestMsg::Increment), Cmd::none()]);
15923        assert_eq!(cmd.count(), 2); // quit + msg, none counts 0
15924    }
15925
15926    #[test]
15927    fn cmd_count_nested() {
15928        let cmd: Cmd<TestMsg> = Cmd::Batch(vec![
15929            Cmd::msg(TestMsg::Increment),
15930            Cmd::Sequence(vec![Cmd::quit(), Cmd::msg(TestMsg::Increment)]),
15931        ]);
15932        assert_eq!(cmd.count(), 3);
15933    }
15934
15935    // =========================================================================
15936    // Cmd::type_name() tests (bd-2yjus)
15937    // =========================================================================
15938
15939    #[test]
15940    fn cmd_type_name_all_variants() {
15941        assert_eq!(Cmd::<TestMsg>::none().type_name(), "None");
15942        assert_eq!(Cmd::<TestMsg>::quit().type_name(), "Quit");
15943        assert_eq!(
15944            Cmd::<TestMsg>::Batch(vec![Cmd::none()]).type_name(),
15945            "Batch"
15946        );
15947        assert_eq!(
15948            Cmd::<TestMsg>::Sequence(vec![Cmd::none()]).type_name(),
15949            "Sequence"
15950        );
15951        assert_eq!(Cmd::<TestMsg>::msg(TestMsg::Increment).type_name(), "Msg");
15952        assert_eq!(
15953            Cmd::<TestMsg>::tick(Duration::from_millis(1)).type_name(),
15954            "Tick"
15955        );
15956        assert_eq!(Cmd::<TestMsg>::log("x").type_name(), "Log");
15957        assert_eq!(
15958            Cmd::<TestMsg>::task(|| TestMsg::Increment).type_name(),
15959            "Task"
15960        );
15961        assert_eq!(Cmd::<TestMsg>::save_state().type_name(), "SaveState");
15962        assert_eq!(Cmd::<TestMsg>::restore_state().type_name(), "RestoreState");
15963        assert_eq!(
15964            Cmd::<TestMsg>::set_mouse_capture(true).type_name(),
15965            "SetMouseCapture"
15966        );
15967    }
15968
15969    // =========================================================================
15970    // Cmd::batch() / Cmd::sequence() edge-case tests (bd-2yjus)
15971    // =========================================================================
15972
15973    #[test]
15974    fn cmd_batch_empty_returns_none() {
15975        let cmd: Cmd<TestMsg> = Cmd::batch(vec![]);
15976        assert!(matches!(cmd, Cmd::None));
15977    }
15978
15979    #[test]
15980    fn cmd_batch_single_unwraps() {
15981        let cmd: Cmd<TestMsg> = Cmd::batch(vec![Cmd::quit()]);
15982        assert!(matches!(cmd, Cmd::Quit));
15983    }
15984
15985    #[test]
15986    fn cmd_batch_multiple_stays_batch() {
15987        let cmd: Cmd<TestMsg> = Cmd::batch(vec![Cmd::quit(), Cmd::msg(TestMsg::Increment)]);
15988        assert!(matches!(cmd, Cmd::Batch(_)));
15989    }
15990
15991    #[test]
15992    fn cmd_sequence_empty_returns_none() {
15993        let cmd: Cmd<TestMsg> = Cmd::sequence(vec![]);
15994        assert!(matches!(cmd, Cmd::None));
15995    }
15996
15997    #[test]
15998    fn cmd_sequence_single_unwraps_to_inner() {
15999        let cmd: Cmd<TestMsg> = Cmd::sequence(vec![Cmd::quit()]);
16000        assert!(matches!(cmd, Cmd::Quit));
16001    }
16002
16003    #[test]
16004    fn cmd_sequence_multiple_stays_sequence() {
16005        let cmd: Cmd<TestMsg> = Cmd::sequence(vec![Cmd::quit(), Cmd::msg(TestMsg::Increment)]);
16006        assert!(matches!(cmd, Cmd::Sequence(_)));
16007    }
16008
16009    // =========================================================================
16010    // Cmd task constructor variants (bd-2yjus)
16011    // =========================================================================
16012
16013    #[test]
16014    fn cmd_task_with_spec() {
16015        let spec = TaskSpec::new(3.0, 25.0).with_name("my_task");
16016        let cmd: Cmd<TestMsg> = Cmd::task_with_spec(spec, || TestMsg::Increment);
16017        match cmd {
16018            Cmd::Task(s, _) => {
16019                assert_eq!(s.weight, 3.0);
16020                assert_eq!(s.estimate_ms, 25.0);
16021                assert_eq!(s.name.as_deref(), Some("my_task"));
16022            }
16023            _ => panic!("expected Task variant"),
16024        }
16025    }
16026
16027    #[test]
16028    fn cmd_task_weighted() {
16029        let cmd: Cmd<TestMsg> = Cmd::task_weighted(2.0, 50.0, || TestMsg::Increment);
16030        match cmd {
16031            Cmd::Task(s, _) => {
16032                assert_eq!(s.weight, 2.0);
16033                assert_eq!(s.estimate_ms, 50.0);
16034                assert!(s.name.is_none());
16035            }
16036            _ => panic!("expected Task variant"),
16037        }
16038    }
16039
16040    #[test]
16041    fn cmd_task_named() {
16042        let cmd: Cmd<TestMsg> = Cmd::task_named("background_fetch", || TestMsg::Increment);
16043        match cmd {
16044            Cmd::Task(s, _) => {
16045                assert_eq!(s.weight, DEFAULT_TASK_WEIGHT);
16046                assert_eq!(s.estimate_ms, DEFAULT_TASK_ESTIMATE_MS);
16047                assert_eq!(s.name.as_deref(), Some("background_fetch"));
16048            }
16049            _ => panic!("expected Task variant"),
16050        }
16051    }
16052
16053    // =========================================================================
16054    // Cmd Debug formatting (bd-2yjus)
16055    // =========================================================================
16056
16057    #[test]
16058    fn cmd_debug_all_variant_strings() {
16059        assert_eq!(format!("{:?}", Cmd::<TestMsg>::none()), "None");
16060        assert_eq!(format!("{:?}", Cmd::<TestMsg>::quit()), "Quit");
16061        assert!(format!("{:?}", Cmd::<TestMsg>::msg(TestMsg::Increment)).starts_with("Msg("));
16062        assert!(
16063            format!("{:?}", Cmd::<TestMsg>::tick(Duration::from_millis(100))).starts_with("Tick(")
16064        );
16065        assert!(format!("{:?}", Cmd::<TestMsg>::log("hi")).starts_with("Log("));
16066        assert!(format!("{:?}", Cmd::<TestMsg>::task(|| TestMsg::Increment)).starts_with("Task"));
16067        assert_eq!(format!("{:?}", Cmd::<TestMsg>::save_state()), "SaveState");
16068        assert_eq!(
16069            format!("{:?}", Cmd::<TestMsg>::restore_state()),
16070            "RestoreState"
16071        );
16072        assert_eq!(
16073            format!("{:?}", Cmd::<TestMsg>::set_mouse_capture(true)),
16074            "SetMouseCapture(true)"
16075        );
16076    }
16077
16078    // =========================================================================
16079    // Cmd::set_mouse_capture headless execution (bd-2yjus)
16080    // =========================================================================
16081
16082    #[test]
16083    fn headless_execute_cmd_set_mouse_capture() {
16084        let mut program =
16085            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
16086        assert!(!program.backend_features.mouse_capture);
16087
16088        program
16089            .execute_cmd(Cmd::set_mouse_capture(true))
16090            .expect("set mouse capture true");
16091        assert!(program.backend_features.mouse_capture);
16092
16093        program
16094            .execute_cmd(Cmd::set_mouse_capture(false))
16095            .expect("set mouse capture false");
16096        assert!(!program.backend_features.mouse_capture);
16097    }
16098
16099    // =========================================================================
16100    // ResizeBehavior tests (bd-2yjus)
16101    // =========================================================================
16102
16103    #[test]
16104    fn resize_behavior_uses_coalescer() {
16105        assert!(ResizeBehavior::Throttled.uses_coalescer());
16106        assert!(!ResizeBehavior::Immediate.uses_coalescer());
16107    }
16108
16109    #[test]
16110    fn resize_behavior_eq_and_debug() {
16111        assert_eq!(ResizeBehavior::Immediate, ResizeBehavior::Immediate);
16112        assert_ne!(ResizeBehavior::Immediate, ResizeBehavior::Throttled);
16113        let debug = format!("{:?}", ResizeBehavior::Throttled);
16114        assert_eq!(debug, "Throttled");
16115    }
16116
16117    // =========================================================================
16118    // WidgetRefreshConfig default values (bd-2yjus)
16119    // =========================================================================
16120
16121    #[test]
16122    fn widget_refresh_config_defaults() {
16123        let config = WidgetRefreshConfig::default();
16124        assert!(config.enabled);
16125        assert_eq!(config.staleness_window_ms, 1_000);
16126        assert_eq!(config.starve_ms, 3_000);
16127        assert_eq!(config.max_starved_per_frame, 2);
16128        assert_eq!(config.max_drop_fraction, 1.0);
16129        assert_eq!(config.weight_priority, 1.0);
16130        assert_eq!(config.weight_staleness, 0.5);
16131        assert_eq!(config.weight_focus, 0.75);
16132        assert_eq!(config.weight_interaction, 0.5);
16133        assert_eq!(config.starve_boost, 1.5);
16134        assert_eq!(config.min_cost_us, 1.0);
16135    }
16136
16137    // =========================================================================
16138    // EffectQueueConfig tests (bd-2yjus)
16139    // =========================================================================
16140
16141    #[test]
16142    fn effect_queue_config_default() {
16143        let config = EffectQueueConfig::default();
16144        assert!(!config.enabled);
16145        assert_eq!(config.backend, TaskExecutorBackend::Spawned);
16146        assert!(!config.explicit_backend);
16147        assert!(config.scheduler.smith_enabled);
16148        assert!(!config.scheduler.force_fifo);
16149        assert!(!config.scheduler.preemptive);
16150    }
16151
16152    #[test]
16153    fn effect_queue_config_with_enabled() {
16154        let config = EffectQueueConfig::default().with_enabled(true);
16155        assert!(config.enabled);
16156        assert_eq!(config.backend, TaskExecutorBackend::EffectQueue);
16157        assert!(config.explicit_backend);
16158    }
16159
16160    #[test]
16161    fn effect_queue_config_with_enabled_false_marks_explicit_spawned_backend() {
16162        let config = EffectQueueConfig::default().with_enabled(false);
16163        assert!(!config.enabled);
16164        assert_eq!(config.backend, TaskExecutorBackend::Spawned);
16165        assert!(config.explicit_backend);
16166    }
16167
16168    #[test]
16169    fn effect_queue_config_with_backend() {
16170        let config = EffectQueueConfig::default().with_backend(TaskExecutorBackend::EffectQueue);
16171        assert!(config.enabled);
16172        assert_eq!(config.backend, TaskExecutorBackend::EffectQueue);
16173        assert!(config.explicit_backend);
16174    }
16175
16176    #[cfg(feature = "asupersync-executor")]
16177    #[test]
16178    fn effect_queue_config_with_asupersync_backend_disables_effect_queue_flag() {
16179        let config = EffectQueueConfig::default().with_backend(TaskExecutorBackend::Asupersync);
16180        assert!(!config.enabled);
16181        assert_eq!(config.backend, TaskExecutorBackend::Asupersync);
16182    }
16183
16184    #[test]
16185    fn effect_queue_config_with_scheduler() {
16186        let sched = SchedulerConfig {
16187            force_fifo: true,
16188            ..Default::default()
16189        };
16190        let config = EffectQueueConfig::default().with_scheduler(sched);
16191        assert!(config.scheduler.force_fifo);
16192    }
16193
16194    // =========================================================================
16195    // InlineAutoRemeasureConfig defaults (bd-2yjus)
16196    // =========================================================================
16197
16198    #[test]
16199    fn inline_auto_remeasure_config_defaults() {
16200        let config = InlineAutoRemeasureConfig::default();
16201        assert_eq!(config.change_threshold_rows, 1);
16202        assert_eq!(config.voi.prior_alpha, 1.0);
16203        assert_eq!(config.voi.prior_beta, 9.0);
16204        assert_eq!(config.voi.max_interval_ms, 1000);
16205        assert_eq!(config.voi.min_interval_ms, 100);
16206        assert_eq!(config.voi.sample_cost, 0.08);
16207    }
16208
16209    // =========================================================================
16210    // HeadlessEventSource direct tests (bd-2yjus)
16211    // =========================================================================
16212
16213    #[test]
16214    fn headless_event_source_size() {
16215        let source = HeadlessEventSource::new(120, 40, BackendFeatures::default());
16216        assert_eq!(source.size().unwrap(), (120, 40));
16217    }
16218
16219    #[test]
16220    fn headless_event_source_poll_always_false() {
16221        let mut source = HeadlessEventSource::new(80, 24, BackendFeatures::default());
16222        assert!(!source.poll_event(Duration::from_millis(100)).unwrap());
16223    }
16224
16225    #[test]
16226    fn headless_event_source_read_always_none() {
16227        let mut source = HeadlessEventSource::new(80, 24, BackendFeatures::default());
16228        assert!(source.read_event().unwrap().is_none());
16229    }
16230
16231    #[test]
16232    fn headless_event_source_set_features() {
16233        let mut source = HeadlessEventSource::new(80, 24, BackendFeatures::default());
16234        let features = BackendFeatures {
16235            mouse_capture: true,
16236            bracketed_paste: true,
16237            focus_events: true,
16238            kitty_keyboard: true,
16239        };
16240        source.set_features(features).unwrap();
16241        assert_eq!(source.features, features);
16242    }
16243
16244    #[test]
16245    fn immediate_drain_budget_adds_backoff_poll_under_burst() {
16246        use ftui_core::event::{KeyCode, KeyEvent};
16247
16248        struct DrainBurstModel {
16249            processed: usize,
16250            quit_after: usize,
16251        }
16252
16253        #[derive(Debug)]
16254        #[allow(dead_code)]
16255        enum DrainBurstMsg {
16256            Event(Event),
16257        }
16258
16259        impl From<Event> for DrainBurstMsg {
16260            fn from(event: Event) -> Self {
16261                DrainBurstMsg::Event(event)
16262            }
16263        }
16264
16265        impl Model for DrainBurstModel {
16266            type Message = DrainBurstMsg;
16267
16268            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
16269                match msg {
16270                    DrainBurstMsg::Event(_) => {
16271                        self.processed = self.processed.saturating_add(1);
16272                        if self.processed >= self.quit_after {
16273                            Cmd::quit()
16274                        } else {
16275                            Cmd::none()
16276                        }
16277                    }
16278                }
16279            }
16280
16281            fn view(&self, _frame: &mut Frame) {}
16282        }
16283
16284        struct DrainBurstEventSource {
16285            queue: VecDeque<Event>,
16286            poll_timeouts: Arc<std::sync::Mutex<Vec<Duration>>>,
16287            size: (u16, u16),
16288        }
16289
16290        impl BackendEventSource for DrainBurstEventSource {
16291            type Error = io::Error;
16292
16293            fn size(&self) -> Result<(u16, u16), Self::Error> {
16294                Ok(self.size)
16295            }
16296
16297            fn set_features(&mut self, _features: BackendFeatures) -> Result<(), Self::Error> {
16298                Ok(())
16299            }
16300
16301            fn poll_event(&mut self, timeout: Duration) -> Result<bool, Self::Error> {
16302                self.poll_timeouts.lock().unwrap().push(timeout);
16303                Ok(!self.queue.is_empty())
16304            }
16305
16306            fn read_event(&mut self) -> Result<Option<Event>, Self::Error> {
16307                Ok(self.queue.pop_front())
16308            }
16309        }
16310
16311        let burst_events = 24usize;
16312        let poll_timeouts = Arc::new(std::sync::Mutex::new(Vec::new()));
16313        let mut queue = VecDeque::new();
16314        for _ in 0..burst_events {
16315            queue.push_back(Event::Key(KeyEvent::new(KeyCode::Char('x'))));
16316        }
16317
16318        let events = DrainBurstEventSource {
16319            queue,
16320            poll_timeouts: poll_timeouts.clone(),
16321            size: (80, 24),
16322        };
16323        let writer = TerminalWriter::new(
16324            Vec::<u8>::new(),
16325            ScreenMode::AltScreen,
16326            UiAnchor::Bottom,
16327            TerminalCapabilities::dumb(),
16328        );
16329        let config = ProgramConfig::default()
16330            .with_forced_size(80, 24)
16331            .with_signal_interception(false)
16332            .with_immediate_drain(ImmediateDrainConfig {
16333                max_zero_timeout_polls_per_burst: 3,
16334                max_burst_duration: Duration::from_secs(1),
16335                backoff_timeout: Duration::from_millis(1),
16336            });
16337
16338        let model = DrainBurstModel {
16339            processed: 0,
16340            quit_after: burst_events,
16341        };
16342        let mut program =
16343            Program::with_event_source(model, events, BackendFeatures::default(), writer, config)
16344                .expect("program creation");
16345        program.run().expect("run burst");
16346
16347        assert_eq!(program.model().processed, burst_events);
16348
16349        let stats = program.immediate_drain_stats();
16350        assert_eq!(stats.bursts, 1);
16351        assert!(stats.capped_bursts >= 1);
16352        assert!(stats.backoff_polls >= 1);
16353        assert!(stats.zero_timeout_polls >= 1);
16354        assert!(stats.max_zero_timeout_polls_in_burst <= 3);
16355
16356        let timeouts = poll_timeouts.lock().unwrap();
16357        assert!(timeouts.contains(&Duration::ZERO));
16358        assert!(timeouts.contains(&Duration::from_millis(1)));
16359    }
16360
16361    /// Regression test for frankentui#95: an event source that reports poll
16362    /// readiness but yields no event from `read_event` (spurious readiness,
16363    /// as the Windows console can produce) must not stall or busy-spin the
16364    /// event loop. The runtime must treat `read_event() == Ok(None)` as
16365    /// "nothing decodable", finish the drain burst via its bounded
16366    /// zero-timeout polls, and return to the timed outer poll so ticks and
16367    /// queued messages keep flowing.
16368    #[test]
16369    fn spurious_poll_readiness_does_not_stall_event_loop() {
16370        struct SpuriousModel {
16371            ticks: usize,
16372            quit_after: usize,
16373        }
16374
16375        #[derive(Debug)]
16376        enum SpuriousMsg {
16377            Tick,
16378            Other,
16379        }
16380
16381        impl From<Event> for SpuriousMsg {
16382            fn from(event: Event) -> Self {
16383                match event {
16384                    Event::Tick => SpuriousMsg::Tick,
16385                    _ => SpuriousMsg::Other,
16386                }
16387            }
16388        }
16389
16390        impl Model for SpuriousModel {
16391            type Message = SpuriousMsg;
16392
16393            fn init(&mut self) -> Cmd<Self::Message> {
16394                Cmd::tick(Duration::from_millis(1))
16395            }
16396
16397            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
16398                match msg {
16399                    SpuriousMsg::Tick => {
16400                        self.ticks = self.ticks.saturating_add(1);
16401                        if self.ticks >= self.quit_after {
16402                            Cmd::quit()
16403                        } else {
16404                            Cmd::none()
16405                        }
16406                    }
16407                    SpuriousMsg::Other => Cmd::none(),
16408                }
16409            }
16410
16411            fn view(&self, _frame: &mut Frame) {}
16412        }
16413
16414        struct SpuriousReadySource {
16415            spurious_polls_remaining: usize,
16416            read_calls: Arc<std::sync::atomic::AtomicUsize>,
16417        }
16418
16419        impl BackendEventSource for SpuriousReadySource {
16420            type Error = io::Error;
16421
16422            fn size(&self) -> Result<(u16, u16), Self::Error> {
16423                Ok((80, 24))
16424            }
16425
16426            fn set_features(&mut self, _features: BackendFeatures) -> Result<(), Self::Error> {
16427                Ok(())
16428            }
16429
16430            fn poll_event(&mut self, _timeout: Duration) -> Result<bool, Self::Error> {
16431                if self.spurious_polls_remaining > 0 {
16432                    self.spurious_polls_remaining -= 1;
16433                    Ok(true)
16434                } else {
16435                    Ok(false)
16436                }
16437            }
16438
16439            fn read_event(&mut self) -> Result<Option<Event>, Self::Error> {
16440                // Readiness was spurious: nothing decodable is ever produced.
16441                self.read_calls
16442                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
16443                Ok(None)
16444            }
16445        }
16446
16447        let spurious_polls = 5usize;
16448        let read_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
16449        let events = SpuriousReadySource {
16450            spurious_polls_remaining: spurious_polls,
16451            read_calls: read_calls.clone(),
16452        };
16453        let writer = TerminalWriter::new(
16454            Vec::<u8>::new(),
16455            ScreenMode::AltScreen,
16456            UiAnchor::Bottom,
16457            TerminalCapabilities::dumb(),
16458        );
16459        let config = ProgramConfig::default()
16460            .with_forced_size(80, 24)
16461            .with_signal_interception(false);
16462
16463        let model = SpuriousModel {
16464            ticks: 0,
16465            quit_after: 3,
16466        };
16467        let mut program =
16468            Program::with_event_source(model, events, BackendFeatures::default(), writer, config)
16469                .expect("program creation");
16470        // If spurious readiness parked the loop (the frankentui#95 failure
16471        // mode with a blocking read), this would hang instead of returning.
16472        program.run().expect("run with spurious readiness");
16473
16474        assert_eq!(program.model().ticks, 3, "ticks must keep flowing");
16475        // Every `true` poll is followed by exactly one read attempt; a
16476        // spurious-ready source must produce a bounded number of empty reads,
16477        // not an unbounded spin.
16478        assert_eq!(
16479            read_calls.load(std::sync::atomic::Ordering::Relaxed),
16480            spurious_polls
16481        );
16482    }
16483
16484    #[test]
16485    fn immediate_drain_zero_poll_limit_is_clamped() {
16486        use ftui_core::event::{KeyCode, KeyEvent};
16487
16488        struct ClampModel {
16489            processed: usize,
16490            quit_after: usize,
16491        }
16492
16493        #[derive(Debug)]
16494        #[allow(dead_code)]
16495        enum ClampMsg {
16496            Event(Event),
16497        }
16498
16499        impl From<Event> for ClampMsg {
16500            fn from(event: Event) -> Self {
16501                ClampMsg::Event(event)
16502            }
16503        }
16504
16505        impl Model for ClampModel {
16506            type Message = ClampMsg;
16507
16508            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
16509                match msg {
16510                    ClampMsg::Event(_) => {
16511                        self.processed = self.processed.saturating_add(1);
16512                        if self.processed >= self.quit_after {
16513                            Cmd::quit()
16514                        } else {
16515                            Cmd::none()
16516                        }
16517                    }
16518                }
16519            }
16520
16521            fn view(&self, _frame: &mut Frame) {}
16522        }
16523
16524        struct ClampSource {
16525            queue: VecDeque<Event>,
16526        }
16527
16528        impl BackendEventSource for ClampSource {
16529            type Error = io::Error;
16530
16531            fn size(&self) -> Result<(u16, u16), Self::Error> {
16532                Ok((80, 24))
16533            }
16534
16535            fn set_features(&mut self, _features: BackendFeatures) -> Result<(), Self::Error> {
16536                Ok(())
16537            }
16538
16539            fn poll_event(&mut self, _timeout: Duration) -> Result<bool, Self::Error> {
16540                Ok(!self.queue.is_empty())
16541            }
16542
16543            fn read_event(&mut self) -> Result<Option<Event>, Self::Error> {
16544                Ok(self.queue.pop_front())
16545            }
16546        }
16547
16548        let burst_events = 8usize;
16549        let mut queue = VecDeque::new();
16550        for _ in 0..burst_events {
16551            queue.push_back(Event::Key(KeyEvent::new(KeyCode::Char('z'))));
16552        }
16553        let events = ClampSource { queue };
16554
16555        let writer = TerminalWriter::new(
16556            Vec::<u8>::new(),
16557            ScreenMode::AltScreen,
16558            UiAnchor::Bottom,
16559            TerminalCapabilities::dumb(),
16560        );
16561        let config = ProgramConfig::default()
16562            .with_forced_size(80, 24)
16563            .with_signal_interception(false)
16564            .with_immediate_drain(ImmediateDrainConfig {
16565                max_zero_timeout_polls_per_burst: 0,
16566                max_burst_duration: Duration::from_secs(1),
16567                backoff_timeout: Duration::from_millis(1),
16568            });
16569        let model = ClampModel {
16570            processed: 0,
16571            quit_after: burst_events,
16572        };
16573
16574        let mut program =
16575            Program::with_event_source(model, events, BackendFeatures::default(), writer, config)
16576                .expect("program creation");
16577        program.run().expect("run clamp");
16578
16579        let stats = program.immediate_drain_stats();
16580        assert!(stats.max_zero_timeout_polls_in_burst <= 1);
16581    }
16582
16583    #[test]
16584    fn quit_stops_draining_remaining_burst_events() {
16585        use ftui_core::event::{KeyCode, KeyEvent};
16586
16587        struct QuitBurstModel {
16588            processed: usize,
16589            quit_after: usize,
16590        }
16591
16592        #[derive(Debug)]
16593        #[allow(dead_code)]
16594        enum QuitBurstMsg {
16595            Event(Event),
16596        }
16597
16598        impl From<Event> for QuitBurstMsg {
16599            fn from(event: Event) -> Self {
16600                Self::Event(event)
16601            }
16602        }
16603
16604        impl Model for QuitBurstModel {
16605            type Message = QuitBurstMsg;
16606
16607            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
16608                match msg {
16609                    QuitBurstMsg::Event(_) => {
16610                        self.processed = self.processed.saturating_add(1);
16611                        if self.processed >= self.quit_after {
16612                            Cmd::quit()
16613                        } else {
16614                            Cmd::none()
16615                        }
16616                    }
16617                }
16618            }
16619
16620            fn view(&self, _frame: &mut Frame) {}
16621        }
16622
16623        struct QuitBurstSource {
16624            queue: VecDeque<Event>,
16625        }
16626
16627        impl BackendEventSource for QuitBurstSource {
16628            type Error = io::Error;
16629
16630            fn size(&self) -> Result<(u16, u16), Self::Error> {
16631                Ok((80, 24))
16632            }
16633
16634            fn set_features(&mut self, _features: BackendFeatures) -> Result<(), Self::Error> {
16635                Ok(())
16636            }
16637
16638            fn poll_event(&mut self, _timeout: Duration) -> Result<bool, Self::Error> {
16639                Ok(!self.queue.is_empty())
16640            }
16641
16642            fn read_event(&mut self) -> Result<Option<Event>, Self::Error> {
16643                Ok(self.queue.pop_front())
16644            }
16645        }
16646
16647        let total_events = 8usize;
16648        let quit_after = 3usize;
16649        let mut queue = VecDeque::new();
16650        for _ in 0..total_events {
16651            queue.push_back(Event::Key(KeyEvent::new(KeyCode::Char('q'))));
16652        }
16653
16654        let writer = TerminalWriter::new(
16655            Vec::<u8>::new(),
16656            ScreenMode::AltScreen,
16657            UiAnchor::Bottom,
16658            TerminalCapabilities::dumb(),
16659        );
16660        let config = ProgramConfig::default()
16661            .with_forced_size(80, 24)
16662            .with_signal_interception(false)
16663            .with_immediate_drain(ImmediateDrainConfig {
16664                max_zero_timeout_polls_per_burst: 64,
16665                max_burst_duration: Duration::from_secs(1),
16666                backoff_timeout: Duration::from_millis(1),
16667            });
16668        let model = QuitBurstModel {
16669            processed: 0,
16670            quit_after,
16671        };
16672        let events = QuitBurstSource { queue };
16673
16674        let mut program =
16675            Program::with_event_source(model, events, BackendFeatures::default(), writer, config)
16676                .expect("program creation");
16677        program.run().expect("run burst quit");
16678
16679        assert_eq!(program.model().processed, quit_after);
16680    }
16681
16682    // =========================================================================
16683    // Program helper methods (bd-2yjus)
16684    // =========================================================================
16685
16686    #[test]
16687    fn headless_program_quit_and_is_running() {
16688        let mut program =
16689            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
16690        assert!(program.is_running());
16691
16692        program.quit();
16693        assert!(!program.is_running());
16694    }
16695
16696    #[test]
16697    fn headless_program_model_mut() {
16698        let mut program =
16699            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
16700        assert_eq!(program.model().value, 0);
16701
16702        program.model_mut().value = 42;
16703        assert_eq!(program.model().value, 42);
16704    }
16705
16706    #[test]
16707    fn headless_program_request_redraw() {
16708        let mut program =
16709            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
16710        program.dirty = false;
16711
16712        program.request_redraw();
16713        assert!(program.dirty);
16714    }
16715
16716    #[test]
16717    fn headless_program_last_widget_signals_initially_empty() {
16718        let program =
16719            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
16720        assert!(program.last_widget_signals().is_empty());
16721    }
16722
16723    #[test]
16724    fn headless_program_no_persistence_by_default() {
16725        let program =
16726            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
16727        assert!(!program.has_persistence());
16728        assert!(program.state_registry().is_none());
16729    }
16730
16731    // =========================================================================
16732    // classify_event_for_fairness (bd-2yjus)
16733    // =========================================================================
16734
16735    #[test]
16736    fn classify_event_fairness_key_is_input() {
16737        let event = Event::Key(ftui_core::event::KeyEvent::new(
16738            ftui_core::event::KeyCode::Char('a'),
16739        ));
16740        let classification =
16741            Program::<TestModel, HeadlessEventSource, Vec<u8>>::classify_event_for_fairness(&event);
16742        assert_eq!(classification, FairnessEventType::Input);
16743    }
16744
16745    #[test]
16746    fn classify_event_fairness_resize_is_resize() {
16747        let event = Event::Resize {
16748            width: 80,
16749            height: 24,
16750        };
16751        let classification =
16752            Program::<TestModel, HeadlessEventSource, Vec<u8>>::classify_event_for_fairness(&event);
16753        assert_eq!(classification, FairnessEventType::Resize);
16754    }
16755
16756    #[test]
16757    fn classify_event_fairness_tick_is_tick() {
16758        let event = Event::Tick;
16759        let classification =
16760            Program::<TestModel, HeadlessEventSource, Vec<u8>>::classify_event_for_fairness(&event);
16761        assert_eq!(classification, FairnessEventType::Tick);
16762    }
16763
16764    #[test]
16765    fn classify_event_fairness_paste_is_input() {
16766        let event = Event::Paste(ftui_core::event::PasteEvent::bracketed("hello"));
16767        let classification =
16768            Program::<TestModel, HeadlessEventSource, Vec<u8>>::classify_event_for_fairness(&event);
16769        assert_eq!(classification, FairnessEventType::Input);
16770    }
16771
16772    #[test]
16773    fn classify_event_fairness_focus_is_input() {
16774        let event = Event::Focus(true);
16775        let classification =
16776            Program::<TestModel, HeadlessEventSource, Vec<u8>>::classify_event_for_fairness(&event);
16777        assert_eq!(classification, FairnessEventType::Input);
16778    }
16779
16780    // =========================================================================
16781    // ProgramConfig builder methods (bd-2yjus)
16782    // =========================================================================
16783
16784    #[test]
16785    fn program_config_with_diff_config() {
16786        let diff = RuntimeDiffConfig::default();
16787        let config = ProgramConfig::default().with_diff_config(diff.clone());
16788        // Just verify it doesn't panic and the field is set
16789        let _ = format!("{:?}", config);
16790    }
16791
16792    #[test]
16793    fn program_config_with_evidence_sink() {
16794        let config =
16795            ProgramConfig::default().with_evidence_sink(EvidenceSinkConfig::enabled_stdout());
16796        let _ = format!("{:?}", config);
16797    }
16798
16799    #[test]
16800    fn program_config_with_render_trace() {
16801        let config = ProgramConfig::default().with_render_trace(RenderTraceConfig::default());
16802        let _ = format!("{:?}", config);
16803    }
16804
16805    #[test]
16806    fn program_config_with_locale() {
16807        let config = ProgramConfig::default().with_locale("fr");
16808        let _ = format!("{:?}", config);
16809    }
16810
16811    #[test]
16812    fn program_config_with_locale_context() {
16813        let config = ProgramConfig::default().with_locale_context(LocaleContext::new("de"));
16814        let _ = format!("{:?}", config);
16815    }
16816
16817    #[test]
16818    fn program_config_without_forced_size() {
16819        let config = ProgramConfig::default()
16820            .with_forced_size(80, 24)
16821            .without_forced_size();
16822        assert!(config.forced_size.is_none());
16823    }
16824
16825    #[test]
16826    fn program_config_forced_size_clamps_min() {
16827        let config = ProgramConfig::default().with_forced_size(0, 0);
16828        assert_eq!(config.forced_size, Some((1, 1)));
16829    }
16830
16831    #[test]
16832    fn program_config_with_widget_refresh() {
16833        let wrc = WidgetRefreshConfig {
16834            enabled: false,
16835            ..Default::default()
16836        };
16837        let config = ProgramConfig::default().with_widget_refresh(wrc);
16838        assert!(!config.widget_refresh.enabled);
16839    }
16840
16841    #[test]
16842    fn program_config_with_effect_queue() {
16843        let eqc = EffectQueueConfig::default().with_enabled(true);
16844        let config = ProgramConfig::default().with_effect_queue(eqc);
16845        assert!(config.effect_queue.enabled);
16846        assert_eq!(
16847            config.effect_queue.backend,
16848            TaskExecutorBackend::EffectQueue
16849        );
16850    }
16851
16852    #[test]
16853    fn program_config_with_resize_coalescer_custom() {
16854        let cc = CoalescerConfig {
16855            steady_delay_ms: 42,
16856            ..Default::default()
16857        };
16858        let config = ProgramConfig::default().with_resize_coalescer(cc);
16859        assert_eq!(config.resize_coalescer.steady_delay_ms, 42);
16860    }
16861
16862    #[test]
16863    fn program_config_with_inline_auto_remeasure() {
16864        let config = ProgramConfig::default()
16865            .with_inline_auto_remeasure(InlineAutoRemeasureConfig::default());
16866        assert!(config.inline_auto_remeasure.is_some());
16867
16868        let config = config.without_inline_auto_remeasure();
16869        assert!(config.inline_auto_remeasure.is_none());
16870    }
16871
16872    #[test]
16873    fn program_config_with_persistence_full() {
16874        let pc = PersistenceConfig::disabled();
16875        let config = ProgramConfig::default().with_persistence(pc);
16876        assert!(config.persistence.registry.is_none());
16877    }
16878
16879    #[test]
16880    fn program_config_with_conformal_config() {
16881        let config = ProgramConfig::default()
16882            .with_conformal_config(ConformalConfig::default())
16883            .without_conformal();
16884        assert!(config.conformal_config.is_none());
16885    }
16886
16887    // =========================================================================
16888    // Rollout config builder methods (bd-2crbt)
16889    // =========================================================================
16890
16891    #[test]
16892    fn program_config_with_lane() {
16893        let config = ProgramConfig::default().with_lane(RuntimeLane::Asupersync);
16894        assert_eq!(config.runtime_lane, RuntimeLane::Asupersync);
16895    }
16896
16897    #[test]
16898    fn program_config_default_lane_resolves_to_spawned_backend() {
16899        // Input-lag regression fix (#78): the default Structured lane now
16900        // resolves to per-task `Spawned` execution instead of the single-worker
16901        // `EffectQueue`. Structured cancellation is independent of the task
16902        // executor backend, so the lane no longer serializes `Cmd::Task` through
16903        // one `effect_queue_loop` worker (which caused per-keystroke head-of-line
16904        // latency for PTY-forwarding apps). `enabled` is the legacy convenience
16905        // flag mirroring the backend, so it is now false for the default lane.
16906        let resolved = ProgramConfig::default().resolved_effect_queue_config();
16907        assert!(!resolved.enabled);
16908        assert_eq!(resolved.backend, TaskExecutorBackend::Spawned);
16909    }
16910
16911    #[test]
16912    fn program_config_legacy_lane_resolves_to_spawned_backend() {
16913        let resolved = ProgramConfig::default()
16914            .with_lane(RuntimeLane::Legacy)
16915            .resolved_effect_queue_config();
16916        assert!(!resolved.enabled);
16917        assert_eq!(resolved.backend, TaskExecutorBackend::Spawned);
16918    }
16919
16920    #[test]
16921    fn program_config_explicit_spawned_backend_is_preserved() {
16922        let resolved = ProgramConfig::default()
16923            .with_effect_queue(EffectQueueConfig::default().with_enabled(false))
16924            .resolved_effect_queue_config();
16925        assert!(!resolved.enabled);
16926        assert_eq!(resolved.backend, TaskExecutorBackend::Spawned);
16927    }
16928
16929    #[test]
16930    fn program_config_with_rollout_policy() {
16931        let config = ProgramConfig::default().with_rollout_policy(RolloutPolicy::Shadow);
16932        assert_eq!(config.rollout_policy, RolloutPolicy::Shadow);
16933    }
16934
16935    #[test]
16936    fn rollout_policy_labels() {
16937        assert_eq!(RolloutPolicy::Off.label(), "off");
16938        assert_eq!(RolloutPolicy::Shadow.label(), "shadow");
16939        assert_eq!(RolloutPolicy::Enabled.label(), "enabled");
16940        assert_eq!(format!("{}", RolloutPolicy::Shadow), "shadow");
16941    }
16942
16943    #[test]
16944    fn rollout_policy_is_shadow() {
16945        assert!(!RolloutPolicy::Off.is_shadow());
16946        assert!(RolloutPolicy::Shadow.is_shadow());
16947        assert!(!RolloutPolicy::Enabled.is_shadow());
16948    }
16949
16950    #[test]
16951    fn rollout_policy_default_is_off() {
16952        assert_eq!(RolloutPolicy::default(), RolloutPolicy::Off);
16953    }
16954
16955    #[test]
16956    fn runtime_lane_parse_legacy() {
16957        assert_eq!(RuntimeLane::parse("legacy"), Some(RuntimeLane::Legacy));
16958    }
16959
16960    #[test]
16961    fn runtime_lane_parse_structured_case_insensitive() {
16962        assert_eq!(
16963            RuntimeLane::parse("Structured"),
16964            Some(RuntimeLane::Structured)
16965        );
16966    }
16967
16968    #[test]
16969    fn runtime_lane_parse_asupersync_uppercase() {
16970        assert_eq!(
16971            RuntimeLane::parse("ASUPERSYNC"),
16972            Some(RuntimeLane::Asupersync)
16973        );
16974    }
16975
16976    #[test]
16977    fn runtime_lane_parse_unrecognized() {
16978        assert_eq!(RuntimeLane::parse("bogus"), None);
16979    }
16980
16981    #[test]
16982    fn rollout_policy_parse_shadow() {
16983        assert_eq!(RolloutPolicy::parse("shadow"), Some(RolloutPolicy::Shadow));
16984    }
16985
16986    #[test]
16987    fn rollout_policy_parse_enabled() {
16988        assert_eq!(
16989            RolloutPolicy::parse("enabled"),
16990            Some(RolloutPolicy::Enabled)
16991        );
16992    }
16993
16994    #[test]
16995    fn rollout_policy_parse_off() {
16996        assert_eq!(RolloutPolicy::parse("off"), Some(RolloutPolicy::Off));
16997    }
16998
16999    #[test]
17000    fn rollout_policy_parse_unrecognized() {
17001        assert_eq!(RolloutPolicy::parse("bogus"), None);
17002    }
17003
17004    // =========================================================================
17005    // PersistenceConfig Debug (bd-2yjus)
17006    // =========================================================================
17007
17008    #[test]
17009    fn persistence_config_debug() {
17010        let config = PersistenceConfig::default();
17011        let debug = format!("{config:?}");
17012        assert!(debug.contains("PersistenceConfig"));
17013        assert!(debug.contains("auto_load"));
17014        assert!(debug.contains("auto_save"));
17015    }
17016
17017    // =========================================================================
17018    // FrameTimingConfig (bd-2yjus)
17019    // =========================================================================
17020
17021    #[test]
17022    fn frame_timing_config_debug() {
17023        use std::sync::Arc;
17024
17025        struct DummySink;
17026        impl FrameTimingSink for DummySink {
17027            fn record_frame(&self, _timing: &FrameTiming) {}
17028        }
17029
17030        let config = FrameTimingConfig::new(Arc::new(DummySink));
17031        let debug = format!("{config:?}");
17032        assert!(debug.contains("FrameTimingConfig"));
17033    }
17034
17035    #[test]
17036    fn program_config_with_frame_timing() {
17037        use std::sync::Arc;
17038
17039        struct DummySink;
17040        impl FrameTimingSink for DummySink {
17041            fn record_frame(&self, _timing: &FrameTiming) {}
17042        }
17043
17044        let config =
17045            ProgramConfig::default().with_frame_timing(FrameTimingConfig::new(Arc::new(DummySink)));
17046        assert!(config.frame_timing.is_some());
17047    }
17048
17049    // =========================================================================
17050    // BudgetDecisionEvidence helper functions (bd-2yjus)
17051    // =========================================================================
17052
17053    #[test]
17054    fn budget_decision_evidence_decision_from_levels() {
17055        use ftui_render::budget::DegradationLevel;
17056        // Degrade: after > before
17057        assert_eq!(
17058            BudgetDecisionEvidence::decision_from_levels(
17059                DegradationLevel::Full,
17060                DegradationLevel::SimpleBorders
17061            ),
17062            BudgetDecision::Degrade
17063        );
17064        // Upgrade: after < before
17065        assert_eq!(
17066            BudgetDecisionEvidence::decision_from_levels(
17067                DegradationLevel::SimpleBorders,
17068                DegradationLevel::Full
17069            ),
17070            BudgetDecision::Upgrade
17071        );
17072        // Hold: same
17073        assert_eq!(
17074            BudgetDecisionEvidence::decision_from_levels(
17075                DegradationLevel::Full,
17076                DegradationLevel::Full
17077            ),
17078            BudgetDecision::Hold
17079        );
17080    }
17081
17082    // =========================================================================
17083    // WidgetRefreshPlan (bd-2yjus)
17084    // =========================================================================
17085
17086    #[test]
17087    fn widget_refresh_plan_clear() {
17088        let mut plan = WidgetRefreshPlan::new();
17089        plan.frame_idx = 5;
17090        plan.budget_us = 100.0;
17091        plan.signal_count = 3;
17092        plan.over_budget = true;
17093        plan.clear();
17094        assert_eq!(plan.frame_idx, 0);
17095        assert_eq!(plan.budget_us, 0.0);
17096        assert_eq!(plan.signal_count, 0);
17097        assert!(!plan.over_budget);
17098    }
17099
17100    #[test]
17101    fn widget_refresh_plan_as_budget_empty_signals() {
17102        let plan = WidgetRefreshPlan::new();
17103        let budget = plan.as_budget();
17104        // With signal_count == 0, should be allow_all (allows any widget)
17105        assert!(budget.allows(0, false));
17106        assert!(budget.allows(999, false));
17107    }
17108
17109    #[test]
17110    fn widget_refresh_plan_to_jsonl_structure() {
17111        let plan = WidgetRefreshPlan::new();
17112        let jsonl = plan.to_jsonl();
17113        assert!(jsonl.contains("\"event\":\"widget_refresh\""));
17114        assert!(jsonl.contains("\"frame_idx\":0"));
17115        assert!(jsonl.contains("\"selected\":[]"));
17116    }
17117
17118    // =========================================================================
17119    // BatchController Default trait (bd-2yjus)
17120    // =========================================================================
17121
17122    #[test]
17123    fn batch_controller_default_trait() {
17124        let bc = BatchController::default();
17125        let bc2 = BatchController::new();
17126        // Should be equivalent
17127        assert_eq!(bc.tau_s(), bc2.tau_s());
17128        assert_eq!(bc.observations(), bc2.observations());
17129    }
17130
17131    #[test]
17132    fn batch_controller_observe_arrival_stale_gap_ignored() {
17133        let mut bc = BatchController::new();
17134        let base = Instant::now();
17135        // First arrival
17136        bc.observe_arrival(base);
17137        // Stale gap > 10s should be ignored
17138        bc.observe_arrival(base + Duration::from_secs(15));
17139        assert_eq!(bc.observations(), 0);
17140    }
17141
17142    #[test]
17143    fn batch_controller_observe_service_out_of_range() {
17144        let mut bc = BatchController::new();
17145        let original_service = bc.service_est_s();
17146        // Out-of-range (>= 10s) should be ignored
17147        bc.observe_service(Duration::from_secs(15));
17148        assert_eq!(bc.service_est_s(), original_service);
17149    }
17150
17151    #[test]
17152    fn batch_controller_lambda_zero_inter_arrival() {
17153        // When ema_inter_arrival_s is effectively 0, lambda should be 0
17154        let bc = BatchController {
17155            ema_inter_arrival_s: 0.0,
17156            ..BatchController::new()
17157        };
17158        assert_eq!(bc.lambda_est(), 0.0);
17159    }
17160
17161    // =========================================================================
17162    // Headless program: Cmd::Log with and without trailing newline (bd-2yjus)
17163    // =========================================================================
17164
17165    #[test]
17166    fn headless_execute_cmd_log_appends_newline_if_missing() {
17167        let mut program =
17168            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
17169        program.execute_cmd(Cmd::log("no newline")).expect("log");
17170
17171        let bytes = program.writer.into_inner().expect("writer output");
17172        let output = String::from_utf8_lossy(&bytes);
17173        // The sanitized output should end with a newline
17174        assert!(output.contains("no newline"));
17175    }
17176
17177    #[test]
17178    fn headless_execute_cmd_log_preserves_trailing_newline() {
17179        let mut program =
17180            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
17181        program
17182            .execute_cmd(Cmd::log("with newline\n"))
17183            .expect("log");
17184
17185        let bytes = program.writer.into_inner().expect("writer output");
17186        let output = String::from_utf8_lossy(&bytes);
17187        assert!(output.contains("with newline"));
17188    }
17189
17190    // =========================================================================
17191    // Headless program: immediate resize behavior (bd-2yjus)
17192    // =========================================================================
17193
17194    #[test]
17195    fn headless_handle_event_immediate_resize() {
17196        struct ResizeModel {
17197            last_size: Option<(u16, u16)>,
17198        }
17199
17200        #[derive(Debug)]
17201        enum ResizeMsg {
17202            Resize(u16, u16),
17203            Other,
17204        }
17205
17206        impl From<Event> for ResizeMsg {
17207            fn from(event: Event) -> Self {
17208                match event {
17209                    Event::Resize { width, height } => ResizeMsg::Resize(width, height),
17210                    _ => ResizeMsg::Other,
17211                }
17212            }
17213        }
17214
17215        impl Model for ResizeModel {
17216            type Message = ResizeMsg;
17217
17218            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
17219                if let ResizeMsg::Resize(w, h) = msg {
17220                    self.last_size = Some((w, h));
17221                }
17222                Cmd::none()
17223            }
17224
17225            fn view(&self, _frame: &mut Frame) {}
17226        }
17227
17228        let config = ProgramConfig::default().with_resize_behavior(ResizeBehavior::Immediate);
17229        let mut program = headless_program_with_config(ResizeModel { last_size: None }, config);
17230
17231        program
17232            .handle_event(Event::Resize {
17233                width: 120,
17234                height: 40,
17235            })
17236            .expect("handle resize");
17237
17238        assert_eq!(program.width, 120);
17239        assert_eq!(program.height, 40);
17240        assert_eq!(program.model().last_size, Some((120, 40)));
17241    }
17242
17243    // =========================================================================
17244    // Headless program: resize clamps zero dimensions (bd-2yjus)
17245    // =========================================================================
17246
17247    #[test]
17248    fn headless_apply_resize_clamps_zero_to_one() {
17249        struct SimpleModel;
17250
17251        #[derive(Debug)]
17252        enum SimpleMsg {
17253            Noop,
17254        }
17255
17256        impl From<Event> for SimpleMsg {
17257            fn from(_: Event) -> Self {
17258                SimpleMsg::Noop
17259            }
17260        }
17261
17262        impl Model for SimpleModel {
17263            type Message = SimpleMsg;
17264
17265            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
17266                Cmd::none()
17267            }
17268
17269            fn view(&self, _frame: &mut Frame) {}
17270        }
17271
17272        let mut program = headless_program_with_config(SimpleModel, ProgramConfig::default());
17273        program
17274            .apply_resize(0, 0, Duration::ZERO, false)
17275            .expect("resize");
17276
17277        // Zero dimensions should be clamped to 1
17278        assert_eq!(program.width, 1);
17279        assert_eq!(program.height, 1);
17280    }
17281
17282    // =========================================================================
17283    // PaneTerminalAdapter::force_cancel_all (bd-24v9m)
17284    // =========================================================================
17285
17286    #[test]
17287    fn force_cancel_all_idle_returns_none() {
17288        let mut adapter =
17289            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
17290        assert!(adapter.force_cancel_all().is_none());
17291    }
17292
17293    #[test]
17294    fn force_cancel_all_after_pointer_down_returns_diagnostics() {
17295        let mut adapter =
17296            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
17297        let target = pane_target(SplitAxis::Horizontal);
17298
17299        let down = Event::Mouse(MouseEvent::new(
17300            MouseEventKind::Down(MouseButton::Left),
17301            5,
17302            5,
17303        ));
17304        let _ = adapter.translate(&down, Some(target));
17305        assert!(adapter.active_pointer_id().is_some());
17306
17307        let diag = adapter
17308            .force_cancel_all()
17309            .expect("should produce diagnostics");
17310        assert!(diag.had_active_pointer);
17311        assert_eq!(diag.active_pointer_id, Some(1));
17312        assert!(diag.machine_transition.is_some());
17313
17314        // Adapter should be fully idle afterwards
17315        assert_eq!(adapter.active_pointer_id(), None);
17316        assert!(matches!(adapter.machine_state(), PaneDragResizeState::Idle));
17317    }
17318
17319    #[test]
17320    fn force_cancel_all_during_drag_returns_diagnostics() {
17321        let mut adapter =
17322            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
17323        let target = pane_target(SplitAxis::Vertical);
17324
17325        // Down → arm
17326        let down = Event::Mouse(MouseEvent::new(
17327            MouseEventKind::Down(MouseButton::Left),
17328            3,
17329            3,
17330        ));
17331        let _ = adapter.translate(&down, Some(target));
17332
17333        // Drag → transition to Dragging
17334        let drag = Event::Mouse(MouseEvent::new(
17335            MouseEventKind::Drag(MouseButton::Left),
17336            8,
17337            3,
17338        ));
17339        let _ = adapter.translate(&drag, None);
17340
17341        let diag = adapter
17342            .force_cancel_all()
17343            .expect("should produce diagnostics");
17344        assert!(diag.had_active_pointer);
17345        assert!(diag.machine_transition.is_some());
17346        let transition = diag.machine_transition.unwrap();
17347        assert!(matches!(
17348            transition.effect,
17349            PaneDragResizeEffect::Canceled {
17350                reason: PaneCancelReason::Programmatic,
17351                ..
17352            }
17353        ));
17354    }
17355
17356    #[test]
17357    fn force_cancel_all_is_idempotent() {
17358        let mut adapter =
17359            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
17360        let target = pane_target(SplitAxis::Horizontal);
17361
17362        let down = Event::Mouse(MouseEvent::new(
17363            MouseEventKind::Down(MouseButton::Left),
17364            5,
17365            5,
17366        ));
17367        let _ = adapter.translate(&down, Some(target));
17368
17369        let first = adapter.force_cancel_all();
17370        assert!(first.is_some());
17371
17372        let second = adapter.force_cancel_all();
17373        assert!(second.is_none());
17374    }
17375
17376    // =========================================================================
17377    // PaneInteractionGuard (bd-24v9m)
17378    // =========================================================================
17379
17380    #[test]
17381    fn pane_interaction_guard_finish_when_idle() {
17382        let mut adapter =
17383            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
17384        let guard = PaneInteractionGuard::new(&mut adapter);
17385        let diag = guard.finish();
17386        assert!(diag.is_none());
17387    }
17388
17389    #[test]
17390    fn pane_interaction_guard_finish_returns_diagnostics() {
17391        let mut adapter =
17392            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
17393        let target = pane_target(SplitAxis::Horizontal);
17394
17395        // Start a drag interaction through the adapter directly
17396        let down = Event::Mouse(MouseEvent::new(
17397            MouseEventKind::Down(MouseButton::Left),
17398            5,
17399            5,
17400        ));
17401        let _ = adapter.translate(&down, Some(target));
17402
17403        let guard = PaneInteractionGuard::new(&mut adapter);
17404        let diag = guard.finish().expect("should produce diagnostics");
17405        assert!(diag.had_active_pointer);
17406        assert_eq!(diag.active_pointer_id, Some(1));
17407    }
17408
17409    #[test]
17410    fn pane_interaction_guard_drop_cancels_active_interaction() {
17411        let mut adapter =
17412            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
17413        let target = pane_target(SplitAxis::Vertical);
17414
17415        let down = Event::Mouse(MouseEvent::new(
17416            MouseEventKind::Down(MouseButton::Left),
17417            7,
17418            7,
17419        ));
17420        let _ = adapter.translate(&down, Some(target));
17421        assert!(adapter.active_pointer_id().is_some());
17422
17423        {
17424            let _guard = PaneInteractionGuard::new(&mut adapter);
17425            // guard drops here without finish()
17426        }
17427
17428        // After guard drop, adapter should be idle
17429        assert_eq!(adapter.active_pointer_id(), None);
17430        assert!(matches!(adapter.machine_state(), PaneDragResizeState::Idle));
17431    }
17432
17433    #[test]
17434    fn pane_interaction_guard_adapter_access_works() {
17435        let mut adapter =
17436            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
17437        let target = pane_target(SplitAxis::Horizontal);
17438
17439        let mut guard = PaneInteractionGuard::new(&mut adapter);
17440
17441        // Use the adapter through the guard
17442        let down = Event::Mouse(MouseEvent::new(
17443            MouseEventKind::Down(MouseButton::Left),
17444            5,
17445            5,
17446        ));
17447        let dispatch = guard.adapter().translate(&down, Some(target));
17448        assert!(dispatch.primary_event.is_some());
17449
17450        // finish should clean up the interaction started through the guard
17451        let diag = guard.finish().expect("should produce diagnostics");
17452        assert!(diag.had_active_pointer);
17453    }
17454
17455    #[test]
17456    fn pane_interaction_guard_finish_then_drop_is_safe() {
17457        let mut adapter =
17458            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
17459        let target = pane_target(SplitAxis::Horizontal);
17460
17461        let down = Event::Mouse(MouseEvent::new(
17462            MouseEventKind::Down(MouseButton::Left),
17463            5,
17464            5,
17465        ));
17466        let _ = adapter.translate(&down, Some(target));
17467
17468        let guard = PaneInteractionGuard::new(&mut adapter);
17469        let _diag = guard.finish();
17470        // guard is consumed by finish(), so drop doesn't double-cancel
17471        // This test proves the API is safe: finish() takes `self` not `&mut self`
17472        assert_eq!(adapter.active_pointer_id(), None);
17473    }
17474
17475    // =========================================================================
17476    // PaneCapabilityMatrix (bd-6u66i)
17477    // =========================================================================
17478
17479    fn caps_modern() -> TerminalCapabilities {
17480        TerminalCapabilities::modern()
17481    }
17482
17483    fn caps_with_mux(
17484        mux: PaneMuxEnvironment,
17485    ) -> ftui_core::terminal_capabilities::TerminalCapabilities {
17486        let mut caps = TerminalCapabilities::modern();
17487        match mux {
17488            PaneMuxEnvironment::Tmux => caps.in_tmux = true,
17489            PaneMuxEnvironment::Screen => caps.in_screen = true,
17490            PaneMuxEnvironment::Zellij => caps.in_zellij = true,
17491            PaneMuxEnvironment::WeztermMux => caps.in_wezterm_mux = true,
17492            PaneMuxEnvironment::None => {}
17493        }
17494        caps
17495    }
17496
17497    #[test]
17498    fn capability_matrix_bare_terminal_modern() {
17499        let caps = caps_modern();
17500        let mat = PaneCapabilityMatrix::from_capabilities(&caps);
17501
17502        assert_eq!(mat.mux, PaneMuxEnvironment::None);
17503        assert!(mat.mouse_sgr);
17504        assert!(mat.mouse_drag_reliable);
17505        assert!(mat.mouse_button_discrimination);
17506        assert!(mat.focus_events);
17507        assert!(mat.unicode_box_drawing);
17508        assert!(mat.true_color);
17509        assert!(!mat.degraded);
17510        assert!(mat.drag_enabled());
17511        assert!(mat.focus_cancel_effective());
17512        assert!(mat.limitations().is_empty());
17513    }
17514
17515    #[test]
17516    fn capability_matrix_tmux() {
17517        let caps = caps_with_mux(PaneMuxEnvironment::Tmux);
17518        let mat = PaneCapabilityMatrix::from_capabilities(&caps);
17519
17520        assert_eq!(mat.mux, PaneMuxEnvironment::Tmux);
17521        // Focus cancel path is conservatively disabled in all muxes.
17522        assert!(mat.mouse_drag_reliable);
17523        assert!(!mat.focus_events);
17524        assert!(mat.drag_enabled());
17525        assert!(!mat.focus_cancel_effective());
17526        assert!(mat.degraded);
17527    }
17528
17529    #[test]
17530    fn capability_matrix_screen_degrades_drag() {
17531        let caps = caps_with_mux(PaneMuxEnvironment::Screen);
17532        let mat = PaneCapabilityMatrix::from_capabilities(&caps);
17533
17534        assert_eq!(mat.mux, PaneMuxEnvironment::Screen);
17535        assert!(!mat.mouse_drag_reliable);
17536        assert!(!mat.focus_events);
17537        assert!(!mat.drag_enabled());
17538        assert!(!mat.focus_cancel_effective());
17539        assert!(mat.degraded);
17540
17541        let lims = mat.limitations();
17542        assert!(lims.iter().any(|l| l.id == "mouse_drag_unreliable"));
17543        assert!(lims.iter().any(|l| l.id == "no_focus_events"));
17544    }
17545
17546    #[test]
17547    fn capability_matrix_zellij() {
17548        let caps = caps_with_mux(PaneMuxEnvironment::Zellij);
17549        let mat = PaneCapabilityMatrix::from_capabilities(&caps);
17550
17551        assert_eq!(mat.mux, PaneMuxEnvironment::Zellij);
17552        assert!(mat.mouse_drag_reliable);
17553        assert!(!mat.focus_events);
17554        assert!(mat.drag_enabled());
17555        assert!(!mat.focus_cancel_effective());
17556        assert!(mat.degraded);
17557    }
17558
17559    #[test]
17560    fn capability_matrix_wezterm_mux_disables_focus_cancel_path() {
17561        let caps = caps_with_mux(PaneMuxEnvironment::WeztermMux);
17562        let mat = PaneCapabilityMatrix::from_capabilities(&caps);
17563
17564        assert_eq!(mat.mux, PaneMuxEnvironment::WeztermMux);
17565        assert!(mat.mouse_drag_reliable);
17566        assert!(!mat.focus_events);
17567        assert!(mat.drag_enabled());
17568        assert!(!mat.focus_cancel_effective());
17569        assert!(mat.degraded);
17570    }
17571
17572    #[test]
17573    fn capability_matrix_no_sgr_mouse() {
17574        let mut caps = caps_modern();
17575        caps.mouse_sgr = false;
17576        let mat = PaneCapabilityMatrix::from_capabilities(&caps);
17577
17578        assert!(!mat.mouse_sgr);
17579        assert!(!mat.mouse_button_discrimination);
17580        assert!(mat.degraded);
17581
17582        let lims = mat.limitations();
17583        assert!(lims.iter().any(|l| l.id == "no_sgr_mouse"));
17584        assert!(lims.iter().any(|l| l.id == "no_button_discrimination"));
17585    }
17586
17587    #[test]
17588    fn capability_matrix_no_focus_events() {
17589        let mut caps = caps_modern();
17590        caps.focus_events = false;
17591        let mat = PaneCapabilityMatrix::from_capabilities(&caps);
17592
17593        assert!(!mat.focus_events);
17594        assert!(!mat.focus_cancel_effective());
17595        assert!(mat.degraded);
17596
17597        let lims = mat.limitations();
17598        assert!(lims.iter().any(|l| l.id == "no_focus_events"));
17599    }
17600
17601    #[test]
17602    fn capability_matrix_dumb_terminal() {
17603        let caps = TerminalCapabilities::dumb();
17604        let mat = PaneCapabilityMatrix::from_capabilities(&caps);
17605
17606        assert_eq!(mat.mux, PaneMuxEnvironment::None);
17607        assert!(!mat.mouse_sgr);
17608        assert!(!mat.focus_events);
17609        assert!(!mat.unicode_box_drawing);
17610        assert!(!mat.true_color);
17611        assert!(mat.degraded);
17612        assert!(mat.limitations().len() >= 3);
17613    }
17614
17615    #[test]
17616    fn capability_matrix_limitations_have_fallbacks() {
17617        let caps = TerminalCapabilities::dumb();
17618        let mat = PaneCapabilityMatrix::from_capabilities(&caps);
17619
17620        for lim in mat.limitations() {
17621            assert!(!lim.id.is_empty());
17622            assert!(!lim.description.is_empty());
17623            assert!(!lim.fallback.is_empty());
17624        }
17625    }
17626
17627    // ========================================================================
17628    // Screen transition detection tests (A.2 + D.3)
17629    // ========================================================================
17630
17631    /// A multi-screen model that implements ScreenTickDispatch, for testing
17632    /// the `check_screen_transition` logic.
17633    struct MultiScreenModel {
17634        active: String,
17635        screens: Vec<String>,
17636        ticked_screens: Vec<(String, u64)>,
17637    }
17638
17639    #[derive(Debug)]
17640    enum MultiScreenMsg {
17641        #[expect(dead_code)]
17642        Event(Event),
17643    }
17644
17645    impl From<Event> for MultiScreenMsg {
17646        fn from(event: Event) -> Self {
17647            MultiScreenMsg::Event(event)
17648        }
17649    }
17650
17651    impl Model for MultiScreenModel {
17652        type Message = MultiScreenMsg;
17653
17654        fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
17655            match msg {
17656                MultiScreenMsg::Event(_) => Cmd::none(),
17657            }
17658        }
17659
17660        fn view(&self, _frame: &mut Frame) {}
17661
17662        fn as_screen_tick_dispatch(
17663            &mut self,
17664        ) -> Option<&mut dyn crate::tick_strategy::ScreenTickDispatch> {
17665            Some(self)
17666        }
17667    }
17668
17669    impl crate::tick_strategy::ScreenTickDispatch for MultiScreenModel {
17670        fn screen_ids(&self) -> Vec<String> {
17671            self.screens.clone()
17672        }
17673
17674        fn active_screen_id(&self) -> String {
17675            self.active.clone()
17676        }
17677
17678        fn tick_screen(&mut self, screen_id: &str, tick_count: u64) {
17679            self.ticked_screens.push((screen_id.to_owned(), tick_count));
17680        }
17681    }
17682
17683    /// Shared log for recording strategy transitions (inspectable after test).
17684    type TransitionLog = Arc<std::sync::Mutex<Vec<(String, String)>>>;
17685
17686    /// A recording tick strategy that logs `on_screen_transition` calls
17687    /// to a shared log that can be inspected from test assertions.
17688    struct RecordingStrategy {
17689        log: TransitionLog,
17690    }
17691
17692    impl RecordingStrategy {
17693        fn new(log: TransitionLog) -> Self {
17694            Self { log }
17695        }
17696    }
17697
17698    impl crate::tick_strategy::TickStrategy for RecordingStrategy {
17699        fn should_tick(
17700            &mut self,
17701            _screen_id: &str,
17702            _tick_count: u64,
17703            _active_screen: &str,
17704        ) -> crate::tick_strategy::TickDecision {
17705            crate::tick_strategy::TickDecision::Skip
17706        }
17707
17708        fn on_screen_transition(&mut self, from: &str, to: &str) {
17709            self.log
17710                .lock()
17711                .unwrap()
17712                .push((from.to_owned(), to.to_owned()));
17713        }
17714
17715        fn name(&self) -> &str {
17716            "Recording"
17717        }
17718
17719        fn debug_stats(&self) -> Vec<(String, String)> {
17720            vec![("strategy".into(), "Recording".into())]
17721        }
17722    }
17723
17724    /// Helper to create a headless Program with a multi-screen model and
17725    /// a recording tick strategy. Returns the program and a shared log of
17726    /// `on_screen_transition` calls for assertions.
17727    fn headless_multi_screen_program(
17728        active: &str,
17729        screens: &[&str],
17730    ) -> (
17731        Program<MultiScreenModel, HeadlessEventSource, Vec<u8>>,
17732        TransitionLog,
17733    ) {
17734        let model = MultiScreenModel {
17735            active: active.to_owned(),
17736            screens: screens.iter().map(|s| (*s).to_owned()).collect(),
17737            ticked_screens: Vec::new(),
17738        };
17739        let events = HeadlessEventSource::new(80, 24, BackendFeatures::default());
17740        let writer = TerminalWriter::new(
17741            Vec::<u8>::new(),
17742            ScreenMode::AltScreen,
17743            UiAnchor::Bottom,
17744            TerminalCapabilities::dumb(),
17745        );
17746        let config = ProgramConfig {
17747            forced_size: Some((80, 24)),
17748            tick_strategy: Some(crate::tick_strategy::TickStrategyKind::ActiveOnly),
17749            ..ProgramConfig::default()
17750        };
17751        let mut prog =
17752            Program::with_event_source(model, events, BackendFeatures::default(), writer, config)
17753                .expect("headless program creation failed");
17754
17755        // Replace the default strategy with our recording strategy.
17756        let log: TransitionLog = Arc::new(std::sync::Mutex::new(Vec::new()));
17757        prog.tick_strategy = Some(Box::new(RecordingStrategy::new(log.clone())));
17758
17759        (prog, log)
17760    }
17761
17762    #[test]
17763    fn check_screen_transition_first_call_records_active() {
17764        let (mut prog, log) = headless_multi_screen_program("A", &["A", "B", "C"]);
17765
17766        assert!(prog.last_active_screen_for_strategy.is_none());
17767        prog.check_screen_transition();
17768        assert_eq!(prog.last_active_screen_for_strategy.as_deref(), Some("A"));
17769
17770        // First observation: no transition event, no force-tick.
17771        assert!(prog.model.ticked_screens.is_empty());
17772        assert!(log.lock().unwrap().is_empty());
17773    }
17774
17775    #[test]
17776    fn check_screen_transition_no_change_is_noop() {
17777        let (mut prog, log) = headless_multi_screen_program("A", &["A", "B", "C"]);
17778
17779        // First call: records.
17780        prog.check_screen_transition();
17781
17782        // Second call with same active screen: no-op.
17783        prog.check_screen_transition();
17784        assert_eq!(prog.last_active_screen_for_strategy.as_deref(), Some("A"));
17785
17786        // No force-tick, no transition notification.
17787        assert!(prog.model.ticked_screens.is_empty());
17788        assert!(log.lock().unwrap().is_empty());
17789    }
17790
17791    #[test]
17792    fn check_screen_transition_detects_switch_and_force_ticks() {
17793        let (mut prog, log) = headless_multi_screen_program("A", &["A", "B", "C"]);
17794
17795        prog.check_screen_transition(); // records "A"
17796
17797        // Simulate model switching to screen "B".
17798        prog.model.active = "B".to_owned();
17799        prog.check_screen_transition();
17800
17801        // D.3: force-tick should have been dispatched for "B".
17802        assert_eq!(prog.model.ticked_screens.len(), 1);
17803        assert_eq!(prog.model.ticked_screens[0].0, "B");
17804
17805        // A.2: strategy should have been notified of A → B.
17806        let transitions = log.lock().unwrap();
17807        assert_eq!(transitions.len(), 1);
17808        assert_eq!(transitions[0], ("A".to_owned(), "B".to_owned()));
17809
17810        // last_active should now be "B".
17811        assert_eq!(prog.last_active_screen_for_strategy.as_deref(), Some("B"));
17812    }
17813
17814    #[test]
17815    fn check_screen_transition_marks_dirty_on_change() {
17816        let (mut prog, _log) = headless_multi_screen_program("A", &["A", "B"]);
17817
17818        prog.check_screen_transition();
17819        prog.dirty = false;
17820
17821        prog.model.active = "B".to_owned();
17822        prog.check_screen_transition();
17823
17824        assert!(prog.dirty);
17825    }
17826
17827    #[test]
17828    fn check_screen_transition_not_dirty_when_unchanged() {
17829        let (mut prog, _log) = headless_multi_screen_program("A", &["A", "B"]);
17830
17831        prog.check_screen_transition();
17832        prog.dirty = false;
17833
17834        prog.check_screen_transition();
17835
17836        assert!(!prog.dirty);
17837    }
17838
17839    #[test]
17840    fn check_screen_transition_noop_without_strategy() {
17841        let (mut prog, _log) = headless_multi_screen_program("A", &["A", "B"]);
17842
17843        // Remove the tick strategy.
17844        prog.tick_strategy = None;
17845
17846        prog.check_screen_transition();
17847        assert!(prog.last_active_screen_for_strategy.is_none());
17848    }
17849
17850    #[test]
17851    fn check_screen_transition_multiple_switches_notifies_strategy() {
17852        let (mut prog, log) = headless_multi_screen_program("A", &["A", "B", "C"]);
17853
17854        prog.check_screen_transition(); // records "A"
17855
17856        // A → B
17857        prog.model.active = "B".to_owned();
17858        prog.check_screen_transition();
17859        assert_eq!(prog.model.ticked_screens.len(), 1);
17860        assert_eq!(prog.model.ticked_screens[0].0, "B");
17861
17862        // B → C
17863        prog.model.active = "C".to_owned();
17864        prog.check_screen_transition();
17865        assert_eq!(prog.model.ticked_screens.len(), 2);
17866        assert_eq!(prog.model.ticked_screens[1].0, "C");
17867
17868        // C → A
17869        prog.model.active = "A".to_owned();
17870        prog.check_screen_transition();
17871        assert_eq!(prog.model.ticked_screens.len(), 3);
17872        assert_eq!(prog.model.ticked_screens[2].0, "A");
17873
17874        // A.2: strategy should have all three transitions.
17875        let transitions = log.lock().unwrap();
17876        assert_eq!(transitions.len(), 3);
17877        assert_eq!(transitions[0], ("A".to_owned(), "B".to_owned()));
17878        assert_eq!(transitions[1], ("B".to_owned(), "C".to_owned()));
17879        assert_eq!(transitions[2], ("C".to_owned(), "A".to_owned()));
17880    }
17881
17882    #[test]
17883    fn check_screen_transition_uses_current_tick_count() {
17884        let (mut prog, _log) = headless_multi_screen_program("A", &["A", "B"]);
17885        prog.tick_count = 42;
17886
17887        prog.check_screen_transition(); // records "A"
17888
17889        prog.model.active = "B".to_owned();
17890        prog.check_screen_transition();
17891
17892        // Force-tick should use the current tick_count.
17893        assert_eq!(prog.model.ticked_screens[0].1, 42);
17894    }
17895
17896    #[test]
17897    fn check_screen_transition_reconciles_subscriptions_after_force_tick() {
17898        use crate::subscription::{StopSignal, SubId, Subscription};
17899
17900        struct TransitionSubModel {
17901            active: String,
17902            screens: Vec<String>,
17903            subscribed: bool,
17904        }
17905
17906        #[derive(Debug)]
17907        #[allow(dead_code)]
17908        enum TransitionSubMsg {
17909            Event(Event),
17910        }
17911
17912        impl From<Event> for TransitionSubMsg {
17913            fn from(event: Event) -> Self {
17914                Self::Event(event)
17915            }
17916        }
17917
17918        impl Model for TransitionSubModel {
17919            type Message = TransitionSubMsg;
17920
17921            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
17922                Cmd::none()
17923            }
17924
17925            fn view(&self, _frame: &mut Frame) {}
17926
17927            fn subscriptions(&self) -> Vec<Box<dyn Subscription<Self::Message>>> {
17928                if self.subscribed {
17929                    vec![Box::new(TransitionSubscription)]
17930                } else {
17931                    vec![]
17932                }
17933            }
17934
17935            fn as_screen_tick_dispatch(
17936                &mut self,
17937            ) -> Option<&mut dyn crate::tick_strategy::ScreenTickDispatch> {
17938                Some(self)
17939            }
17940        }
17941
17942        impl crate::tick_strategy::ScreenTickDispatch for TransitionSubModel {
17943            fn screen_ids(&self) -> Vec<String> {
17944                self.screens.clone()
17945            }
17946
17947            fn active_screen_id(&self) -> String {
17948                self.active.clone()
17949            }
17950
17951            fn tick_screen(&mut self, screen_id: &str, _tick_count: u64) {
17952                if screen_id == self.active {
17953                    self.subscribed = true;
17954                }
17955            }
17956        }
17957
17958        struct TransitionSubscription;
17959
17960        impl Subscription<TransitionSubMsg> for TransitionSubscription {
17961            fn id(&self) -> SubId {
17962                1
17963            }
17964
17965            fn run(&self, _sender: mpsc::Sender<TransitionSubMsg>, _stop: StopSignal) {}
17966        }
17967
17968        struct TransitionStrategy;
17969
17970        impl crate::tick_strategy::TickStrategy for TransitionStrategy {
17971            fn should_tick(
17972                &mut self,
17973                _screen_id: &str,
17974                _tick_count: u64,
17975                _active_screen: &str,
17976            ) -> crate::tick_strategy::TickDecision {
17977                crate::tick_strategy::TickDecision::Skip
17978            }
17979
17980            fn on_screen_transition(&mut self, _from: &str, _to: &str) {}
17981
17982            fn name(&self) -> &str {
17983                "TransitionStrategy"
17984            }
17985
17986            fn debug_stats(&self) -> Vec<(String, String)> {
17987                vec![]
17988            }
17989        }
17990
17991        let model = TransitionSubModel {
17992            active: "A".to_owned(),
17993            screens: vec!["A".to_owned(), "B".to_owned()],
17994            subscribed: false,
17995        };
17996        let events = HeadlessEventSource::new(80, 24, BackendFeatures::default());
17997        let writer = TerminalWriter::new(
17998            Vec::<u8>::new(),
17999            ScreenMode::AltScreen,
18000            UiAnchor::Bottom,
18001            TerminalCapabilities::dumb(),
18002        );
18003        let config = ProgramConfig::default().with_forced_size(80, 24);
18004
18005        let mut program =
18006            Program::with_event_source(model, events, BackendFeatures::default(), writer, config)
18007                .expect("program creation");
18008        program.tick_strategy = Some(Box::new(TransitionStrategy));
18009
18010        program.check_screen_transition();
18011        assert_eq!(program.subscriptions.active_count(), 0);
18012
18013        program.model.active = "B".to_owned();
18014        program.check_screen_transition();
18015
18016        assert!(program.model().subscribed);
18017        assert_eq!(program.subscriptions.active_count(), 1);
18018    }
18019
18020    #[test]
18021    fn tick_strategy_stats_returns_empty_without_strategy() {
18022        let (mut prog, _log) = headless_multi_screen_program("A", &["A", "B"]);
18023        prog.tick_strategy = None;
18024        assert!(prog.tick_strategy_stats().is_empty());
18025    }
18026
18027    #[test]
18028    fn tick_strategy_stats_returns_strategy_fields() {
18029        let (prog, _log) = headless_multi_screen_program("A", &["A", "B"]);
18030        let stats = prog.tick_strategy_stats();
18031        // RecordingStrategy returns [("strategy", "Recording")]
18032        assert!(
18033            !stats.is_empty(),
18034            "stats should not be empty when strategy is configured"
18035        );
18036    }
18037}