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_presenter::TerminalPresenter;
69#[cfg(any(feature = "crossterm-compat", test))]
70use crate::terminal_writer::TerminalWriter;
71use crate::terminal_writer::{RuntimeDiffConfig, ScreenMode, UiAnchor};
72use crate::voi_sampling::{VoiConfig, VoiSampler};
73use crate::{BucketKey, ConformalConfig, ConformalPrediction, ConformalPredictor, ConformalStatus};
74#[cfg(feature = "asupersync-executor")]
75use asupersync::runtime::{BlockingTaskHandle, Runtime as AsupersyncRuntime, RuntimeBuilder};
76use ftui_a11y::tree::{A11yTree, A11yTreeBuilder, ScreenReaderAnnouncement, ScreenReaderPolicy};
77use ftui_backend::{BackendEventSource, BackendFeatures, BackendPresenter};
78use ftui_core::event::{
79    Event, KeyCode, KeyEvent, KeyEventKind, Modifiers, MouseButton, MouseEvent, MouseEventKind,
80};
81#[cfg(feature = "crossterm-compat")]
82use ftui_core::terminal_capabilities::TerminalCapabilities;
83#[cfg(feature = "crossterm-compat")]
84use ftui_core::terminal_session::{SessionOptions, TerminalSession};
85use ftui_layout::{
86    PANE_DRAG_RESIZE_DEFAULT_HYSTERESIS, PANE_DRAG_RESIZE_DEFAULT_THRESHOLD, PaneCancelReason,
87    PaneDragResizeMachine, PaneDragResizeMachineError, PaneDragResizeState,
88    PaneDragResizeTransition, PaneInertialThrow, PaneLayout, PaneModifierSnapshot,
89    PaneMotionVector, PaneNodeKind, PanePointerButton, PanePointerPosition,
90    PanePressureSnapProfile, PaneResizeDirection, PaneResizeTarget, PaneSemanticInputEvent,
91    PaneSemanticInputEventKind, PaneTree, Rect, SplitAxis,
92};
93use ftui_render::arena::FrameArena;
94use ftui_render::budget::{
95    BudgetControllerConfig, BudgetDecision, BudgetDecisionReason, DegradationLevel,
96    FrameBudgetConfig, RenderBudget,
97};
98use ftui_render::buffer::Buffer;
99use ftui_render::diff_strategy::DiffStrategy;
100use ftui_render::frame::{Frame, HitData, HitId, HitRegion, WidgetBudget, WidgetSignal};
101use ftui_render::frame_guardrails::{
102    AlertSeverity, FrameGuardrails, GuardrailKind, GuardrailsConfig,
103};
104use ftui_render::sanitize::{SanitizeMode, Text};
105use std::any::Any;
106use std::collections::HashMap;
107use std::io::{self, Stdout};
108use std::panic::{self, AssertUnwindSafe};
109use std::sync::Arc;
110
111/// Check for pending termination signal. Returns `None` when crossterm is not
112/// enabled (headless / wasm builds don't install signal handlers).
113#[inline]
114fn check_termination_signal() -> Option<i32> {
115    ftui_core::shutdown_signal::pending_termination_signal()
116}
117
118/// Clear the pending termination signal.
119#[inline]
120fn clear_termination_signal() {
121    ftui_core::shutdown_signal::clear_pending_termination_signal();
122}
123
124/// Name of the terminal backend that [`AppBuilder::run`] and `Program::open`
125/// select in this build: `"native"` (ftui-tty, Unix), `"crossterm"`, or
126/// `"none"` when neither backend feature was compiled (in which case
127/// `Program::open` and `DefaultProgram` do not exist).
128#[cfg(all(feature = "native-backend", unix))]
129pub const DEFAULT_BACKEND: &str = "native";
130/// Name of the terminal backend that [`AppBuilder::run`] and `Program::open`
131/// select in this build: `"native"` (ftui-tty, Unix), `"crossterm"`, or
132/// `"none"` when neither backend feature was compiled (in which case
133/// `Program::open` and `DefaultProgram` do not exist).
134#[cfg(all(
135    feature = "crossterm-compat",
136    not(all(feature = "native-backend", unix))
137))]
138pub const DEFAULT_BACKEND: &str = "crossterm";
139/// Name of the terminal backend that [`AppBuilder::run`] and `Program::open`
140/// select in this build: `"native"` (ftui-tty, Unix), `"crossterm"`, or
141/// `"none"` when neither backend feature was compiled (in which case
142/// `Program::open` and `DefaultProgram` do not exist).
143#[cfg(not(any(all(feature = "native-backend", unix), feature = "crossterm-compat")))]
144pub const DEFAULT_BACKEND: &str = "none";
145
146/// Error text returned by [`AppBuilder::run`] when no terminal backend was compiled.
147pub const NO_BACKEND_MESSAGE: &str =
148    "no terminal backend compiled: enable `native-backend` (unix) or `crossterm-compat`";
149
150/// The concrete [`Program`] type that `Program::open` returns in this build.
151#[cfg(all(feature = "native-backend", unix))]
152pub type DefaultProgram<M> = Program<M, ftui_tty::TtyBackend, TerminalPresenter<Stdout>>;
153/// The concrete [`Program`] type that `Program::open` returns in this build.
154#[cfg(all(
155    feature = "crossterm-compat",
156    not(all(feature = "native-backend", unix))
157))]
158pub type DefaultProgram<M> = Program<M, CrosstermEventSource, TerminalPresenter<Stdout>>;
159
160/// Ask the live terminal what environment detection could not establish.
161///
162/// Runs once per interactive session, after raw mode is active, and only
163/// for the two capabilities that matter for correctness and that identity
164/// heuristics routinely get wrong:
165///
166/// - **Truecolor**, when detection settled on 256 colors: an `ssh` hop
167///   forwards `TERM` but strips `COLORTERM`/`TERM_PROGRAM`, so a truecolor
168///   terminal is mis-detected. The XTGETTCAP `RGB` query round-trips to the
169///   real terminal. Restricted to the 256-color case so explicit monochrome
170///   policy (`NO_COLOR`, dumb/vt100) can never be upgraded.
171/// - **Synchronized output (DEC 2026)**, when the identity allowlist did not
172///   enable it: plain `xterm-256color`, iTerm2, VS Code and every terminal
173///   behind ssh support flicker-free frames but were rendered without them.
174///   The DECRPM `?2026$p` query is authoritative. Skipped inside a
175///   multiplexer, where `use_sync_output()` would veto the result anyway.
176///
177/// Every probe is bounded by a timeout, fail-open (a non-answer changes
178/// nothing) and upgrade-only. `FTUI_CAPS_PROBE=0` disables probing.
179#[cfg(any(all(feature = "native-backend", unix), feature = "crossterm-compat"))]
180fn probe_live_terminal(
181    capabilities: &mut ftui_core::terminal_capabilities::TerminalCapabilities,
182) -> Vec<ftui_core::caps_probe::CapabilityDecision> {
183    use ftui_core::caps_probe::{
184        ProbeConfig, ProbeResult, decisions_from_probe, probe_capabilities,
185    };
186
187    let before = *capabilities;
188    let probing_disabled = std::env::var_os("FTUI_CAPS_PROBE").is_some_and(|value| value == "0");
189    let wants_truecolor = !probing_disabled
190        && capabilities.color_depth == ftui_core::terminal_capabilities::ColorDepth::Ansi256;
191    let wants_sync_output =
192        !probing_disabled && !capabilities.sync_output && !capabilities.in_any_mux();
193    let config = ProbeConfig {
194        timeout: std::time::Duration::from_millis(300),
195        probe_da1: false,
196        probe_da2: false,
197        probe_background: false,
198        probe_truecolor: wants_truecolor,
199        probe_sync_output: wants_sync_output,
200    };
201    let probe = if wants_truecolor || wants_sync_output {
202        let probe = probe_capabilities(&config);
203        capabilities.refine_from_probe(&probe);
204        probe
205    } else {
206        ProbeResult::default()
207    };
208    // The operator switches (sync output, scroll region, OSC 52) outrank
209    // everything, including a terminal that answers the probe positively.
210    // (`with_overrides()` applied them once already; re-applying after the
211    // probe is what makes them win over a positive answer.)
212    let overrides = ftui_core::capability_override::apply_env_policy_overrides(capabilities);
213    #[cfg(feature = "tracing")]
214    tracing::debug!(
215        target: crate::telemetry_schema::TARGET_RUNTIME,
216        probed_truecolor = wants_truecolor,
217        probed_sync_output = wants_sync_output,
218        truecolor = ?probe.true_color,
219        sync_output = ?probe.sync_output,
220        "live terminal capability probe"
221    );
222    // Every session gets a decision ledger, probed or not, so the evidence
223    // file always says why sync output / scroll regions are on or off.
224    decisions_from_probe(&before, &config, &probe, overrides, capabilities)
225}
226
227/// Outcome of the DECSTBM self-test for the writer: the verdict (or `None`
228/// when the test did not run) plus the geometry it was judged against.
229#[cfg(any(all(feature = "native-backend", unix), feature = "crossterm-compat"))]
230struct ScrollRegionCheck {
231    verdict: Option<ftui_core::caps_probe::ScrollRegionVerdict>,
232    rows: u16,
233    region_bottom: u16,
234}
235
236/// Run the DECSTBM self-test (`caps_probe::probe_scroll_region`) when the
237/// selected inline strategy is going to rely on a scroll region. Runs right
238/// after `probe_live_terminal`, with raw mode on and no input reader alive,
239/// so the reply cannot race the event loop. Skipped for the alternate
240/// screen, when the terminal is a multiplexer or lacks the capability
241/// (overlay redraw is selected anyway), when `FTUI_SCROLL_REGION=1` trusts
242/// the region explicitly, when `FTUI_CAPS_PROBE=0` disables probing, or
243/// when the UI leaves no region to test.
244#[cfg(any(all(feature = "native-backend", unix), feature = "crossterm-compat"))]
245fn verify_scroll_region(
246    capabilities: &ftui_core::terminal_capabilities::TerminalCapabilities,
247    screen_mode: ScreenMode,
248    size: Option<(u16, u16)>,
249) -> ScrollRegionCheck {
250    use ftui_core::inline_mode::InlineStrategy;
251
252    let ui_height = match screen_mode {
253        ScreenMode::Inline { ui_height } => ui_height,
254        ScreenMode::InlineAuto { max_height, .. } => max_height,
255        ScreenMode::AltScreen => 0,
256    };
257    let rows = size.map_or(0, |(_, rows)| rows);
258    let region_bottom = rows.saturating_sub(ui_height);
259    let skip = ScrollRegionCheck {
260        verdict: None,
261        rows,
262        region_bottom,
263    };
264    if ui_height == 0 || rows == 0 {
265        return skip;
266    }
267    if !matches!(
268        InlineStrategy::select(capabilities),
269        InlineStrategy::ScrollRegion | InlineStrategy::Hybrid
270    ) {
271        return skip;
272    }
273    let env = |name: &str| std::env::var_os(name);
274    if env("FTUI_CAPS_PROBE").is_some_and(|value| value == "0")
275        || env("FTUI_SCROLL_REGION").is_some_and(|value| value == "1")
276    {
277        return skip;
278    }
279    let verdict = ftui_core::caps_probe::probe_scroll_region(
280        rows,
281        ui_height,
282        std::time::Duration::from_millis(150),
283    );
284    #[cfg(feature = "tracing")]
285    tracing::debug!(
286        target: crate::telemetry_schema::span::RENDER_SCROLL_REGION,
287        rows,
288        region_bottom,
289        verdict = ?verdict,
290        "DECSTBM self-test"
291    );
292    ScrollRegionCheck {
293        verdict,
294        rows,
295        region_bottom,
296    }
297}
298
299/// Run a program to completion and translate a signal-termination error into
300/// the conventional `128 + signal` process exit, after the program (and with it
301/// the terminal session) has been dropped and the terminal restored.
302///
303/// Shared by every [`AppBuilder`] run method so the three backend paths cannot
304/// drift in how they honor the `SignalTerminationError` contract.
305#[cfg(any(all(feature = "native-backend", unix), feature = "crossterm-compat"))]
306fn finish_run<M, E, P>(mut program: Program<M, E, P>) -> io::Result<()>
307where
308    M: Model,
309    E: BackendEventSource<Error = io::Error>,
310    P: BackendPresenter<Error = io::Error>,
311{
312    let result = program.run();
313    if let Err(ref err) = result
314        && let Some(signal) = signal_termination_from_error(err)
315    {
316        drop(program);
317        std::process::exit(128 + signal);
318    }
319    result
320}
321use std::sync::mpsc;
322use std::thread::{self, JoinHandle};
323use tracing::{debug, debug_span, info, info_span, trace};
324use web_time::{Duration, Instant};
325
326/// The accessibility tree built for one rendered frame, handed to
327/// [`Model::on_accessibility`] whenever the tree changed (requires
328/// [`ProgramConfig::accessibility`]).
329#[derive(Debug, Clone, Copy)]
330pub struct AccessibilityFrame<'a> {
331    /// Index of the frame the tree was built from.
332    pub frame_idx: u64,
333    /// The tree: the nodes widgets pushed during `view`, with the first
334    /// parentless node as the root unless the view set one explicitly.
335    pub tree: &'a A11yTree,
336    /// Reading order: node IDs in widget push order.
337    pub order: &'a [u64],
338    /// Screen-reader announcements derived from the diff against the
339    /// previous frame, bounded by the configured [`ScreenReaderPolicy`].
340    pub announcements: &'a [ScreenReaderAnnouncement],
341    /// Announcements the policy cap dropped this frame.
342    pub dropped: usize,
343}
344
345impl AccessibilityFrame<'_> {
346    /// Indented, one-node-per-line dump of the tree in reading order.
347    #[must_use]
348    pub fn dump(&self) -> String {
349        self.tree.dump_text(self.order)
350    }
351}
352
353/// The Model trait defines application state and behavior.
354///
355/// Implementations define how the application responds to events
356/// and renders its current state.
357pub trait Model: Sized {
358    /// The message type for this model.
359    ///
360    /// Messages represent actions that update the model state.
361    /// Must be convertible from terminal events.
362    type Message: From<Event> + Send + 'static;
363
364    /// Initialize the model with startup commands.
365    ///
366    /// Called once when the program starts. Return commands to execute
367    /// initial side effects like loading data.
368    fn init(&mut self) -> Cmd<Self::Message> {
369        Cmd::none()
370    }
371
372    /// Update the model in response to a message.
373    ///
374    /// This is the core state transition function. Returns commands
375    /// for any side effects that should be executed.
376    fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message>;
377
378    /// Render the current state to a frame.
379    ///
380    /// Called after updates when the UI needs to be redrawn.
381    fn view(&self, frame: &mut Frame);
382
383    /// Declare active subscriptions.
384    ///
385    /// Called after each `update()`. The runtime compares the returned set
386    /// (by `SubId`) against currently running subscriptions and starts/stops
387    /// as needed. Returning an empty vec stops all subscriptions.
388    ///
389    /// # Default
390    ///
391    /// Returns an empty vec (no subscriptions).
392    fn subscriptions(&self) -> Vec<Box<dyn crate::subscription::Subscription<Self::Message>>> {
393        vec![]
394    }
395
396    /// React to a recognized gesture: click, double/triple click, long
397    /// press, drag start/move/end/cancel, or key chord (see
398    /// [`SemanticEvent`](ftui_core::semantic_event::SemanticEvent)).
399    ///
400    /// Only called when [`ProgramConfig::gestures`] is set. The runtime then
401    /// feeds every input event through a
402    /// [`GestureRecognizer`](ftui_core::gesture::GestureRecognizer) after the
403    /// ordinary `update()` call and delivers each recognized gesture here;
404    /// long presses are checked once per tick. Raw events keep flowing to
405    /// `update()` unchanged, so enabling gestures never alters existing
406    /// behavior. Default: ignore gestures.
407    fn on_gesture(
408        &mut self,
409        gesture: ftui_core::semantic_event::SemanticEvent,
410    ) -> Cmd<Self::Message> {
411        let _ = gesture;
412        Cmd::none()
413    }
414
415    /// React to a changed accessibility tree: inspect the tree the last
416    /// frame produced and the screen-reader announcements derived from its
417    /// diff (see [`AccessibilityFrame`]). Typical uses: mirror the
418    /// announcements into an on-screen live region or a screen-reader
419    /// bridge, or expose the tree in a debug panel.
420    ///
421    /// Only called when [`ProgramConfig::accessibility`] is set, and only
422    /// for frames whose tree differs from the previous one; it runs after
423    /// the frame was presented and the runtime schedules one more frame
424    /// so state changed here is rendered. Default: ignore.
425    fn on_accessibility(&mut self, a11y: AccessibilityFrame<'_>) -> Cmd<Self::Message> {
426        let _ = a11y;
427        Cmd::none()
428    }
429
430    /// Downcast to [`ScreenTickDispatch`](crate::tick_strategy::ScreenTickDispatch)
431    /// for per-screen tick control.
432    ///
433    /// Override this to return `Some(self)` in multi-screen Models. The runtime
434    /// will then consult the active [`TickStrategy`](crate::tick_strategy::TickStrategy)
435    /// for each inactive screen instead of ticking monolithically.
436    ///
437    /// Default: `None` (all screens tick every frame, backwards-compatible).
438    fn as_screen_tick_dispatch(
439        &mut self,
440    ) -> Option<&mut dyn crate::tick_strategy::ScreenTickDispatch> {
441        None
442    }
443
444    /// Called before the runtime exits, whether via [`Cmd::Quit`] or signal.
445    ///
446    /// Return cleanup commands (e.g., saving state, closing connections).
447    /// The runtime executes these before teardown.
448    ///
449    /// # Migration rationale
450    ///
451    /// Source frameworks use `componentWillUnmount`, `useEffect` cleanup, or
452    /// `beforeDestroy` hooks. This provides an equivalent lifecycle point.
453    fn on_shutdown(&mut self) -> Cmd<Self::Message> {
454        Cmd::none()
455    }
456
457    /// Called when a runtime, command, or background subscription error occurs.
458    ///
459    /// Return commands for error recovery or graceful degradation. The
460    /// `error` string contains the error description. Fatal runtime and
461    /// command errors still terminate after this hook runs; isolated
462    /// subscription failures may recover and keep the program running.
463    ///
464    /// # Migration rationale
465    ///
466    /// Source frameworks use `componentDidCatch`, error boundaries, or
467    /// `onError` hooks. This provides an equivalent error recovery point.
468    fn on_error(&mut self, _error: &str) -> Cmd<Self::Message> {
469        Cmd::none()
470    }
471}
472
473/// Default weight assigned to background tasks.
474const DEFAULT_TASK_WEIGHT: f64 = 1.0;
475
476/// Frames between soft-tier memory capacity trims.
477///
478/// A soft alert fires on retained capacity; trimming (arena rebuild +
479/// grapheme-pool gc) releases it so the sensor can move again, but trimming
480/// every alerting frame would thrash allocations when usage hovers near the
481/// limit. One trim per 60 alerting frames bounds that churn (bd-1za0z).
482const SOFT_TRIM_COOLDOWN_FRAMES: u64 = 60;
483
484/// Default estimated task cost (ms) used for scheduling.
485const DEFAULT_TASK_ESTIMATE_MS: f64 = 10.0;
486
487/// Scheduling metadata for background tasks.
488#[derive(Debug, Clone)]
489pub struct TaskSpec {
490    /// Task weight (importance). Higher = more priority.
491    pub weight: f64,
492    /// Estimated task cost in milliseconds.
493    pub estimate_ms: f64,
494    /// Optional task name for evidence logging.
495    pub name: Option<String>,
496}
497
498impl Default for TaskSpec {
499    fn default() -> Self {
500        Self {
501            weight: DEFAULT_TASK_WEIGHT,
502            estimate_ms: DEFAULT_TASK_ESTIMATE_MS,
503            name: None,
504        }
505    }
506}
507
508impl TaskSpec {
509    /// Create a task spec with an explicit weight and estimate.
510    #[must_use]
511    pub fn new(weight: f64, estimate_ms: f64) -> Self {
512        Self {
513            weight,
514            estimate_ms,
515            name: None,
516        }
517    }
518
519    /// Attach a task name for diagnostics.
520    #[must_use]
521    pub fn with_name(mut self, name: impl Into<String>) -> Self {
522        self.name = Some(name.into());
523        self
524    }
525}
526
527/// Per-frame timing data for profiling.
528#[derive(Debug, Clone, Copy)]
529pub struct FrameTiming {
530    pub frame_idx: u64,
531    pub update_us: u64,
532    pub render_us: u64,
533    pub diff_us: u64,
534    pub present_us: u64,
535    pub total_us: u64,
536}
537
538#[derive(Debug)]
539struct SignalTerminationError {
540    signal: i32,
541}
542
543impl std::fmt::Display for SignalTerminationError {
544    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
545        write!(f, "terminated by signal {}", self.signal)
546    }
547}
548
549impl std::error::Error for SignalTerminationError {}
550
551/// If this error represents an interrupted runtime terminated by a signal,
552/// return the signal number (e.g. 15 for SIGTERM, 2 for SIGINT).
553#[must_use]
554pub fn signal_termination_from_error(err: &io::Error) -> Option<i32> {
555    err.get_ref()
556        .and_then(|inner| inner.downcast_ref::<SignalTerminationError>())
557        .map(|inner| inner.signal)
558}
559
560/// Sink for frame timing events.
561pub trait FrameTimingSink: Send + Sync {
562    fn record_frame(&self, timing: &FrameTiming);
563}
564
565/// Configuration for frame timing capture.
566#[derive(Clone)]
567pub struct FrameTimingConfig {
568    pub sink: Arc<dyn FrameTimingSink>,
569}
570
571impl FrameTimingConfig {
572    #[must_use]
573    pub fn new(sink: Arc<dyn FrameTimingSink>) -> Self {
574        Self { sink }
575    }
576}
577
578impl std::fmt::Debug for FrameTimingConfig {
579    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
580        f.debug_struct("FrameTimingConfig")
581            .field("sink", &"<dyn FrameTimingSink>")
582            .finish()
583    }
584}
585
586/// Clipboard requests captured by host-driven runners and test simulators.
587#[derive(Debug, Clone, PartialEq, Eq)]
588pub enum ClipboardRequest {
589    /// Copy text to the system clipboard.
590    Set(String),
591    /// Request clipboard text; the host delivers an `Event::Clipboard` reply.
592    Get,
593}
594
595/// Commands represent side effects to be executed by the runtime.
596///
597/// Commands are returned from `init()` and `update()` to trigger
598/// actions like quitting, sending messages, or scheduling ticks.
599#[derive(Default)]
600pub enum Cmd<M> {
601    /// No operation.
602    #[default]
603    None,
604    /// Quit the application.
605    Quit,
606    /// Execute multiple commands as a batch (currently sequential).
607    Batch(Vec<Cmd<M>>),
608    /// Execute commands sequentially.
609    Sequence(Vec<Cmd<M>>),
610    /// Send a message to the model.
611    Msg(M),
612    /// Schedule a tick after a duration.
613    Tick(Duration),
614    /// Write a log message to the terminal output.
615    ///
616    /// This writes to the scrollback region in inline mode, or is ignored/handled
617    /// appropriately in alternate screen mode. The policy is applied at the
618    /// output boundary. Prefer [`Cmd::log`] or [`Cmd::log_sgr_only`]; raw output
619    /// is an explicit opt-in that can corrupt terminal state.
620    Log { text: String, mode: SanitizeMode },
621    /// Execute a blocking operation on a background thread.
622    ///
623    /// When effect queue scheduling is enabled, tasks are enqueued and executed
624    /// in Smith-rule order on a dedicated worker thread. Otherwise the closure
625    /// runs on a spawned thread immediately. The return value is sent back
626    /// as a message to the model.
627    Task(TaskSpec, Box<dyn FnOnce() -> M + Send>),
628    /// Save widget state to the persistence registry.
629    ///
630    /// Triggers a flush of the state registry to the storage backend.
631    /// No-op if persistence is not configured.
632    SaveState,
633    /// Restore widget state from the persistence registry.
634    ///
635    /// Triggers a load from the storage backend and updates the cache.
636    /// No-op if persistence is not configured. Returns a message via
637    /// callback if state was successfully restored.
638    RestoreState,
639    /// Toggle mouse capture at runtime.
640    ///
641    /// Instructs the terminal session to enable or disable mouse event capture.
642    /// No-op in test simulators.
643    SetMouseCapture(bool),
644    /// Copy text using OSC 52 on supported terminals.
645    SetClipboard(String),
646    /// Request clipboard text asynchronously as an `Event::Clipboard` reply.
647    /// Unsupported terminals may ignore the request; no reply is guaranteed.
648    GetClipboard,
649    /// Replace the tick strategy at runtime.
650    ///
651    /// Takes ownership of a boxed strategy. Use when switching from one
652    /// strategy to another (e.g., `Uniform` โ†’ `Predictive` after loading
653    /// persisted transition data).
654    SetTickStrategy(Box<dyn crate::tick_strategy::TickStrategy>),
655}
656
657impl<M: std::fmt::Debug> std::fmt::Debug for Cmd<M> {
658    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
659        match self {
660            Self::None => write!(f, "None"),
661            Self::Quit => write!(f, "Quit"),
662            Self::Batch(cmds) => f.debug_tuple("Batch").field(cmds).finish(),
663            Self::Sequence(cmds) => f.debug_tuple("Sequence").field(cmds).finish(),
664            Self::Msg(m) => f.debug_tuple("Msg").field(m).finish(),
665            Self::Tick(d) => f.debug_tuple("Tick").field(d).finish(),
666            Self::Log { text, mode } => f.debug_tuple("Log").field(text).field(mode).finish(),
667            Self::Task(spec, _) => f.debug_struct("Task").field("spec", spec).finish(),
668            Self::SaveState => write!(f, "SaveState"),
669            Self::RestoreState => write!(f, "RestoreState"),
670            Self::SetMouseCapture(b) => write!(f, "SetMouseCapture({b})"),
671            Self::SetClipboard(text) => f
672                .debug_struct("SetClipboard")
673                .field("bytes", &text.len())
674                .finish(),
675            Self::GetClipboard => write!(f, "GetClipboard"),
676            Self::SetTickStrategy(s) => write!(f, "SetTickStrategy({})", s.name()),
677        }
678    }
679}
680
681impl<M> Cmd<M> {
682    /// Create a no-op command.
683    #[inline]
684    pub fn none() -> Self {
685        Self::None
686    }
687
688    /// Create a quit command.
689    #[inline]
690    pub fn quit() -> Self {
691        Self::Quit
692    }
693
694    /// Create a message command.
695    #[inline]
696    pub fn msg(m: M) -> Self {
697        Self::Msg(m)
698    }
699
700    /// Create a log command.
701    ///
702    /// The message will be sanitized and written to the terminal log (scrollback).
703    /// A newline is appended if not present.
704    #[inline]
705    pub fn log(msg: impl Into<String>) -> Self {
706        Self::Log {
707            text: msg.into(),
708            mode: SanitizeMode::Strip,
709        }
710    }
711
712    /// Log colored text while filtering cursor, clipboard and terminal controls.
713    ///
714    /// The native writer permits only bounded SGR styling and resets styles at
715    /// each line/write. As with [`Self::log`], native output normalizes newlines
716    /// to CRLF and appends a final newline; overlay mode displays only the first
717    /// width-clamped line. Capturing hosts retain logical text without adding
718    /// terminal newlines or reset sequences.
719    #[inline]
720    pub fn log_sgr_only(msg: impl Into<String>) -> Self {
721        Self::Log {
722            text: msg.into(),
723            mode: SanitizeMode::SgrOnly,
724        }
725    }
726
727    /// Log trusted text, including arbitrary terminal commands.
728    ///
729    /// The caller asserts the contents are trusted. Cursor movement, mode
730    /// changes and clearing can corrupt inline chrome. Prefer
731    /// [`Self::log_sgr_only`] for compiler/test output. This is a logical log
732    /// message: native CRLF normalization and final-newline insertion still
733    /// apply, so this is not a byte-transparent transport.
734    #[inline]
735    pub fn log_raw(msg: impl Into<String>) -> Self {
736        Self::Log {
737            text: msg.into(),
738            mode: SanitizeMode::Raw,
739        }
740    }
741
742    /// Log annotated text using its explicit output policy.
743    ///
744    /// The output boundary reapplies the policy even when the marker was
745    /// constructed directly. See [`Self::log_raw`] for trusted-text behavior.
746    pub fn log_text(text: Text<'_>) -> Self {
747        Self::Log {
748            text: text.as_str().to_owned(),
749            mode: text.mode(),
750        }
751    }
752
753    /// Create a batch of commands.
754    pub fn batch(cmds: Vec<Self>) -> Self {
755        if cmds.is_empty() {
756            Self::None
757        } else if cmds.len() == 1 {
758            cmds.into_iter().next().unwrap_or(Self::None)
759        } else {
760            Self::Batch(cmds)
761        }
762    }
763
764    /// Create a sequence of commands.
765    pub fn sequence(cmds: Vec<Self>) -> Self {
766        if cmds.is_empty() {
767            Self::None
768        } else if cmds.len() == 1 {
769            cmds.into_iter().next().unwrap_or(Self::None)
770        } else {
771            Self::Sequence(cmds)
772        }
773    }
774
775    /// Return a stable name for telemetry and tracing.
776    #[inline]
777    pub fn type_name(&self) -> &'static str {
778        match self {
779            Self::None => "None",
780            Self::Quit => "Quit",
781            Self::Batch(_) => "Batch",
782            Self::Sequence(_) => "Sequence",
783            Self::Msg(_) => "Msg",
784            Self::Tick(_) => "Tick",
785            Self::Log { .. } => "Log",
786            Self::Task(..) => "Task",
787            Self::SaveState => "SaveState",
788            Self::RestoreState => "RestoreState",
789            Self::SetMouseCapture(_) => "SetMouseCapture",
790            Self::SetClipboard(_) => "SetClipboard",
791            Self::GetClipboard => "GetClipboard",
792            Self::SetTickStrategy(_) => "SetTickStrategy",
793        }
794    }
795
796    /// Create a tick command.
797    #[inline]
798    pub fn tick(duration: Duration) -> Self {
799        Self::Tick(duration)
800    }
801
802    /// Create a background task command.
803    ///
804    /// The closure runs on a spawned thread (or the effect queue worker when
805    /// scheduling is enabled). When it completes, the returned message is
806    /// sent back to the model's `update()`.
807    pub fn task<F>(f: F) -> Self
808    where
809        F: FnOnce() -> M + Send + 'static,
810    {
811        Self::Task(TaskSpec::default(), Box::new(f))
812    }
813
814    /// Create a background task command with explicit scheduling metadata.
815    pub fn task_with_spec<F>(spec: TaskSpec, f: F) -> Self
816    where
817        F: FnOnce() -> M + Send + 'static,
818    {
819        Self::Task(spec, Box::new(f))
820    }
821
822    /// Create a background task command with explicit weight and estimate.
823    pub fn task_weighted<F>(weight: f64, estimate_ms: f64, f: F) -> Self
824    where
825        F: FnOnce() -> M + Send + 'static,
826    {
827        Self::Task(TaskSpec::new(weight, estimate_ms), Box::new(f))
828    }
829
830    /// Create a named background task command.
831    pub fn task_named<F>(name: impl Into<String>, f: F) -> Self
832    where
833        F: FnOnce() -> M + Send + 'static,
834    {
835        Self::Task(TaskSpec::default().with_name(name), Box::new(f))
836    }
837
838    /// Replace the active tick strategy at runtime.
839    ///
840    /// Use when switching strategies (e.g., `Uniform` โ†’ `Predictive` after
841    /// loading persisted transition data).
842    pub fn set_tick_strategy(strategy: impl crate::tick_strategy::TickStrategy + 'static) -> Self {
843        Self::SetTickStrategy(Box::new(strategy))
844    }
845
846    /// Create a save state command.
847    ///
848    /// Triggers a flush of the state registry to the storage backend.
849    /// No-op if persistence is not configured.
850    #[inline]
851    pub fn save_state() -> Self {
852        Self::SaveState
853    }
854
855    /// Create a restore state command.
856    ///
857    /// Triggers a load from the storage backend.
858    /// No-op if persistence is not configured.
859    #[inline]
860    pub fn restore_state() -> Self {
861        Self::RestoreState
862    }
863
864    /// Create a mouse capture toggle command.
865    ///
866    /// Instructs the runtime to enable or disable mouse event capture on the
867    /// underlying terminal session.
868    #[inline]
869    pub fn set_mouse_capture(enabled: bool) -> Self {
870        Self::SetMouseCapture(enabled)
871    }
872
873    /// Copy text to the system clipboard through the runtime's output owner.
874    pub fn set_clipboard(text: impl Into<String>) -> Self {
875        Self::SetClipboard(text.into())
876    }
877
878    /// Request clipboard text. Handle `Event::Clipboard` for the reply.
879    pub fn get_clipboard() -> Self {
880        Self::GetClipboard
881    }
882
883    /// Count the number of atomic commands in this command.
884    ///
885    /// Returns 0 for None, 1 for atomic commands, and recursively counts for Batch/Sequence.
886    pub fn count(&self) -> usize {
887        match self {
888            Self::None => 0,
889            Self::Batch(cmds) | Self::Sequence(cmds) => cmds.iter().map(Self::count).sum(),
890            _ => 1,
891        }
892    }
893}
894
895/// Resize handling behavior for the runtime.
896#[derive(Debug, Clone, Copy, PartialEq, Eq)]
897pub enum ResizeBehavior {
898    /// Apply resize immediately (no debounce, no placeholder).
899    Immediate,
900    /// Coalesce resize events for continuous reflow.
901    Throttled,
902}
903
904impl ResizeBehavior {
905    const fn uses_coalescer(self) -> bool {
906        matches!(self, ResizeBehavior::Throttled)
907    }
908}
909
910/// Policy controlling when terminal mouse capture is enabled.
911///
912/// Mouse capture can steal normal scrollback interaction in inline mode.
913/// `Auto` keeps inline mode scrollback-safe while still enabling mouse in
914/// alt-screen mode.
915#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
916pub enum MouseCapturePolicy {
917    /// Enable in alt-screen mode, disable in inline modes.
918    #[default]
919    Auto,
920    /// Always enable mouse capture.
921    On,
922    /// Always disable mouse capture.
923    Off,
924}
925
926impl MouseCapturePolicy {
927    /// Resolve the policy to a concrete mouse-capture toggle.
928    #[must_use]
929    pub const fn resolve(self, screen_mode: ScreenMode) -> bool {
930        match self {
931            Self::Auto => matches!(screen_mode, ScreenMode::AltScreen),
932            Self::On => true,
933            Self::Off => false,
934        }
935    }
936}
937
938const PANE_TERMINAL_DEFAULT_HIT_THICKNESS: u16 = 3;
939const PANE_TERMINAL_TARGET_AXIS_MASK: u64 = 0b1;
940
941/// One splitter handle region in terminal cell-space.
942#[derive(Debug, Clone, Copy, PartialEq, Eq)]
943pub struct PaneTerminalSplitterHandle {
944    /// Semantic resize target represented by this handle.
945    pub target: PaneResizeTarget,
946    /// Cell-space hit rectangle for this handle.
947    pub rect: Rect,
948    /// Split boundary coordinate used for deterministic nearest-target ranking.
949    pub boundary: i32,
950}
951
952/// Build deterministic splitter handle regions for terminal hit-testing.
953///
954/// Handles are emitted in split-id order and are clamped to the split rect.
955#[must_use]
956pub fn pane_terminal_splitter_handles(
957    tree: &PaneTree,
958    layout: &PaneLayout,
959    hit_thickness: u16,
960) -> Vec<PaneTerminalSplitterHandle> {
961    let thickness = if hit_thickness == 0 {
962        PANE_TERMINAL_DEFAULT_HIT_THICKNESS
963    } else {
964        hit_thickness
965    };
966    let mut handles = Vec::new();
967    for node in tree.nodes() {
968        let PaneNodeKind::Split(split) = &node.kind else {
969            continue;
970        };
971        let Some(split_rect) = layout.rect(node.id) else {
972            continue;
973        };
974        if split_rect.is_empty() {
975            continue;
976        }
977        let Some(first_rect) = layout.rect(split.first) else {
978            continue;
979        };
980        let Some(second_rect) = layout.rect(split.second) else {
981            continue;
982        };
983
984        let boundary_u16 = match split.axis {
985            SplitAxis::Horizontal => {
986                // Horizontal split => left/right panes => vertical splitter line.
987                if second_rect.x == split_rect.x {
988                    first_rect.right()
989                } else {
990                    second_rect.x
991                }
992            }
993            SplitAxis::Vertical => {
994                // Vertical split => top/bottom panes => horizontal splitter line.
995                if second_rect.y == split_rect.y {
996                    first_rect.bottom()
997                } else {
998                    second_rect.y
999                }
1000            }
1001        };
1002        let Some(rect) = splitter_hit_rect(split.axis, split_rect, boundary_u16, thickness) else {
1003            continue;
1004        };
1005        handles.push(PaneTerminalSplitterHandle {
1006            target: PaneResizeTarget {
1007                split_id: node.id,
1008                axis: split.axis,
1009            },
1010            rect,
1011            boundary: i32::from(boundary_u16),
1012        });
1013    }
1014    handles
1015}
1016
1017/// Resolve a semantic splitter target from a terminal cell position.
1018///
1019/// If multiple handles overlap, chooses deterministically by:
1020/// 1) smallest distance to the splitter boundary, then
1021/// 2) smaller split_id, then
1022/// 3) horizontal axis before vertical axis.
1023#[must_use]
1024pub fn pane_terminal_resolve_splitter_target(
1025    handles: &[PaneTerminalSplitterHandle],
1026    x: u16,
1027    y: u16,
1028) -> Option<PaneResizeTarget> {
1029    let px = i32::from(x);
1030    let py = i32::from(y);
1031    let mut best: Option<((u32, u64, u8), PaneResizeTarget)> = None;
1032
1033    for handle in handles {
1034        if !rect_contains_cell(handle.rect, x, y) {
1035            continue;
1036        }
1037        let distance = match handle.target.axis {
1038            SplitAxis::Horizontal => px.abs_diff(handle.boundary),
1039            SplitAxis::Vertical => py.abs_diff(handle.boundary),
1040        };
1041        let axis_rank = match handle.target.axis {
1042            SplitAxis::Horizontal => 0,
1043            SplitAxis::Vertical => 1,
1044        };
1045        let key = (distance, handle.target.split_id.get(), axis_rank);
1046        if best.as_ref().is_none_or(|(best_key, _)| key < *best_key) {
1047            best = Some((key, handle.target));
1048        }
1049    }
1050
1051    best.map(|(_, target)| target)
1052}
1053
1054/// Register pane splitter handles into the frame hit-grid.
1055///
1056/// Each handle is registered as `HitRegion::Handle` with encoded target data.
1057/// Returns number of successfully-registered regions.
1058pub fn register_pane_terminal_splitter_hits(
1059    frame: &mut Frame,
1060    handles: &[PaneTerminalSplitterHandle],
1061    hit_id_base: u32,
1062) -> usize {
1063    let mut registered = 0usize;
1064    for (idx, handle) in handles.iter().enumerate() {
1065        let Ok(offset) = u32::try_from(idx) else {
1066            break;
1067        };
1068        let hit_id = HitId::new(hit_id_base.saturating_add(offset));
1069        if frame.register_hit(
1070            handle.rect,
1071            hit_id,
1072            HitRegion::Handle,
1073            encode_pane_resize_target(handle.target),
1074        ) {
1075            registered = registered.saturating_add(1);
1076        }
1077    }
1078    registered
1079}
1080
1081/// Decode pane resize target from a hit-grid tuple produced by pane handle registration.
1082#[must_use]
1083pub fn pane_terminal_target_from_hit(hit: (HitId, HitRegion, HitData)) -> Option<PaneResizeTarget> {
1084    let (_, region, data) = hit;
1085    if region != HitRegion::Handle {
1086        return None;
1087    }
1088    decode_pane_resize_target(data)
1089}
1090
1091fn splitter_hit_rect(
1092    axis: SplitAxis,
1093    split_rect: Rect,
1094    boundary: u16,
1095    thickness: u16,
1096) -> Option<Rect> {
1097    let half = thickness.saturating_sub(1) / 2;
1098    match axis {
1099        SplitAxis::Horizontal => {
1100            let start = boundary.saturating_sub(half).max(split_rect.x);
1101            let end = boundary
1102                .saturating_add(thickness.saturating_sub(half))
1103                .min(split_rect.right());
1104            let width = end.saturating_sub(start);
1105            (width > 0 && split_rect.height > 0).then_some(Rect::new(
1106                start,
1107                split_rect.y,
1108                width,
1109                split_rect.height,
1110            ))
1111        }
1112        SplitAxis::Vertical => {
1113            let start = boundary.saturating_sub(half).max(split_rect.y);
1114            let end = boundary
1115                .saturating_add(thickness.saturating_sub(half))
1116                .min(split_rect.bottom());
1117            let height = end.saturating_sub(start);
1118            (height > 0 && split_rect.width > 0).then_some(Rect::new(
1119                split_rect.x,
1120                start,
1121                split_rect.width,
1122                height,
1123            ))
1124        }
1125    }
1126}
1127
1128fn rect_contains_cell(rect: Rect, x: u16, y: u16) -> bool {
1129    x >= rect.x && x < rect.right() && y >= rect.y && y < rect.bottom()
1130}
1131
1132fn encode_pane_resize_target(target: PaneResizeTarget) -> HitData {
1133    let axis = match target.axis {
1134        SplitAxis::Horizontal => 0_u64,
1135        SplitAxis::Vertical => PANE_TERMINAL_TARGET_AXIS_MASK,
1136    };
1137    (target.split_id.get() << 1) | axis
1138}
1139
1140fn decode_pane_resize_target(data: HitData) -> Option<PaneResizeTarget> {
1141    let axis = if data & PANE_TERMINAL_TARGET_AXIS_MASK == 0 {
1142        SplitAxis::Horizontal
1143    } else {
1144        SplitAxis::Vertical
1145    };
1146    let split_id = ftui_layout::PaneId::new(data >> 1).ok()?;
1147    Some(PaneResizeTarget { split_id, axis })
1148}
1149
1150// ============================================================================
1151// Pane capability matrix for multiplexer / terminal compat (bd-6u66i)
1152// ============================================================================
1153
1154/// Which multiplexer environment the terminal is running inside.
1155#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1156pub enum PaneMuxEnvironment {
1157    /// No multiplexer detected โ€” direct terminal access.
1158    None,
1159    /// tmux (TMUX env var set, or DA2 terminal type 84).
1160    Tmux,
1161    /// GNU Screen (STY env var set, or DA2 terminal type 83).
1162    Screen,
1163    /// Zellij (ZELLIJ env var set).
1164    Zellij,
1165    /// WezTerm mux-served pane/session.
1166    WeztermMux,
1167}
1168
1169/// Resolved capability matrix describing which pane interaction features
1170/// are available in the current terminal + multiplexer environment.
1171///
1172/// Derived from [`ftui_core::terminal_capabilities::TerminalCapabilities`]
1173/// via [`PaneCapabilityMatrix::from_capabilities`].
1174/// The adapter uses this to decide which code-paths are safe and which
1175/// need deterministic fallbacks.
1176#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1177pub struct PaneCapabilityMatrix {
1178    /// Detected multiplexer environment.
1179    pub mux: PaneMuxEnvironment,
1180
1181    // --- Mouse input capabilities ---
1182    /// SGR (1006) extended mouse protocol available.
1183    /// Without this, mouse coordinates are limited to 223 columns/rows.
1184    pub mouse_sgr: bool,
1185    /// Mouse drag events are reliably delivered.
1186    /// False in some screen versions where drag tracking is incomplete.
1187    pub mouse_drag_reliable: bool,
1188    /// Mouse button events include correct button identity on release.
1189    /// X10/normal mode sends button 3 for all releases; SGR preserves it.
1190    pub mouse_button_discrimination: bool,
1191
1192    // --- Focus / lifecycle ---
1193    /// Terminal delivers CSI I / CSI O focus events.
1194    pub focus_events: bool,
1195    /// Bracketed paste mode available (affects interaction cancel heuristics).
1196    pub bracketed_paste: bool,
1197
1198    // --- Rendering affordances ---
1199    /// Unicode box-drawing glyphs available for splitter rendering.
1200    pub unicode_box_drawing: bool,
1201    /// True-color support for splitter highlight/drag feedback.
1202    pub true_color: bool,
1203
1204    // --- Fallback summary ---
1205    /// One or more pane features are degraded due to environment constraints.
1206    pub degraded: bool,
1207}
1208
1209/// Human-readable description of a known limitation and its fallback.
1210#[derive(Debug, Clone, PartialEq, Eq)]
1211pub struct PaneCapabilityLimitation {
1212    /// Short identifier (e.g. `"mouse_drag_unreliable"`).
1213    pub id: &'static str,
1214    /// What the limitation is.
1215    pub description: &'static str,
1216    /// What the adapter does instead.
1217    pub fallback: &'static str,
1218}
1219
1220impl PaneCapabilityMatrix {
1221    /// Derive the pane capability matrix from terminal capabilities.
1222    ///
1223    /// This is the single source of truth for which pane features are
1224    /// available. All fallback decisions flow from this matrix.
1225    #[must_use]
1226    pub fn from_capabilities(
1227        caps: &ftui_core::terminal_capabilities::TerminalCapabilities,
1228    ) -> Self {
1229        let mux = if caps.in_tmux {
1230            PaneMuxEnvironment::Tmux
1231        } else if caps.in_screen {
1232            PaneMuxEnvironment::Screen
1233        } else if caps.in_zellij {
1234            PaneMuxEnvironment::Zellij
1235        } else if caps.in_wezterm_mux {
1236            PaneMuxEnvironment::WeztermMux
1237        } else {
1238            PaneMuxEnvironment::None
1239        };
1240
1241        let mouse_sgr = caps.mouse_sgr;
1242
1243        // GNU Screen has historically unreliable drag event delivery.
1244        // tmux and zellij forward drags correctly in modern versions.
1245        let mouse_drag_reliable = !matches!(mux, PaneMuxEnvironment::Screen);
1246
1247        // Button discrimination requires SGR mouse protocol.
1248        // Without it, X10/normal mode reports button 3 for all releases.
1249        let mouse_button_discrimination = mouse_sgr;
1250
1251        // Focus events are conservatively disabled in any mux context.
1252        let focus_events = caps.focus_events && !caps.in_any_mux();
1253
1254        let bracketed_paste = caps.bracketed_paste;
1255        let unicode_box_drawing = caps.unicode_box_drawing;
1256        let true_color = caps.supports_true_color();
1257
1258        let degraded =
1259            !mouse_sgr || !mouse_drag_reliable || !mouse_button_discrimination || !focus_events;
1260
1261        Self {
1262            mux,
1263            mouse_sgr,
1264            mouse_drag_reliable,
1265            mouse_button_discrimination,
1266            focus_events,
1267            bracketed_paste,
1268            unicode_box_drawing,
1269            true_color,
1270            degraded,
1271        }
1272    }
1273
1274    /// Whether pane drag interactions should be enabled at all.
1275    ///
1276    /// Drag requires at minimum mouse event support. If drag events
1277    /// are unreliable (e.g. GNU Screen), drag is disabled and the
1278    /// adapter falls back to keyboard-only resize.
1279    #[must_use]
1280    pub const fn drag_enabled(&self) -> bool {
1281        self.mouse_drag_reliable
1282    }
1283
1284    /// Whether focus-loss auto-cancel is effective.
1285    ///
1286    /// When focus events are unavailable, the adapter cannot detect
1287    /// window blur โ€” interactions must rely on timeout or explicit
1288    /// keyboard cancel instead.
1289    #[must_use]
1290    pub const fn focus_cancel_effective(&self) -> bool {
1291        self.focus_events
1292    }
1293
1294    /// Collect all active limitations with their fallback descriptions.
1295    #[must_use]
1296    pub fn limitations(&self) -> Vec<PaneCapabilityLimitation> {
1297        let mut out = Vec::new();
1298
1299        if !self.mouse_sgr {
1300            out.push(PaneCapabilityLimitation {
1301                id: "no_sgr_mouse",
1302                description: "SGR mouse protocol not available; coordinates limited to 223 columns/rows",
1303                fallback: "Pane splitters beyond column 223 are unreachable by mouse; use keyboard resize",
1304            });
1305        }
1306
1307        if !self.mouse_drag_reliable {
1308            out.push(PaneCapabilityLimitation {
1309                id: "mouse_drag_unreliable",
1310                description: "Mouse drag events are unreliably delivered (e.g. GNU Screen)",
1311                fallback: "Mouse drag disabled; use keyboard arrow keys to resize panes",
1312            });
1313        }
1314
1315        if !self.mouse_button_discrimination {
1316            out.push(PaneCapabilityLimitation {
1317                id: "no_button_discrimination",
1318                description: "Mouse release events do not identify which button was released",
1319                fallback: "Any mouse release cancels the active drag; multi-button interactions unavailable",
1320            });
1321        }
1322
1323        if !self.focus_events {
1324            out.push(PaneCapabilityLimitation {
1325                id: "no_focus_events",
1326                description: "Terminal does not deliver focus-in/focus-out events",
1327                fallback: "Focus-loss auto-cancel disabled; use Escape key to cancel active drag",
1328            });
1329        }
1330
1331        out
1332    }
1333}
1334
1335/// Configuration for terminal-to-pane semantic input translation.
1336///
1337/// This adapter normalizes terminal `Event` streams into
1338/// `PaneSemanticInputEvent` values accepted by `PaneDragResizeMachine`.
1339#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1340pub struct PaneTerminalAdapterConfig {
1341    /// Drag start threshold in pane-local units.
1342    pub drag_threshold: u16,
1343    /// Drag update hysteresis threshold in pane-local units.
1344    pub update_hysteresis: u16,
1345    /// Mouse button required to begin a drag sequence.
1346    pub activation_button: PanePointerButton,
1347    /// Minimum drag delta (Manhattan distance, cells) before forwarding
1348    /// updates while already in the dragging state.
1349    pub drag_update_coalesce_distance: u16,
1350    /// Cancel active interactions on focus loss.
1351    pub cancel_on_focus_lost: bool,
1352    /// Cancel active interactions on terminal resize.
1353    pub cancel_on_resize: bool,
1354}
1355
1356impl Default for PaneTerminalAdapterConfig {
1357    fn default() -> Self {
1358        Self {
1359            drag_threshold: PANE_DRAG_RESIZE_DEFAULT_THRESHOLD,
1360            update_hysteresis: PANE_DRAG_RESIZE_DEFAULT_HYSTERESIS,
1361            activation_button: PanePointerButton::Primary,
1362            drag_update_coalesce_distance: 2,
1363            cancel_on_focus_lost: true,
1364            cancel_on_resize: true,
1365        }
1366    }
1367}
1368
1369#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1370struct PaneTerminalActivePointer {
1371    pointer_id: u32,
1372    target: PaneResizeTarget,
1373    button: PanePointerButton,
1374    last_position: PanePointerPosition,
1375    cumulative_delta_x: i32,
1376    cumulative_delta_y: i32,
1377    direction_changes: u16,
1378    sample_count: u32,
1379    previous_step_delta_x: i32,
1380    previous_step_delta_y: i32,
1381    start_time: Instant,
1382}
1383
1384/// Lifecycle phase observed while translating a terminal event.
1385#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1386pub enum PaneTerminalLifecyclePhase {
1387    MouseDown,
1388    MouseDrag,
1389    MouseMove,
1390    MouseUp,
1391    MouseScroll,
1392    KeyResize,
1393    KeyCancel,
1394    FocusLoss,
1395    ResizeInterrupt,
1396    Other,
1397}
1398
1399/// Deterministic reason a terminal event did not map to pane semantics.
1400#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1401pub enum PaneTerminalIgnoredReason {
1402    MissingTarget,
1403    NoActivePointer,
1404    PointerButtonMismatch,
1405    ActivationButtonRequired,
1406    WindowNotFocused,
1407    UnsupportedKey,
1408    FocusGainNoop,
1409    ResizeNoop,
1410    DragCoalesced,
1411    NonSemanticEvent,
1412    MachineRejectedEvent,
1413}
1414
1415/// Translation outcome for one raw terminal event.
1416#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1417pub enum PaneTerminalLogOutcome {
1418    SemanticForwarded,
1419    SemanticForwardedAfterRecovery,
1420    Ignored(PaneTerminalIgnoredReason),
1421}
1422
1423/// Structured translation log entry for one raw terminal event.
1424#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1425pub struct PaneTerminalLogEntry {
1426    pub phase: PaneTerminalLifecyclePhase,
1427    pub sequence: Option<u64>,
1428    pub pointer_id: Option<u32>,
1429    pub target: Option<PaneResizeTarget>,
1430    pub recovery_cancel_sequence: Option<u64>,
1431    pub outcome: PaneTerminalLogOutcome,
1432}
1433
1434/// Output of one terminal event translation step.
1435///
1436/// `recovery_*` fields are populated when the adapter first emits an internal
1437/// cancel (for stale/missing mouse-up recovery) and then forwards the incoming
1438/// event as a fresh semantic event.
1439#[derive(Debug, Clone, PartialEq)]
1440pub struct PaneTerminalDispatch {
1441    pub primary_event: Option<PaneSemanticInputEvent>,
1442    pub primary_transition: Option<PaneDragResizeTransition>,
1443    pub motion: Option<PaneMotionVector>,
1444    pub inertial_throw: Option<PaneInertialThrow>,
1445    pub projected_position: Option<PanePointerPosition>,
1446    pub recovery_event: Option<PaneSemanticInputEvent>,
1447    pub recovery_transition: Option<PaneDragResizeTransition>,
1448    pub log: PaneTerminalLogEntry,
1449}
1450
1451impl PaneTerminalDispatch {
1452    fn ignored(
1453        phase: PaneTerminalLifecyclePhase,
1454        reason: PaneTerminalIgnoredReason,
1455        pointer_id: Option<u32>,
1456        target: Option<PaneResizeTarget>,
1457    ) -> Self {
1458        Self {
1459            primary_event: None,
1460            primary_transition: None,
1461            motion: None,
1462            inertial_throw: None,
1463            projected_position: None,
1464            recovery_event: None,
1465            recovery_transition: None,
1466            log: PaneTerminalLogEntry {
1467                phase,
1468                sequence: None,
1469                pointer_id,
1470                target,
1471                recovery_cancel_sequence: None,
1472                outcome: PaneTerminalLogOutcome::Ignored(reason),
1473            },
1474        }
1475    }
1476
1477    fn forwarded(
1478        phase: PaneTerminalLifecyclePhase,
1479        pointer_id: Option<u32>,
1480        target: Option<PaneResizeTarget>,
1481        event: PaneSemanticInputEvent,
1482        transition: PaneDragResizeTransition,
1483    ) -> Self {
1484        let sequence = Some(event.sequence);
1485        Self {
1486            primary_event: Some(event),
1487            primary_transition: Some(transition),
1488            motion: None,
1489            inertial_throw: None,
1490            projected_position: None,
1491            recovery_event: None,
1492            recovery_transition: None,
1493            log: PaneTerminalLogEntry {
1494                phase,
1495                sequence,
1496                pointer_id,
1497                target,
1498                recovery_cancel_sequence: None,
1499                outcome: PaneTerminalLogOutcome::SemanticForwarded,
1500            },
1501        }
1502    }
1503
1504    /// Derive dynamic snap profile from translated pointer motion.
1505    #[must_use]
1506    pub fn pressure_snap_profile(&self) -> Option<PanePressureSnapProfile> {
1507        self.motion.map(PanePressureSnapProfile::from_motion)
1508    }
1509}
1510
1511/// Deterministic terminal adapter mapping raw `Event` values into
1512/// schema-validated pane semantic interaction events.
1513#[derive(Debug, Clone)]
1514pub struct PaneTerminalAdapter {
1515    machine: PaneDragResizeMachine,
1516    config: PaneTerminalAdapterConfig,
1517    active: Option<PaneTerminalActivePointer>,
1518    window_focused: bool,
1519    next_sequence: u64,
1520}
1521
1522impl PaneTerminalAdapter {
1523    /// Construct a new adapter with validated drag thresholds.
1524    pub fn new(config: PaneTerminalAdapterConfig) -> Result<Self, PaneDragResizeMachineError> {
1525        let config = PaneTerminalAdapterConfig {
1526            drag_update_coalesce_distance: config.drag_update_coalesce_distance.max(1),
1527            ..config
1528        };
1529        let machine = PaneDragResizeMachine::new_with_hysteresis(
1530            config.drag_threshold,
1531            config.update_hysteresis,
1532        )?;
1533        Ok(Self {
1534            machine,
1535            config,
1536            active: None,
1537            window_focused: true,
1538            next_sequence: 1,
1539        })
1540    }
1541
1542    /// Adapter configuration.
1543    #[must_use]
1544    pub const fn config(&self) -> PaneTerminalAdapterConfig {
1545        self.config
1546    }
1547
1548    /// Active pointer id currently tracked by the adapter, if any.
1549    #[must_use]
1550    pub fn active_pointer_id(&self) -> Option<u32> {
1551        self.active.map(|active| active.pointer_id)
1552    }
1553
1554    /// Whether the host window is currently focused.
1555    #[must_use]
1556    pub const fn window_focused(&self) -> bool {
1557        self.window_focused
1558    }
1559
1560    /// Current pane drag/resize machine state.
1561    #[must_use]
1562    pub const fn machine_state(&self) -> PaneDragResizeState {
1563        self.machine.state()
1564    }
1565
1566    /// Translate one raw terminal event into pane semantic event(s).
1567    ///
1568    /// `target_hint` is provided by host hit-testing (upcoming pane-terminal
1569    /// tasks). Pointer drag/move/up reuse active target continuity once armed.
1570    pub fn translate(
1571        &mut self,
1572        event: &Event,
1573        target_hint: Option<PaneResizeTarget>,
1574    ) -> PaneTerminalDispatch {
1575        match event {
1576            Event::Mouse(mouse) => self.translate_mouse(*mouse, target_hint),
1577            Event::Key(key) => self.translate_key(*key, target_hint),
1578            Event::Focus(focused) => self.translate_focus(*focused),
1579            Event::Resize { .. } => self.translate_resize(),
1580            _ => PaneTerminalDispatch::ignored(
1581                PaneTerminalLifecyclePhase::Other,
1582                PaneTerminalIgnoredReason::NonSemanticEvent,
1583                None,
1584                target_hint,
1585            ),
1586        }
1587    }
1588
1589    /// Translate one raw terminal event while resolving splitter targets from
1590    /// terminal hit regions.
1591    ///
1592    /// This is a convenience wrapper for host code that already has splitter
1593    /// handle regions from [`pane_terminal_splitter_handles`].
1594    pub fn translate_with_handles(
1595        &mut self,
1596        event: &Event,
1597        handles: &[PaneTerminalSplitterHandle],
1598    ) -> PaneTerminalDispatch {
1599        let active_target = self.active.map(|active| active.target);
1600        let target_hint = match event {
1601            Event::Mouse(mouse) => {
1602                let resolved = pane_terminal_resolve_splitter_target(handles, mouse.x, mouse.y);
1603                match mouse.kind {
1604                    MouseEventKind::Down(_)
1605                    | MouseEventKind::ScrollUp
1606                    | MouseEventKind::ScrollDown
1607                    | MouseEventKind::ScrollLeft
1608                    | MouseEventKind::ScrollRight => resolved,
1609                    MouseEventKind::Drag(_) | MouseEventKind::Moved | MouseEventKind::Up(_) => {
1610                        resolved.or(active_target)
1611                    }
1612                }
1613            }
1614            Event::Key(_) => active_target,
1615            _ => None,
1616        };
1617        self.translate(event, target_hint)
1618    }
1619
1620    fn translate_mouse(
1621        &mut self,
1622        mouse: MouseEvent,
1623        target_hint: Option<PaneResizeTarget>,
1624    ) -> PaneTerminalDispatch {
1625        let position = mouse_position(mouse);
1626        let modifiers = pane_modifiers(mouse.modifiers);
1627        match mouse.kind {
1628            MouseEventKind::Down(button) => {
1629                let pane_button = pane_button(button);
1630                if pane_button != self.config.activation_button {
1631                    return PaneTerminalDispatch::ignored(
1632                        PaneTerminalLifecyclePhase::MouseDown,
1633                        PaneTerminalIgnoredReason::ActivationButtonRequired,
1634                        Some(pointer_id_for_button(pane_button)),
1635                        target_hint,
1636                    );
1637                }
1638                let Some(target) = target_hint else {
1639                    return PaneTerminalDispatch::ignored(
1640                        PaneTerminalLifecyclePhase::MouseDown,
1641                        PaneTerminalIgnoredReason::MissingTarget,
1642                        Some(pointer_id_for_button(pane_button)),
1643                        None,
1644                    );
1645                };
1646
1647                let recovery = self.cancel_active_internal(PaneCancelReason::PointerCancel);
1648                let pointer_id = pointer_id_for_button(pane_button);
1649                let kind = PaneSemanticInputEventKind::PointerDown {
1650                    target,
1651                    pointer_id,
1652                    button: pane_button,
1653                    position,
1654                };
1655                let mut dispatch = self.forward_semantic(
1656                    PaneTerminalLifecyclePhase::MouseDown,
1657                    Some(pointer_id),
1658                    Some(target),
1659                    kind,
1660                    modifiers,
1661                );
1662                if dispatch.primary_transition.is_some() {
1663                    self.active = Some(PaneTerminalActivePointer {
1664                        pointer_id,
1665                        target,
1666                        button: pane_button,
1667                        last_position: position,
1668                        cumulative_delta_x: 0,
1669                        cumulative_delta_y: 0,
1670                        direction_changes: 0,
1671                        sample_count: 0,
1672                        previous_step_delta_x: 0,
1673                        previous_step_delta_y: 0,
1674                        start_time: Instant::now(),
1675                    });
1676                }
1677                if let Some((cancel_event, cancel_transition)) = recovery {
1678                    dispatch.recovery_event = Some(cancel_event);
1679                    dispatch.recovery_transition = Some(cancel_transition);
1680                    dispatch.log.recovery_cancel_sequence =
1681                        dispatch.recovery_event.as_ref().map(|event| event.sequence);
1682                    if matches!(
1683                        dispatch.log.outcome,
1684                        PaneTerminalLogOutcome::SemanticForwarded
1685                    ) {
1686                        dispatch.log.outcome =
1687                            PaneTerminalLogOutcome::SemanticForwardedAfterRecovery;
1688                    }
1689                }
1690                dispatch
1691            }
1692            MouseEventKind::Drag(button) => {
1693                let pane_button = pane_button(button);
1694                let Some(active) = self.active else {
1695                    return PaneTerminalDispatch::ignored(
1696                        PaneTerminalLifecyclePhase::MouseDrag,
1697                        PaneTerminalIgnoredReason::NoActivePointer,
1698                        Some(pointer_id_for_button(pane_button)),
1699                        target_hint,
1700                    );
1701                };
1702                if active.button != pane_button {
1703                    return PaneTerminalDispatch::ignored(
1704                        PaneTerminalLifecyclePhase::MouseDrag,
1705                        PaneTerminalIgnoredReason::PointerButtonMismatch,
1706                        Some(pointer_id_for_button(pane_button)),
1707                        Some(active.target),
1708                    );
1709                }
1710                self.apply_pointer_motion(
1711                    active,
1712                    position,
1713                    modifiers,
1714                    PaneTerminalLifecyclePhase::MouseDrag,
1715                )
1716            }
1717            MouseEventKind::Moved => {
1718                let Some(active) = self.active else {
1719                    return PaneTerminalDispatch::ignored(
1720                        PaneTerminalLifecyclePhase::MouseMove,
1721                        PaneTerminalIgnoredReason::NoActivePointer,
1722                        None,
1723                        target_hint,
1724                    );
1725                };
1726                self.apply_pointer_motion(
1727                    active,
1728                    position,
1729                    modifiers,
1730                    PaneTerminalLifecyclePhase::MouseMove,
1731                )
1732            }
1733            MouseEventKind::Up(button) => {
1734                let pane_button = pane_button(button);
1735                let Some(active) = self.active else {
1736                    return PaneTerminalDispatch::ignored(
1737                        PaneTerminalLifecyclePhase::MouseUp,
1738                        PaneTerminalIgnoredReason::NoActivePointer,
1739                        Some(pointer_id_for_button(pane_button)),
1740                        target_hint,
1741                    );
1742                };
1743                if active.button != pane_button {
1744                    return PaneTerminalDispatch::ignored(
1745                        PaneTerminalLifecyclePhase::MouseUp,
1746                        PaneTerminalIgnoredReason::PointerButtonMismatch,
1747                        Some(pointer_id_for_button(pane_button)),
1748                        Some(active.target),
1749                    );
1750                }
1751                let kind = PaneSemanticInputEventKind::PointerUp {
1752                    target: active.target,
1753                    pointer_id: active.pointer_id,
1754                    button: active.button,
1755                    position,
1756                };
1757                let mut dispatch = self.forward_semantic(
1758                    PaneTerminalLifecyclePhase::MouseUp,
1759                    Some(active.pointer_id),
1760                    Some(active.target),
1761                    kind,
1762                    modifiers,
1763                );
1764                if dispatch.primary_transition.is_some() {
1765                    let duration = active.start_time.elapsed().as_millis() as u32;
1766                    let motion = PaneMotionVector::from_delta(
1767                        active.cumulative_delta_x,
1768                        active.cumulative_delta_y,
1769                        duration,
1770                        active.direction_changes,
1771                    );
1772                    let inertial_throw = PaneInertialThrow::from_motion(motion);
1773                    dispatch.motion = Some(motion);
1774                    dispatch.projected_position = Some(inertial_throw.projected_pointer(position));
1775                    dispatch.inertial_throw = Some(inertial_throw);
1776                    self.active = None;
1777                }
1778                dispatch
1779            }
1780            MouseEventKind::ScrollUp
1781            | MouseEventKind::ScrollDown
1782            | MouseEventKind::ScrollLeft
1783            | MouseEventKind::ScrollRight => {
1784                let target = target_hint.or(self.active.map(|active| active.target));
1785                let Some(target) = target else {
1786                    return PaneTerminalDispatch::ignored(
1787                        PaneTerminalLifecyclePhase::MouseScroll,
1788                        PaneTerminalIgnoredReason::MissingTarget,
1789                        None,
1790                        None,
1791                    );
1792                };
1793                let lines = match mouse.kind {
1794                    MouseEventKind::ScrollUp | MouseEventKind::ScrollLeft => -1,
1795                    MouseEventKind::ScrollDown | MouseEventKind::ScrollRight => 1,
1796                    _ => unreachable!("handled by outer match"),
1797                };
1798                let kind = PaneSemanticInputEventKind::WheelNudge { target, lines };
1799                self.forward_semantic(
1800                    PaneTerminalLifecyclePhase::MouseScroll,
1801                    None,
1802                    Some(target),
1803                    kind,
1804                    modifiers,
1805                )
1806            }
1807        }
1808    }
1809
1810    /// Shared motion bookkeeping for the `Drag` and `Moved` mouse arms.
1811    ///
1812    /// Once each arm's arm-specific guards pass (`Drag` additionally checks the
1813    /// pressed button), both perform byte-identical work: compute the step
1814    /// delta, honor drag coalescing, fold direction-change and cumulative-motion
1815    /// tracking into `active`, forward a `PointerMove`, and โ€” only on a committed
1816    /// transition โ€” advance `last_position` and attach the motion vector. The
1817    /// sole caller-specific input is `phase` (`MouseDrag` vs `MouseMove`), used
1818    /// for both the coalesced-ignore and the forwarded event so each caller's
1819    /// diagnostics are unchanged. This is a pure extraction of the two
1820    /// previously-duplicated arm bodies โ€” event ordering and semantics are
1821    /// identical, and the single shared path is cheaper to audit and roll back.
1822    fn apply_pointer_motion(
1823        &mut self,
1824        mut active: PaneTerminalActivePointer,
1825        position: PanePointerPosition,
1826        modifiers: PaneModifierSnapshot,
1827        phase: PaneTerminalLifecyclePhase,
1828    ) -> PaneTerminalDispatch {
1829        let delta_x = position.x.saturating_sub(active.last_position.x);
1830        let delta_y = position.y.saturating_sub(active.last_position.y);
1831        if self.should_coalesce_drag(delta_x, delta_y) {
1832            return PaneTerminalDispatch::ignored(
1833                phase,
1834                PaneTerminalIgnoredReason::DragCoalesced,
1835                Some(active.pointer_id),
1836                Some(active.target),
1837            );
1838        }
1839        if active.sample_count > 0 {
1840            let flipped_x = delta_x.signum() != 0
1841                && active.previous_step_delta_x.signum() != 0
1842                && delta_x.signum() != active.previous_step_delta_x.signum();
1843            let flipped_y = delta_y.signum() != 0
1844                && active.previous_step_delta_y.signum() != 0
1845                && delta_y.signum() != active.previous_step_delta_y.signum();
1846            if flipped_x || flipped_y {
1847                active.direction_changes = active.direction_changes.saturating_add(1);
1848            }
1849        }
1850        active.cumulative_delta_x = active.cumulative_delta_x.saturating_add(delta_x);
1851        active.cumulative_delta_y = active.cumulative_delta_y.saturating_add(delta_y);
1852        active.sample_count = active.sample_count.saturating_add(1);
1853        active.previous_step_delta_x = delta_x;
1854        active.previous_step_delta_y = delta_y;
1855        let kind = PaneSemanticInputEventKind::PointerMove {
1856            target: active.target,
1857            pointer_id: active.pointer_id,
1858            position,
1859            delta_x,
1860            delta_y,
1861        };
1862        let mut dispatch = self.forward_semantic(
1863            phase,
1864            Some(active.pointer_id),
1865            Some(active.target),
1866            kind,
1867            modifiers,
1868        );
1869        if dispatch.primary_transition.is_some() {
1870            active.last_position = position;
1871            self.active = Some(active);
1872            let duration = active.start_time.elapsed().as_millis() as u32;
1873            dispatch.motion = Some(PaneMotionVector::from_delta(
1874                active.cumulative_delta_x,
1875                active.cumulative_delta_y,
1876                duration,
1877                active.direction_changes,
1878            ));
1879        }
1880        dispatch
1881    }
1882
1883    fn translate_key(
1884        &mut self,
1885        key: KeyEvent,
1886        target_hint: Option<PaneResizeTarget>,
1887    ) -> PaneTerminalDispatch {
1888        if !self.window_focused {
1889            return PaneTerminalDispatch::ignored(
1890                PaneTerminalLifecyclePhase::KeyResize,
1891                PaneTerminalIgnoredReason::WindowNotFocused,
1892                self.active_pointer_id(),
1893                target_hint.or(self.active.map(|active| active.target)),
1894            );
1895        }
1896        if key.kind == KeyEventKind::Release {
1897            return PaneTerminalDispatch::ignored(
1898                PaneTerminalLifecyclePhase::Other,
1899                PaneTerminalIgnoredReason::UnsupportedKey,
1900                None,
1901                target_hint,
1902            );
1903        }
1904        if matches!(key.code, KeyCode::Escape) {
1905            return self.cancel_active_dispatch(
1906                PaneTerminalLifecyclePhase::KeyCancel,
1907                PaneCancelReason::EscapeKey,
1908                PaneTerminalIgnoredReason::NoActivePointer,
1909            );
1910        }
1911        let target = target_hint.or(self.active.map(|active| active.target));
1912        let Some(target) = target else {
1913            return PaneTerminalDispatch::ignored(
1914                PaneTerminalLifecyclePhase::KeyResize,
1915                PaneTerminalIgnoredReason::MissingTarget,
1916                None,
1917                None,
1918            );
1919        };
1920        let Some(direction) = keyboard_resize_direction(key.code, target.axis) else {
1921            return PaneTerminalDispatch::ignored(
1922                PaneTerminalLifecyclePhase::KeyResize,
1923                PaneTerminalIgnoredReason::UnsupportedKey,
1924                None,
1925                Some(target),
1926            );
1927        };
1928        let units = keyboard_resize_units(key.modifiers);
1929        let kind = PaneSemanticInputEventKind::KeyboardResize {
1930            target,
1931            direction,
1932            units,
1933        };
1934        self.forward_semantic(
1935            PaneTerminalLifecyclePhase::KeyResize,
1936            self.active_pointer_id(),
1937            Some(target),
1938            kind,
1939            pane_modifiers(key.modifiers),
1940        )
1941    }
1942
1943    fn translate_focus(&mut self, focused: bool) -> PaneTerminalDispatch {
1944        if focused {
1945            self.window_focused = true;
1946            return PaneTerminalDispatch::ignored(
1947                PaneTerminalLifecyclePhase::Other,
1948                PaneTerminalIgnoredReason::FocusGainNoop,
1949                self.active_pointer_id(),
1950                self.active.map(|active| active.target),
1951            );
1952        }
1953        self.window_focused = false;
1954        if !self.config.cancel_on_focus_lost {
1955            return PaneTerminalDispatch::ignored(
1956                PaneTerminalLifecyclePhase::FocusLoss,
1957                PaneTerminalIgnoredReason::ResizeNoop,
1958                self.active_pointer_id(),
1959                self.active.map(|active| active.target),
1960            );
1961        }
1962        self.cancel_active_dispatch(
1963            PaneTerminalLifecyclePhase::FocusLoss,
1964            PaneCancelReason::FocusLost,
1965            PaneTerminalIgnoredReason::NoActivePointer,
1966        )
1967    }
1968
1969    fn translate_resize(&mut self) -> PaneTerminalDispatch {
1970        if !self.config.cancel_on_resize {
1971            return PaneTerminalDispatch::ignored(
1972                PaneTerminalLifecyclePhase::ResizeInterrupt,
1973                PaneTerminalIgnoredReason::ResizeNoop,
1974                self.active_pointer_id(),
1975                self.active.map(|active| active.target),
1976            );
1977        }
1978        self.cancel_active_dispatch(
1979            PaneTerminalLifecyclePhase::ResizeInterrupt,
1980            PaneCancelReason::Programmatic,
1981            PaneTerminalIgnoredReason::ResizeNoop,
1982        )
1983    }
1984
1985    fn cancel_active_dispatch(
1986        &mut self,
1987        phase: PaneTerminalLifecyclePhase,
1988        reason: PaneCancelReason,
1989        no_active_reason: PaneTerminalIgnoredReason,
1990    ) -> PaneTerminalDispatch {
1991        let Some(active) = self.active else {
1992            return PaneTerminalDispatch::ignored(phase, no_active_reason, None, None);
1993        };
1994        let kind = PaneSemanticInputEventKind::Cancel {
1995            target: Some(active.target),
1996            reason,
1997        };
1998        let dispatch = self.forward_semantic(
1999            phase,
2000            Some(active.pointer_id),
2001            Some(active.target),
2002            kind,
2003            PaneModifierSnapshot::default(),
2004        );
2005        if dispatch.primary_transition.is_some() {
2006            self.active = None;
2007        }
2008        dispatch
2009    }
2010
2011    fn cancel_active_internal(
2012        &mut self,
2013        reason: PaneCancelReason,
2014    ) -> Option<(PaneSemanticInputEvent, PaneDragResizeTransition)> {
2015        let active = self.active?;
2016        let kind = PaneSemanticInputEventKind::Cancel {
2017            target: Some(active.target),
2018            reason,
2019        };
2020        let result = self
2021            .apply_semantic(kind, PaneModifierSnapshot::default())
2022            .ok();
2023        if result.is_some() {
2024            self.active = None;
2025        }
2026        result
2027    }
2028
2029    fn forward_semantic(
2030        &mut self,
2031        phase: PaneTerminalLifecyclePhase,
2032        pointer_id: Option<u32>,
2033        target: Option<PaneResizeTarget>,
2034        kind: PaneSemanticInputEventKind,
2035        modifiers: PaneModifierSnapshot,
2036    ) -> PaneTerminalDispatch {
2037        match self.apply_semantic(kind, modifiers) {
2038            Ok((event, transition)) => {
2039                PaneTerminalDispatch::forwarded(phase, pointer_id, target, event, transition)
2040            }
2041            Err(_) => PaneTerminalDispatch::ignored(
2042                phase,
2043                PaneTerminalIgnoredReason::MachineRejectedEvent,
2044                pointer_id,
2045                target,
2046            ),
2047        }
2048    }
2049
2050    fn apply_semantic(
2051        &mut self,
2052        kind: PaneSemanticInputEventKind,
2053        modifiers: PaneModifierSnapshot,
2054    ) -> Result<(PaneSemanticInputEvent, PaneDragResizeTransition), PaneDragResizeMachineError>
2055    {
2056        let mut event = PaneSemanticInputEvent::new(self.next_sequence(), kind);
2057        event.modifiers = modifiers;
2058        let transition = self.machine.apply_event(&event)?;
2059        Ok((event, transition))
2060    }
2061
2062    fn next_sequence(&mut self) -> u64 {
2063        let sequence = self.next_sequence;
2064        self.next_sequence = self.next_sequence.saturating_add(1);
2065        sequence
2066    }
2067
2068    fn should_coalesce_drag(&self, delta_x: i32, delta_y: i32) -> bool {
2069        if !matches!(self.machine.state(), PaneDragResizeState::Dragging { .. }) {
2070            return false;
2071        }
2072        let movement = delta_x
2073            .unsigned_abs()
2074            .saturating_add(delta_y.unsigned_abs());
2075        movement < u32::from(self.config.drag_update_coalesce_distance)
2076    }
2077
2078    /// Force-cancel any active pane interaction and return diagnostic info.
2079    ///
2080    /// This is the safety-valve for cleanup paths (RAII guard drops, signal
2081    /// handlers, panic hooks) where constructing a proper semantic event is
2082    /// not feasible. It resets both the underlying drag/resize state machine
2083    /// and the adapter's active-pointer tracking.
2084    ///
2085    /// Returns `None` if no interaction was active.
2086    pub fn force_cancel_all(&mut self) -> Option<PaneCleanupDiagnostics> {
2087        let was_active = self.active.is_some();
2088        let machine_state_before = self.machine.state();
2089        let machine_transition = self.machine.force_cancel();
2090        let active_pointer = self.active.take();
2091        if !was_active && machine_transition.is_none() {
2092            return None;
2093        }
2094        Some(PaneCleanupDiagnostics {
2095            had_active_pointer: was_active,
2096            active_pointer_id: active_pointer.map(|a| a.pointer_id),
2097            machine_state_before,
2098            machine_transition,
2099        })
2100    }
2101}
2102
2103/// Structured diagnostics emitted when pane interaction state is force-cleaned.
2104///
2105/// Fields mirror the pane layout types which are already `Serialize`/`Deserialize`,
2106/// so callers can convert this struct to JSON for evidence logging.
2107#[derive(Debug, Clone, PartialEq, Eq)]
2108pub struct PaneCleanupDiagnostics {
2109    /// Whether the adapter had an active pointer tracker when cleanup ran.
2110    pub had_active_pointer: bool,
2111    /// The pointer ID that was active (if any).
2112    pub active_pointer_id: Option<u32>,
2113    /// The machine state before force-cancel was applied.
2114    pub machine_state_before: PaneDragResizeState,
2115    /// The transition produced by force-cancel, or `None` if the machine
2116    /// was already idle.
2117    pub machine_transition: Option<PaneDragResizeTransition>,
2118}
2119
2120/// RAII guard that ensures pane interaction state is cleanly canceled on drop.
2121///
2122/// When a pane interaction session is active and the guard drops (due to
2123/// panic, scope exit, or any other unwind), it force-cancels any in-progress
2124/// drag/resize and collects cleanup diagnostics.
2125///
2126/// # Usage
2127///
2128/// ```ignore
2129/// let guard = PaneInteractionGuard::new(&mut adapter);
2130/// // ... pane interaction event loop ...
2131/// // If this scope panics, guard's Drop will force-cancel the drag machine
2132/// let diagnostics = guard.finish(); // explicit clean finish
2133/// ```
2134pub struct PaneInteractionGuard<'a> {
2135    adapter: &'a mut PaneTerminalAdapter,
2136    finished: bool,
2137    diagnostics: Option<PaneCleanupDiagnostics>,
2138}
2139
2140impl<'a> PaneInteractionGuard<'a> {
2141    /// Create a new guard wrapping the given adapter.
2142    pub fn new(adapter: &'a mut PaneTerminalAdapter) -> Self {
2143        Self {
2144            adapter,
2145            finished: false,
2146            diagnostics: None,
2147        }
2148    }
2149
2150    /// Access the wrapped adapter for normal event translation.
2151    pub fn adapter(&mut self) -> &mut PaneTerminalAdapter {
2152        self.adapter
2153    }
2154
2155    /// Explicitly finish the guard, returning any cleanup diagnostics.
2156    ///
2157    /// Calling `finish()` is optional โ€” the guard will also clean up on drop.
2158    /// However, `finish()` gives the caller access to the diagnostics.
2159    pub fn finish(mut self) -> Option<PaneCleanupDiagnostics> {
2160        self.finished = true;
2161        let diagnostics = self.adapter.force_cancel_all();
2162        self.diagnostics = diagnostics.clone();
2163        diagnostics
2164    }
2165}
2166
2167impl Drop for PaneInteractionGuard<'_> {
2168    fn drop(&mut self) {
2169        if !self.finished {
2170            self.diagnostics = self.adapter.force_cancel_all();
2171        }
2172    }
2173}
2174
2175fn pane_button(button: MouseButton) -> PanePointerButton {
2176    match button {
2177        MouseButton::Left => PanePointerButton::Primary,
2178        MouseButton::Right => PanePointerButton::Secondary,
2179        MouseButton::Middle => PanePointerButton::Middle,
2180    }
2181}
2182
2183fn pointer_id_for_button(button: PanePointerButton) -> u32 {
2184    match button {
2185        PanePointerButton::Primary => 1,
2186        PanePointerButton::Secondary => 2,
2187        PanePointerButton::Middle => 3,
2188    }
2189}
2190
2191fn mouse_position(mouse: MouseEvent) -> PanePointerPosition {
2192    PanePointerPosition::new(i32::from(mouse.x), i32::from(mouse.y))
2193}
2194
2195fn pane_modifiers(modifiers: Modifiers) -> PaneModifierSnapshot {
2196    PaneModifierSnapshot {
2197        shift: modifiers.contains(Modifiers::SHIFT),
2198        alt: modifiers.contains(Modifiers::ALT),
2199        ctrl: modifiers.contains(Modifiers::CTRL),
2200        meta: modifiers.contains(Modifiers::SUPER),
2201    }
2202}
2203
2204fn keyboard_resize_direction(code: KeyCode, axis: SplitAxis) -> Option<PaneResizeDirection> {
2205    match (axis, code) {
2206        (SplitAxis::Horizontal, KeyCode::Left) => Some(PaneResizeDirection::Decrease),
2207        (SplitAxis::Horizontal, KeyCode::Right) => Some(PaneResizeDirection::Increase),
2208        (SplitAxis::Vertical, KeyCode::Up) => Some(PaneResizeDirection::Decrease),
2209        (SplitAxis::Vertical, KeyCode::Down) => Some(PaneResizeDirection::Increase),
2210        (_, KeyCode::Char('-')) => Some(PaneResizeDirection::Decrease),
2211        (_, KeyCode::Char('+') | KeyCode::Char('=')) => Some(PaneResizeDirection::Increase),
2212        _ => None,
2213    }
2214}
2215
2216fn keyboard_resize_units(modifiers: Modifiers) -> u16 {
2217    if modifiers.contains(Modifiers::SHIFT) {
2218        5
2219    } else {
2220        1
2221    }
2222}
2223
2224/// Configuration for state persistence in the program runtime.
2225///
2226/// Controls when and how widget state is saved/restored.
2227#[derive(Clone)]
2228pub struct PersistenceConfig {
2229    /// State registry for persistence. If None, persistence is disabled.
2230    pub registry: Option<std::sync::Arc<StateRegistry>>,
2231    /// Interval for periodic checkpoint saves. None disables checkpoints.
2232    pub checkpoint_interval: Option<Duration>,
2233    /// Automatically load state on program start.
2234    pub auto_load: bool,
2235    /// Automatically save state on program exit.
2236    pub auto_save: bool,
2237}
2238
2239impl Default for PersistenceConfig {
2240    fn default() -> Self {
2241        Self {
2242            registry: None,
2243            checkpoint_interval: None,
2244            auto_load: true,
2245            auto_save: true,
2246        }
2247    }
2248}
2249
2250impl std::fmt::Debug for PersistenceConfig {
2251    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2252        f.debug_struct("PersistenceConfig")
2253            .field(
2254                "registry",
2255                &self.registry.as_ref().map(|r| r.backend_name()),
2256            )
2257            .field("checkpoint_interval", &self.checkpoint_interval)
2258            .field("auto_load", &self.auto_load)
2259            .field("auto_save", &self.auto_save)
2260            .finish()
2261    }
2262}
2263
2264impl PersistenceConfig {
2265    /// Create a disabled persistence config.
2266    #[must_use]
2267    pub fn disabled() -> Self {
2268        Self::default()
2269    }
2270
2271    /// Create a persistence config with the given registry.
2272    #[must_use]
2273    pub fn with_registry(registry: std::sync::Arc<StateRegistry>) -> Self {
2274        Self {
2275            registry: Some(registry),
2276            ..Default::default()
2277        }
2278    }
2279
2280    /// Set the checkpoint interval.
2281    #[must_use]
2282    pub fn checkpoint_every(mut self, interval: Duration) -> Self {
2283        self.checkpoint_interval = Some(interval);
2284        self
2285    }
2286
2287    /// Enable or disable auto-load on start.
2288    #[must_use]
2289    pub fn auto_load(mut self, enabled: bool) -> Self {
2290        self.auto_load = enabled;
2291        self
2292    }
2293
2294    /// Enable or disable auto-save on exit.
2295    #[must_use]
2296    pub fn auto_save(mut self, enabled: bool) -> Self {
2297        self.auto_save = enabled;
2298        self
2299    }
2300}
2301
2302/// Configuration for widget refresh selection under render budget.
2303///
2304/// Defaults are conservative and deterministic:
2305/// - enabled: true
2306/// - staleness_window_ms: 1_000
2307/// - starve_ms: 3_000
2308/// - max_starved_per_frame: 2
2309/// - max_drop_fraction: 1.0 (disabled)
2310/// - weights: priority 1.0, staleness 0.5, focus 0.75, interaction 0.5
2311/// - starve_boost: 1.5
2312/// - min_cost_us: 1.0
2313#[derive(Debug, Clone)]
2314pub struct WidgetRefreshConfig {
2315    /// Enable budgeted widget refresh selection.
2316    pub enabled: bool,
2317    /// Staleness decay window (ms) used to normalize staleness scores.
2318    pub staleness_window_ms: u64,
2319    /// Staleness threshold that triggers starvation guard (ms).
2320    pub starve_ms: u64,
2321    /// Maximum number of starved widgets to force in per frame.
2322    pub max_starved_per_frame: usize,
2323    /// Maximum fraction of non-essential widgets that may be dropped.
2324    /// Set to 1.0 to disable the guardrail.
2325    pub max_drop_fraction: f32,
2326    /// Weight for base priority signal.
2327    pub weight_priority: f32,
2328    /// Weight for staleness signal.
2329    pub weight_staleness: f32,
2330    /// Weight for focus boost.
2331    pub weight_focus: f32,
2332    /// Weight for interaction boost.
2333    pub weight_interaction: f32,
2334    /// Additive boost to value for starved widgets.
2335    pub starve_boost: f32,
2336    /// Minimum cost (us) to avoid divide-by-zero.
2337    pub min_cost_us: f32,
2338}
2339
2340impl Default for WidgetRefreshConfig {
2341    fn default() -> Self {
2342        Self {
2343            enabled: true,
2344            staleness_window_ms: 1_000,
2345            starve_ms: 3_000,
2346            max_starved_per_frame: 2,
2347            max_drop_fraction: 1.0,
2348            weight_priority: 1.0,
2349            weight_staleness: 0.5,
2350            weight_focus: 0.75,
2351            weight_interaction: 0.5,
2352            starve_boost: 1.5,
2353            min_cost_us: 1.0,
2354        }
2355    }
2356}
2357
2358/// Configuration for effect queue scheduling.
2359#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2360pub enum TaskExecutorBackend {
2361    /// Spawn one native thread per task and reap finished handles on the main loop.
2362    #[default]
2363    Spawned,
2364    /// Route tasks through the runtime's queueing scheduler.
2365    EffectQueue,
2366    /// Route blocking task closures through an Asupersync blocking pool.
2367    #[cfg(feature = "asupersync-executor")]
2368    Asupersync,
2369}
2370
2371#[derive(Debug, Clone)]
2372pub struct EffectQueueConfig {
2373    /// Whether effect queue scheduling is enabled.
2374    ///
2375    /// This legacy convenience flag is kept in sync with `backend`. New code
2376    /// should prefer `backend` for executor selection.
2377    pub enabled: bool,
2378    /// Which task executor backend to use for `Cmd::Task`.
2379    pub backend: TaskExecutorBackend,
2380    /// Scheduler configuration (Smith's rule by default).
2381    pub scheduler: SchedulerConfig,
2382    /// Maximum queue depth before backpressure kicks in (bd-2zd0a).
2383    ///
2384    /// When the queue depth exceeds this limit, new tasks are dropped with
2385    /// a `tracing::warn!` and the `effects_queue_dropped` counter increments.
2386    /// A value of `0` means unbounded (no backpressure).
2387    pub max_queue_depth: usize,
2388    /// Whether the backend selection was set explicitly by the caller.
2389    explicit_backend: bool,
2390}
2391
2392impl Default for EffectQueueConfig {
2393    fn default() -> Self {
2394        let scheduler = SchedulerConfig {
2395            smith_enabled: true,
2396            force_fifo: false,
2397            preemptive: false,
2398            aging_factor: 0.0,
2399            wait_starve_ms: 0.0,
2400            enable_logging: false,
2401            ..Default::default()
2402        };
2403        Self {
2404            enabled: false,
2405            backend: TaskExecutorBackend::Spawned,
2406            scheduler,
2407            max_queue_depth: 0,
2408            explicit_backend: false,
2409        }
2410    }
2411}
2412
2413impl EffectQueueConfig {
2414    /// Enable effect queue scheduling with the provided scheduler config.
2415    #[must_use]
2416    pub fn with_enabled(mut self, enabled: bool) -> Self {
2417        self.enabled = enabled;
2418        self.backend = if enabled {
2419            TaskExecutorBackend::EffectQueue
2420        } else {
2421            TaskExecutorBackend::Spawned
2422        };
2423        self.explicit_backend = true;
2424        self
2425    }
2426
2427    /// Select the task executor backend for `Cmd::Task`.
2428    #[must_use]
2429    pub fn with_backend(mut self, backend: TaskExecutorBackend) -> Self {
2430        self.enabled = matches!(backend, TaskExecutorBackend::EffectQueue);
2431        self.backend = backend;
2432        self.explicit_backend = true;
2433        self
2434    }
2435
2436    /// Override the scheduler configuration.
2437    #[must_use]
2438    pub fn with_scheduler(mut self, scheduler: SchedulerConfig) -> Self {
2439        self.scheduler = scheduler;
2440        self
2441    }
2442
2443    /// Set the maximum queue depth for backpressure (bd-2zd0a).
2444    ///
2445    /// When the queue depth exceeds this limit, new tasks are dropped.
2446    /// A value of `0` means unbounded (no backpressure, the default).
2447    #[must_use]
2448    pub fn with_max_queue_depth(mut self, depth: usize) -> Self {
2449        self.max_queue_depth = depth;
2450        self
2451    }
2452
2453    #[must_use]
2454    fn uses_legacy_default_backend(&self) -> bool {
2455        !self.explicit_backend && !self.enabled && self.backend == TaskExecutorBackend::Spawned
2456    }
2457}
2458
2459/// Immediate event-drain policy for the runtime main loop.
2460///
2461/// When a poll reports readiness, the runtime drains events by repeatedly
2462/// checking `poll_event(Duration::ZERO)` to avoid latency between buffered
2463/// inputs. This policy bounds that immediate-drain path so bursty workloads do
2464/// not devolve into zero-timeout spin storms.
2465#[derive(Debug, Clone)]
2466pub struct ImmediateDrainConfig {
2467    /// Maximum consecutive zero-timeout polls allowed in a single burst window.
2468    pub max_zero_timeout_polls_per_burst: usize,
2469    /// Maximum wall-clock time spent in a single immediate-drain burst window.
2470    pub max_burst_duration: Duration,
2471    /// Non-zero poll timeout used when the burst window budget is exhausted.
2472    pub backoff_timeout: Duration,
2473}
2474
2475impl Default for ImmediateDrainConfig {
2476    fn default() -> Self {
2477        Self {
2478            max_zero_timeout_polls_per_burst: 64,
2479            max_burst_duration: Duration::from_millis(2),
2480            backoff_timeout: Duration::from_millis(1),
2481        }
2482    }
2483}
2484
2485/// Runtime counters for immediate-drain behavior.
2486#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2487pub struct ImmediateDrainStats {
2488    /// Number of event-drain bursts observed.
2489    pub bursts: u64,
2490    /// Total zero-timeout polls executed (`poll_event(Duration::ZERO)`).
2491    pub zero_timeout_polls: u64,
2492    /// Total non-zero backoff polls executed after exhausting burst budget.
2493    pub backoff_polls: u64,
2494    /// Number of bursts that hit the configured immediate-drain cap.
2495    pub capped_bursts: u64,
2496    /// Max number of zero-timeout polls seen in a single burst window.
2497    pub max_zero_timeout_polls_in_burst: u64,
2498}
2499
2500/// User-visible runtime mode reported by the conservative load governor.
2501///
2502/// These modes mirror the `bd-8vstx` runtime contract:
2503///
2504/// - `Healthy`: admit all work normally; no explicit fallback is active.
2505/// - `Stressed`: strict work is preserved while visible/coalescible or
2506///   background work may be slowed before user-visible ambiguity appears.
2507/// - `Degraded`: bounded fallback is active; strict interactive semantics
2508///   still hold while background/best-effort work is deferred or dropped.
2509/// - `Recovered`: a degraded interval has closed after the configured
2510///   hysteresis window; the next steady interval returns to `Healthy`.
2511/// - `Unsafe`: a strict semantic guarantee cannot be preserved, so optimistic
2512///   degradation must stop and the caller must surface explicit failure.
2513#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2514pub enum RuntimeLoadMode {
2515    /// No sustained pressure and no active fallback.
2516    Healthy,
2517    /// Elevated pressure while strict guarantees still hold.
2518    Stressed,
2519    /// Explicit bounded fallback is active.
2520    Degraded,
2521    /// Recovery interval has been observed and reported.
2522    Recovered,
2523    /// A strict semantic guarantee was violated.
2524    Unsafe,
2525}
2526
2527impl RuntimeLoadMode {
2528    /// Stable string for evidence logs.
2529    #[inline]
2530    #[must_use]
2531    pub const fn as_str(self) -> &'static str {
2532        match self {
2533            Self::Healthy => "healthy",
2534            Self::Stressed => "stressed",
2535            Self::Degraded => "degraded",
2536            Self::Recovered => "recovered",
2537            Self::Unsafe => "unsafe",
2538        }
2539    }
2540}
2541
2542/// Pressure envelope inferred from measured runtime signals.
2543#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2544pub enum RuntimePressureClass {
2545    /// Within steady-state envelope.
2546    SteadyState,
2547    /// Early overload band; bounded coalescing/deferment may begin.
2548    SoftOverload,
2549    /// Degraded band; explicit fallback is active.
2550    HardOverload,
2551    /// Terminal strict-semantics failure.
2552    Unsafe,
2553}
2554
2555impl RuntimePressureClass {
2556    /// Stable string for evidence logs.
2557    #[inline]
2558    #[must_use]
2559    pub const fn as_str(self) -> &'static str {
2560        match self {
2561            Self::SteadyState => "steady_state",
2562            Self::SoftOverload => "soft_overload",
2563            Self::HardOverload => "hard_overload",
2564            Self::Unsafe => "unsafe",
2565        }
2566    }
2567}
2568
2569/// Work disposition allowed by the current runtime mode.
2570#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2571pub enum RuntimeWorkDisposition {
2572    /// Admit all work normally.
2573    AdmitAll,
2574    /// Preserve strict work; coalesce visible work and slow background work.
2575    CoalesceVisibleDeferBackground,
2576    /// Preserve strict work; defer background work and drop best-effort work.
2577    DeferBackgroundDropBestEffort,
2578    /// Re-admit deferred work after the hysteresis window closed.
2579    ReadmitAfterHysteresis,
2580    /// Stop optimistic degradation because a strict guarantee failed.
2581    FailFastStrictGuarantee,
2582}
2583
2584impl RuntimeWorkDisposition {
2585    /// Stable string for evidence logs.
2586    #[inline]
2587    #[must_use]
2588    pub const fn as_str(self) -> &'static str {
2589        match self {
2590            Self::AdmitAll => "admit_all",
2591            Self::CoalesceVisibleDeferBackground => "coalesce_visible_defer_background",
2592            Self::DeferBackgroundDropBestEffort => "defer_background_drop_best_effort",
2593            Self::ReadmitAfterHysteresis => "readmit_after_hysteresis",
2594            Self::FailFastStrictGuarantee => "fail_fast_strict_guarantee",
2595        }
2596    }
2597}
2598
2599/// Conservative policy for classifying runtime load.
2600///
2601/// The first runtime governor intentionally uses one primary control family:
2602/// render-budget degradation and explicit coalescing/admission evidence. Queue
2603/// watermarks are advisory inputs when a queue cap exists; when the queue is
2604/// uncapped, frame-budget and coalescer signals drive fallback classification.
2605#[derive(Debug, Clone, Copy, PartialEq)]
2606pub struct LoadGovernorPolicy {
2607    /// Queue occupancy ratio that enters `stressed`.
2608    pub stressed_queue_watermark: f64,
2609    /// Queue occupancy ratio that enters `degraded`.
2610    pub degraded_queue_watermark: f64,
2611    /// Queue occupancy ratio required before closing a degraded interval.
2612    pub recovery_queue_watermark: f64,
2613    /// Consecutive steady intervals required before reporting recovery.
2614    pub recovery_intervals: u8,
2615    /// Frame-time ratio over budget that enters `stressed` when uncapped.
2616    pub budget_overrun_soft_ratio: f64,
2617}
2618
2619impl Default for LoadGovernorPolicy {
2620    fn default() -> Self {
2621        Self {
2622            stressed_queue_watermark: 0.5,
2623            degraded_queue_watermark: 0.8,
2624            recovery_queue_watermark: 0.25,
2625            recovery_intervals: 3,
2626            budget_overrun_soft_ratio: 1.0,
2627        }
2628    }
2629}
2630
2631impl LoadGovernorPolicy {
2632    #[must_use]
2633    fn normalized(self) -> Self {
2634        let recovery = normalize_ratio(self.recovery_queue_watermark, 0.25);
2635        let stressed = normalize_ratio(self.stressed_queue_watermark, 0.5).max(recovery);
2636        let degraded = normalize_ratio(self.degraded_queue_watermark, 0.8).max(stressed);
2637        Self {
2638            recovery_queue_watermark: recovery,
2639            stressed_queue_watermark: stressed,
2640            degraded_queue_watermark: degraded,
2641            recovery_intervals: self.recovery_intervals.max(1),
2642            budget_overrun_soft_ratio: normalize_positive_ratio(
2643                self.budget_overrun_soft_ratio,
2644                1.0,
2645            ),
2646        }
2647    }
2648}
2649
2650#[inline]
2651fn normalize_ratio(value: f64, fallback: f64) -> f64 {
2652    if value.is_finite() {
2653        value.clamp(0.0, 1.0)
2654    } else {
2655        fallback
2656    }
2657}
2658
2659#[inline]
2660fn normalize_positive_ratio(value: f64, fallback: f64) -> f64 {
2661    if value.is_finite() && value > 0.0 {
2662        value
2663    } else {
2664        fallback
2665    }
2666}
2667
2668/// Conservative runtime load-governor configuration.
2669///
2670/// The first runtime governor keeps one primary control objective:
2671/// responsiveness under render pressure. It drives adaptive render degradation
2672/// through `RenderBudget`, classifies runtime mode with queue/coalescer inputs,
2673/// and emits replayable evidence for the allowed work disposition. Disabling
2674/// this config falls back to the legacy threshold path.
2675#[derive(Debug, Clone, PartialEq)]
2676pub struct LoadGovernorConfig {
2677    /// Whether the adaptive governor is active.
2678    pub enabled: bool,
2679    /// Controller used to decide degrade/upgrade transitions from frame timing.
2680    pub budget_controller: BudgetControllerConfig,
2681    /// Runtime-mode and work-disposition classification policy.
2682    pub policy: LoadGovernorPolicy,
2683}
2684
2685impl Default for LoadGovernorConfig {
2686    fn default() -> Self {
2687        Self {
2688            enabled: true,
2689            budget_controller: BudgetControllerConfig::default(),
2690            policy: LoadGovernorPolicy::default(),
2691        }
2692    }
2693}
2694
2695impl LoadGovernorConfig {
2696    /// Create an enabled governor with conservative defaults.
2697    #[must_use]
2698    pub fn enabled() -> Self {
2699        Self::default()
2700    }
2701
2702    /// Disable the governor and use the legacy render-budget threshold path.
2703    #[must_use]
2704    pub fn disabled() -> Self {
2705        Self {
2706            enabled: false,
2707            budget_controller: BudgetControllerConfig::default(),
2708            policy: LoadGovernorPolicy::default(),
2709        }
2710    }
2711
2712    /// Toggle governor activation.
2713    #[must_use]
2714    pub fn with_enabled(mut self, enabled: bool) -> Self {
2715        self.enabled = enabled;
2716        self
2717    }
2718
2719    /// Replace the adaptive budget controller configuration.
2720    #[must_use]
2721    pub fn with_budget_controller(mut self, config: BudgetControllerConfig) -> Self {
2722        self.budget_controller = config;
2723        self
2724    }
2725
2726    /// Replace the runtime-mode classification policy.
2727    #[must_use]
2728    pub fn with_policy(mut self, policy: LoadGovernorPolicy) -> Self {
2729        self.policy = policy.normalized();
2730        self
2731    }
2732}
2733
2734#[derive(Debug, Clone, Copy)]
2735struct LoadGovernorObservation {
2736    frame_time_us: f64,
2737    budget_us: f64,
2738    degradation: DegradationLevel,
2739    queue: crate::effect_system::QueueTelemetry,
2740    resize_coalescing_active: bool,
2741    strict_semantics_violation: bool,
2742}
2743
2744#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2745struct LoadGovernorSnapshot {
2746    mode: RuntimeLoadMode,
2747    mode_before: RuntimeLoadMode,
2748    pressure_class: RuntimePressureClass,
2749    disposition: RuntimeWorkDisposition,
2750    reason_code: &'static str,
2751    transition: bool,
2752    strict_semantics_preserved: bool,
2753    queue_in_flight: u64,
2754    queue_max_depth: Option<usize>,
2755    queue_dropped_delta: u64,
2756    resize_coalescing_active: bool,
2757    recovery_intervals_observed: u8,
2758    recovery_intervals_required: u8,
2759    deferred_work_total: u64,
2760    coalesced_work_total: u64,
2761    dropped_work_total: u64,
2762}
2763
2764#[derive(Debug, Clone)]
2765struct LoadGovernorState {
2766    enabled: bool,
2767    policy: LoadGovernorPolicy,
2768    max_queue_depth: usize,
2769    mode: RuntimeLoadMode,
2770    recovery_intervals_observed: u8,
2771    last_queue_dropped: u64,
2772    queue_baseline_initialized: bool,
2773    deferred_work_total: u64,
2774    coalesced_work_total: u64,
2775    dropped_work_total: u64,
2776}
2777
2778impl LoadGovernorState {
2779    fn new(config: LoadGovernorConfig, max_queue_depth: usize) -> Self {
2780        Self {
2781            enabled: config.enabled,
2782            policy: config.policy.normalized(),
2783            max_queue_depth,
2784            mode: RuntimeLoadMode::Healthy,
2785            recovery_intervals_observed: 0,
2786            last_queue_dropped: 0,
2787            queue_baseline_initialized: false,
2788            deferred_work_total: 0,
2789            coalesced_work_total: 0,
2790            dropped_work_total: 0,
2791        }
2792    }
2793
2794    fn observe(&mut self, observation: LoadGovernorObservation) -> LoadGovernorSnapshot {
2795        if !self.enabled {
2796            return self.snapshot(
2797                RuntimeLoadMode::Healthy,
2798                RuntimeLoadMode::Healthy,
2799                RuntimePressureClass::SteadyState,
2800                RuntimeWorkDisposition::AdmitAll,
2801                "governor_disabled",
2802                false,
2803                true,
2804                observation,
2805                0,
2806            );
2807        }
2808
2809        let dropped_delta = self.queue_dropped_delta(observation.queue.dropped);
2810        let pressure = self.classify_pressure(observation, dropped_delta);
2811        let mode_before = self.mode;
2812        let reason_code = self.reason_code(observation, pressure, dropped_delta);
2813
2814        match pressure {
2815            RuntimePressureClass::Unsafe => {
2816                self.mode = RuntimeLoadMode::Unsafe;
2817                self.recovery_intervals_observed = 0;
2818            }
2819            // Strict-semantics failure is terminal: once Unsafe is entered the
2820            // governor latches there regardless of later pressure (this mirrors
2821            // the `Unsafe => {}` arm in `observe_steady_interval`, which already
2822            // refuses to recover Unsafe under steady load). Without this guard,
2823            // a subsequent overload interval would downgrade Unsafe to
2824            // Degraded/Stressed and then recover to Healthy, silently escaping
2825            // the fail-fast guarantee. Only an explicit reset clears Unsafe.
2826            _ if self.mode == RuntimeLoadMode::Unsafe => {
2827                self.recovery_intervals_observed = 0;
2828            }
2829            RuntimePressureClass::HardOverload => {
2830                self.mode = RuntimeLoadMode::Degraded;
2831                self.recovery_intervals_observed = 0;
2832            }
2833            RuntimePressureClass::SoftOverload => {
2834                if self.mode != RuntimeLoadMode::Degraded {
2835                    self.mode = RuntimeLoadMode::Stressed;
2836                }
2837                self.recovery_intervals_observed = 0;
2838            }
2839            RuntimePressureClass::SteadyState => self.observe_steady_interval(),
2840        }
2841
2842        self.record_work_disposition(observation, dropped_delta);
2843        let disposition = Self::disposition_for_mode(self.mode);
2844        self.snapshot(
2845            self.mode,
2846            mode_before,
2847            pressure,
2848            disposition,
2849            if self.mode == RuntimeLoadMode::Unsafe {
2850                // Whether freshly violated this interval or latched from a prior
2851                // one, the terminal cause is always the strict-semantics failure.
2852                "strict_semantics_violation"
2853            } else if self.mode == RuntimeLoadMode::Recovered {
2854                "recovery_hysteresis_satisfied"
2855            } else if mode_before == RuntimeLoadMode::Recovered
2856                && self.mode == RuntimeLoadMode::Healthy
2857            {
2858                "recovered_interval_closed"
2859            } else {
2860                reason_code
2861            },
2862            mode_before != self.mode,
2863            // Reflect the latched mode, not the instantaneous pressure: once the
2864            // governor is Unsafe, strict semantics stay unpreserved even on an
2865            // interval whose raw pressure classified lower.
2866            self.mode != RuntimeLoadMode::Unsafe,
2867            observation,
2868            dropped_delta,
2869        )
2870    }
2871
2872    fn queue_dropped_delta(&mut self, dropped_total: u64) -> u64 {
2873        if !self.queue_baseline_initialized {
2874            self.queue_baseline_initialized = true;
2875            self.last_queue_dropped = dropped_total;
2876            return 0;
2877        }
2878        let delta = dropped_total.saturating_sub(self.last_queue_dropped);
2879        self.last_queue_dropped = dropped_total;
2880        delta
2881    }
2882
2883    fn classify_pressure(
2884        &self,
2885        observation: LoadGovernorObservation,
2886        dropped_delta: u64,
2887    ) -> RuntimePressureClass {
2888        if observation.strict_semantics_violation {
2889            return RuntimePressureClass::Unsafe;
2890        }
2891        if dropped_delta > 0
2892            || self
2893                .queue_ratio(observation.queue.in_flight)
2894                .is_some_and(|ratio| ratio >= self.policy.degraded_queue_watermark)
2895            || observation.degradation > DegradationLevel::Full
2896        {
2897            return RuntimePressureClass::HardOverload;
2898        }
2899        if self
2900            .queue_ratio(observation.queue.in_flight)
2901            .is_some_and(|ratio| ratio >= self.policy.stressed_queue_watermark)
2902            || observation.resize_coalescing_active
2903            || observation.frame_time_us
2904                > observation.budget_us * self.policy.budget_overrun_soft_ratio
2905        {
2906            return RuntimePressureClass::SoftOverload;
2907        }
2908        RuntimePressureClass::SteadyState
2909    }
2910
2911    fn observe_steady_interval(&mut self) {
2912        match self.mode {
2913            RuntimeLoadMode::Degraded => {
2914                self.recovery_intervals_observed = self
2915                    .recovery_intervals_observed
2916                    .saturating_add(1)
2917                    .min(self.policy.recovery_intervals);
2918                if self.recovery_intervals_observed >= self.policy.recovery_intervals {
2919                    self.mode = RuntimeLoadMode::Recovered;
2920                }
2921            }
2922            RuntimeLoadMode::Recovered | RuntimeLoadMode::Stressed => {
2923                self.mode = RuntimeLoadMode::Healthy;
2924                self.recovery_intervals_observed = 0;
2925            }
2926            RuntimeLoadMode::Healthy => {
2927                self.recovery_intervals_observed = 0;
2928            }
2929            RuntimeLoadMode::Unsafe => {}
2930        }
2931    }
2932
2933    fn record_work_disposition(
2934        &mut self,
2935        observation: LoadGovernorObservation,
2936        dropped_delta: u64,
2937    ) {
2938        if dropped_delta > 0 {
2939            self.dropped_work_total = self.dropped_work_total.saturating_add(dropped_delta);
2940        }
2941        match self.mode {
2942            RuntimeLoadMode::Stressed => {
2943                if observation.resize_coalescing_active {
2944                    self.coalesced_work_total = self.coalesced_work_total.saturating_add(1);
2945                }
2946            }
2947            RuntimeLoadMode::Degraded => {
2948                self.deferred_work_total = self.deferred_work_total.saturating_add(1);
2949                if observation.resize_coalescing_active {
2950                    self.coalesced_work_total = self.coalesced_work_total.saturating_add(1);
2951                }
2952            }
2953            RuntimeLoadMode::Healthy | RuntimeLoadMode::Recovered | RuntimeLoadMode::Unsafe => {}
2954        }
2955    }
2956
2957    fn reason_code(
2958        &self,
2959        observation: LoadGovernorObservation,
2960        pressure: RuntimePressureClass,
2961        dropped_delta: u64,
2962    ) -> &'static str {
2963        match pressure {
2964            RuntimePressureClass::Unsafe => "strict_semantics_violation",
2965            RuntimePressureClass::HardOverload if dropped_delta > 0 => "effect_queue_drop",
2966            RuntimePressureClass::HardOverload
2967                if self
2968                    .queue_ratio(observation.queue.in_flight)
2969                    .is_some_and(|ratio| ratio >= self.policy.degraded_queue_watermark) =>
2970            {
2971                "queue_degraded_watermark"
2972            }
2973            RuntimePressureClass::HardOverload => "budget_degradation_active",
2974            RuntimePressureClass::SoftOverload
2975                if self
2976                    .queue_ratio(observation.queue.in_flight)
2977                    .is_some_and(|ratio| ratio >= self.policy.stressed_queue_watermark) =>
2978            {
2979                "queue_stressed_watermark"
2980            }
2981            RuntimePressureClass::SoftOverload if observation.resize_coalescing_active => {
2982                "resize_coalescing_active"
2983            }
2984            RuntimePressureClass::SoftOverload => "frame_budget_overrun",
2985            RuntimePressureClass::SteadyState if self.mode == RuntimeLoadMode::Degraded => {
2986                "recovery_hysteresis_pending"
2987            }
2988            RuntimePressureClass::SteadyState => "steady_state",
2989        }
2990    }
2991
2992    fn queue_ratio(&self, in_flight: u64) -> Option<f64> {
2993        (self.max_queue_depth > 0).then(|| in_flight as f64 / self.max_queue_depth as f64)
2994    }
2995
2996    const fn disposition_for_mode(mode: RuntimeLoadMode) -> RuntimeWorkDisposition {
2997        match mode {
2998            RuntimeLoadMode::Healthy => RuntimeWorkDisposition::AdmitAll,
2999            RuntimeLoadMode::Stressed => RuntimeWorkDisposition::CoalesceVisibleDeferBackground,
3000            RuntimeLoadMode::Degraded => RuntimeWorkDisposition::DeferBackgroundDropBestEffort,
3001            RuntimeLoadMode::Recovered => RuntimeWorkDisposition::ReadmitAfterHysteresis,
3002            RuntimeLoadMode::Unsafe => RuntimeWorkDisposition::FailFastStrictGuarantee,
3003        }
3004    }
3005
3006    // Internal constructor that gathers all snapshot fields in one place; the
3007    // wide signature is intentional (a builder would add indirection for a
3008    // private helper). Pre-existing lint, unrelated to the #78 fix.
3009    #[allow(clippy::too_many_arguments)]
3010    fn snapshot(
3011        &self,
3012        mode: RuntimeLoadMode,
3013        mode_before: RuntimeLoadMode,
3014        pressure_class: RuntimePressureClass,
3015        disposition: RuntimeWorkDisposition,
3016        reason_code: &'static str,
3017        transition: bool,
3018        strict_semantics_preserved: bool,
3019        observation: LoadGovernorObservation,
3020        dropped_delta: u64,
3021    ) -> LoadGovernorSnapshot {
3022        LoadGovernorSnapshot {
3023            mode,
3024            mode_before,
3025            pressure_class,
3026            disposition,
3027            reason_code,
3028            transition,
3029            strict_semantics_preserved,
3030            queue_in_flight: observation.queue.in_flight,
3031            queue_max_depth: (self.max_queue_depth > 0).then_some(self.max_queue_depth),
3032            queue_dropped_delta: dropped_delta,
3033            resize_coalescing_active: observation.resize_coalescing_active,
3034            recovery_intervals_observed: self.recovery_intervals_observed,
3035            recovery_intervals_required: self.policy.recovery_intervals,
3036            deferred_work_total: self.deferred_work_total,
3037            coalesced_work_total: self.coalesced_work_total,
3038            dropped_work_total: self.dropped_work_total,
3039        }
3040    }
3041}
3042
3043/// Runtime lane for the Asupersync migration rollout.
3044///
3045/// Controls which subscription/effect execution backend is active.
3046/// The default is `Structured`, reflecting the completed CancellationToken migration (bd-3tmu4).
3047///
3048/// # Migration rollout
3049///
3050/// 1. `Legacy` โ€” pre-migration thread-based subscriptions with manual stop coordination
3051/// 2. `Structured` โ€” CancellationToken-backed subscriptions (current default after bd-3tmu4)
3052/// 3. `Asupersync` โ€” Asupersync blocking-task execution with structured subscriptions
3053///
3054/// Selection is logged at startup so operators can tell which lane is active.
3055/// Without `asupersync-executor`, requesting `Asupersync` falls back to `Structured`.
3056/// Executor initialization errors are returned to the caller.
3057#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
3058pub enum RuntimeLane {
3059    /// Pre-migration behavior: thread-based subscriptions with manual stop coordination.
3060    /// This is the safe default that preserves all existing semantics.
3061    Legacy,
3062    /// Structured cancellation: subscriptions use CancellationToken internally.
3063    /// Externally observable behavior is identical to Legacy.
3064    #[default]
3065    Structured,
3066    /// Execute tasks through the Asupersync blocking pool, retaining structured
3067    /// subscription cancellation. Requires the `asupersync-executor` feature;
3068    /// without it, falls back to Structured with a warning.
3069    Asupersync,
3070}
3071
3072impl RuntimeLane {
3073    /// Whether [`Self::Asupersync`] is backed by a real executor in this
3074    /// build, rather than falling back to [`Self::Structured`].
3075    ///
3076    /// Exposed because a feature flag is invisible to downstream crates:
3077    /// `#[cfg(feature = "asupersync-executor")]` in a crate that merely
3078    /// *depends* on `ftui-runtime` tests that crate's own features, not
3079    /// these. Without this, such a crate can only hard-code one of the two
3080    /// behaviours and be wrong in the other build - which is exactly what
3081    /// `ftui-harness`'s `runbook_step4_promote_to_enabled` did.
3082    #[must_use]
3083    pub const fn asupersync_available() -> bool {
3084        cfg!(feature = "asupersync-executor")
3085    }
3086
3087    /// Resolve the effective lane, applying fallback rules.
3088    ///
3089    /// Asupersync is available when `asupersync-executor` is compiled in -
3090    /// see [`Self::asupersync_available`]. Otherwise, its tasks use
3091    /// Structured's default executor.
3092    #[must_use]
3093    pub fn resolve(self) -> Self {
3094        #[cfg(not(feature = "asupersync-executor"))]
3095        if self == Self::Asupersync {
3096            tracing::warn!(
3097                target: crate::telemetry_schema::TARGET_RUNTIME,
3098                requested = "asupersync",
3099                resolved = "structured",
3100                missing_feature = "asupersync-executor",
3101                "Asupersync lane requires asupersync-executor; falling back to structured cancellation"
3102            );
3103            return Self::Structured;
3104        }
3105        self
3106    }
3107
3108    /// Returns a human-readable label for logging.
3109    #[must_use]
3110    pub fn label(self) -> &'static str {
3111        match self {
3112            Self::Legacy => "legacy",
3113            Self::Structured => "structured",
3114            Self::Asupersync => "asupersync",
3115        }
3116    }
3117
3118    /// Check if this lane uses structured cancellation (CancellationToken).
3119    #[must_use]
3120    pub fn uses_structured_cancellation(self) -> bool {
3121        matches!(self, Self::Structured | Self::Asupersync)
3122    }
3123
3124    /// Resolve the default task executor backend for this lane.
3125    ///
3126    /// # Input-lag regression fix (#78)
3127    ///
3128    /// The `Structured` lane changes *subscription cancellation* semantics
3129    /// (CancellationToken-backed stop signals in `subscription.rs`); it must
3130    /// NOT also collapse `Cmd::Task` concurrency. Earlier this returned
3131    /// `EffectQueue`, which routed every `Cmd::Task` through a single
3132    /// `effect_queue_loop` worker thread with a Smith's-rule (SPT) scheduler,
3133    /// serializing all tasks. Apps that forward PTY output via per-pane
3134    /// `Cmd::task` polling loops (e.g. 10ms drains) then contended for one
3135    /// serialized worker, adding per-keystroke head-of-line latency versus
3136    /// v0.2.1, where each `Cmd::task` got its own `std::thread::spawn`.
3137    ///
3138    /// Structured cancellation does not depend on the effect queue (stop
3139    /// signals are token-backed regardless of executor backend), so the two
3140    /// concerns are decoupled here: `Structured` keeps the structured
3141    /// cancellation semantics but restores per-task-thread (`Spawned`)
3142    /// execution. Apps that explicitly opt into `EffectQueue` still get it
3143    /// (the lane default only applies when the app uses the legacy default
3144    /// backend โ€” see `EffectQueueConfig::uses_legacy_default_backend`).
3145    #[must_use]
3146    fn task_executor_backend(self) -> TaskExecutorBackend {
3147        #[cfg(feature = "asupersync-executor")]
3148        if self == Self::Asupersync {
3149            return TaskExecutorBackend::Asupersync;
3150        }
3151        // Structured cancellation does not serialize tasks. An unavailable
3152        // Asupersync lane resolves to Structured before backend selection.
3153        TaskExecutorBackend::Spawned
3154    }
3155
3156    /// Read the lane from the `FTUI_RUNTIME_LANE` environment variable.
3157    ///
3158    /// Accepted values (case-insensitive): `legacy`, `structured`, `asupersync`.
3159    /// Returns `None` if the variable is unset or contains an unrecognized value.
3160    #[must_use]
3161    pub fn from_env() -> Option<Self> {
3162        let val = std::env::var("FTUI_RUNTIME_LANE").ok()?;
3163        Self::parse(&val)
3164    }
3165
3166    /// Parse a lane name (case-insensitive).
3167    ///
3168    /// Returns `None` for unrecognized values.
3169    #[must_use]
3170    pub fn parse(s: &str) -> Option<Self> {
3171        match s.to_ascii_lowercase().as_str() {
3172            "legacy" => Some(Self::Legacy),
3173            "structured" => Some(Self::Structured),
3174            "asupersync" => Some(Self::Asupersync),
3175            _ => {
3176                tracing::warn!(
3177                    target: crate::telemetry_schema::TARGET_RUNTIME,
3178                    value = s,
3179                    "RuntimeLane::parse: unrecognized value"
3180                );
3181                None
3182            }
3183        }
3184    }
3185}
3186
3187/// Rollout policy for the Asupersync migration (bd-2crbt).
3188///
3189/// Controls how the runtime lane transition is managed:
3190///
3191/// - `Off` โ€” use only the configured lane, no shadow comparison.
3192/// - `Shadow` โ€” run both baseline and candidate lanes, compare outputs,
3193///   but use only the baseline lane for actual rendering. Evidence is emitted
3194///   to the configured JSONL sink for operator review.
3195/// - `Enabled` โ€” use the candidate lane for rendering (requires prior shadow
3196///   evidence showing deterministic match).
3197///
3198/// The policy is logged at startup and can be overridden via the
3199/// `FTUI_ROLLOUT_POLICY` environment variable (`off`, `shadow`, `enabled`).
3200#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
3201pub enum RolloutPolicy {
3202    /// No rollout activity โ€” use the configured lane directly.
3203    #[default]
3204    Off,
3205    /// Shadow-run comparison mode: run both lanes, emit evidence, use baseline.
3206    Shadow,
3207    /// Candidate lane is live โ€” requires prior shadow evidence.
3208    Enabled,
3209}
3210
3211impl RolloutPolicy {
3212    /// Read the policy from the `FTUI_ROLLOUT_POLICY` environment variable.
3213    ///
3214    /// Accepted values (case-insensitive): `off`, `shadow`, `enabled`.
3215    /// Returns `None` if unset or unrecognized.
3216    #[must_use]
3217    pub fn from_env() -> Option<Self> {
3218        let val = std::env::var("FTUI_ROLLOUT_POLICY").ok()?;
3219        Self::parse(&val)
3220    }
3221
3222    /// Parse a rollout policy name (case-insensitive).
3223    ///
3224    /// Returns `None` for unrecognized values.
3225    #[must_use]
3226    pub fn parse(s: &str) -> Option<Self> {
3227        match s.to_ascii_lowercase().as_str() {
3228            "off" => Some(Self::Off),
3229            "shadow" => Some(Self::Shadow),
3230            "enabled" => Some(Self::Enabled),
3231            _ => {
3232                tracing::warn!(
3233                    target: crate::telemetry_schema::TARGET_RUNTIME,
3234                    value = s,
3235                    "RolloutPolicy::parse: unrecognized value"
3236                );
3237                None
3238            }
3239        }
3240    }
3241
3242    /// Returns a human-readable label for logging.
3243    #[must_use]
3244    pub fn label(self) -> &'static str {
3245        match self {
3246            Self::Off => "off",
3247            Self::Shadow => "shadow",
3248            Self::Enabled => "enabled",
3249        }
3250    }
3251
3252    /// Whether this policy involves shadow comparison.
3253    #[must_use]
3254    pub fn is_shadow(self) -> bool {
3255        matches!(self, Self::Shadow)
3256    }
3257}
3258
3259impl std::fmt::Display for RolloutPolicy {
3260    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3261        f.write_str(self.label())
3262    }
3263}
3264
3265impl std::fmt::Display for RuntimeLane {
3266    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3267        f.write_str(self.label())
3268    }
3269}
3270
3271/// Configuration for the program runtime.
3272#[derive(Debug, Clone)]
3273pub struct ProgramConfig {
3274    /// Screen mode (inline or alternate screen).
3275    pub screen_mode: ScreenMode,
3276    /// UI anchor for inline mode.
3277    pub ui_anchor: UiAnchor,
3278    /// Optional maximum distinct hyperlinks admitted per rendered frame.
3279    ///
3280    /// Retains at most twice this many registry slots so the last presented
3281    /// frame keeps stable IDs during diffing. Excess links render as plain
3282    /// text. Models opting in must register URLs on each view, rather than
3283    /// cache numeric link IDs across frames. `None` preserves unmanaged IDs;
3284    /// `Some(0)` disables link registration. The limit is clamped to half the
3285    /// 24-bit ID space. Applying it to an existing writer invalidates its IDs
3286    /// and presentation baseline.
3287    pub hyperlink_limit: Option<usize>,
3288    /// Frame budget configuration.
3289    pub budget: FrameBudgetConfig,
3290    /// Runtime load-governor configuration.
3291    pub load_governor: LoadGovernorConfig,
3292    /// Diff strategy configuration for the terminal writer.
3293    pub diff_config: RuntimeDiffConfig,
3294    /// Evidence JSONL sink configuration.
3295    pub evidence_sink: EvidenceSinkConfig,
3296    /// Render-trace recorder configuration.
3297    pub render_trace: RenderTraceConfig,
3298    /// Optional frame timing sink.
3299    pub frame_timing: Option<FrameTimingConfig>,
3300    /// Conformal predictor configuration for frame-time risk gating.
3301    pub conformal_config: Option<ConformalConfig>,
3302    /// Locale context used for rendering.
3303    pub locale_context: LocaleContext,
3304    /// Input poll timeout.
3305    pub poll_timeout: Duration,
3306    /// Immediate event-drain policy for burst handling.
3307    pub immediate_drain: ImmediateDrainConfig,
3308    /// Resize coalescer configuration.
3309    pub resize_coalescer: CoalescerConfig,
3310    /// Resize handling behavior (immediate/throttled).
3311    pub resize_behavior: ResizeBehavior,
3312    /// Forced terminal size override (when set, resize events are ignored).
3313    pub forced_size: Option<(u16, u16)>,
3314    /// Mouse capture policy (`Auto`, `On`, `Off`).
3315    ///
3316    /// `Auto` is inline-safe: off in inline modes, on in alt-screen mode.
3317    pub mouse_capture_policy: MouseCapturePolicy,
3318    /// Enable bracketed paste.
3319    pub bracketed_paste: bool,
3320    /// Enable focus reporting.
3321    pub focus_reporting: bool,
3322    /// Enable Kitty keyboard protocol (repeat/release events).
3323    pub kitty_keyboard: bool,
3324    /// State persistence configuration.
3325    pub persistence: PersistenceConfig,
3326    /// Inline auto UI height remeasurement policy.
3327    pub inline_auto_remeasure: Option<InlineAutoRemeasureConfig>,
3328    /// Gesture recognition (clicks, drags, long press, chords) delivered to
3329    /// [`Model::on_gesture`]; `None` (the default) runs no recognizer.
3330    pub gestures: Option<ftui_core::gesture::GestureConfig>,
3331    /// Accessibility tree collection. When set, every rendered frame builds
3332    /// an [`A11yTree`] from the nodes widgets push into the [`Frame`], diffs
3333    /// it against the previous frame and derives screen-reader
3334    /// announcements under this policy. Tracing and evidence export metadata
3335    /// only by default; [`Model::on_accessibility`] receives the complete
3336    /// local announcements. `None` (the default) collects nothing and adds
3337    /// no per-frame work.
3338    pub accessibility: Option<ScreenReaderPolicy>,
3339    /// Include announcement text in the explicitly configured evidence sink.
3340    ///
3341    /// Defaults to `false`: evidence rows contain `"text": null`. Enable only
3342    /// for an intentional local content capture; labels and edited text may
3343    /// be sensitive. Ordinary tracing never includes announcement content,
3344    /// and this setting does not change the local accessibility callback.
3345    pub accessibility_evidence_text: bool,
3346    /// Widget refresh selection configuration.
3347    pub widget_refresh: WidgetRefreshConfig,
3348    /// Effect queue scheduling configuration.
3349    pub effect_queue: EffectQueueConfig,
3350    /// Frame guardrails configuration (memory + queue safety limits).
3351    pub guardrails: GuardrailsConfig,
3352    /// Install signal handlers for cleanup on SIGINT/SIGTERM/SIGHUP.
3353    ///
3354    /// Defaults to `true` for application safety. Set to `false` in tests or
3355    /// when the embedding application manages signals.
3356    pub intercept_signals: bool,
3357    /// Handle job-control stops (SIGTSTP, SIGTTIN, SIGTTOU): hand the terminal
3358    /// back to the shell before the process stops and restore it, with a full
3359    /// repaint, when it is continued (`docs/spec/suspend-resume.md`).
3360    ///
3361    /// Defaults to `true`. Takes effect only with [`intercept_signals`](Self::intercept_signals)
3362    /// and a backend that can release its terminal session (the native TTY
3363    /// backend); elsewhere the signals keep their default action, which stops
3364    /// the process with the terminal still in raw mode.
3365    pub job_control: bool,
3366    /// Treat a Ctrl-Z key press as a request to suspend (default: `false`).
3367    ///
3368    /// Raw mode turns off the terminal's own Ctrl-Z handling, so the key
3369    /// arrives as an ordinary event. It is off by default because Ctrl-Z is
3370    /// undo in `TextArea` and in the showcase's editors; with it on, the key
3371    /// never reaches the model. Requires [`job_control`](Self::job_control).
3372    pub ctrl_z_suspends: bool,
3373    /// Optional tick strategy for selective background screen ticking.
3374    ///
3375    /// When `None` (default), all screens tick every frame (current behavior).
3376    /// When set, the runtime consults the strategy for each inactive screen.
3377    pub tick_strategy: Option<crate::tick_strategy::TickStrategyKind>,
3378    /// Runtime execution lane for the Asupersync migration rollout.
3379    ///
3380    /// Controls which subscription/effect backend is active.
3381    /// Defaults to `Structured` (CancellationToken-backed, current migration state).
3382    /// Logged at startup so operators can identify the active lane.
3383    pub runtime_lane: RuntimeLane,
3384    /// Rollout policy for the Asupersync migration (bd-2crbt).
3385    ///
3386    /// Controls whether shadow-run comparison is active during this session.
3387    /// When `Shadow`, both the baseline and candidate lanes run in parallel
3388    /// and evidence is emitted; rendering uses the baseline lane only.
3389    pub rollout_policy: RolloutPolicy,
3390    /// Coalesce high-frequency mouse moves and consecutive same-direction scrolls.
3391    ///
3392    /// When `false` (the default), every input event triggers a model update.
3393    /// When `true`, mouse move bursts and consecutive same-direction scroll
3394    /// events are coalesced so intermediate states do not trigger redundant
3395    /// updates and renders. The recognizer still receives all raw events.
3396    pub event_coalescing: bool,
3397}
3398
3399impl Default for ProgramConfig {
3400    fn default() -> Self {
3401        Self {
3402            screen_mode: ScreenMode::Inline { ui_height: 4 },
3403            ui_anchor: UiAnchor::Bottom,
3404            hyperlink_limit: None,
3405            budget: FrameBudgetConfig::default(),
3406            load_governor: LoadGovernorConfig::default(),
3407            diff_config: RuntimeDiffConfig::default(),
3408            evidence_sink: EvidenceSinkConfig::default(),
3409            render_trace: RenderTraceConfig::default(),
3410            frame_timing: None,
3411            // Conformal frame-time risk gating is on by default: the predictor
3412            // only starts gating once a bucket has `min_samples` (20) real
3413            // frame timings, so a fresh program renders at full fidelity
3414            // during warm-up and degrades only on measured evidence. Use
3415            // `without_conformal()` to opt out.
3416            conformal_config: Some(ConformalConfig::default()),
3417            locale_context: LocaleContext::global(),
3418            poll_timeout: Duration::from_millis(100),
3419            immediate_drain: ImmediateDrainConfig::default(),
3420            resize_coalescer: CoalescerConfig::default(),
3421            resize_behavior: ResizeBehavior::Throttled,
3422            forced_size: None,
3423            mouse_capture_policy: MouseCapturePolicy::Auto,
3424            bracketed_paste: true,
3425            focus_reporting: false,
3426            kitty_keyboard: false,
3427            persistence: PersistenceConfig::default(),
3428            inline_auto_remeasure: None,
3429            gestures: None,
3430            accessibility: None,
3431            accessibility_evidence_text: false,
3432            widget_refresh: WidgetRefreshConfig::default(),
3433            effect_queue: EffectQueueConfig::default(),
3434            guardrails: GuardrailsConfig::default(),
3435            intercept_signals: true,
3436            job_control: true,
3437            ctrl_z_suspends: false,
3438            tick_strategy: None,
3439            runtime_lane: RuntimeLane::default(),
3440            rollout_policy: RolloutPolicy::default(),
3441            event_coalescing: false,
3442        }
3443    }
3444}
3445
3446impl ProgramConfig {
3447    /// Create config for fullscreen applications.
3448    pub fn fullscreen() -> Self {
3449        Self {
3450            screen_mode: ScreenMode::AltScreen,
3451            ..Default::default()
3452        }
3453    }
3454
3455    /// Create config for inline mode with specified height.
3456    pub fn inline(height: u16) -> Self {
3457        Self {
3458            screen_mode: ScreenMode::Inline { ui_height: height },
3459            ..Default::default()
3460        }
3461    }
3462
3463    /// Create config for inline mode with automatic UI height.
3464    pub fn inline_auto(min_height: u16, max_height: u16) -> Self {
3465        Self {
3466            screen_mode: ScreenMode::InlineAuto {
3467                min_height,
3468                max_height,
3469            },
3470            inline_auto_remeasure: Some(InlineAutoRemeasureConfig::default()),
3471            ..Default::default()
3472        }
3473    }
3474
3475    /// Run a gesture recognizer over the input stream and deliver recognized
3476    /// gestures to [`Model::on_gesture`]. Mouse gestures need mouse capture
3477    /// (see [`Self::with_mouse_capture_policy`]).
3478    #[must_use]
3479    pub fn with_gestures(mut self, config: ftui_core::gesture::GestureConfig) -> Self {
3480        self.gestures = Some(config);
3481        self
3482    }
3483
3484    /// Coalesce high-frequency mouse moves and consecutive same-direction scrolls.
3485    ///
3486    /// When enabled, mouse move bursts and same-direction scrolls are coalesced
3487    /// so intermediate positions do not trigger individual model updates and renders.
3488    /// Pending events are flushed at the end of ready event bursts, before
3489    /// non-coalescable events, and on ticks. Raw events are still fed to the
3490    /// gesture recognizer before coalescing.
3491    #[must_use]
3492    pub fn with_event_coalescing(mut self, enabled: bool) -> Self {
3493        self.event_coalescing = enabled;
3494        self
3495    }
3496
3497    /// Build an accessibility tree every frame and derive screen-reader
3498    /// announcements under `policy` (see [`Self::accessibility`]). Read the
3499    /// results through [`Program::accessibility_tree`] and
3500    /// [`Program::accessibility_announcements`].
3501    #[must_use]
3502    pub fn with_accessibility(mut self, policy: ScreenReaderPolicy) -> Self {
3503        self.accessibility = Some(policy);
3504        self
3505    }
3506
3507    /// Opt into announcement content in the configured evidence sink.
3508    /// See [`Self::accessibility_evidence_text`] for the privacy contract.
3509    #[must_use]
3510    pub fn with_accessibility_evidence_text(mut self, include_text: bool) -> Self {
3511        self.accessibility_evidence_text = include_text;
3512        self
3513    }
3514
3515    /// Enable mouse support.
3516    #[must_use]
3517    pub fn with_mouse(mut self) -> Self {
3518        self.mouse_capture_policy = MouseCapturePolicy::On;
3519        self
3520    }
3521
3522    /// Set mouse capture policy.
3523    #[must_use]
3524    pub fn with_mouse_capture_policy(mut self, policy: MouseCapturePolicy) -> Self {
3525        self.mouse_capture_policy = policy;
3526        self
3527    }
3528
3529    /// Force mouse capture enabled/disabled regardless of screen mode.
3530    #[must_use]
3531    pub fn with_mouse_enabled(mut self, enabled: bool) -> Self {
3532        self.mouse_capture_policy = if enabled {
3533            MouseCapturePolicy::On
3534        } else {
3535            MouseCapturePolicy::Off
3536        };
3537        self
3538    }
3539
3540    /// Resolve mouse capture using the configured policy and screen mode.
3541    #[must_use]
3542    pub const fn resolved_mouse_capture(&self) -> bool {
3543        self.mouse_capture_policy.resolve(self.screen_mode)
3544    }
3545
3546    /// Set the budget configuration.
3547    #[must_use]
3548    pub fn with_budget(mut self, budget: FrameBudgetConfig) -> Self {
3549        self.budget = budget;
3550        self
3551    }
3552
3553    /// Bound per-frame hyperlink admission and retire unused URLs.
3554    /// See [`Self::hyperlink_limit`] for the ID lifetime contract.
3555    #[must_use]
3556    pub fn with_hyperlink_limit(mut self, limit: usize) -> Self {
3557        self.hyperlink_limit = Some(limit);
3558        self
3559    }
3560
3561    /// Set the runtime load-governor configuration.
3562    #[must_use]
3563    pub fn with_load_governor(mut self, config: LoadGovernorConfig) -> Self {
3564        self.load_governor = config;
3565        self
3566    }
3567
3568    /// Disable the adaptive load governor and use legacy render-budget behavior.
3569    #[must_use]
3570    pub fn without_load_governor(mut self) -> Self {
3571        self.load_governor = LoadGovernorConfig::disabled();
3572        self
3573    }
3574
3575    /// Set the diff strategy configuration for the terminal writer.
3576    #[must_use]
3577    pub fn with_diff_config(mut self, diff_config: RuntimeDiffConfig) -> Self {
3578        self.diff_config = diff_config;
3579        self
3580    }
3581
3582    /// Set the evidence JSONL sink configuration.
3583    #[must_use]
3584    pub fn with_evidence_sink(mut self, config: EvidenceSinkConfig) -> Self {
3585        self.evidence_sink = config;
3586        self
3587    }
3588
3589    /// Set the render-trace recorder configuration.
3590    #[must_use]
3591    pub fn with_render_trace(mut self, config: RenderTraceConfig) -> Self {
3592        self.render_trace = config;
3593        self
3594    }
3595
3596    /// Set a frame timing sink for per-frame profiling.
3597    #[must_use]
3598    pub fn with_frame_timing(mut self, config: FrameTimingConfig) -> Self {
3599        self.frame_timing = Some(config);
3600        self
3601    }
3602
3603    /// Enable conformal frame-time risk gating with the given config.
3604    #[must_use]
3605    pub fn with_conformal_config(mut self, config: ConformalConfig) -> Self {
3606        self.conformal_config = Some(config);
3607        self
3608    }
3609
3610    /// Disable conformal frame-time risk gating.
3611    #[must_use]
3612    pub fn without_conformal(mut self) -> Self {
3613        self.conformal_config = None;
3614        self
3615    }
3616
3617    /// Set the locale context used for rendering.
3618    #[must_use]
3619    pub fn with_locale_context(mut self, locale_context: LocaleContext) -> Self {
3620        self.locale_context = locale_context;
3621        self
3622    }
3623
3624    /// Set the base locale used for rendering.
3625    #[must_use]
3626    pub fn with_locale(mut self, locale: impl Into<crate::locale::Locale>) -> Self {
3627        self.locale_context = LocaleContext::new(locale);
3628        self
3629    }
3630
3631    /// Set the widget refresh selection configuration.
3632    #[must_use]
3633    pub fn with_widget_refresh(mut self, config: WidgetRefreshConfig) -> Self {
3634        self.widget_refresh = config;
3635        self
3636    }
3637
3638    /// Set the effect queue scheduling configuration.
3639    #[must_use]
3640    pub fn with_effect_queue(mut self, config: EffectQueueConfig) -> Self {
3641        self.effect_queue = config;
3642        self
3643    }
3644
3645    /// Set the resize coalescer configuration.
3646    #[must_use]
3647    pub fn with_resize_coalescer(mut self, config: CoalescerConfig) -> Self {
3648        self.resize_coalescer = config;
3649        self
3650    }
3651
3652    /// Set the resize handling behavior.
3653    #[must_use]
3654    pub fn with_resize_behavior(mut self, behavior: ResizeBehavior) -> Self {
3655        self.resize_behavior = behavior;
3656        self
3657    }
3658
3659    /// Force a fixed terminal size (cols, rows). Resize events are ignored.
3660    #[must_use]
3661    pub fn with_forced_size(mut self, width: u16, height: u16) -> Self {
3662        let width = width.max(1);
3663        let height = height.max(1);
3664        self.forced_size = Some((width, height));
3665        self
3666    }
3667
3668    /// Clear any forced terminal size override.
3669    #[must_use]
3670    pub fn without_forced_size(mut self) -> Self {
3671        self.forced_size = None;
3672        self
3673    }
3674
3675    /// Toggle legacy immediate-resize behavior for migration.
3676    #[must_use]
3677    pub fn with_legacy_resize(mut self, enabled: bool) -> Self {
3678        if enabled {
3679            self.resize_behavior = ResizeBehavior::Immediate;
3680        }
3681        self
3682    }
3683
3684    /// Set the persistence configuration.
3685    #[must_use]
3686    pub fn with_persistence(mut self, persistence: PersistenceConfig) -> Self {
3687        self.persistence = persistence;
3688        self
3689    }
3690
3691    /// Enable persistence with the given registry.
3692    #[must_use]
3693    pub fn with_registry(mut self, registry: std::sync::Arc<StateRegistry>) -> Self {
3694        self.persistence = PersistenceConfig::with_registry(registry);
3695        self
3696    }
3697
3698    /// Enable inline auto UI height remeasurement with the given policy.
3699    #[must_use]
3700    pub fn with_inline_auto_remeasure(mut self, config: InlineAutoRemeasureConfig) -> Self {
3701        self.inline_auto_remeasure = Some(config);
3702        self
3703    }
3704
3705    /// Disable inline auto UI height remeasurement.
3706    #[must_use]
3707    pub fn without_inline_auto_remeasure(mut self) -> Self {
3708        self.inline_auto_remeasure = None;
3709        self
3710    }
3711
3712    /// Enable or disable signal interception (SIGHUP/SIGTERM/SIGINT) for cleanup.
3713    #[must_use]
3714    pub fn with_signal_interception(mut self, enabled: bool) -> Self {
3715        self.intercept_signals = enabled;
3716        self
3717    }
3718
3719    /// Enable or disable job-control handling (SIGTSTP/SIGTTIN/SIGTTOU).
3720    /// See [`ProgramConfig::job_control`].
3721    #[must_use]
3722    pub fn with_job_control(mut self, enabled: bool) -> Self {
3723        self.job_control = enabled;
3724        self
3725    }
3726
3727    /// Make a Ctrl-Z key press suspend the program instead of reaching the
3728    /// model. See [`ProgramConfig::ctrl_z_suspends`].
3729    #[must_use]
3730    pub fn with_ctrl_z_suspend(mut self, enabled: bool) -> Self {
3731        self.ctrl_z_suspends = enabled;
3732        self
3733    }
3734
3735    /// Set frame guardrails configuration.
3736    #[must_use]
3737    pub fn with_guardrails(mut self, config: GuardrailsConfig) -> Self {
3738        self.guardrails = config;
3739        self
3740    }
3741
3742    /// Set the immediate event-drain policy for burst handling.
3743    #[must_use]
3744    pub fn with_immediate_drain(mut self, config: ImmediateDrainConfig) -> Self {
3745        self.immediate_drain = config;
3746        self
3747    }
3748
3749    /// Set the tick strategy for selective background screen ticking.
3750    ///
3751    /// When set, the runtime consults the strategy to decide which inactive
3752    /// screens should tick on each frame. Without a strategy, all screens
3753    /// tick every frame (backwards-compatible default).
3754    ///
3755    /// ```ignore
3756    /// ProgramConfig::default()
3757    ///     .with_tick_strategy(TickStrategyKind::Uniform { divisor: 5 })
3758    /// ```
3759    #[must_use]
3760    pub fn with_tick_strategy(mut self, strategy: crate::tick_strategy::TickStrategyKind) -> Self {
3761        self.tick_strategy = Some(strategy);
3762        self
3763    }
3764
3765    /// Set the runtime execution lane.
3766    #[must_use]
3767    pub fn with_lane(mut self, lane: RuntimeLane) -> Self {
3768        self.runtime_lane = lane;
3769        self
3770    }
3771
3772    /// Set the rollout policy for the Asupersync migration.
3773    #[must_use]
3774    pub fn with_rollout_policy(mut self, policy: RolloutPolicy) -> Self {
3775        self.rollout_policy = policy;
3776        self
3777    }
3778
3779    /// Apply environment-variable overrides for lane and rollout policy.
3780    ///
3781    /// Reads `FTUI_RUNTIME_LANE` and `FTUI_ROLLOUT_POLICY`. Unset variables
3782    /// are ignored. Unrecognized values emit a `tracing::warn` and are
3783    /// ignored (the programmatic default or prior builder value is retained).
3784    #[must_use]
3785    pub fn with_env_overrides(mut self) -> Self {
3786        if let Some(lane) = RuntimeLane::from_env() {
3787            self.runtime_lane = lane;
3788        }
3789        if let Some(policy) = RolloutPolicy::from_env() {
3790            self.rollout_policy = policy;
3791        }
3792        self
3793    }
3794
3795    #[must_use]
3796    fn resolved_effect_queue_config(&self, resolved_lane: RuntimeLane) -> EffectQueueConfig {
3797        if !self.effect_queue.uses_legacy_default_backend() {
3798            return self.effect_queue.clone();
3799        }
3800
3801        self.effect_queue
3802            .clone()
3803            .with_backend(resolved_lane.task_executor_backend())
3804    }
3805}
3806
3807fn render_budget_from_program_config(config: &ProgramConfig) -> RenderBudget {
3808    let budget = RenderBudget::from_config(&config.budget);
3809    if config.load_governor.enabled {
3810        let mut controller = config.load_governor.budget_controller.clone();
3811        controller.target = config.budget.total;
3812        budget.with_controller(controller)
3813    } else {
3814        budget
3815    }
3816}
3817
3818enum EffectCommand<M> {
3819    Enqueue(TaskSpec, Box<dyn FnOnce() -> M + Send>),
3820    Shutdown,
3821}
3822
3823#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3824enum EffectLoopControl {
3825    Continue,
3826    ShutdownRequested,
3827}
3828
3829struct EffectQueue<M: Send + 'static> {
3830    sender: mpsc::Sender<EffectCommand<M>>,
3831    handle: Option<JoinHandle<()>>,
3832    closed: bool,
3833    /// Tasks accepted by the loop thread and not yet run (published by the
3834    /// loop each iteration; read by the frame guardrail).
3835    depth: std::sync::Arc<std::sync::atomic::AtomicUsize>,
3836}
3837
3838impl<M: Send + 'static> EffectQueue<M> {
3839    fn start(
3840        config: EffectQueueConfig,
3841        result_sender: mpsc::Sender<M>,
3842        evidence_sink: Option<EvidenceSink>,
3843    ) -> io::Result<Self> {
3844        let (tx, rx) = mpsc::channel::<EffectCommand<M>>();
3845        let depth = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
3846        let loop_depth = std::sync::Arc::clone(&depth);
3847        let handle = thread::Builder::new()
3848            .name("ftui-effects".into())
3849            .spawn(move || {
3850                effect_queue_loop(config, rx, result_sender, evidence_sink, &loop_depth);
3851            })?;
3852
3853        Ok(Self {
3854            sender: tx,
3855            handle: Some(handle),
3856            closed: false,
3857            depth,
3858        })
3859    }
3860
3861    /// Tasks accepted by the queue that have not run yet.
3862    fn in_flight(&self) -> usize {
3863        self.depth.load(std::sync::atomic::Ordering::Relaxed)
3864    }
3865
3866    fn enqueue(&self, spec: TaskSpec, task: Box<dyn FnOnce() -> M + Send>) {
3867        if self.closed {
3868            crate::effect_system::record_queue_drop("post_shutdown");
3869            tracing::debug!("rejecting task enqueue after effect queue shutdown");
3870            return;
3871        }
3872        if self
3873            .sender
3874            .send(EffectCommand::Enqueue(spec, task))
3875            .is_err()
3876        {
3877            crate::effect_system::record_queue_drop("channel_closed");
3878        }
3879    }
3880
3881    /// Timeout for the effect-queue thread to finish after sending Shutdown.
3882    const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(2);
3883    /// Poll interval when waiting for the effect-queue thread (bd-170o5).
3884    ///
3885    /// This sleep-poll pattern is the idiomatic Rust approach for bounded
3886    /// thread joins โ€” `JoinHandle` has no `join_timeout` in stable Rust.
3887    /// 1ms is chosen to minimize shutdown latency while avoiding spin.
3888    const SHUTDOWN_POLL: Duration = Duration::from_millis(1);
3889
3890    fn shutdown(&mut self) {
3891        self.closed = true;
3892        let _ = self.sender.send(EffectCommand::Shutdown);
3893        if let Some(handle) = self.handle.take() {
3894            let start = Instant::now();
3895            // Fast path: most shutdowns complete nearly instantly after the
3896            // Shutdown command is drained. Check once before entering poll loop.
3897            if handle.is_finished() {
3898                let _ = handle.join();
3899                let elapsed_us = start.elapsed().as_micros() as u64;
3900                tracing::debug!(
3901                    target: crate::telemetry_schema::TARGET_RUNTIME,
3902                    elapsed_us,
3903                    "effect-queue shutdown (fast path)"
3904                );
3905                return;
3906            }
3907            // Slow path: bounded poll loop for in-flight tasks (bd-170o5).
3908            while !handle.is_finished() {
3909                if start.elapsed() >= Self::SHUTDOWN_TIMEOUT {
3910                    tracing::warn!(
3911                        target: crate::telemetry_schema::TARGET_RUNTIME,
3912                        timeout_ms = Self::SHUTDOWN_TIMEOUT.as_millis() as u64,
3913                        "effect-queue thread did not stop within timeout; detaching"
3914                    );
3915                    return;
3916                }
3917                thread::sleep(Self::SHUTDOWN_POLL);
3918            }
3919            let _ = handle.join();
3920            let elapsed_us = start.elapsed().as_micros() as u64;
3921            tracing::debug!(
3922                target: crate::telemetry_schema::TARGET_RUNTIME,
3923                elapsed_us,
3924                "effect-queue shutdown (slow path)"
3925            );
3926        }
3927    }
3928}
3929
3930impl<M: Send + 'static> Drop for EffectQueue<M> {
3931    fn drop(&mut self) {
3932        self.shutdown();
3933    }
3934}
3935
3936struct SpawnTaskExecutor<M: Send + 'static> {
3937    result_sender: mpsc::Sender<M>,
3938    evidence_sink: Option<EvidenceSink>,
3939    handles: Vec<JoinHandle<()>>,
3940    /// Backpressure bound on in-flight spawned threads (`0` = unbounded),
3941    /// matching the EffectQueue / asupersync lanes.
3942    max_queue_depth: usize,
3943    /// Tasks shed by backpressure or post-shutdown rejection.
3944    dropped: u64,
3945    closed: bool,
3946}
3947
3948impl<M: Send + 'static> SpawnTaskExecutor<M> {
3949    const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(2);
3950    /// Poll interval for bounded thread joins (bd-170o5).
3951    ///
3952    /// Same rationale as `EffectQueue::SHUTDOWN_POLL` โ€” `JoinHandle` has no
3953    /// `join_timeout` in stable Rust, so we poll `is_finished()` with a
3954    /// 1ms sleep to minimize shutdown latency while avoiding spin.
3955    const SHUTDOWN_POLL: Duration = Duration::from_millis(1);
3956
3957    fn new(
3958        result_sender: mpsc::Sender<M>,
3959        evidence_sink: Option<EvidenceSink>,
3960        max_queue_depth: usize,
3961    ) -> Self {
3962        Self {
3963            result_sender,
3964            evidence_sink,
3965            handles: Vec::new(),
3966            max_queue_depth,
3967            dropped: 0,
3968            closed: false,
3969        }
3970    }
3971
3972    fn submit(&mut self, task: Box<dyn FnOnce() -> M + Send>) {
3973        if self.closed {
3974            self.dropped += 1;
3975            crate::effect_system::record_queue_drop("post_shutdown");
3976            tracing::debug!("rejecting spawned task submit after shutdown");
3977            return;
3978        }
3979        // Join finished threads first so the in-flight depth used for
3980        // backpressure reflects only tasks that are still running.
3981        self.reap_finished();
3982        // Backpressure: bound the number of in-flight spawned threads. The
3983        // `with_max_queue_depth` contract promises drops + counters for every
3984        // backend; this lane previously spawned unboundedly and counted
3985        // nothing. `0` means unbounded.
3986        if self.max_queue_depth > 0 && self.handles.len() >= self.max_queue_depth {
3987            self.dropped += 1;
3988            crate::effect_system::record_queue_drop("backpressure");
3989            emit_task_executor_backpressure_evidence(
3990                self.evidence_sink.as_ref(),
3991                "spawned",
3992                "drop",
3993                self.handles.len(),
3994                self.max_queue_depth,
3995                self.dropped,
3996            );
3997            return;
3998        }
3999        crate::effect_system::record_queue_enqueue(self.handles.len() as u64 + 1);
4000        let sender = self.result_sender.clone();
4001        let evidence_sink = self.evidence_sink.clone();
4002        let handle = thread::spawn(move || {
4003            let _ = run_task_closure(task, "spawned", evidence_sink.as_ref(), &sender);
4004            crate::effect_system::record_queue_processed();
4005        });
4006        self.handles.push(handle);
4007    }
4008
4009    fn reap_finished(&mut self) {
4010        if self.handles.is_empty() {
4011            return;
4012        }
4013
4014        let mut i = 0;
4015        while i < self.handles.len() {
4016            if self.handles[i].is_finished() {
4017                let handle = self.handles.swap_remove(i);
4018                let _ = handle.join();
4019            } else {
4020                i += 1;
4021            }
4022        }
4023    }
4024
4025    fn shutdown(&mut self) {
4026        self.closed = true;
4027        let start = Instant::now();
4028        // Fast path: reap any already-finished handles first.
4029        self.reap_finished();
4030        if self.handles.is_empty() {
4031            let elapsed_us = start.elapsed().as_micros() as u64;
4032            tracing::debug!(
4033                target: crate::telemetry_schema::TARGET_RUNTIME,
4034                elapsed_us,
4035                "spawn-executor shutdown (fast path, all tasks already finished)"
4036            );
4037            return;
4038        }
4039        // Slow path: bounded poll loop for in-flight tasks (bd-170o5).
4040        let pending_at_start = self.handles.len();
4041        while self.handles.iter().any(|handle| !handle.is_finished()) {
4042            if start.elapsed() >= Self::SHUTDOWN_TIMEOUT {
4043                let still_pending = self
4044                    .handles
4045                    .iter()
4046                    .filter(|handle| !handle.is_finished())
4047                    .count();
4048                tracing::warn!(
4049                    target: crate::telemetry_schema::TARGET_RUNTIME,
4050                    timeout_ms = Self::SHUTDOWN_TIMEOUT.as_millis() as u64,
4051                    pending_handles = still_pending,
4052                    "background task threads did not stop within timeout; detaching"
4053                );
4054                self.handles.clear();
4055                return;
4056            }
4057            thread::sleep(Self::SHUTDOWN_POLL);
4058        }
4059        self.reap_finished();
4060        let elapsed_us = start.elapsed().as_micros() as u64;
4061        tracing::debug!(
4062            target: crate::telemetry_schema::TARGET_RUNTIME,
4063            elapsed_us,
4064            pending_at_start,
4065            "spawn-executor shutdown (slow path)"
4066        );
4067    }
4068}
4069
4070#[cfg(feature = "asupersync-executor")]
4071struct AsupersyncTaskExecutor<M: Send + 'static> {
4072    result_sender: mpsc::Sender<M>,
4073    evidence_sink: Option<EvidenceSink>,
4074    runtime: AsupersyncRuntime,
4075    handles: Vec<BlockingTaskHandle>,
4076    /// Backpressure cap on in-flight blocking tasks (`0` = unbounded). Mirrors
4077    /// the `EffectQueue` lane's `max_queue_depth` so both backends shed load and
4078    /// report queue telemetry identically.
4079    max_queue_depth: usize,
4080    /// Total tasks rejected by backpressure or post-shutdown submission.
4081    dropped: u64,
4082    closed: bool,
4083}
4084
4085#[cfg(feature = "asupersync-executor")]
4086impl<M: Send + 'static> AsupersyncTaskExecutor<M> {
4087    const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(2);
4088
4089    fn new(
4090        result_sender: mpsc::Sender<M>,
4091        evidence_sink: Option<EvidenceSink>,
4092        max_queue_depth: usize,
4093    ) -> io::Result<Self> {
4094        let max_threads = thread::available_parallelism().map_or(1, |count| count.get().max(1));
4095        let runtime = RuntimeBuilder::new()
4096            .blocking_threads(1, max_threads)
4097            .thread_name_prefix("ftui-asupersync-task")
4098            .build()
4099            .map_err(|error| {
4100                io::Error::other(format!("asupersync runtime init failed: {error}"))
4101            })?;
4102
4103        Ok(Self {
4104            result_sender,
4105            evidence_sink,
4106            runtime,
4107            handles: Vec::new(),
4108            max_queue_depth,
4109            dropped: 0,
4110            closed: false,
4111        })
4112    }
4113
4114    fn submit(&mut self, task: Box<dyn FnOnce() -> M + Send>) {
4115        if self.closed {
4116            self.dropped += 1;
4117            crate::effect_system::record_queue_drop("post_shutdown");
4118            tracing::debug!("rejecting asupersync task submit after shutdown");
4119            return;
4120        }
4121        // Prune completed handles so the in-flight depth used for backpressure
4122        // reflects only tasks that are still running or queued in the pool.
4123        self.handles.retain(|handle| !handle.is_done());
4124        // Backpressure: bound the number of in-flight blocking tasks, matching
4125        // the EffectQueue lane (bd-2zd0a). `0` means unbounded.
4126        if self.max_queue_depth > 0 && self.handles.len() >= self.max_queue_depth {
4127            self.dropped += 1;
4128            crate::effect_system::record_queue_drop("backpressure");
4129            emit_task_executor_backpressure_evidence(
4130                self.evidence_sink.as_ref(),
4131                "asupersync",
4132                "drop",
4133                self.handles.len(),
4134                self.max_queue_depth,
4135                self.dropped,
4136            );
4137            return;
4138        }
4139        crate::effect_system::record_queue_enqueue(self.handles.len() as u64 + 1);
4140        let sender = self.result_sender.clone();
4141        let evidence_sink = self.evidence_sink.clone();
4142        let handle = self
4143            .runtime
4144            .spawn_blocking(move || {
4145                let _ = run_task_closure(task, "asupersync", evidence_sink.as_ref(), &sender);
4146                crate::effect_system::record_queue_processed();
4147            })
4148            .expect("asupersync blocking pool must be configured");
4149        self.handles.push(handle);
4150    }
4151
4152    fn reap_finished(&mut self) {
4153        self.handles.retain(|handle| !handle.is_done());
4154    }
4155
4156    fn shutdown(&mut self) {
4157        self.closed = true;
4158        let deadline = Instant::now() + Self::SHUTDOWN_TIMEOUT;
4159        for handle in &self.handles {
4160            let remaining = deadline.saturating_duration_since(Instant::now());
4161            if remaining.is_zero() || !handle.wait_timeout(remaining) {
4162                tracing::warn!(
4163                    timeout_ms = Self::SHUTDOWN_TIMEOUT.as_millis() as u64,
4164                    pending_handles = self
4165                        .handles
4166                        .iter()
4167                        .filter(|pending| !pending.is_done())
4168                        .count(),
4169                    "Asupersync blocking tasks did not stop within timeout; detaching"
4170                );
4171                self.handles.clear();
4172                return;
4173            }
4174        }
4175        self.handles.clear();
4176    }
4177}
4178
4179enum TaskExecutor<M: Send + 'static> {
4180    Spawned(SpawnTaskExecutor<M>),
4181    Queued(EffectQueue<M>),
4182    #[cfg(feature = "asupersync-executor")]
4183    Asupersync(AsupersyncTaskExecutor<M>),
4184}
4185
4186impl<M: Send + 'static> TaskExecutor<M> {
4187    fn new(
4188        config: &EffectQueueConfig,
4189        result_sender: mpsc::Sender<M>,
4190        evidence_sink: Option<EvidenceSink>,
4191    ) -> io::Result<Self> {
4192        let executor = match config.backend {
4193            TaskExecutorBackend::Spawned => Self::Spawned(SpawnTaskExecutor::new(
4194                result_sender,
4195                evidence_sink.clone(),
4196                config.max_queue_depth,
4197            )),
4198            TaskExecutorBackend::EffectQueue => Self::Queued(EffectQueue::start(
4199                config.clone(),
4200                result_sender,
4201                evidence_sink.clone(),
4202            )?),
4203            #[cfg(feature = "asupersync-executor")]
4204            TaskExecutorBackend::Asupersync => Self::Asupersync(AsupersyncTaskExecutor::new(
4205                result_sender,
4206                evidence_sink.clone(),
4207                config.max_queue_depth,
4208            )?),
4209        };
4210
4211        emit_task_executor_backend_evidence(evidence_sink.as_ref(), executor.kind_name_for_logs());
4212        Ok(executor)
4213    }
4214
4215    fn submit(&mut self, spec: TaskSpec, task: Box<dyn FnOnce() -> M + Send>) {
4216        match self {
4217            Self::Spawned(executor) => executor.submit(task),
4218            Self::Queued(queue) => queue.enqueue(spec, task),
4219            #[cfg(feature = "asupersync-executor")]
4220            Self::Asupersync(executor) => executor.submit(task),
4221        }
4222    }
4223
4224    fn reap_finished(&mut self) {
4225        match self {
4226            Self::Spawned(executor) => executor.reap_finished(),
4227            #[cfg(feature = "asupersync-executor")]
4228            Self::Asupersync(executor) => executor.reap_finished(),
4229            Self::Queued(_) => {}
4230        }
4231    }
4232
4233    /// Tasks this executor accepted that have not produced their message
4234    /// yet: live worker threads for the spawned and asupersync lanes, the
4235    /// loop's unrun task map for the effect queue. Per program, unlike the
4236    /// process-global `effect_system::queue_telemetry()` counters, so one
4237    /// program's backlog never shows up in another's frame guardrail.
4238    fn in_flight(&mut self) -> usize {
4239        match self {
4240            Self::Spawned(executor) => {
4241                executor.reap_finished();
4242                executor.handles.len()
4243            }
4244            #[cfg(feature = "asupersync-executor")]
4245            Self::Asupersync(executor) => {
4246                executor.reap_finished();
4247                executor.handles.len()
4248            }
4249            Self::Queued(queue) => queue.in_flight(),
4250        }
4251    }
4252
4253    fn shutdown(&mut self) {
4254        match self {
4255            Self::Spawned(executor) => executor.shutdown(),
4256            Self::Queued(queue) => queue.shutdown(),
4257            #[cfg(feature = "asupersync-executor")]
4258            Self::Asupersync(executor) => executor.shutdown(),
4259        }
4260    }
4261
4262    #[cfg(test)]
4263    fn kind_name(&self) -> &'static str {
4264        self.kind_name_for_logs()
4265    }
4266
4267    fn kind_name_for_logs(&self) -> &'static str {
4268        match self {
4269            Self::Spawned(_) => "spawned",
4270            Self::Queued(_) => "queued",
4271            #[cfg(feature = "asupersync-executor")]
4272            Self::Asupersync(_) => "asupersync",
4273        }
4274    }
4275}
4276
4277fn emit_task_executor_backend_evidence(sink: Option<&EvidenceSink>, backend: &str) {
4278    let Some(sink) = sink else {
4279        return;
4280    };
4281    let _ = sink.write_jsonl(&format!(
4282        r#"{{"schema_version":"ftui-evidence-v1","event":"task_executor_backend","backend":"{backend}"}}"#
4283    ));
4284}
4285
4286fn emit_task_executor_completion_evidence(
4287    sink: Option<&EvidenceSink>,
4288    backend: &str,
4289    duration_us: u64,
4290) {
4291    let Some(sink) = sink else {
4292        return;
4293    };
4294    let _ = sink.write_jsonl(&format!(
4295        r#"{{"schema_version":"ftui-evidence-v1","event":"task_executor_complete","backend":"{backend}","duration_us":{duration_us}}}"#
4296    ));
4297}
4298
4299fn emit_task_executor_panic_evidence(sink: Option<&EvidenceSink>, backend: &str, panic_msg: &str) {
4300    let Some(sink) = sink else {
4301        return;
4302    };
4303    let escaped = panic_msg
4304        .replace('\\', "\\\\")
4305        .replace('"', "\\\"")
4306        .replace('\n', "\\n")
4307        .replace('\r', "\\r")
4308        .replace('\t', "\\t");
4309    let _ = sink.write_jsonl(&format!(
4310        r#"{{"schema_version":"ftui-evidence-v1","event":"task_executor_panic","backend":"{backend}","panic_msg":"{escaped}"}}"#
4311    ));
4312}
4313
4314fn emit_task_executor_backpressure_evidence(
4315    sink: Option<&EvidenceSink>,
4316    backend: &str,
4317    action: &str,
4318    queue_length: usize,
4319    max_queue_size: usize,
4320    total_rejected: u64,
4321) {
4322    let Some(sink) = sink else {
4323        return;
4324    };
4325    let _ = sink.write_jsonl(&format!(
4326        r#"{{"schema_version":"ftui-evidence-v1","event":"task_executor_backpressure","backend":"{backend}","action":"{action}","queue_length":{queue_length},"max_queue_size":{max_queue_size},"total_rejected":{total_rejected}}}"#
4327    ));
4328}
4329
4330fn panic_payload_message(payload: Box<dyn Any + Send>) -> String {
4331    if let Some(s) = payload.downcast_ref::<&str>() {
4332        (*s).to_owned()
4333    } else if let Some(s) = payload.downcast_ref::<String>() {
4334        s.clone()
4335    } else {
4336        "unknown panic payload".to_owned()
4337    }
4338}
4339
4340fn log_task_executor_panic(backend: &str, panic_msg: &str) {
4341    #[cfg(feature = "tracing")]
4342    tracing::error!(
4343        executor_backend = backend,
4344        panic_msg,
4345        "task executor task panicked"
4346    );
4347    #[cfg(not(feature = "tracing"))]
4348    eprintln!("ftui: task executor task panicked ({backend}): {panic_msg}");
4349}
4350
4351fn run_task_closure<M: Send + 'static>(
4352    task: Box<dyn FnOnce() -> M + Send>,
4353    backend: &str,
4354    evidence_sink: Option<&EvidenceSink>,
4355    result_sender: &mpsc::Sender<M>,
4356) -> bool {
4357    let start = Instant::now();
4358    // This is a RECOVERABLE panic boundary โ€” the program keeps running.
4359    // Suppress the terminal panic hook: without this, a panicking task
4360    // triggers best_effort_cleanup mid-run (scroll-region reset, alt-screen
4361    // leave, raw-mode exit) and the still-live UI renders onto a cooked,
4362    // echoing main screen.
4363    let caught =
4364        ftui_core::with_panic_cleanup_suppressed(|| panic::catch_unwind(AssertUnwindSafe(task)));
4365    match caught {
4366        Ok(msg) => {
4367            let duration_us = start.elapsed().as_micros() as u64;
4368            tracing::debug!(
4369                target: crate::telemetry_schema::TARGET_EFFECT,
4370                command_type = "task",
4371                executor_backend = backend,
4372                duration_us = duration_us,
4373                effect_duration_us = duration_us,
4374                "task effect completed"
4375            );
4376            emit_task_executor_completion_evidence(evidence_sink, backend, duration_us);
4377            let _ = result_sender.send(msg);
4378            true
4379        }
4380        Err(payload) => {
4381            let panic_msg = panic_payload_message(payload);
4382            log_task_executor_panic(backend, &panic_msg);
4383            emit_task_executor_panic_evidence(evidence_sink, backend, &panic_msg);
4384            false
4385        }
4386    }
4387}
4388
4389fn effect_queue_loop<M: Send + 'static>(
4390    config: EffectQueueConfig,
4391    rx: mpsc::Receiver<EffectCommand<M>>,
4392    result_sender: mpsc::Sender<M>,
4393    evidence_sink: Option<EvidenceSink>,
4394    depth: &std::sync::atomic::AtomicUsize,
4395) {
4396    let mut scheduler = QueueingScheduler::new(config.scheduler);
4397    let mut tasks: HashMap<u64, Box<dyn FnOnce() -> M + Send>> = HashMap::new();
4398    let mut shutdown_requested = false;
4399    let max_depth = config.max_queue_depth;
4400
4401    loop {
4402        // Publish the accepted-but-unrun depth for the frame guardrail; the
4403        // loop comes back here after every command batch and every task.
4404        depth.store(tasks.len(), std::sync::atomic::Ordering::Relaxed);
4405        if tasks.is_empty() {
4406            if shutdown_requested {
4407                return;
4408            }
4409            match rx.recv() {
4410                Ok(cmd) => {
4411                    if matches!(
4412                        handle_effect_command(
4413                            cmd,
4414                            &mut scheduler,
4415                            &mut tasks,
4416                            &result_sender,
4417                            evidence_sink.as_ref(),
4418                            max_depth,
4419                        ),
4420                        EffectLoopControl::ShutdownRequested
4421                    ) {
4422                        shutdown_requested = true;
4423                    }
4424                }
4425                Err(_) => return,
4426            }
4427        }
4428
4429        while let Ok(cmd) = rx.try_recv() {
4430            if shutdown_requested && matches!(cmd, EffectCommand::Enqueue(_, _)) {
4431                crate::effect_system::record_queue_drop("post_shutdown");
4432                continue;
4433            }
4434            if matches!(
4435                handle_effect_command(
4436                    cmd,
4437                    &mut scheduler,
4438                    &mut tasks,
4439                    &result_sender,
4440                    evidence_sink.as_ref(),
4441                    max_depth,
4442                ),
4443                EffectLoopControl::ShutdownRequested
4444            ) {
4445                shutdown_requested = true;
4446            }
4447        }
4448
4449        if tasks.is_empty() {
4450            if shutdown_requested {
4451                return;
4452            }
4453            continue;
4454        }
4455
4456        let Some(job) = scheduler.peek_next().cloned() else {
4457            continue;
4458        };
4459
4460        if let Some(ref sink) = evidence_sink {
4461            let evidence = scheduler.evidence();
4462            let _ = sink.write_jsonl(&evidence.to_jsonl("effect_queue_select"));
4463        }
4464
4465        let completed = scheduler.tick(job.remaining_time);
4466        for job_id in completed {
4467            if let Some(task) = tasks.remove(&job_id) {
4468                let _ = run_task_closure(task, "queued", evidence_sink.as_ref(), &result_sender);
4469                crate::effect_system::record_queue_processed();
4470            }
4471        }
4472    }
4473}
4474
4475fn handle_effect_command<M: Send + 'static>(
4476    cmd: EffectCommand<M>,
4477    scheduler: &mut QueueingScheduler,
4478    tasks: &mut HashMap<u64, Box<dyn FnOnce() -> M + Send>>,
4479    result_sender: &mpsc::Sender<M>,
4480    evidence_sink: Option<&EvidenceSink>,
4481    max_depth: usize,
4482) -> EffectLoopControl {
4483    match cmd {
4484        EffectCommand::Enqueue(spec, task) => {
4485            // Backpressure: drop task if queue depth exceeds limit (bd-2zd0a)
4486            if max_depth > 0 && tasks.len() >= max_depth {
4487                crate::effect_system::record_queue_drop("backpressure");
4488                return EffectLoopControl::Continue;
4489            }
4490            let weight_source = if spec.weight == DEFAULT_TASK_WEIGHT {
4491                WeightSource::Default
4492            } else {
4493                WeightSource::Explicit
4494            };
4495            let estimate_source = if spec.estimate_ms == DEFAULT_TASK_ESTIMATE_MS {
4496                EstimateSource::Default
4497            } else {
4498                EstimateSource::Explicit
4499            };
4500            let id = scheduler.submit_with_sources(
4501                spec.weight,
4502                spec.estimate_ms,
4503                weight_source,
4504                estimate_source,
4505                spec.name,
4506            );
4507            if let Some(id) = id {
4508                tasks.insert(id, task);
4509                crate::effect_system::record_queue_enqueue(tasks.len() as u64);
4510            } else {
4511                let stats = scheduler.stats();
4512                emit_task_executor_backpressure_evidence(
4513                    evidence_sink,
4514                    "queued",
4515                    "inline_fallback",
4516                    stats.queue_length,
4517                    scheduler.max_queue_size(),
4518                    stats.total_rejected,
4519                );
4520                let _ =
4521                    run_task_closure(task, "queued-inline-fallback", evidence_sink, result_sender);
4522            }
4523            EffectLoopControl::Continue
4524        }
4525        EffectCommand::Shutdown => EffectLoopControl::ShutdownRequested,
4526    }
4527}
4528
4529// removed: legacy ResizeDebouncer (superseded by ResizeCoalescer)
4530
4531/// Policy for remeasuring inline auto UI height.
4532///
4533/// Uses VOI (value-of-information) sampling to decide when to perform
4534/// a costly full-height measurement, with any-time valid guarantees via
4535/// the embedded e-process in `VoiSampler`.
4536#[derive(Debug, Clone)]
4537pub struct InlineAutoRemeasureConfig {
4538    /// VOI sampling configuration.
4539    pub voi: VoiConfig,
4540    /// Minimum row delta to count as a "violation".
4541    pub change_threshold_rows: u16,
4542}
4543
4544impl Default for InlineAutoRemeasureConfig {
4545    fn default() -> Self {
4546        Self {
4547            voi: VoiConfig {
4548                // Height changes are expected to be rare; bias toward fewer samples.
4549                prior_alpha: 1.0,
4550                prior_beta: 9.0,
4551                // Allow ~1s max latency to adapt to growth/shrink.
4552                max_interval_ms: 1000,
4553                // Avoid over-sampling in high-FPS loops.
4554                min_interval_ms: 100,
4555                // Disable event forcing; use time-based gating.
4556                max_interval_events: 0,
4557                min_interval_events: 0,
4558                // Treat sampling as moderately expensive.
4559                sample_cost: 0.08,
4560                ..VoiConfig::default()
4561            },
4562            change_threshold_rows: 1,
4563        }
4564    }
4565}
4566
4567#[derive(Debug)]
4568struct InlineAutoRemeasureState {
4569    config: InlineAutoRemeasureConfig,
4570    sampler: VoiSampler,
4571}
4572
4573impl InlineAutoRemeasureState {
4574    fn new(config: InlineAutoRemeasureConfig) -> Self {
4575        let sampler = VoiSampler::new(config.voi.clone());
4576        Self { config, sampler }
4577    }
4578
4579    fn reset(&mut self) {
4580        self.sampler = VoiSampler::new(self.config.voi.clone());
4581    }
4582}
4583
4584#[derive(Debug, Clone)]
4585struct ConformalEvidence {
4586    bucket_key: String,
4587    n_b: usize,
4588    alpha: f64,
4589    q_b: Option<f64>,
4590    y_hat: f64,
4591    upper_us: Option<f64>,
4592    risk: bool,
4593    status: ConformalStatus,
4594    required_rank: usize,
4595    fallback_level: u8,
4596    window_size: usize,
4597    reset_count: u64,
4598}
4599
4600impl ConformalEvidence {
4601    fn from_prediction(prediction: &ConformalPrediction) -> Self {
4602        Self {
4603            bucket_key: prediction.bucket.to_string(),
4604            n_b: prediction.sample_count,
4605            alpha: prediction.alpha,
4606            q_b: prediction.quantile,
4607            y_hat: prediction.y_hat,
4608            upper_us: prediction.upper_us,
4609            risk: prediction.risk,
4610            status: prediction.status,
4611            required_rank: prediction.required_rank,
4612            fallback_level: prediction.fallback_level,
4613            window_size: prediction.window_size,
4614            reset_count: prediction.reset_count,
4615        }
4616    }
4617}
4618
4619#[derive(Debug, Clone)]
4620struct BudgetDecisionEvidence {
4621    frame_idx: u64,
4622    decision: BudgetDecision,
4623    controller_decision: BudgetDecision,
4624    degradation_before: DegradationLevel,
4625    degradation_after: DegradationLevel,
4626    frame_time_us: f64,
4627    budget_us: f64,
4628    pid_output: f64,
4629    pid_p: f64,
4630    pid_i: f64,
4631    pid_d: f64,
4632    e_value: f64,
4633    frames_observed: u32,
4634    frames_since_change: u32,
4635    in_warmup: bool,
4636    recovery_streak: u32,
4637    total_degrades: u64,
4638    total_recoveries: u64,
4639    controller_reason: BudgetDecisionReason,
4640    load_governor: LoadGovernorSnapshot,
4641    /// Detector that made the resize coalescer's latest regime decision.
4642    resize_detector: &'static str,
4643    conformal: Option<ConformalEvidence>,
4644}
4645
4646impl BudgetDecisionEvidence {
4647    fn decision_from_levels(before: DegradationLevel, after: DegradationLevel) -> BudgetDecision {
4648        if after > before {
4649            BudgetDecision::Degrade
4650        } else if after < before {
4651            BudgetDecision::Upgrade
4652        } else {
4653            BudgetDecision::Hold
4654        }
4655    }
4656
4657    #[must_use]
4658    fn to_jsonl(&self) -> String {
4659        let conformal = self.conformal.as_ref();
4660        let bucket_key = Self::opt_str(conformal.map(|c| c.bucket_key.as_str()));
4661        let n_b = Self::opt_usize(conformal.map(|c| c.n_b));
4662        let alpha = crate::conformal_predictor::finite_json_number(conformal.map(|c| c.alpha), 17);
4663        let q_b = Self::opt_f64(conformal.and_then(|c| c.q_b));
4664        let y_hat = Self::opt_f64(conformal.map(|c| c.y_hat));
4665        let upper_us = Self::opt_f64(conformal.and_then(|c| c.upper_us));
4666        let risk = Self::opt_bool(conformal.map(|c| c.risk));
4667        let conformal_status = Self::opt_str(conformal.map(|c| c.status.as_str()));
4668        let required_rank = Self::opt_usize(conformal.map(|c| c.required_rank));
4669        let fallback_level = Self::opt_u8(conformal.map(|c| c.fallback_level));
4670        let window_size = Self::opt_usize(conformal.map(|c| c.window_size));
4671        let reset_count = Self::opt_u64(conformal.map(|c| c.reset_count));
4672        let queue_max_depth = Self::opt_usize(self.load_governor.queue_max_depth);
4673
4674        format!(
4675            r#"{{"schema_version":"ftui-evidence-v1","event":"budget_decision","frame_idx":{},"decision":"{}","decision_controller":"{}","decision_controller_reason":"{}","degradation_before":"{}","degradation_after":"{}","frame_time_us":{:.6},"budget_us":{:.6},"pid_output":{:.6},"pid_p":{:.6},"pid_i":{:.6},"pid_d":{:.6},"e_value":{:.6},"frames_observed":{},"frames_since_change":{},"in_warmup":{},"recovery_streak":{},"total_degrades":{},"total_recoveries":{},"runtime_mode":"{}","runtime_mode_before":"{}","pressure_class":"{}","work_disposition":"{}","governor_reason":"{}","governor_transition":{},"strict_semantics_preserved":{},"queue_in_flight":{},"queue_max_depth":{},"queue_dropped_delta":{},"resize_coalescing_active":{},"resize_detector":"{}","recovery_intervals_observed":{},"recovery_intervals_required":{},"deferred_work_total":{},"coalesced_work_total":{},"dropped_work_total":{},"bucket_key":{},"n_b":{},"alpha":{},"q_b":{},"y_hat":{},"upper_us":{},"risk":{},"conformal_status":{},"required_rank":{},"fallback_level":{},"window_size":{},"reset_count":{}}}"#,
4676            self.frame_idx,
4677            self.decision.as_str(),
4678            self.controller_decision.as_str(),
4679            self.controller_reason.as_str(),
4680            self.degradation_before.as_str(),
4681            self.degradation_after.as_str(),
4682            self.frame_time_us,
4683            self.budget_us,
4684            self.pid_output,
4685            self.pid_p,
4686            self.pid_i,
4687            self.pid_d,
4688            self.e_value,
4689            self.frames_observed,
4690            self.frames_since_change,
4691            self.in_warmup,
4692            self.recovery_streak,
4693            self.total_degrades,
4694            self.total_recoveries,
4695            self.load_governor.mode.as_str(),
4696            self.load_governor.mode_before.as_str(),
4697            self.load_governor.pressure_class.as_str(),
4698            self.load_governor.disposition.as_str(),
4699            self.load_governor.reason_code,
4700            self.load_governor.transition,
4701            self.load_governor.strict_semantics_preserved,
4702            self.load_governor.queue_in_flight,
4703            queue_max_depth,
4704            self.load_governor.queue_dropped_delta,
4705            self.load_governor.resize_coalescing_active,
4706            self.resize_detector,
4707            self.load_governor.recovery_intervals_observed,
4708            self.load_governor.recovery_intervals_required,
4709            self.load_governor.deferred_work_total,
4710            self.load_governor.coalesced_work_total,
4711            self.load_governor.dropped_work_total,
4712            bucket_key,
4713            n_b,
4714            alpha,
4715            q_b,
4716            y_hat,
4717            upper_us,
4718            risk,
4719            conformal_status,
4720            required_rank,
4721            fallback_level,
4722            window_size,
4723            reset_count
4724        )
4725    }
4726
4727    fn opt_f64(value: Option<f64>) -> String {
4728        crate::conformal_predictor::finite_json_number(value, 6)
4729    }
4730
4731    fn opt_u64(value: Option<u64>) -> String {
4732        value
4733            .map(|v| v.to_string())
4734            .unwrap_or_else(|| "null".to_string())
4735    }
4736
4737    fn opt_u8(value: Option<u8>) -> String {
4738        value
4739            .map(|v| v.to_string())
4740            .unwrap_or_else(|| "null".to_string())
4741    }
4742
4743    fn opt_usize(value: Option<usize>) -> String {
4744        value
4745            .map(|v| v.to_string())
4746            .unwrap_or_else(|| "null".to_string())
4747    }
4748
4749    fn opt_bool(value: Option<bool>) -> String {
4750        value
4751            .map(|v| v.to_string())
4752            .unwrap_or_else(|| "null".to_string())
4753    }
4754
4755    fn opt_str(value: Option<&str>) -> String {
4756        value
4757            .map(|v| {
4758                format!(
4759                    "\"{}\"",
4760                    v.replace('\\', "\\\\")
4761                        .replace('"', "\\\"")
4762                        .replace('\n', "\\n")
4763                        .replace('\r', "\\r")
4764                        .replace('\t', "\\t")
4765                )
4766            })
4767            .unwrap_or_else(|| "null".to_string())
4768    }
4769}
4770
4771#[derive(Debug, Clone)]
4772struct FairnessConfigEvidence {
4773    enabled: bool,
4774    input_priority_threshold_ms: u64,
4775    dominance_threshold: u32,
4776    fairness_threshold: f64,
4777}
4778
4779impl FairnessConfigEvidence {
4780    #[must_use]
4781    fn to_jsonl(&self) -> String {
4782        format!(
4783            r#"{{"event":"fairness_config","enabled":{},"input_priority_threshold_ms":{},"dominance_threshold":{},"fairness_threshold":{:.6}}}"#,
4784            self.enabled,
4785            self.input_priority_threshold_ms,
4786            self.dominance_threshold,
4787            self.fairness_threshold
4788        )
4789    }
4790}
4791
4792#[derive(Debug, Clone)]
4793struct FairnessDecisionEvidence {
4794    frame_idx: u64,
4795    decision: &'static str,
4796    reason: &'static str,
4797    pending_input_latency_ms: Option<u64>,
4798    jain_index: f64,
4799    resize_dominance_count: u32,
4800    dominance_threshold: u32,
4801    fairness_threshold: f64,
4802    input_priority_threshold_ms: u64,
4803}
4804
4805impl FairnessDecisionEvidence {
4806    #[must_use]
4807    fn to_jsonl(&self) -> String {
4808        let pending_latency = self
4809            .pending_input_latency_ms
4810            .map(|v| v.to_string())
4811            .unwrap_or_else(|| "null".to_string());
4812        format!(
4813            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":{}}}"#,
4814            self.frame_idx,
4815            self.decision,
4816            self.reason,
4817            pending_latency,
4818            self.jain_index,
4819            self.resize_dominance_count,
4820            self.dominance_threshold,
4821            self.fairness_threshold,
4822            self.input_priority_threshold_ms
4823        )
4824    }
4825}
4826
4827#[derive(Debug, Clone)]
4828struct WidgetRefreshEntry {
4829    widget_id: u64,
4830    essential: bool,
4831    starved: bool,
4832    value: f32,
4833    cost_us: f32,
4834    score: f32,
4835    staleness_ms: u64,
4836}
4837
4838impl WidgetRefreshEntry {
4839    fn to_json(&self) -> String {
4840        format!(
4841            r#"{{"id":{},"cost_us":{:.3},"value":{:.4},"score":{:.4},"essential":{},"starved":{},"staleness_ms":{}}}"#,
4842            self.widget_id,
4843            self.cost_us,
4844            self.value,
4845            self.score,
4846            self.essential,
4847            self.starved,
4848            self.staleness_ms
4849        )
4850    }
4851}
4852
4853#[derive(Debug, Clone)]
4854struct WidgetRefreshPlan {
4855    frame_idx: u64,
4856    budget_us: f64,
4857    degradation: DegradationLevel,
4858    essentials_cost_us: f64,
4859    selected_cost_us: f64,
4860    selected_value: f64,
4861    signal_count: usize,
4862    selected: Vec<WidgetRefreshEntry>,
4863    skipped_count: usize,
4864    skipped_starved: usize,
4865    starved_selected: usize,
4866    over_budget: bool,
4867}
4868
4869impl WidgetRefreshPlan {
4870    fn new() -> Self {
4871        Self {
4872            frame_idx: 0,
4873            budget_us: 0.0,
4874            degradation: DegradationLevel::Full,
4875            essentials_cost_us: 0.0,
4876            selected_cost_us: 0.0,
4877            selected_value: 0.0,
4878            signal_count: 0,
4879            selected: Vec::new(),
4880            skipped_count: 0,
4881            skipped_starved: 0,
4882            starved_selected: 0,
4883            over_budget: false,
4884        }
4885    }
4886
4887    fn clear(&mut self) {
4888        self.frame_idx = 0;
4889        self.budget_us = 0.0;
4890        self.degradation = DegradationLevel::Full;
4891        self.essentials_cost_us = 0.0;
4892        self.selected_cost_us = 0.0;
4893        self.selected_value = 0.0;
4894        self.signal_count = 0;
4895        self.selected.clear();
4896        self.skipped_count = 0;
4897        self.skipped_starved = 0;
4898        self.starved_selected = 0;
4899        self.over_budget = false;
4900    }
4901
4902    fn as_budget(&self) -> WidgetBudget {
4903        if self.signal_count == 0 {
4904            return WidgetBudget::allow_all();
4905        }
4906        let ids = self.selected.iter().map(|entry| entry.widget_id).collect();
4907        WidgetBudget::allow_only(ids)
4908    }
4909
4910    fn recompute(
4911        &mut self,
4912        frame_idx: u64,
4913        budget_us: f64,
4914        degradation: DegradationLevel,
4915        signals: &[WidgetSignal],
4916        config: &WidgetRefreshConfig,
4917    ) {
4918        self.clear();
4919        self.frame_idx = frame_idx;
4920        self.budget_us = budget_us;
4921        self.degradation = degradation;
4922
4923        if !config.enabled || signals.is_empty() {
4924            return;
4925        }
4926
4927        self.signal_count = signals.len();
4928        let mut essentials_cost = 0.0f64;
4929        let mut selected_cost = 0.0f64;
4930        let mut selected_value = 0.0f64;
4931
4932        let staleness_window = config.staleness_window_ms.max(1) as f32;
4933        let mut candidates: Vec<WidgetRefreshEntry> = Vec::with_capacity(signals.len());
4934
4935        for signal in signals {
4936            let starved = config.starve_ms > 0 && signal.staleness_ms >= config.starve_ms;
4937            let staleness_score = (signal.staleness_ms as f32 / staleness_window).min(1.0);
4938            let mut value = config.weight_priority * signal.priority
4939                + config.weight_staleness * staleness_score
4940                + config.weight_focus * signal.focus_boost
4941                + config.weight_interaction * signal.interaction_boost;
4942            if starved {
4943                value += config.starve_boost;
4944            }
4945            let raw_cost = if signal.recent_cost_us > 0.0 {
4946                signal.recent_cost_us
4947            } else {
4948                signal.cost_estimate_us
4949            };
4950            let cost_us = raw_cost.max(config.min_cost_us);
4951            let score = if cost_us > 0.0 {
4952                value / cost_us
4953            } else {
4954                value
4955            };
4956
4957            let entry = WidgetRefreshEntry {
4958                widget_id: signal.widget_id,
4959                essential: signal.essential,
4960                starved,
4961                value,
4962                cost_us,
4963                score,
4964                staleness_ms: signal.staleness_ms,
4965            };
4966
4967            if degradation >= DegradationLevel::EssentialOnly && !signal.essential {
4968                self.skipped_count += 1;
4969                if starved {
4970                    self.skipped_starved = self.skipped_starved.saturating_add(1);
4971                }
4972                continue;
4973            }
4974
4975            if signal.essential {
4976                essentials_cost += cost_us as f64;
4977                selected_cost += cost_us as f64;
4978                selected_value += value as f64;
4979                if starved {
4980                    self.starved_selected = self.starved_selected.saturating_add(1);
4981                }
4982                self.selected.push(entry);
4983            } else {
4984                candidates.push(entry);
4985            }
4986        }
4987
4988        let mut remaining = budget_us - selected_cost;
4989
4990        if degradation < DegradationLevel::EssentialOnly {
4991            let nonessential_total = candidates.len();
4992            let max_drop_fraction = config.max_drop_fraction.clamp(0.0, 1.0);
4993            let enforce_drop_rate = max_drop_fraction < 1.0 && nonessential_total > 0;
4994            let min_nonessential_selected = if enforce_drop_rate {
4995                let min_fraction = (1.0 - max_drop_fraction).max(0.0);
4996                ((min_fraction * nonessential_total as f32).ceil() as usize).min(nonessential_total)
4997            } else {
4998                0
4999            };
5000
5001            candidates.sort_by(|a, b| {
5002                b.starved
5003                    .cmp(&a.starved)
5004                    .then_with(|| b.score.total_cmp(&a.score))
5005                    .then_with(|| b.value.total_cmp(&a.value))
5006                    .then_with(|| a.cost_us.total_cmp(&b.cost_us))
5007                    .then_with(|| a.widget_id.cmp(&b.widget_id))
5008            });
5009
5010            let mut forced_starved = 0usize;
5011            let mut nonessential_selected = 0usize;
5012            let mut skipped_candidates = if enforce_drop_rate {
5013                Vec::with_capacity(candidates.len())
5014            } else {
5015                Vec::new()
5016            };
5017
5018            for entry in candidates.into_iter() {
5019                if entry.starved && forced_starved >= config.max_starved_per_frame {
5020                    self.skipped_count += 1;
5021                    self.skipped_starved = self.skipped_starved.saturating_add(1);
5022                    if enforce_drop_rate {
5023                        skipped_candidates.push(entry);
5024                    }
5025                    continue;
5026                }
5027
5028                if remaining >= entry.cost_us as f64 {
5029                    remaining -= entry.cost_us as f64;
5030                    selected_cost += entry.cost_us as f64;
5031                    selected_value += entry.value as f64;
5032                    if entry.starved {
5033                        self.starved_selected = self.starved_selected.saturating_add(1);
5034                        forced_starved += 1;
5035                    }
5036                    nonessential_selected += 1;
5037                    self.selected.push(entry);
5038                } else if entry.starved
5039                    && forced_starved < config.max_starved_per_frame
5040                    && nonessential_selected == 0
5041                {
5042                    // Starvation guard: ensure at least one starved widget can refresh.
5043                    selected_cost += entry.cost_us as f64;
5044                    selected_value += entry.value as f64;
5045                    self.starved_selected = self.starved_selected.saturating_add(1);
5046                    forced_starved += 1;
5047                    nonessential_selected += 1;
5048                    self.selected.push(entry);
5049                } else {
5050                    self.skipped_count += 1;
5051                    if entry.starved {
5052                        self.skipped_starved = self.skipped_starved.saturating_add(1);
5053                    }
5054                    if enforce_drop_rate {
5055                        skipped_candidates.push(entry);
5056                    }
5057                }
5058            }
5059
5060            if enforce_drop_rate && nonessential_selected < min_nonessential_selected {
5061                for entry in skipped_candidates.into_iter() {
5062                    if nonessential_selected >= min_nonessential_selected {
5063                        break;
5064                    }
5065                    if entry.starved && forced_starved >= config.max_starved_per_frame {
5066                        continue;
5067                    }
5068                    selected_cost += entry.cost_us as f64;
5069                    selected_value += entry.value as f64;
5070                    if entry.starved {
5071                        self.starved_selected = self.starved_selected.saturating_add(1);
5072                        forced_starved += 1;
5073                        self.skipped_starved = self.skipped_starved.saturating_sub(1);
5074                    }
5075                    self.skipped_count = self.skipped_count.saturating_sub(1);
5076                    nonessential_selected += 1;
5077                    self.selected.push(entry);
5078                }
5079            }
5080        }
5081
5082        self.essentials_cost_us = essentials_cost;
5083        self.selected_cost_us = selected_cost;
5084        self.selected_value = selected_value;
5085        self.over_budget = selected_cost > budget_us;
5086    }
5087
5088    #[must_use]
5089    fn to_jsonl(&self) -> String {
5090        let mut out = String::with_capacity(256 + self.selected.len() * 96);
5091        out.push_str(r#"{"schema_version":"ftui-evidence-v1","event":"widget_refresh""#);
5092        out.push_str(&format!(
5093            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":{}"#,
5094            self.frame_idx,
5095            self.budget_us,
5096            self.degradation.as_str(),
5097            self.essentials_cost_us,
5098            self.selected_cost_us,
5099            self.selected_value,
5100            self.selected.len(),
5101            self.skipped_count,
5102            self.starved_selected,
5103            self.skipped_starved,
5104            self.over_budget
5105        ));
5106        out.push_str(r#","selected":["#);
5107        for (i, entry) in self.selected.iter().enumerate() {
5108            if i > 0 {
5109                out.push(',');
5110            }
5111            out.push_str(&entry.to_json());
5112        }
5113        out.push_str("]}");
5114        out
5115    }
5116}
5117
5118// =============================================================================
5119// CrosstermEventSource: BackendEventSource adapter for TerminalSession
5120// =============================================================================
5121
5122#[cfg(feature = "crossterm-compat")]
5123/// Adapter that wraps [`TerminalSession`] to implement [`BackendEventSource`].
5124///
5125/// This provides the bridge between the legacy crossterm-based terminal session
5126/// and the new backend abstraction. Once the native `ftui-tty` backend fully
5127/// replaces crossterm, this adapter will be removed.
5128pub struct CrosstermEventSource {
5129    session: TerminalSession,
5130    features: BackendFeatures,
5131}
5132
5133#[cfg(feature = "crossterm-compat")]
5134impl CrosstermEventSource {
5135    /// Create a new crossterm event source from a terminal session.
5136    pub fn new(session: TerminalSession, initial_features: BackendFeatures) -> Self {
5137        Self {
5138            session,
5139            features: initial_features,
5140        }
5141    }
5142}
5143
5144#[cfg(feature = "crossterm-compat")]
5145impl BackendEventSource for CrosstermEventSource {
5146    type Error = io::Error;
5147
5148    fn size(&self) -> Result<(u16, u16), io::Error> {
5149        self.session.size()
5150    }
5151
5152    fn set_features(&mut self, features: BackendFeatures) -> Result<(), io::Error> {
5153        if features.mouse_capture != self.features.mouse_capture {
5154            self.session.set_mouse_capture(features.mouse_capture)?;
5155        }
5156        // bracketed_paste, focus_events, and kitty_keyboard are set at session
5157        // construction and cleaned up in TerminalSession::Drop. Runtime toggling
5158        // is not supported by the crossterm backend.
5159        self.features = features;
5160        Ok(())
5161    }
5162
5163    fn poll_event(&mut self, timeout: Duration) -> Result<bool, io::Error> {
5164        self.session.poll_event(timeout)
5165    }
5166
5167    fn read_event(&mut self) -> Result<Option<Event>, io::Error> {
5168        self.session.read_event()
5169    }
5170
5171    fn supports_suspend(&self) -> bool {
5172        self.session.is_live()
5173    }
5174
5175    fn suspend(&mut self) -> Result<bool, io::Error> {
5176        self.session.suspend()
5177    }
5178
5179    fn resume(&mut self) -> Result<(), io::Error> {
5180        self.session.resume()
5181    }
5182}
5183
5184// =============================================================================
5185// HeadlessEventSource: no-op event source for headless/test programs
5186// =============================================================================
5187
5188/// A no-op event source for headless and test programs.
5189///
5190/// Returns a fixed terminal size, accepts feature changes silently, and never
5191/// produces events. This allows the test helper to construct a `Program`
5192/// without depending on crossterm or a real terminal.
5193pub struct HeadlessEventSource {
5194    width: u16,
5195    height: u16,
5196    features: BackendFeatures,
5197}
5198
5199impl HeadlessEventSource {
5200    /// Create a headless event source with the given terminal size.
5201    pub fn new(width: u16, height: u16, features: BackendFeatures) -> Self {
5202        Self {
5203            width,
5204            height,
5205            features,
5206        }
5207    }
5208}
5209
5210impl BackendEventSource for HeadlessEventSource {
5211    type Error = io::Error;
5212
5213    fn size(&self) -> Result<(u16, u16), io::Error> {
5214        Ok((self.width, self.height))
5215    }
5216
5217    fn set_features(&mut self, features: BackendFeatures) -> Result<(), io::Error> {
5218        self.features = features;
5219        Ok(())
5220    }
5221
5222    fn poll_event(&mut self, _timeout: Duration) -> Result<bool, io::Error> {
5223        Ok(false)
5224    }
5225
5226    fn read_event(&mut self) -> Result<Option<Event>, io::Error> {
5227        Ok(None)
5228    }
5229}
5230
5231// =============================================================================
5232// Program
5233// =============================================================================
5234
5235/// The program runtime that manages the update/view loop.
5236pub struct Program<
5237    M: Model,
5238    E: BackendEventSource<Error = io::Error>,
5239    P: BackendPresenter<Error = io::Error> = TerminalPresenter<Stdout>,
5240> {
5241    /// The application model.
5242    model: M,
5243    /// Terminal output presenter.
5244    presenter: P,
5245    /// Event source (terminal input, size queries, feature toggles).
5246    events: E,
5247    /// Currently active backend feature toggles.
5248    backend_features: BackendFeatures,
5249    /// Whether the program is running.
5250    running: bool,
5251    /// Whether the model shutdown hook and runtime teardown have completed.
5252    shutdown_complete: bool,
5253    /// Current tick rate (if any).
5254    tick_rate: Option<Duration>,
5255    /// Total commands actually executed by the runtime.
5256    executed_cmd_count: usize,
5257    /// Last tick time.
5258    last_tick: Instant,
5259    /// Whether the UI needs to be redrawn.
5260    dirty: bool,
5261    /// Monotonic frame index for evidence logging.
5262    frame_idx: u64,
5263    /// Monotonic tick index for tick-strategy scheduling.
5264    tick_count: u64,
5265    /// Widget scheduling signals captured during the last render.
5266    widget_signals: Vec<WidgetSignal>,
5267    /// Widget refresh selection configuration.
5268    widget_refresh_config: WidgetRefreshConfig,
5269    /// Last computed widget refresh plan.
5270    widget_refresh_plan: WidgetRefreshPlan,
5271    /// Current terminal width.
5272    width: u16,
5273    /// Current terminal height.
5274    height: u16,
5275    /// Forced terminal size override (when set, resize events are ignored).
5276    forced_size: Option<(u16, u16)>,
5277    /// Poll timeout when no tick is scheduled.
5278    poll_timeout: Duration,
5279    /// Whether the runtime should observe process-level termination signals.
5280    intercept_signals: bool,
5281    /// Termination signal recorded for this program instance (0 = none).
5282    ///
5283    /// Interactive constructors additionally consult the process-global slot
5284    /// that the OS signal handler thread writes to (`global_signal_slot`);
5285    /// headless and simulator programs only ever see signals injected through
5286    /// [`Program::inject_termination_signal`], so parallel tests can never
5287    /// clear or observe each other's pending signal.
5288    pending_signal: Arc<std::sync::atomic::AtomicI32>,
5289    /// Whether `observed_termination_signal` also reads the process-global
5290    /// slot written by the installed OS signal handler.
5291    global_signal_slot: bool,
5292    /// Job-control stop requested for this instance (0 = none): a Ctrl-Z key
5293    /// with `ctrl_z_suspends`, or [`Program::inject_suspend_signal`]. OS stop
5294    /// signals arrive through `job_control_claim` instead.
5295    pending_suspend: Arc<std::sync::atomic::AtomicI32>,
5296    /// Whether a stop request suspends at all: job control is configured on
5297    /// and the event source can release its terminal session.
5298    suspend_enabled: bool,
5299    /// Whether a Ctrl-Z key press requests a suspend instead of reaching the model.
5300    ctrl_z_suspends: bool,
5301    /// This program's hold on the OS stop signals; interactive programs only.
5302    job_control_claim: Option<ftui_core::job_control::JobControlClaim>,
5303    /// Stops the process after the terminal is handed back. Tests replace it:
5304    /// a test process that really stopped would hang the suite.
5305    stop_process: fn(i32) -> io::Result<()>,
5306    /// Immediate drain policy for bursty input handling.
5307    immediate_drain_config: ImmediateDrainConfig,
5308    /// Runtime counters for immediate-drain behavior.
5309    immediate_drain_stats: ImmediateDrainStats,
5310    /// Frame budget configuration.
5311    budget: RenderBudget,
5312    /// Runtime load-governor state for mode and fallback evidence.
5313    load_governor: LoadGovernorState,
5314    /// Conformal predictor for frame-time risk gating.
5315    conformal_predictor: Option<ConformalPredictor>,
5316    /// Last observed frame time (microseconds), used as a baseline predictor.
5317    last_frame_time_us: Option<f64>,
5318    /// Last observed update duration (microseconds).
5319    last_update_us: Option<u64>,
5320    /// Optional frame timing sink for profiling.
5321    frame_timing: Option<FrameTimingConfig>,
5322    /// Locale context used for rendering.
5323    locale_context: LocaleContext,
5324    /// Last observed locale version.
5325    locale_version: u64,
5326    /// Resize coalescer for rapid resize events.
5327    resize_coalescer: ResizeCoalescer,
5328    /// Shared evidence sink for decision logs (optional).
5329    evidence_sink: Option<EvidenceSink>,
5330    /// Whether fairness config has been logged to evidence sink.
5331    fairness_config_logged: bool,
5332    /// Resize handling behavior.
5333    resize_behavior: ResizeBehavior,
5334    /// Input fairness guard for scheduler integration.
5335    fairness_guard: InputFairnessGuard,
5336    /// Optional event recorder for macro capture.
5337    event_recorder: Option<EventRecorder>,
5338    /// Subscription lifecycle manager.
5339    subscriptions: SubscriptionManager<M::Message>,
5340    /// Channel for receiving messages from background tasks.
5341    #[cfg(test)]
5342    task_sender: std::sync::mpsc::Sender<M::Message>,
5343    /// Channel for receiving messages from background tasks.
5344    task_receiver: std::sync::mpsc::Receiver<M::Message>,
5345    /// Internal task execution substrate behind `Cmd::Task`.
5346    task_executor: TaskExecutor<M::Message>,
5347    /// Optional state registry for widget persistence.
5348    state_registry: Option<std::sync::Arc<StateRegistry>>,
5349    /// Persistence configuration.
5350    persistence_config: PersistenceConfig,
5351    /// Last checkpoint save time.
5352    last_checkpoint: Instant,
5353    /// Inline auto UI height remeasurement state.
5354    inline_auto_remeasure: Option<InlineAutoRemeasureState>,
5355    /// Gesture recognizer fed by `handle_event` when
5356    /// `ProgramConfig::gestures` is set.
5357    gesture_recognizer: Option<ftui_core::gesture::GestureRecognizer>,
5358    /// Event coalescer for mouse moves and scrolls when
5359    /// `ProgramConfig::event_coalescing` is enabled.
5360    event_coalescer: Option<ftui_core::event_coalescer::EventCoalescer>,
5361    /// Screen-reader policy when `ProgramConfig::accessibility` is set.
5362    a11y_policy: Option<ScreenReaderPolicy>,
5363    /// Explicit content capture policy for accessibility evidence only.
5364    a11y_evidence_text: bool,
5365    /// Accessibility tree built from the last rendered frame.
5366    a11y_tree: Option<A11yTree>,
5367    /// Reading order (node IDs, push order) of the last accessibility tree.
5368    a11y_order: Vec<u64>,
5369    /// Screen-reader announcements derived from the last frame's tree diff.
5370    a11y_announcements: Vec<ScreenReaderAnnouncement>,
5371    /// Tree and reading order collected during `render_buffer`, consumed by
5372    /// `process_a11y_frame` once the frame has been rendered.
5373    a11y_pending: Option<(A11yTree, Vec<u64>)>,
5374    /// Set by `process_a11y_frame` when the tree differed from the previous
5375    /// frame; `render_frame` then delivers [`Model::on_accessibility`].
5376    a11y_changed: bool,
5377    /// Announcements dropped by the policy cap in the last frame.
5378    a11y_dropped: usize,
5379    /// Input events recovered from bytes the startup capability probes read
5380    /// off the tty while waiting for terminal replies; delivered before the
5381    /// main loop so a key or click during startup is not lost.
5382    startup_events: Vec<Event>,
5383    /// Preserve sequence state across successive recovered byte chunks.
5384    startup_parser: ftui_core::input_parser::InputParser,
5385    /// Per-frame bump arena for temporary render-path allocations.
5386    frame_arena: FrameArena,
5387    /// Unified frame guardrails (memory/queue limits).
5388    guardrails: FrameGuardrails,
5389    /// Frame index of the last soft-tier capacity trim (`None` = never
5390    /// trimmed).
5391    ///
5392    /// Soft memory alerts fire on retained CAPACITY that only a rebuild can
5393    /// shed; trimming every alerting frame would thrash allocations when
5394    /// usage hovers near the limit, so trims are cooldown-gated
5395    /// (bd-1za0z: actuator must be able to move the sensor).
5396    last_soft_trim_frame: Option<u64>,
5397    /// Optional tick strategy for selective background screen ticking.
5398    tick_strategy: Option<Box<dyn crate::tick_strategy::TickStrategy>>,
5399    /// Last active screen observed by the tick strategy dispatch path.
5400    last_active_screen_for_strategy: Option<String>,
5401}
5402
5403#[cfg(feature = "crossterm-compat")]
5404impl<M: Model> Program<M, CrosstermEventSource, TerminalPresenter<Stdout>> {
5405    /// Create a new program with default configuration.
5406    pub fn new(model: M) -> io::Result<Self>
5407    where
5408        M::Message: Send + 'static,
5409    {
5410        Self::with_config(model, ProgramConfig::default())
5411    }
5412
5413    /// Create a new program with the specified configuration.
5414    pub fn with_config(model: M, config: ProgramConfig) -> io::Result<Self>
5415    where
5416        M::Message: Send + 'static,
5417    {
5418        let resolved_lane = config.runtime_lane.resolve();
5419        let effect_queue_config = config.resolved_effect_queue_config(resolved_lane);
5420        let mut capabilities = TerminalCapabilities::with_overrides();
5421        let mouse_capture = config.resolved_mouse_capture();
5422        let requested_features = BackendFeatures {
5423            mouse_capture,
5424            bracketed_paste: config.bracketed_paste,
5425            focus_events: config.focus_reporting,
5426            kitty_keyboard: config.kitty_keyboard,
5427        };
5428        let initial_features =
5429            sanitize_backend_features_for_capabilities(requested_features, &capabilities);
5430        let session = TerminalSession::new(SessionOptions {
5431            alternate_screen: matches!(config.screen_mode, ScreenMode::AltScreen),
5432            mouse_capture: initial_features.mouse_capture,
5433            bracketed_paste: initial_features.bracketed_paste,
5434            focus_events: initial_features.focus_events,
5435            kitty_keyboard: initial_features.kitty_keyboard,
5436            intercept_signals: config.intercept_signals,
5437        })?;
5438        let events = CrosstermEventSource::new(session, initial_features);
5439
5440        // Raw mode is active now, so the terminal can answer probes; the
5441        // writer built below must see the refined capabilities.
5442        let capability_decisions = probe_live_terminal(&mut capabilities);
5443        let scroll_region =
5444            verify_scroll_region(&capabilities, config.screen_mode, events.size().ok());
5445
5446        let mut writer = TerminalWriter::with_diff_config(
5447            io::stdout(),
5448            config.screen_mode,
5449            config.ui_anchor,
5450            capabilities,
5451            config.diff_config.clone(),
5452        )
5453        .with_capability_decisions(capability_decisions);
5454        if let Some(limit) = config.hyperlink_limit {
5455            writer.set_hyperlink_limit(limit);
5456        }
5457        writer.set_scroll_region_verified(
5458            scroll_region.verdict,
5459            scroll_region.rows,
5460            scroll_region.region_bottom,
5461        );
5462
5463        let frame_timing = config.frame_timing.clone();
5464        writer.set_timing_enabled(frame_timing.is_some());
5465
5466        let evidence_sink = EvidenceSink::from_config(&config.evidence_sink)?;
5467        if let Some(ref sink) = evidence_sink {
5468            writer = writer.with_evidence_sink(sink.clone());
5469        }
5470
5471        let render_trace = crate::RenderTraceRecorder::from_config(
5472            &config.render_trace,
5473            crate::RenderTraceContext {
5474                capabilities: writer.capabilities(),
5475                diff_config: config.diff_config.clone(),
5476                resize_config: config.resize_coalescer.clone(),
5477                conformal_config: config.conformal_config.clone(),
5478            },
5479        )?;
5480        if let Some(recorder) = render_trace {
5481            writer = writer.with_render_trace(recorder);
5482        }
5483
5484        // Get terminal size for initial frame (or forced size override).
5485        let (w, h) = config
5486            .forced_size
5487            .unwrap_or_else(|| events.size().unwrap_or((80, 24)));
5488        let width = w.max(1);
5489        let height = h.max(1);
5490        writer.set_size(width, height);
5491
5492        let budget = render_budget_from_program_config(&config);
5493        let load_governor = LoadGovernorState::new(
5494            config.load_governor.clone(),
5495            effect_queue_config.max_queue_depth,
5496        );
5497        let conformal_predictor = config
5498            .conformal_config
5499            .clone()
5500            .map(ConformalPredictor::new)
5501            .transpose()
5502            .map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error))?;
5503        let locale_context = config.locale_context.clone();
5504        let locale_version = locale_context.version();
5505        let mut resize_coalescer =
5506            ResizeCoalescer::new(config.resize_coalescer.clone(), (width, height))
5507                .with_screen_mode(config.screen_mode);
5508        if let Some(ref sink) = evidence_sink {
5509            resize_coalescer = resize_coalescer.with_evidence_sink(sink.clone());
5510        }
5511        let subscriptions = SubscriptionManager::new();
5512        let (task_sender, task_receiver) = std::sync::mpsc::channel();
5513        let inline_auto_remeasure = config
5514            .inline_auto_remeasure
5515            .clone()
5516            .map(InlineAutoRemeasureState::new);
5517        let gesture_recognizer = config
5518            .gestures
5519            .clone()
5520            .map(ftui_core::gesture::GestureRecognizer::new);
5521        let event_coalescer = if config.event_coalescing {
5522            Some(ftui_core::event_coalescer::EventCoalescer::new())
5523        } else {
5524            None
5525        };
5526        let task_executor = TaskExecutor::new(
5527            &effect_queue_config,
5528            task_sender.clone(),
5529            evidence_sink.clone(),
5530        )?;
5531        let guardrails = FrameGuardrails::new(config.guardrails);
5532
5533        // Log runtime lane and rollout policy at startup (bd-2crbt)
5534        tracing::info!(
5535            target: crate::telemetry_schema::TARGET_RUNTIME,
5536            requested_lane = config.runtime_lane.label(),
5537            resolved_lane = resolved_lane.label(),
5538            task_backend = task_executor.kind_name_for_logs(),
5539            rollout_policy = config.rollout_policy.label(),
5540            "runtime startup: lane={}, rollout={}",
5541            resolved_lane.label(),
5542            config.rollout_policy.label(),
5543        );
5544
5545        let suspend_enabled = config.job_control && events.supports_suspend();
5546        let job_control_claim = (suspend_enabled && config.intercept_signals)
5547            .then(ftui_core::job_control::JobControlClaim::acquire)
5548            .flatten();
5549
5550        Ok(Self {
5551            model,
5552            presenter: TerminalPresenter::new(writer),
5553            events,
5554            backend_features: initial_features,
5555            running: true,
5556            shutdown_complete: false,
5557            tick_rate: None,
5558            executed_cmd_count: 0,
5559            last_tick: Instant::now(),
5560            dirty: true,
5561            frame_idx: 0,
5562            tick_count: 0,
5563            widget_signals: Vec::new(),
5564            a11y_policy: config.accessibility,
5565            a11y_evidence_text: config.accessibility_evidence_text,
5566            a11y_tree: None,
5567            a11y_order: Vec::new(),
5568            a11y_announcements: Vec::new(),
5569            a11y_pending: None,
5570            a11y_changed: false,
5571            a11y_dropped: 0,
5572            startup_events: Vec::new(),
5573            startup_parser: ftui_core::input_parser::InputParser::new(),
5574            widget_refresh_config: config.widget_refresh,
5575            widget_refresh_plan: WidgetRefreshPlan::new(),
5576            width,
5577            height,
5578            forced_size: config.forced_size,
5579            poll_timeout: config.poll_timeout,
5580            intercept_signals: config.intercept_signals,
5581            pending_signal: Arc::new(std::sync::atomic::AtomicI32::new(0)),
5582            global_signal_slot: true,
5583            pending_suspend: Arc::new(std::sync::atomic::AtomicI32::new(0)),
5584            suspend_enabled,
5585            ctrl_z_suspends: config.ctrl_z_suspends,
5586            job_control_claim,
5587            stop_process: ftui_core::job_control::stop_process,
5588            immediate_drain_config: config.immediate_drain,
5589            immediate_drain_stats: ImmediateDrainStats::default(),
5590            budget,
5591            load_governor,
5592            conformal_predictor,
5593            last_frame_time_us: None,
5594            last_update_us: None,
5595            frame_timing,
5596            locale_context,
5597            locale_version,
5598            resize_coalescer,
5599            evidence_sink,
5600            fairness_config_logged: false,
5601            resize_behavior: config.resize_behavior,
5602            fairness_guard: InputFairnessGuard::new(),
5603            event_recorder: None,
5604            subscriptions,
5605            #[cfg(test)]
5606            task_sender,
5607            task_receiver,
5608            task_executor,
5609            state_registry: config.persistence.registry.clone(),
5610            persistence_config: config.persistence,
5611            last_checkpoint: Instant::now(),
5612            inline_auto_remeasure,
5613            gesture_recognizer,
5614            event_coalescer,
5615            frame_arena: FrameArena::default(),
5616            guardrails,
5617            last_soft_trim_frame: None,
5618            tick_strategy: config
5619                .tick_strategy
5620                .map(|strategy| Box::new(strategy) as Box<dyn crate::tick_strategy::TickStrategy>),
5621            last_active_screen_for_strategy: None,
5622        })
5623    }
5624}
5625
5626impl<M: Model, E: BackendEventSource<Error = io::Error>, P: BackendPresenter<Error = io::Error>>
5627    Program<M, E, P>
5628{
5629    /// Create a program with an externally-constructed event source and presenter.
5630    ///
5631    /// This is the generic entry point for alternative backends (native tty,
5632    /// WASM, headless testing). The caller is responsible for terminal
5633    /// lifecycle (raw mode, cleanup) โ€” the event source should handle that
5634    /// via its `Drop` impl or an external RAII guard.
5635    pub fn with_event_source(
5636        model: M,
5637        events: E,
5638        backend_features: BackendFeatures,
5639        presenter: P,
5640        config: ProgramConfig,
5641    ) -> io::Result<Self>
5642    where
5643        M::Message: Send + 'static,
5644    {
5645        let resolved_lane = config.runtime_lane.resolve();
5646        let effect_queue_config = config.resolved_effect_queue_config(resolved_lane);
5647        let (width, height) = config
5648            .forced_size
5649            .unwrap_or_else(|| events.size().unwrap_or((80, 24)));
5650        let width = width.max(1);
5651        let height = height.max(1);
5652
5653        let mut presenter = presenter;
5654        if let Some(limit) = config.hyperlink_limit {
5655            presenter.set_hyperlink_limit(limit);
5656        }
5657        presenter.resize(width, height);
5658
5659        let evidence_sink = EvidenceSink::from_config(&config.evidence_sink)?;
5660        if let Some(ref sink) = evidence_sink {
5661            let sink_clone = sink.clone();
5662            presenter.set_evidence_writer(Some(Arc::new(move |line| {
5663                let _ = sink_clone.write_jsonl(line);
5664            })));
5665        }
5666
5667        let frame_timing = config.frame_timing.clone();
5668        presenter.set_timing_enabled(frame_timing.is_some());
5669
5670        let budget = render_budget_from_program_config(&config);
5671        let load_governor = LoadGovernorState::new(
5672            config.load_governor.clone(),
5673            effect_queue_config.max_queue_depth,
5674        );
5675        let conformal_predictor = config
5676            .conformal_config
5677            .clone()
5678            .map(ConformalPredictor::new)
5679            .transpose()
5680            .map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error))?;
5681        let locale_context = config.locale_context.clone();
5682        let locale_version = locale_context.version();
5683        let mut resize_coalescer =
5684            ResizeCoalescer::new(config.resize_coalescer.clone(), (width, height))
5685                .with_screen_mode(config.screen_mode);
5686        if let Some(ref sink) = evidence_sink {
5687            resize_coalescer = resize_coalescer.with_evidence_sink(sink.clone());
5688        }
5689        let subscriptions = SubscriptionManager::new();
5690        let (task_sender, task_receiver) = std::sync::mpsc::channel();
5691        let inline_auto_remeasure = config
5692            .inline_auto_remeasure
5693            .clone()
5694            .map(InlineAutoRemeasureState::new);
5695        let gesture_recognizer = config
5696            .gestures
5697            .clone()
5698            .map(ftui_core::gesture::GestureRecognizer::new);
5699        let event_coalescer = if config.event_coalescing {
5700            Some(ftui_core::event_coalescer::EventCoalescer::new())
5701        } else {
5702            None
5703        };
5704        let task_executor = TaskExecutor::new(
5705            &effect_queue_config,
5706            task_sender.clone(),
5707            evidence_sink.clone(),
5708        )?;
5709
5710        let guardrails = FrameGuardrails::new(config.guardrails);
5711
5712        tracing::info!(
5713            target: crate::telemetry_schema::TARGET_RUNTIME,
5714            requested_lane = config.runtime_lane.label(),
5715            resolved_lane = resolved_lane.label(),
5716            task_backend = task_executor.kind_name_for_logs(),
5717            rollout_policy = config.rollout_policy.label(),
5718            "runtime startup: lane={}, rollout={}",
5719            resolved_lane.label(),
5720            config.rollout_policy.label(),
5721        );
5722
5723        let suspend_enabled = config.job_control && events.supports_suspend();
5724        let job_control_claim = (suspend_enabled && config.intercept_signals)
5725            .then(ftui_core::job_control::JobControlClaim::acquire)
5726            .flatten();
5727
5728        Ok(Self {
5729            model,
5730            presenter,
5731            events,
5732            backend_features,
5733            running: true,
5734            shutdown_complete: false,
5735            tick_rate: None,
5736            executed_cmd_count: 0,
5737            last_tick: Instant::now(),
5738            dirty: true,
5739            frame_idx: 0,
5740            tick_count: 0,
5741            widget_signals: Vec::new(),
5742            a11y_policy: config.accessibility,
5743            a11y_evidence_text: config.accessibility_evidence_text,
5744            a11y_tree: None,
5745            a11y_order: Vec::new(),
5746            a11y_announcements: Vec::new(),
5747            a11y_pending: None,
5748            a11y_changed: false,
5749            a11y_dropped: 0,
5750            startup_events: Vec::new(),
5751            startup_parser: ftui_core::input_parser::InputParser::new(),
5752            widget_refresh_config: config.widget_refresh,
5753            widget_refresh_plan: WidgetRefreshPlan::new(),
5754            width,
5755            height,
5756            forced_size: config.forced_size,
5757            poll_timeout: config.poll_timeout,
5758            intercept_signals: config.intercept_signals,
5759            pending_signal: Arc::new(std::sync::atomic::AtomicI32::new(0)),
5760            global_signal_slot: true,
5761            pending_suspend: Arc::new(std::sync::atomic::AtomicI32::new(0)),
5762            suspend_enabled,
5763            ctrl_z_suspends: config.ctrl_z_suspends,
5764            job_control_claim,
5765            stop_process: ftui_core::job_control::stop_process,
5766            immediate_drain_config: config.immediate_drain,
5767            immediate_drain_stats: ImmediateDrainStats::default(),
5768            budget,
5769            load_governor,
5770            conformal_predictor,
5771            last_frame_time_us: None,
5772            last_update_us: None,
5773            frame_timing,
5774            locale_context,
5775            locale_version,
5776            resize_coalescer,
5777            evidence_sink,
5778            fairness_config_logged: false,
5779            resize_behavior: config.resize_behavior,
5780            fairness_guard: InputFairnessGuard::new(),
5781            event_recorder: None,
5782            subscriptions,
5783            #[cfg(test)]
5784            task_sender,
5785            task_receiver,
5786            task_executor,
5787            state_registry: config.persistence.registry.clone(),
5788            persistence_config: config.persistence,
5789            last_checkpoint: Instant::now(),
5790            inline_auto_remeasure,
5791            gesture_recognizer,
5792            event_coalescer,
5793            frame_arena: FrameArena::default(),
5794            guardrails,
5795            last_soft_trim_frame: None,
5796            tick_strategy: config
5797                .tick_strategy
5798                .map(|strategy| Box::new(strategy) as Box<dyn crate::tick_strategy::TickStrategy>),
5799            last_active_screen_for_strategy: None,
5800        })
5801    }
5802}
5803
5804// =============================================================================
5805// Native TTY backend constructor (feature-gated)
5806// =============================================================================
5807
5808#[cfg(any(feature = "crossterm-compat", feature = "native-backend"))]
5809#[inline]
5810const fn sanitize_backend_features_for_capabilities(
5811    requested: BackendFeatures,
5812    capabilities: &ftui_core::terminal_capabilities::TerminalCapabilities,
5813) -> BackendFeatures {
5814    let focus_events_supported = capabilities.focus_events && !capabilities.in_any_mux();
5815    let kitty_keyboard_supported = capabilities.kitty_keyboard && !capabilities.in_any_mux();
5816
5817    BackendFeatures {
5818        mouse_capture: requested.mouse_capture && capabilities.mouse_sgr,
5819        bracketed_paste: requested.bracketed_paste && capabilities.bracketed_paste,
5820        focus_events: requested.focus_events && focus_events_supported,
5821        kitty_keyboard: requested.kitty_keyboard && kitty_keyboard_supported,
5822    }
5823}
5824
5825#[cfg(all(feature = "native-backend", unix))]
5826impl<M: Model> Program<M, ftui_tty::TtyBackend, TerminalPresenter<Stdout>> {
5827    /// Open the default backend for this build (the native TTY backend).
5828    ///
5829    /// See [`DEFAULT_BACKEND`] and [`DefaultProgram`]; on builds without
5830    /// `native-backend` (or on non-Unix targets) this resolves to the Crossterm
5831    /// backend instead, and it does not exist when no backend was compiled.
5832    pub fn open(model: M, config: ProgramConfig) -> io::Result<Self>
5833    where
5834        M::Message: Send + 'static,
5835    {
5836        Self::with_native_backend(model, config)
5837    }
5838
5839    /// Create a program backed by the native TTY backend (no Crossterm).
5840    ///
5841    /// This opens a live terminal session via `ftui-tty`, entering raw mode
5842    /// and enabling the requested features. When the program exits (or panics),
5843    /// `TtyBackend::drop()` restores the terminal to its original state.
5844    ///
5845    /// **Unix-only.** `ftui-tty` does not yet have a Windows-native backend.
5846    /// On non-Unix targets call [`Program::with_config`] (with `crossterm-compat`)
5847    /// instead โ€” calling `with_native_backend` from Windows used to silently
5848    /// fall through to the headless 0ร—0 test backend and produce a single
5849    /// init-frame-then-silence pattern that looks like a hung TUI.
5850    #[cfg(unix)]
5851    pub fn with_native_backend(model: M, config: ProgramConfig) -> io::Result<Self>
5852    where
5853        M::Message: Send + 'static,
5854    {
5855        let mut capabilities =
5856            ftui_core::terminal_capabilities::TerminalCapabilities::with_overrides();
5857        let mouse_capture = config.resolved_mouse_capture();
5858        let requested_features = BackendFeatures {
5859            mouse_capture,
5860            bracketed_paste: config.bracketed_paste,
5861            focus_events: config.focus_reporting,
5862            kitty_keyboard: config.kitty_keyboard,
5863        };
5864        let features =
5865            sanitize_backend_features_for_capabilities(requested_features, &capabilities);
5866        let options = ftui_tty::TtySessionOptions {
5867            alternate_screen: matches!(config.screen_mode, ScreenMode::AltScreen),
5868            features,
5869            intercept_signals: config.intercept_signals,
5870        };
5871        let backend = ftui_tty::TtyBackend::open(0, 0, options)?;
5872
5873        // The native session is live (raw mode), so the terminal can be asked
5874        // directly what it supports; see `probe_live_terminal`.
5875        let capability_decisions = probe_live_terminal(&mut capabilities);
5876        let scroll_region =
5877            verify_scroll_region(&capabilities, config.screen_mode, backend.size().ok());
5878
5879        let mut writer = TerminalWriter::with_diff_config(
5880            io::stdout(),
5881            config.screen_mode,
5882            config.ui_anchor,
5883            capabilities,
5884            config.diff_config.clone(),
5885        )
5886        .with_capability_decisions(capability_decisions);
5887        writer.set_scroll_region_verified(
5888            scroll_region.verdict,
5889            scroll_region.rows,
5890            scroll_region.region_bottom,
5891        );
5892        let evidence_sink = EvidenceSink::from_config(&config.evidence_sink)?;
5893        if let Some(ref sink) = evidence_sink {
5894            writer = writer.with_evidence_sink(sink.clone());
5895        }
5896
5897        let render_trace = crate::RenderTraceRecorder::from_config(
5898            &config.render_trace,
5899            crate::RenderTraceContext {
5900                capabilities: writer.capabilities(),
5901                diff_config: config.diff_config.clone(),
5902                resize_config: config.resize_coalescer.clone(),
5903                conformal_config: config.conformal_config.clone(),
5904            },
5905        )?;
5906        if let Some(recorder) = render_trace {
5907            writer = writer.with_render_trace(recorder);
5908        }
5909
5910        Self::with_event_source(
5911            model,
5912            backend,
5913            features,
5914            TerminalPresenter::new(writer),
5915            config,
5916        )
5917    }
5918}
5919
5920impl<M: Model, E: BackendEventSource<Error = io::Error>, P: BackendPresenter<Error = io::Error>>
5921    Program<M, E, P>
5922{
5923    /// Run the main event loop.
5924    ///
5925    /// This is the main entry point. It handles:
5926    /// 1. Initialization (terminal setup, raw mode)
5927    /// 2. Event polling and message dispatch
5928    /// 3. Frame rendering
5929    /// 4. Shutdown (terminal cleanup)
5930    pub fn run(&mut self) -> io::Result<()> {
5931        if self.shutdown_complete {
5932            return Err(io::Error::new(
5933                io::ErrorKind::InvalidInput,
5934                "program lifecycle has already completed",
5935            ));
5936        }
5937
5938        let run_result = self.run_event_loop();
5939        self.complete_lifecycle(run_result)
5940    }
5941
5942    #[inline]
5943    fn observed_termination_signal(&self) -> Option<i32> {
5944        if !self.intercept_signals {
5945            return None;
5946        }
5947        match self
5948            .pending_signal
5949            .load(std::sync::atomic::Ordering::SeqCst)
5950        {
5951            0 => {}
5952            signal => return Some(signal),
5953        }
5954        if self.global_signal_slot {
5955            check_termination_signal()
5956        } else {
5957            None
5958        }
5959    }
5960
5961    /// Record a termination signal for this program instance, as if the OS
5962    /// signal handler had delivered it. The first pending signal wins until
5963    /// the run loop consumes it. Intended for harnesses and tests; interactive
5964    /// programs receive real signals through the installed handler.
5965    pub fn inject_termination_signal(&self, signal: i32) {
5966        let _ = self.pending_signal.compare_exchange(
5967            0,
5968            signal,
5969            std::sync::atomic::Ordering::SeqCst,
5970            std::sync::atomic::Ordering::SeqCst,
5971        );
5972    }
5973
5974    /// Request a job-control stop for this program instance, as if `signal`
5975    /// (SIGTSTP, SIGTTIN or SIGTTOU) had been delivered. The run loop hands the
5976    /// terminal back, stops the process and restores the terminal when it is
5977    /// continued. Ignored unless job control is enabled and the event source
5978    /// supports suspend.
5979    pub fn inject_suspend_signal(&self, signal: i32) {
5980        self.pending_suspend
5981            .store(signal, std::sync::atomic::Ordering::SeqCst);
5982    }
5983
5984    /// The pending stop request: this instance's own first (Ctrl-Z key,
5985    /// injection), then the OS signal recorded against this program's claim.
5986    fn take_suspend_request(&mut self) -> Option<i32> {
5987        if !self.suspend_enabled {
5988            return None;
5989        }
5990        match self
5991            .pending_suspend
5992            .swap(0, std::sync::atomic::Ordering::SeqCst)
5993        {
5994            0 => self
5995                .job_control_claim
5996                .as_ref()
5997                .and_then(ftui_core::job_control::JobControlClaim::take_pending),
5998            signal => Some(signal),
5999        }
6000    }
6001
6002    /// Serve a pending stop request (`docs/spec/suspend-resume.md` ยง5-6):
6003    /// release the presenter's and then the backend's terminal state, stop
6004    /// the process, and on continue re-arm the backend, re-read the size and
6005    /// force a full repaint. Coalesces: requests that arrive meanwhile are
6006    /// taken with this one's.
6007    fn service_suspend(&mut self) -> io::Result<()> {
6008        let Some(signal) = self.take_suspend_request() else {
6009            return Ok(());
6010        };
6011        // Termination outranks suspension (ยง2 invariant 3); the caller's next
6012        // termination check ends the loop.
6013        if self.observed_termination_signal().is_some() {
6014            return Ok(());
6015        }
6016        self.presenter.suspend()?;
6017        if !self.events.suspend()? {
6018            // Nothing was released, so stopping would strand a raw terminal.
6019            // The presenter did let go of its state, so repaint in full.
6020            self.presenter.resize(self.width, self.height);
6021            self.mark_dirty();
6022            return Ok(());
6023        }
6024        self.write_job_control_evidence("suspend", signal, None);
6025        let stopped = (self.stop_process)(signal);
6026
6027        // Continued, or the stop failed: take the terminal back either way.
6028        self.events.resume()?;
6029        let _ = self.take_suspend_request();
6030        let (width, height) = self
6031            .forced_size
6032            .unwrap_or_else(|| self.events.size().unwrap_or((self.width, self.height)));
6033        let (width, height) = (width.max(1), height.max(1));
6034        let size_changed = (width, height) != (self.width, self.height);
6035        if size_changed {
6036            // Resize first, so layout runs once, at the new size (ยง6j).
6037            self.resize_coalescer
6038                .record_external_apply(width, height, Instant::now());
6039            self.apply_resize(width, height, Duration::ZERO, false)?;
6040        } else {
6041            // Drops the diff baseline: the shell may have drawn anything.
6042            self.presenter.resize(width, height);
6043            self.mark_dirty();
6044        }
6045        self.write_job_control_evidence("resume", signal, Some(size_changed));
6046        if let Err(error) = stopped {
6047            tracing::warn!(signal, %error, "job-control stop failed; resumed without stopping");
6048        }
6049        Ok(())
6050    }
6051
6052    /// One `suspend` or `resume` evidence row (schema in
6053    /// `docs/spec/telemetry-events.md`).
6054    fn write_job_control_evidence(&self, event: &str, signal: i32, size_changed: Option<bool>) {
6055        let Some(ref sink) = self.evidence_sink else {
6056            return;
6057        };
6058        let size_changed = size_changed.map_or(String::new(), |changed| {
6059            format!(r#","size_changed":{changed}"#)
6060        });
6061        let _ = sink.write_jsonl(&format!(
6062            r#"{{"schema_version":"{}","event":"{}","signal":{},"screen_mode":"{}","cols":{},"rows":{}{}}}"#,
6063            crate::evidence_sink::EVIDENCE_SCHEMA_VERSION,
6064            event,
6065            signal,
6066            crate::resize_coalescer::screen_mode_str(self.presenter.screen_mode()),
6067            self.width,
6068            self.height,
6069            size_changed,
6070        ));
6071    }
6072
6073    /// The termination signal pending for this program instance, if any.
6074    #[must_use]
6075    pub fn pending_termination_signal(&self) -> Option<i32> {
6076        match self
6077            .pending_signal
6078            .load(std::sync::atomic::Ordering::SeqCst)
6079        {
6080            0 => None,
6081            signal => Some(signal),
6082        }
6083    }
6084
6085    /// Access widget scheduling signals captured on the last render.
6086    #[inline]
6087    pub fn last_widget_signals(&self) -> &[WidgetSignal] {
6088        &self.widget_signals
6089    }
6090
6091    /// Snapshot immediate-drain runtime counters.
6092    #[inline]
6093    pub fn immediate_drain_stats(&self) -> ImmediateDrainStats {
6094        self.immediate_drain_stats
6095    }
6096
6097    /// The inner event loop, separated for proper cleanup handling.
6098    /// Parse raw input bytes (as the tty would have delivered them) into
6099    /// events that the main loop delivers before it starts polling. Used for
6100    /// the bytes the startup capability probes read off the tty while
6101    /// waiting for terminal replies (`caps_probe::take_probe_leftover_input`).
6102    pub fn queue_startup_input(&mut self, bytes: &[u8]) {
6103        if bytes.is_empty() {
6104            return;
6105        }
6106        let events = self.startup_parser.parse(bytes);
6107        debug!(
6108            bytes = bytes.len(),
6109            events = events.len(),
6110            "queued startup input recovered from the capability probes"
6111        );
6112        self.startup_events.extend(events);
6113    }
6114
6115    /// Deliver the queued startup events in arrival order.
6116    fn drain_startup_events(&mut self) -> io::Result<()> {
6117        // The probe-read batch is complete. Resolve an ambiguous trailing key
6118        // before handing input ownership back to the live event source; dropping
6119        // the parser here used to silently lose a lone Escape.
6120        if let Some(event) = self.startup_parser.timeout() {
6121            self.startup_events.push(event);
6122        }
6123        let events = std::mem::take(&mut self.startup_events);
6124        for event in events {
6125            if !self.running {
6126                break;
6127            }
6128            self.handle_event(event)?;
6129        }
6130        Ok(())
6131    }
6132
6133    fn run_event_loop(&mut self) -> io::Result<Option<i32>> {
6134        // Auto-load state on start
6135        if self.persistence_config.auto_load {
6136            self.load_state();
6137        }
6138
6139        // Input the constructors' probes swallowed belongs to this program.
6140        let leftover = ftui_core::caps_probe::take_probe_leftover_input();
6141        self.queue_startup_input(&leftover);
6142
6143        // Initialize
6144        let cmd = {
6145            let _span = info_span!(crate::telemetry_schema::span::PROGRAM_INIT).entered();
6146            self.model.init()
6147        };
6148        self.execute_cmd(cmd)?;
6149
6150        let mut termination_signal = self.observed_termination_signal();
6151        if self.running && termination_signal.is_none() {
6152            // Reconcile initial subscriptions
6153            self.reconcile_subscriptions();
6154            self.process_subscription_failures(false)?;
6155
6156            // Initial render
6157            if self.running {
6158                self.render_frame()?;
6159            }
6160        }
6161
6162        // Deliver input that arrived during startup before polling for more.
6163        if self.running && termination_signal.is_none() {
6164            self.drain_startup_events()?;
6165        }
6166
6167        // Main loop
6168        let mut loop_count: u64 = 0;
6169        while self.running {
6170            termination_signal = termination_signal.or_else(|| self.observed_termination_signal());
6171            if termination_signal.is_some() {
6172                self.running = false;
6173                break;
6174            }
6175            // A stop signal lands here within one poll interval: signal-hook
6176            // handlers only set a flag, and poll(2) is not interrupted early.
6177            self.service_suspend()?;
6178
6179            loop_count += 1;
6180            // Log heartbeat every 100 iterations to avoid flooding stderr
6181            if loop_count.is_multiple_of(100) {
6182                crate::debug_trace!("main loop heartbeat: iteration {}", loop_count);
6183            }
6184
6185            // Poll for input with tick timeout
6186            let timeout = self.effective_timeout();
6187
6188            // Poll for events with timeout
6189            let poll_result = self.events.poll_event(timeout)?;
6190            termination_signal = termination_signal.or_else(|| self.observed_termination_signal());
6191            if termination_signal.is_some() {
6192                self.running = false;
6193                break;
6194            }
6195            if poll_result {
6196                self.drain_ready_events()?;
6197            }
6198            if !self.running {
6199                break;
6200            }
6201            termination_signal = termination_signal.or_else(|| self.observed_termination_signal());
6202            if termination_signal.is_some() {
6203                self.running = false;
6204                break;
6205            }
6206            // Before rendering: a Ctrl-Z from the batch just drained must not
6207            // draw a frame first.
6208            self.service_suspend()?;
6209
6210            // Process subscription messages
6211            self.process_subscription_messages()?;
6212            self.process_subscription_failures(false)?;
6213            if !self.running {
6214                break;
6215            }
6216
6217            // Process background task results
6218            self.process_task_results()?;
6219            self.reap_finished_tasks();
6220            if !self.running {
6221                break;
6222            }
6223
6224            self.process_resize_coalescer()?;
6225            if !self.running {
6226                break;
6227            }
6228            termination_signal = termination_signal.or_else(|| self.observed_termination_signal());
6229            if termination_signal.is_some() {
6230                self.running = false;
6231                break;
6232            }
6233
6234            // Detect screen transitions from any update() calls above.
6235            // A.2: notifies the tick strategy so predictive strategies learn.
6236            // D.3: force-ticks the newly active screen for immediate refresh.
6237            self.check_screen_transition();
6238
6239            // Check for tick - deliver to model so periodic logic can run
6240            if self.should_tick() {
6241                self.tick_count = self.tick_count.wrapping_add(1);
6242                let tick_count = self.tick_count;
6243
6244                let mut used_screen_dispatch = false;
6245
6246                // Per-screen tick dispatch: if the model supports multi-screen
6247                // dispatch and a tick strategy is configured, tick individual
6248                // screens selectively instead of calling monolithic
6249                // `update(Tick)`.
6250                if let Some(strategy) = self.tick_strategy.as_mut() {
6251                    // Snapshot screen topology first so the mutable borrow of the
6252                    // dispatch adapter does not overlap strategy decisions.
6253                    let dispatch_snapshot = self.model.as_screen_tick_dispatch().map(|dispatch| {
6254                        let active = dispatch.active_screen_id();
6255                        let all_screens = dispatch.screen_ids();
6256                        (active, all_screens)
6257                    });
6258
6259                    if let Some((active, all_screens)) = dispatch_snapshot {
6260                        used_screen_dispatch = true;
6261
6262                        // Feed active-screen transitions into the strategy so
6263                        // predictive strategies can learn from real navigation.
6264                        if let Some(previous_active) =
6265                            self.last_active_screen_for_strategy.as_deref()
6266                            && previous_active != active
6267                        {
6268                            strategy.on_screen_transition(previous_active, &active);
6269                        }
6270                        self.last_active_screen_for_strategy = Some(active.clone());
6271
6272                        let all_screens_count = all_screens.len();
6273                        let mut tick_targets = Vec::with_capacity(all_screens_count.max(1));
6274                        // Active screen is always ticked.
6275                        tick_targets.push(active.clone());
6276
6277                        // Tick inactive screens according to the strategy.
6278                        for screen_id in all_screens {
6279                            if screen_id != active
6280                                && strategy.should_tick(&screen_id, tick_count, &active)
6281                                    == crate::tick_strategy::TickDecision::Tick
6282                            {
6283                                tick_targets.push(screen_id);
6284                            }
6285                        }
6286
6287                        // Compute skipped screens for tracing.
6288                        let skipped_count = all_screens_count.saturating_sub(tick_targets.len());
6289
6290                        if let Some(dispatch) = self.model.as_screen_tick_dispatch() {
6291                            for screen_id in &tick_targets {
6292                                dispatch.tick_screen(screen_id, tick_count);
6293                            }
6294                        }
6295
6296                        trace!(
6297                            tick = tick_count,
6298                            active = %active,
6299                            ticked = tick_targets.len(),
6300                            skipped = skipped_count,
6301                            "tick_strategy.frame"
6302                        );
6303
6304                        // Maintenance tick for the strategy.
6305                        strategy.maintenance_tick(tick_count);
6306                        self.mark_dirty();
6307                    }
6308                }
6309
6310                if used_screen_dispatch && self.running {
6311                    self.reconcile_subscriptions();
6312                }
6313
6314                // A stationary mouse-down only becomes a long press with the
6315                // passage of time, so the recognizer is polled once per tick.
6316                if let Some(gesture) = self
6317                    .gesture_recognizer
6318                    .as_mut()
6319                    .and_then(|recognizer| recognizer.check_long_press(Instant::now()))
6320                {
6321                    self.deliver_gesture(gesture)?;
6322                }
6323
6324                // Flush any pending coalesced events on tick so they do not sit unrendered.
6325                if self.running {
6326                    self.flush_coalesced_events()?;
6327                }
6328
6329                if !used_screen_dispatch {
6330                    // Monolithic model path does not expose active-screen
6331                    // transitions, so clear dispatch-local transition state.
6332                    self.last_active_screen_for_strategy = None;
6333                    let msg = M::Message::from(Event::Tick);
6334                    let cmd = {
6335                        let _span = debug_span!(
6336                            crate::telemetry_schema::span::PROGRAM_UPDATE,
6337                            msg_type = "Tick",
6338                            duration_us = tracing::field::Empty,
6339                            cmd_type = tracing::field::Empty
6340                        )
6341                        .entered();
6342                        let start = Instant::now();
6343                        let cmd = self.model.update(msg);
6344                        tracing::Span::current()
6345                            .record("duration_us", start.elapsed().as_micros() as u64);
6346                        tracing::Span::current()
6347                            .record("cmd_type", format!("{:?}", std::mem::discriminant(&cmd)));
6348                        cmd
6349                    };
6350                    self.mark_dirty();
6351                    self.execute_cmd(cmd)?;
6352                    if self.running {
6353                        self.reconcile_subscriptions();
6354                    }
6355                }
6356            }
6357
6358            // Check for periodic checkpoint save
6359            self.check_checkpoint_save();
6360
6361            // Detect locale changes outside the event loop.
6362            self.check_locale_change();
6363            termination_signal = termination_signal.or_else(|| self.observed_termination_signal());
6364            if termination_signal.is_some() {
6365                self.running = false;
6366                break;
6367            }
6368
6369            // Render if dirty
6370            if self.dirty {
6371                self.render_frame()?;
6372            }
6373
6374            // Periodic grapheme pool GC
6375            if loop_count.is_multiple_of(1000) {
6376                self.presenter.gc();
6377            }
6378        }
6379
6380        Ok(termination_signal)
6381    }
6382
6383    /// Complete the model/runtime lifecycle after every event-loop exit path.
6384    fn complete_lifecycle(&mut self, run_result: io::Result<Option<i32>>) -> io::Result<()> {
6385        let (loop_signal, primary_error) = match run_result {
6386            Ok(signal) => (signal, None),
6387            Err(error) => (None, Some(error)),
6388        };
6389        let termination_signal = loop_signal.or_else(|| self.observed_termination_signal());
6390
6391        // The event loop is over. Lifecycle commands may run model updates,
6392        // but they must never restart normal event processing.
6393        self.running = false;
6394
6395        let mut hook_error = None;
6396        if let Some(error) = primary_error.as_ref()
6397            && let Err(error) = self.invoke_error_hook(&error.to_string(), true)
6398        {
6399            hook_error = Some(error);
6400        }
6401
6402        if let Err(error) = self.process_subscription_failures(true) {
6403            hook_error.get_or_insert(error);
6404        }
6405
6406        let shutdown_error = self.shutdown_once().err();
6407
6408        // A pending termination signal takes precedence over lifecycle-step
6409        // errors: it is what ended the loop, and callers rely on the
6410        // SignalTerminationError contract for the 128+signal process exit.
6411        if let Some(signal) = termination_signal {
6412            self.pending_signal
6413                .store(0, std::sync::atomic::Ordering::SeqCst);
6414            if self.global_signal_slot {
6415                clear_termination_signal();
6416            }
6417            let error = io::Error::new(
6418                io::ErrorKind::Interrupted,
6419                SignalTerminationError { signal },
6420            );
6421            debug_assert_eq!(signal_termination_from_error(&error), Some(signal));
6422            return Err(error);
6423        }
6424
6425        if let Some(error) = primary_error {
6426            return Err(error);
6427        }
6428
6429        if let Some(error) = hook_error {
6430            return Err(error);
6431        }
6432
6433        if let Some(error) = shutdown_error {
6434            // A failing cleanup command is still a command error. Report it
6435            // after the one-shot shutdown hook without attempting teardown a
6436            // second time.
6437            let _ = self.invoke_error_hook(&error.to_string(), true);
6438            return Err(error);
6439        }
6440
6441        Ok(())
6442    }
6443
6444    /// Run model shutdown and runtime teardown at most once.
6445    fn shutdown_once(&mut self) -> io::Result<()> {
6446        if self.shutdown_complete {
6447            return Ok(());
6448        }
6449        self.shutdown_complete = true;
6450
6451        let shutdown_cmd = {
6452            let _span = info_span!(crate::telemetry_schema::span::PROGRAM_SHUTDOWN).entered();
6453            self.model.on_shutdown()
6454        };
6455        // The shutdown sequence is error-isolated: a failing shutdown command
6456        // must not skip auto-save, strategy/executor shutdown, or signal exit
6457        // mapping. The first error is captured and surfaced after cleanup.
6458        let mut shutdown_error = self.execute_lifecycle_cmd(shutdown_cmd).err();
6459
6460        if self.persistence_config.auto_save {
6461            self.save_state();
6462        }
6463
6464        if let Some(ref mut strategy) = self.tick_strategy {
6465            strategy.shutdown();
6466        }
6467
6468        self.subscriptions.stop_all();
6469        if let Err(error) = self.process_subscription_failures(true) {
6470            shutdown_error.get_or_insert(error);
6471        }
6472
6473        self.task_executor.shutdown();
6474        self.reap_finished_tasks();
6475        if let Err(error) = self.drain_shutdown_task_results() {
6476            shutdown_error.get_or_insert(error);
6477        }
6478
6479        if let Some(ref sink) = self.evidence_sink {
6480            let (hits, misses, len, capacity, enabled) =
6481                if let Some(stats) = ftui_core::text_width::width_cache_stats() {
6482                    (
6483                        stats.hits,
6484                        stats.misses,
6485                        stats.small_size + stats.main_size,
6486                        stats.capacity,
6487                        true,
6488                    )
6489                } else {
6490                    (0, 0, 0, 0, false)
6491                };
6492            let line = format!(
6493                r#"{{"schema_version":"{}","event":"width_cache_stats","hits":{},"misses":{},"len":{},"capacity":{},"enabled":{},"thread":"main"}}"#,
6494                crate::evidence_sink::EVIDENCE_SCHEMA_VERSION,
6495                hits,
6496                misses,
6497                len,
6498                capacity,
6499                enabled,
6500            );
6501            let _ = sink.write_jsonl(&line);
6502        }
6503
6504        match shutdown_error {
6505            Some(error) => Err(error),
6506            None => Ok(()),
6507        }
6508    }
6509
6510    /// Drain ready events while bounding zero-timeout polling work.
6511    ///
6512    /// The runtime preserves low-latency draining by polling with
6513    /// `Duration::ZERO`, but switches to a bounded backoff path when a burst
6514    /// exceeds configured immediate-drain budgets.
6515    fn drain_ready_events(&mut self) -> io::Result<()> {
6516        self.immediate_drain_stats.bursts = self.immediate_drain_stats.bursts.saturating_add(1);
6517
6518        let zero_poll_limit = self
6519            .immediate_drain_config
6520            .max_zero_timeout_polls_per_burst
6521            .max(1);
6522        let max_burst_duration = self.immediate_drain_config.max_burst_duration;
6523        let backoff_timeout = self.immediate_drain_config.backoff_timeout;
6524
6525        let mut burst_start = Instant::now();
6526        let mut zero_polls_in_burst_window: u64 = 0;
6527        let mut capped_this_burst = false;
6528
6529        loop {
6530            // `read_event` may return `Ok(None)` even though the preceding
6531            // poll reported readiness: the event may be unrepresentable in
6532            // ftui's canonical event types, and on Windows console readiness
6533            // can be spurious (discarded key-release/focus/menu records), in
6534            // which case the crossterm-backed source re-polls with a zero
6535            // timeout instead of parking in a blocking read (frankentui#95).
6536            // Either way we simply fall through to the bounded zero-timeout
6537            // poll below; when nothing is pending the burst ends and the
6538            // outer loop parks in its normal timed poll โ€” no busy-spin.
6539            if let Some(event) = self.events.read_event()? {
6540                self.handle_event(event)?;
6541                if !self.running {
6542                    break;
6543                }
6544            }
6545
6546            let budget_exhausted = (zero_polls_in_burst_window as usize) >= zero_poll_limit
6547                || burst_start.elapsed() >= max_burst_duration;
6548
6549            if budget_exhausted {
6550                if !capped_this_burst {
6551                    capped_this_burst = true;
6552                    self.immediate_drain_stats.capped_bursts =
6553                        self.immediate_drain_stats.capped_bursts.saturating_add(1);
6554                }
6555
6556                self.immediate_drain_stats.max_zero_timeout_polls_in_burst = self
6557                    .immediate_drain_stats
6558                    .max_zero_timeout_polls_in_burst
6559                    .max(zero_polls_in_burst_window);
6560
6561                std::thread::yield_now();
6562                self.immediate_drain_stats.backoff_polls =
6563                    self.immediate_drain_stats.backoff_polls.saturating_add(1);
6564                if !self.events.poll_event(backoff_timeout)? {
6565                    break;
6566                }
6567                zero_polls_in_burst_window = 0;
6568                burst_start = Instant::now();
6569                continue;
6570            }
6571
6572            self.immediate_drain_stats.zero_timeout_polls = self
6573                .immediate_drain_stats
6574                .zero_timeout_polls
6575                .saturating_add(1);
6576            zero_polls_in_burst_window = zero_polls_in_burst_window.saturating_add(1);
6577            if !self.events.poll_event(Duration::ZERO)? {
6578                break;
6579            }
6580        }
6581
6582        self.immediate_drain_stats.max_zero_timeout_polls_in_burst = self
6583            .immediate_drain_stats
6584            .max_zero_timeout_polls_in_burst
6585            .max(zero_polls_in_burst_window);
6586
6587        if self.running {
6588            self.flush_coalesced_events()?;
6589        }
6590
6591        Ok(())
6592    }
6593
6594    /// Load state from the persistence registry.
6595    fn load_state(&mut self) {
6596        if let Some(registry) = &self.state_registry {
6597            match registry.load() {
6598                Ok(count) => {
6599                    info!(count, "loaded widget state from persistence");
6600                }
6601                Err(e) => {
6602                    tracing::warn!(error = %e, "failed to load widget state");
6603                }
6604            }
6605        }
6606    }
6607
6608    /// Save state to the persistence registry.
6609    fn save_state(&mut self) {
6610        if let Some(registry) = &self.state_registry {
6611            match registry.flush() {
6612                Ok(true) => {
6613                    debug!("saved widget state to persistence");
6614                }
6615                Ok(false) => {
6616                    // No changes to save
6617                }
6618                Err(e) => {
6619                    tracing::warn!(error = %e, "failed to save widget state");
6620                }
6621            }
6622        }
6623    }
6624
6625    /// Check if it's time for a periodic checkpoint save.
6626    fn check_checkpoint_save(&mut self) {
6627        if let Some(interval) = self.persistence_config.checkpoint_interval
6628            && self.last_checkpoint.elapsed() >= interval
6629        {
6630            self.save_state();
6631            self.last_checkpoint = Instant::now();
6632        }
6633    }
6634
6635    /// Hand one recognized gesture to `Model::on_gesture` and run the
6636    /// resulting command like any update command.
6637    fn deliver_gesture(
6638        &mut self,
6639        gesture: ftui_core::semantic_event::SemanticEvent,
6640    ) -> io::Result<()> {
6641        let cmd = {
6642            let _span = debug_span!(
6643                crate::telemetry_schema::span::PROGRAM_UPDATE,
6644                msg_type = "gesture"
6645            )
6646            .entered();
6647            self.model.on_gesture(gesture)
6648        };
6649        self.mark_dirty();
6650        self.execute_cmd(cmd)?;
6651        if self.running {
6652            self.reconcile_subscriptions();
6653        }
6654        Ok(())
6655    }
6656
6657    fn handle_event(&mut self, event: Event) -> io::Result<()> {
6658        // Track event start time and type for fairness scheduling.
6659        let event_start = Instant::now();
6660        let fairness_event_type = Self::classify_event_for_fairness(&event);
6661        if fairness_event_type == FairnessEventType::Input {
6662            self.fairness_guard.input_arrived(event_start);
6663        }
6664
6665        // Record event before processing (no-op when recorder is None or idle).
6666        if let Some(recorder) = &mut self.event_recorder {
6667            recorder.record(&event);
6668        }
6669
6670        // Raw mode turns off the terminal's own ^Z, so with `ctrl_z_suspends`
6671        // the key stands in for SIGTSTP and never reaches the model.
6672        if self.ctrl_z_suspends
6673            && self.suspend_enabled
6674            && let Event::Key(key) = &event
6675            && key.kind == ftui_core::event::KeyEventKind::Press
6676            && key.code == ftui_core::event::KeyCode::Char('z')
6677            && key.modifiers == ftui_core::event::Modifiers::CTRL
6678        {
6679            self.pending_suspend.store(
6680                ftui_core::job_control::KEYBOARD_STOP_SIGNAL,
6681                std::sync::atomic::Ordering::SeqCst,
6682            );
6683            self.fairness_guard.event_processed(
6684                fairness_event_type,
6685                event_start.elapsed(),
6686                Instant::now(),
6687            );
6688            return Ok(());
6689        }
6690
6691        let event = match event {
6692            Event::Resize { width, height } => {
6693                if let Some(ref mut coalescer) = self.event_coalescer {
6694                    coalescer.clear();
6695                }
6696                debug!(
6697                    width,
6698                    height,
6699                    behavior = ?self.resize_behavior,
6700                    "Resize event received"
6701                );
6702                if let Some((forced_width, forced_height)) = self.forced_size {
6703                    debug!(
6704                        forced_width,
6705                        forced_height, "Resize ignored due to forced size override"
6706                    );
6707                    self.fairness_guard.event_processed(
6708                        fairness_event_type,
6709                        event_start.elapsed(),
6710                        Instant::now(),
6711                    );
6712                    return Ok(());
6713                }
6714                // Clamp to minimum 1 to prevent Buffer::new panic on zero dimensions
6715                let width = width.max(1);
6716                let height = height.max(1);
6717                match self.resize_behavior {
6718                    ResizeBehavior::Immediate => {
6719                        self.resize_coalescer
6720                            .record_external_apply(width, height, Instant::now());
6721                        let result = self.apply_resize(width, height, Duration::ZERO, false);
6722                        self.fairness_guard.event_processed(
6723                            fairness_event_type,
6724                            event_start.elapsed(),
6725                            Instant::now(),
6726                        );
6727                        return result;
6728                    }
6729                    ResizeBehavior::Throttled => {
6730                        let action = self.resize_coalescer.handle_resize(width, height);
6731                        if let CoalesceAction::ApplyResize {
6732                            width,
6733                            height,
6734                            coalesce_time,
6735                            forced_by_deadline,
6736                        } = action
6737                        {
6738                            let result =
6739                                self.apply_resize(width, height, coalesce_time, forced_by_deadline);
6740                            self.fairness_guard.event_processed(
6741                                fairness_event_type,
6742                                event_start.elapsed(),
6743                                Instant::now(),
6744                            );
6745                            return result;
6746                        }
6747
6748                        self.fairness_guard.event_processed(
6749                            fairness_event_type,
6750                            event_start.elapsed(),
6751                            Instant::now(),
6752                        );
6753                        return Ok(());
6754                    }
6755                }
6756            }
6757            other => other,
6758        };
6759
6760        // Gesture recognition runs beside the raw event, never instead of it:
6761        // the raw event still reaches `update()` below, and any gesture the
6762        // recognizer completes is delivered to `on_gesture` afterwards.
6763        let gestures = self
6764            .gesture_recognizer
6765            .as_mut()
6766            .map(|recognizer| recognizer.process(&event, Instant::now()))
6767            .unwrap_or_default();
6768
6769        if self.event_coalescer.is_some() {
6770            let is_coalescable = match &event {
6771                Event::Mouse(m) => matches!(
6772                    m.kind,
6773                    MouseEventKind::Moved
6774                        | MouseEventKind::ScrollUp
6775                        | MouseEventKind::ScrollDown
6776                        | MouseEventKind::ScrollLeft
6777                        | MouseEventKind::ScrollRight
6778                ),
6779                _ => false,
6780            };
6781
6782            let mut to_dispatch = Vec::new();
6783            if let Some(coalescer) = self.event_coalescer.as_mut() {
6784                if !is_coalescable && coalescer.has_pending() {
6785                    to_dispatch.extend(coalescer.flush());
6786                }
6787                if let Some(evt) = coalescer.push(event) {
6788                    to_dispatch.push(evt);
6789                }
6790            }
6791
6792            for evt in to_dispatch {
6793                self.dispatch_input_event(evt)?;
6794                if !self.running {
6795                    return Ok(());
6796                }
6797            }
6798        } else {
6799            self.dispatch_input_event(event)?;
6800        }
6801
6802        if self.running {
6803            for gesture in gestures {
6804                self.deliver_gesture(gesture)?;
6805            }
6806        }
6807
6808        // Track input event processing for fairness.
6809        self.fairness_guard.event_processed(
6810            fairness_event_type,
6811            event_start.elapsed(),
6812            Instant::now(),
6813        );
6814
6815        Ok(())
6816    }
6817
6818    /// Dispatch a single input event to the model's `update()` method,
6819    /// mark dirty, execute the returned command, and reconcile subscriptions.
6820    fn dispatch_input_event(&mut self, event: Event) -> io::Result<()> {
6821        if !self.running {
6822            return Ok(());
6823        }
6824        let msg = M::Message::from(event);
6825        let cmd = {
6826            let _span = debug_span!(
6827                crate::telemetry_schema::span::PROGRAM_UPDATE,
6828                msg_type = "event",
6829                duration_us = tracing::field::Empty,
6830                cmd_type = tracing::field::Empty
6831            )
6832            .entered();
6833            let start = Instant::now();
6834            let cmd = self.model.update(msg);
6835            let elapsed_us = start.elapsed().as_micros() as u64;
6836            self.last_update_us = Some(elapsed_us);
6837            tracing::Span::current().record("duration_us", elapsed_us);
6838            tracing::Span::current()
6839                .record("cmd_type", format!("{:?}", std::mem::discriminant(&cmd)));
6840            cmd
6841        };
6842        self.mark_dirty();
6843        self.execute_cmd(cmd)?;
6844        if self.running {
6845            self.reconcile_subscriptions();
6846        }
6847        Ok(())
6848    }
6849
6850    /// Flush any pending coalesced input events to the model.
6851    pub fn flush_coalesced_events(&mut self) -> io::Result<()> {
6852        let pending = match self.event_coalescer.as_mut() {
6853            Some(coalescer) if coalescer.has_pending() => coalescer.flush(),
6854            _ => return Ok(()),
6855        };
6856        for event in pending {
6857            self.dispatch_input_event(event)?;
6858            if !self.running {
6859                break;
6860            }
6861        }
6862        Ok(())
6863    }
6864
6865    /// Access the event coalescer, if enabled.
6866    #[must_use]
6867    pub fn event_coalescer(&self) -> Option<&ftui_core::event_coalescer::EventCoalescer> {
6868        self.event_coalescer.as_ref()
6869    }
6870
6871    /// Classify an event for fairness tracking.
6872    fn classify_event_for_fairness(event: &Event) -> FairnessEventType {
6873        match event {
6874            Event::Key(_)
6875            | Event::Mouse(_)
6876            | Event::Paste(_)
6877            | Event::Ime(_)
6878            | Event::Focus(_)
6879            | Event::Clipboard(_) => FairnessEventType::Input,
6880            Event::Resize { .. } => FairnessEventType::Resize,
6881            Event::Tick => FairnessEventType::Tick,
6882        }
6883    }
6884
6885    /// Reconcile the model's declared subscriptions with running ones.
6886    fn reconcile_subscriptions(&mut self) {
6887        let _span = debug_span!(
6888            crate::telemetry_schema::span::PROGRAM_SUBSCRIPTIONS,
6889            active_count = tracing::field::Empty,
6890            started = tracing::field::Empty,
6891            stopped = tracing::field::Empty
6892        )
6893        .entered();
6894        let subs = self.model.subscriptions();
6895        let before_count = self.subscriptions.active_count();
6896        self.subscriptions.reconcile(subs);
6897        let after_count = self.subscriptions.active_count();
6898        let started = after_count.saturating_sub(before_count);
6899        let stopped = before_count.saturating_sub(after_count);
6900        crate::debug_trace!(
6901            "subscriptions reconcile: before={}, after={}, started={}, stopped={}",
6902            before_count,
6903            after_count,
6904            started,
6905            stopped
6906        );
6907        if after_count == 0 {
6908            crate::debug_trace!("subscriptions reconcile: no active subscriptions");
6909        }
6910        let current = tracing::Span::current();
6911        current.record("active_count", after_count);
6912        // started/stopped would require tracking in SubscriptionManager
6913        current.record("started", started);
6914        current.record("stopped", stopped);
6915    }
6916
6917    /// Report newly observed subscription failures through `Model::on_error`.
6918    fn process_subscription_failures(&mut self, during_lifecycle: bool) -> io::Result<()> {
6919        let mut first_error = None;
6920        for failure in self.subscriptions.drain_failures() {
6921            let error = format!("subscription {} failed: {}", failure.id, failure.error);
6922            if let Err(error) = self.invoke_error_hook(&error, during_lifecycle) {
6923                first_error.get_or_insert(error);
6924            }
6925        }
6926
6927        match first_error {
6928            Some(error) => Err(error),
6929            None => Ok(()),
6930        }
6931    }
6932
6933    /// Invoke the model error hook and execute its recovery command.
6934    fn invoke_error_hook(&mut self, error: &str, during_lifecycle: bool) -> io::Result<()> {
6935        let cmd = {
6936            let _span = info_span!(crate::telemetry_schema::span::PROGRAM_ERROR, error).entered();
6937            self.model.on_error(error)
6938        };
6939        if during_lifecycle {
6940            self.execute_lifecycle_cmd(cmd)
6941        } else {
6942            self.execute_cmd(cmd)
6943        }
6944    }
6945
6946    /// Execute a lifecycle command even after the normal loop stopped.
6947    ///
6948    /// `Cmd::Batch` and `Cmd::Sequence` use the running flag as their halt
6949    /// boundary, so temporarily reopening dispatch is required for cleanup
6950    /// batches. An explicit `Cmd::Quit` inside the lifecycle command still
6951    /// halts the remaining commands.
6952    fn execute_lifecycle_cmd(&mut self, cmd: Cmd<M::Message>) -> io::Result<()> {
6953        let was_running = std::mem::replace(&mut self.running, true);
6954        let result = self.execute_cmd(cmd);
6955        self.running = was_running && self.running;
6956        // Lifecycle hooks may run after the render loop has stopped.
6957        let flush_result = self.presenter.flush();
6958        result.and(flush_result)
6959    }
6960
6961    /// Process pending messages from subscriptions.
6962    fn process_subscription_messages(&mut self) -> io::Result<()> {
6963        let messages = self.subscriptions.drain_messages();
6964        let msg_count = messages.len();
6965        if msg_count > 0 {
6966            crate::debug_trace!("processing {} subscription message(s)", msg_count);
6967        }
6968        for msg in messages {
6969            let cmd = {
6970                let _span = debug_span!(
6971                    crate::telemetry_schema::span::PROGRAM_UPDATE,
6972                    msg_type = "subscription",
6973                    duration_us = tracing::field::Empty,
6974                    cmd_type = tracing::field::Empty
6975                )
6976                .entered();
6977                let start = Instant::now();
6978                let cmd = self.model.update(msg);
6979                let elapsed_us = start.elapsed().as_micros() as u64;
6980                self.last_update_us = Some(elapsed_us);
6981                tracing::Span::current().record("duration_us", elapsed_us);
6982                tracing::Span::current()
6983                    .record("cmd_type", format!("{:?}", std::mem::discriminant(&cmd)));
6984                cmd
6985            };
6986            self.mark_dirty();
6987            self.execute_cmd(cmd)?;
6988            if !self.running {
6989                break;
6990            }
6991        }
6992        if self.running && self.dirty {
6993            self.reconcile_subscriptions();
6994        }
6995        Ok(())
6996    }
6997
6998    /// Process results from background tasks.
6999    fn process_task_results(&mut self) -> io::Result<()> {
7000        while let Ok(msg) = self.task_receiver.try_recv() {
7001            let cmd = {
7002                let _span = debug_span!(
7003                    crate::telemetry_schema::span::PROGRAM_UPDATE,
7004                    msg_type = "task",
7005                    duration_us = tracing::field::Empty,
7006                    cmd_type = tracing::field::Empty
7007                )
7008                .entered();
7009                let start = Instant::now();
7010                let cmd = self.model.update(msg);
7011                let elapsed_us = start.elapsed().as_micros() as u64;
7012                self.last_update_us = Some(elapsed_us);
7013                tracing::Span::current().record("duration_us", elapsed_us);
7014                tracing::Span::current()
7015                    .record("cmd_type", format!("{:?}", std::mem::discriminant(&cmd)));
7016                cmd
7017            };
7018            self.mark_dirty();
7019            self.execute_cmd(cmd)?;
7020            if !self.running {
7021                break;
7022            }
7023        }
7024        if self.running && self.dirty {
7025            self.reconcile_subscriptions();
7026        }
7027        Ok(())
7028    }
7029
7030    /// Execute a command.
7031    fn execute_cmd(&mut self, cmd: Cmd<M::Message>) -> io::Result<()> {
7032        // Commands run depth-first from an explicit stack of batch iterators,
7033        // in the order the recursive version used. A model that answers a
7034        // message with `Cmd::Msg` for its next step recursed once per step:
7035        // a chain of about 10k steps overflowed the stack, and a stack
7036        // overflow aborts the process without restoring the terminal.
7037        let mut batches: Vec<std::vec::IntoIter<Cmd<M::Message>>> = Vec::new();
7038        let mut next = Some(cmd);
7039        loop {
7040            let cmd = match next.take() {
7041                Some(cmd) => cmd,
7042                None => {
7043                    // Resume the innermost batch. A batch stops after any
7044                    // command that ends the program.
7045                    let Some(rest) = batches.last_mut() else {
7046                        return Ok(());
7047                    };
7048                    if !self.running {
7049                        return Ok(());
7050                    }
7051                    match rest.next() {
7052                        Some(cmd) => cmd,
7053                        None => {
7054                            batches.pop();
7055                            continue;
7056                        }
7057                    }
7058                }
7059            };
7060            next = self.execute_one_cmd(cmd, &mut batches)?;
7061        }
7062    }
7063
7064    /// Execute `cmd` for [`Self::execute_cmd`], returning the command to run
7065    /// next (the `update` result for `Cmd::Msg`, the first command of a batch)
7066    /// and pushing the rest of a batch onto `batches`.
7067    fn execute_one_cmd(
7068        &mut self,
7069        cmd: Cmd<M::Message>,
7070        batches: &mut Vec<std::vec::IntoIter<Cmd<M::Message>>>,
7071    ) -> io::Result<Option<Cmd<M::Message>>> {
7072        self.executed_cmd_count = self.executed_cmd_count.saturating_add(1);
7073        match cmd {
7074            Cmd::None => {}
7075            Cmd::Quit => {
7076                self.running = false;
7077                self.presenter.flush()?;
7078            }
7079            Cmd::Msg(m) => {
7080                let start = Instant::now();
7081                let cmd = self.model.update(m);
7082                let elapsed_us = start.elapsed().as_micros() as u64;
7083                self.last_update_us = Some(elapsed_us);
7084                self.mark_dirty();
7085                return Ok(Some(cmd));
7086            }
7087            // Batch currently executes sequentially, like Sequence. This is
7088            // intentional until an async runtime or task scheduler is added.
7089            Cmd::Batch(cmds) | Cmd::Sequence(cmds) => {
7090                let mut rest = cmds.into_iter();
7091                let first = rest.next();
7092                batches.push(rest);
7093                return Ok(first);
7094            }
7095            Cmd::Tick(duration) => {
7096                self.tick_rate = Some(duration);
7097                self.last_tick = Instant::now();
7098            }
7099            Cmd::Log { text, mode } => {
7100                self.presenter.write_log_line_with_mode(&text, mode)?;
7101            }
7102            Cmd::Task(spec, f) => {
7103                crate::effect_system::record_command_effect("task", 0);
7104                self.task_executor.submit(spec, f);
7105            }
7106            Cmd::SaveState => {
7107                self.save_state();
7108            }
7109            Cmd::RestoreState => {
7110                self.load_state();
7111            }
7112            Cmd::SetMouseCapture(enabled) => {
7113                self.backend_features.mouse_capture = enabled;
7114                self.events.set_features(self.backend_features)?;
7115            }
7116            Cmd::SetClipboard(text) => {
7117                self.presenter.write_osc52_set(
7118                    ftui_core::osc52::ClipboardSelection::Clipboard,
7119                    text.as_bytes(),
7120                )?;
7121                if !self.dirty {
7122                    self.presenter.flush()?;
7123                }
7124            }
7125            Cmd::GetClipboard => {
7126                self.presenter
7127                    .write_osc52_query(ftui_core::osc52::ClipboardSelection::Clipboard)?;
7128                if !self.dirty {
7129                    self.presenter.flush()?;
7130                }
7131            }
7132            Cmd::SetTickStrategy(strategy) => {
7133                let new_name = strategy.name().to_owned();
7134                if let Some(mut previous) = self.tick_strategy.replace(strategy) {
7135                    let old_name = previous.name().to_owned();
7136                    previous.shutdown();
7137                    info!(old = %old_name, new = %new_name, "tick strategy changed at runtime");
7138                } else {
7139                    info!(new = %new_name, "tick strategy changed at runtime");
7140                }
7141                self.last_active_screen_for_strategy = None;
7142            }
7143        }
7144        Ok(None)
7145    }
7146
7147    /// Detect active-screen transitions after any `update()` call and react:
7148    ///
7149    /// - **A.2** โ€” notify the tick strategy via `on_screen_transition()` so
7150    ///   predictive strategies can learn navigation patterns.
7151    /// - **D.3** โ€” force-tick the newly active screen so it renders fresh
7152    ///   content immediately, without waiting for the next tick interval.
7153    ///
7154    /// This is a no-op when no tick strategy is configured or when the model
7155    /// does not implement [`ScreenTickDispatch`].
7156    fn check_screen_transition(&mut self) {
7157        if self.tick_strategy.is_none() {
7158            return;
7159        }
7160
7161        // Snapshot the current active screen (releases &mut self.model).
7162        let current_active = match self.model.as_screen_tick_dispatch() {
7163            Some(dispatch) => dispatch.active_screen_id(),
7164            None => return,
7165        };
7166
7167        // First observation: just record, no transition event.
7168        let previous = match self.last_active_screen_for_strategy.take() {
7169            Some(prev) => prev,
7170            None => {
7171                self.last_active_screen_for_strategy = Some(current_active);
7172                return;
7173            }
7174        };
7175
7176        if previous == current_active {
7177            self.last_active_screen_for_strategy = Some(current_active);
7178            return;
7179        }
7180
7181        // A.2: Notify strategy of the transition.
7182        if let Some(strategy) = self.tick_strategy.as_mut() {
7183            strategy.on_screen_transition(&previous, &current_active);
7184        }
7185
7186        // D.3: Force-tick the newly active screen immediately.
7187        let mut force_ticked = false;
7188        if let Some(dispatch) = self.model.as_screen_tick_dispatch() {
7189            dispatch.tick_screen(&current_active, self.tick_count);
7190            force_ticked = true;
7191        }
7192        if force_ticked && self.running {
7193            self.reconcile_subscriptions();
7194        }
7195
7196        self.last_active_screen_for_strategy = Some(current_active);
7197        self.mark_dirty();
7198    }
7199
7200    fn reap_finished_tasks(&mut self) {
7201        self.task_executor.reap_finished();
7202    }
7203
7204    fn drain_shutdown_task_results(&mut self) -> io::Result<()> {
7205        while let Ok(msg) = self.task_receiver.try_recv() {
7206            let cmd = {
7207                let _span = debug_span!(
7208                    crate::telemetry_schema::span::PROGRAM_UPDATE,
7209                    msg_type = "shutdown_task",
7210                    duration_us = tracing::field::Empty,
7211                    cmd_type = tracing::field::Empty
7212                )
7213                .entered();
7214                let start = Instant::now();
7215                let cmd = self.model.update(msg);
7216                let elapsed_us = start.elapsed().as_micros() as u64;
7217                self.last_update_us = Some(elapsed_us);
7218                tracing::Span::current().record("duration_us", elapsed_us);
7219                tracing::Span::current()
7220                    .record("cmd_type", format!("{:?}", std::mem::discriminant(&cmd)));
7221                cmd
7222            };
7223            self.mark_dirty();
7224            self.execute_lifecycle_cmd(cmd)?;
7225        }
7226        Ok(())
7227    }
7228
7229    /// Render a frame with budget tracking.
7230    fn render_frame(&mut self) -> io::Result<()> {
7231        crate::debug_trace!("render_frame: {}x{}", self.width, self.height);
7232
7233        self.frame_idx = self.frame_idx.wrapping_add(1);
7234        let frame_idx = self.frame_idx;
7235        let degradation_start = self.budget.degradation();
7236
7237        // Reset budget for new frame, potentially upgrading quality
7238        self.budget.next_frame();
7239
7240        // Check frame guardrails (memory/queue limits). The frame loop itself
7241        // is synchronous, so "queue depth" is the effect backlog: tasks this
7242        // program handed to its executor that have not produced their
7243        // message yet (`TaskExecutor::in_flight`). This is the value the
7244        // queue guardrail thresholds (warn/max/emergency) were designed
7245        // against; it used to be hard-coded to 0, which made the whole queue
7246        // guardrail dead in production (bd-1za0z item 3). It is measured per
7247        // program rather than from the process-global queue counters so a
7248        // second program in the same process (or a leaked counter) cannot
7249        // make this one shed frames.
7250        // Retained capacity, not live usage: sustained growth across frames is
7251        // the leak signal. Usage-level accounting requires an allocator hook.
7252        let memory_bytes =
7253            self.presenter.estimate_memory_usage() + self.frame_arena.allocated_bytes();
7254        let queue_depth = u32::try_from(self.task_executor.in_flight()).unwrap_or(u32::MAX);
7255        let verdict = self.guardrails.check_frame(memory_bytes, queue_depth);
7256
7257        // F2 observability: export a guardrail snapshot whenever any
7258        // guardrail fires (including suspected retained-capacity growth).
7259        // This stays quiet in healthy runs
7260        // (bd-1za0z: GuardrailSnapshot::to_jsonl was production-dead).
7261        if !verdict.alerts.is_empty()
7262            && let Some(ref sink) = self.evidence_sink
7263        {
7264            let line = format!(
7265                r#"{{"schema_version":"{}","event":"guardrail_snapshot","snapshot":{}}}"#,
7266                crate::evidence_sink::EVIDENCE_SCHEMA_VERSION,
7267                self.guardrails.snapshot().to_jsonl(),
7268            );
7269            let _ = sink.write_jsonl(&line);
7270        }
7271
7272        if let Some(ref alert) = verdict.leak_alert {
7273            tracing::warn!(
7274                target: crate::telemetry_schema::TARGET_GUARDRAILS,
7275                e_value = alert.e_value,
7276                cusum = alert.cusum_upper,
7277                mean_bytes = self.guardrails.snapshot().leak_mean_bytes,
7278                "allocation leak suspected"
7279            );
7280        }
7281
7282        if verdict.should_drop_frame() {
7283            // Emergency shed: skip this frame entirely to prevent OOM.
7284            // CRUCIALLY, remediate: two of the sensor's components are
7285            // retained CAPACITY that never shrinks on its own (bumpalo keeps
7286            // its largest chunk across reset(); the grapheme pool's Vec never
7287            // shrinks). Without releasing them the verdict is permanent and
7288            // the UI freezes forever โ€” dropping frames cannot move the
7289            // sensor. Rebuilding the arena frees the retained chunk so the
7290            // next frame re-measures honestly.
7291            self.frame_arena = FrameArena::default();
7292            self.presenter.gc();
7293            self.guardrails.reset_leak_detector();
7294            tracing::warn!(
7295                target: crate::telemetry_schema::TARGET_GUARDRAILS,
7296                memory_bytes,
7297                "emergency frame drop: memory guardrail tripped; arena rebuilt"
7298            );
7299            return Ok(());
7300        }
7301
7302        if verdict.should_degrade() {
7303            // Apply guardrail-recommended degradation if it's stricter than budget's
7304            let current = self.budget.degradation();
7305            if verdict.recommended_level > current {
7306                self.budget.set_degradation(verdict.recommended_level);
7307            }
7308
7309            // Soft-tier early trim (bd-1za0z): the memory sensor measures
7310            // retained CAPACITY, so once past the soft limit nothing the
7311            // degradation actuator does can lower it again โ€” only releasing
7312            // capacity can. Trim early (same remediation as the emergency
7313            // shed, but non-fatal) instead of waiting for the emergency
7314            // tier; cooldown-gated so hovering near the limit cannot thrash
7315            // allocations.
7316            let soft_alert = verdict.alerts.iter().any(|alert| {
7317                alert.kind == GuardrailKind::Memory && alert.severity == AlertSeverity::Warning
7318            });
7319            let cooldown_elapsed = match self.last_soft_trim_frame {
7320                None => true,
7321                Some(last) => self.frame_idx.saturating_sub(last) >= SOFT_TRIM_COOLDOWN_FRAMES,
7322            };
7323            if soft_alert && cooldown_elapsed {
7324                self.frame_arena = FrameArena::default();
7325                self.presenter.gc();
7326                self.guardrails.reset_leak_detector();
7327                self.last_soft_trim_frame = Some(self.frame_idx);
7328                tracing::debug!(
7329                    target: crate::telemetry_schema::TARGET_GUARDRAILS,
7330                    memory_bytes,
7331                    "soft memory alert: arena rebuilt to release retained capacity"
7332                );
7333            }
7334        }
7335
7336        // Apply conformal risk gate before rendering (if enabled)
7337        let mut conformal_prediction = None;
7338        if let Some(predictor) = self.conformal_predictor.as_ref() {
7339            let baseline_us = self
7340                .last_frame_time_us
7341                .unwrap_or_else(|| self.budget.total().as_secs_f64() * 1_000_000.0);
7342            let diff_strategy = self
7343                .presenter
7344                .last_diff_strategy()
7345                .unwrap_or(DiffStrategy::Full);
7346            let frame_height_hint = self.presenter.render_height_hint().max(1);
7347            let key = BucketKey::from_context(
7348                self.presenter.screen_mode(),
7349                diff_strategy,
7350                self.width,
7351                frame_height_hint,
7352            );
7353            let budget_us = self.budget.total().as_secs_f64() * 1_000_000.0;
7354            let prediction = predictor.predict(key, baseline_us, budget_us);
7355            // An unavailable bound supplies no confidence-based action. Defer
7356            // explicitly to the independent measured-budget controller, which
7357            // already ran in next_frame(); do not erase its degradation or
7358            // stop collecting measurements by repeatedly degrading to SkipFrame.
7359            if !predictor.is_calibrated(&prediction) {
7360                debug!(
7361                    bucket = %prediction.bucket,
7362                    sample_count = prediction.sample_count,
7363                    fallback_level = prediction.fallback_level,
7364                    status = prediction.status.as_str(),
7365                    required_rank = prediction.required_rank,
7366                    action = "defer_to_budget_controller",
7367                    "conformal bound unavailable"
7368                );
7369            } else if prediction.risk {
7370                self.budget.degrade();
7371                info!(
7372                    bucket = %prediction.bucket,
7373                    upper_us = ?prediction.upper_us,
7374                    budget_us = prediction.budget_us,
7375                    fallback_level = prediction.fallback_level,
7376                    degradation = self.budget.degradation().as_str(),
7377                    "conformal gate triggered strategy downgrade"
7378                );
7379                debug!(
7380                    monotonic.counter.conformal_gate_triggers_total = 1_u64,
7381                    bucket = %prediction.bucket,
7382                    "conformal gate trigger"
7383                );
7384            }
7385            debug!(
7386                bucket = %prediction.bucket,
7387                upper_us = ?prediction.upper_us,
7388                budget_us = prediction.budget_us,
7389                fallback = prediction.fallback_level,
7390                risk = prediction.risk,
7391                "conformal risk gate"
7392            );
7393            if predictor.is_calibrated(&prediction)
7394                && let Some(quantile) = prediction.quantile
7395            {
7396                debug!(
7397                    monotonic.histogram.conformal_prediction_interval_width_us = quantile.max(0.0),
7398                    bucket = %prediction.bucket,
7399                    "conformal prediction interval width"
7400                );
7401            }
7402            conformal_prediction = Some(prediction);
7403        }
7404
7405        // Early skip if budget says to skip this frame entirely
7406        if self.budget.exhausted() {
7407            self.budget.record_frame_time(Duration::ZERO);
7408            let load_snapshot =
7409                self.update_load_governor_snapshot(frame_idx, 0.0, conformal_prediction.as_ref());
7410            self.emit_budget_evidence(
7411                frame_idx,
7412                degradation_start,
7413                0.0,
7414                conformal_prediction.as_ref(),
7415                &load_snapshot,
7416            );
7417            crate::debug_trace!(
7418                "frame skipped: budget exhausted (degradation={})",
7419                self.budget.degradation().as_str()
7420            );
7421            debug!(
7422                degradation = self.budget.degradation().as_str(),
7423                "frame skipped: budget exhausted before render"
7424            );
7425            // Keep dirty=true: the UI update was never presented, so a
7426            // future frame must still pick it up.
7427            return Ok(());
7428        }
7429
7430        let auto_bounds = self.presenter.inline_auto_bounds();
7431        let needs_measure = auto_bounds.is_some() && self.presenter.auto_ui_height().is_none();
7432        let mut should_measure = needs_measure;
7433        if auto_bounds.is_some()
7434            && let Some(state) = self.inline_auto_remeasure.as_mut()
7435        {
7436            let decision = state.sampler.decide(Instant::now());
7437            // The VOI decision is an evidence event like diff and budget
7438            // decisions: without this line the sampler's reasoning was only
7439            // visible through the in-process telemetry snapshot.
7440            if let Some(ref sink) = self.evidence_sink {
7441                let _ = sink.write_jsonl(&decision.to_jsonl());
7442            }
7443            if decision.should_sample {
7444                should_measure = true;
7445            }
7446        } else {
7447            crate::voi_telemetry::clear_inline_auto_voi_snapshot();
7448        }
7449
7450        // --- Render phase ---
7451        let render_start = Instant::now();
7452        if let (Some((min_height, max_height)), true) = (auto_bounds, should_measure) {
7453            let measure_height = if needs_measure {
7454                self.presenter.render_height_hint().max(1)
7455            } else {
7456                max_height.max(1)
7457            };
7458            let (measure_buffer, _) = self.render_measure_buffer(measure_height);
7459            let measured_height = measure_buffer.content_height();
7460            let clamped = measured_height.clamp(min_height, max_height);
7461            let previous_height = self.presenter.auto_ui_height();
7462            self.presenter.set_auto_ui_height(clamped);
7463            if let Some(state) = self.inline_auto_remeasure.as_mut() {
7464                let threshold = state.config.change_threshold_rows;
7465                let violated = previous_height
7466                    .map(|prev| prev.abs_diff(clamped) >= threshold)
7467                    .unwrap_or(false);
7468                state.sampler.observe(violated);
7469            }
7470        }
7471        if auto_bounds.is_some()
7472            && let Some(state) = self.inline_auto_remeasure.as_ref()
7473        {
7474            let snapshot = state.sampler.snapshot(8, crate::debug_trace::elapsed_ms());
7475            crate::voi_telemetry::set_inline_auto_voi_snapshot(Some(snapshot));
7476        }
7477
7478        let frame_height = self.presenter.render_height_hint().max(1);
7479        let _frame_span = info_span!(
7480            crate::telemetry_schema::span::RENDER_FRAME,
7481            width = self.width,
7482            height = frame_height,
7483            duration_us = tracing::field::Empty
7484        )
7485        .entered();
7486        let (buffer, cursor, cursor_visible) = self.render_buffer(frame_height);
7487        self.process_a11y_frame();
7488        self.update_widget_refresh_plan(frame_idx);
7489        let render_elapsed = render_start.elapsed();
7490        let mut present_elapsed = Duration::ZERO;
7491        let mut presented = false;
7492
7493        // Check if render phase overspent its budget
7494        let render_budget = self.budget.phase_budgets().render;
7495        if render_elapsed > render_budget {
7496            debug!(
7497                render_ms = render_elapsed.as_millis() as u32,
7498                budget_ms = render_budget.as_millis() as u32,
7499                "render phase exceeded budget"
7500            );
7501            // With the load governor active, the controller decides degradation
7502            // from measured frame history at the next frame boundary. The
7503            // legacy path keeps its immediate threshold fallback.
7504            if self.budget.controller().is_none() && self.budget.should_degrade(render_budget) {
7505                self.budget.degrade();
7506            }
7507        }
7508
7509        // --- Present phase ---
7510        if !self.budget.exhausted() {
7511            let present_start = Instant::now();
7512            {
7513                let _present_span =
7514                    debug_span!(crate::telemetry_schema::span::RENDER_PRESENT).entered();
7515                self.presenter
7516                    .present_ui_owned(buffer, cursor, cursor_visible)?;
7517            }
7518            presented = true;
7519            present_elapsed = present_start.elapsed();
7520
7521            let present_budget = self.budget.phase_budgets().present;
7522            if present_elapsed > present_budget {
7523                debug!(
7524                    present_ms = present_elapsed.as_millis() as u32,
7525                    budget_ms = present_budget.as_millis() as u32,
7526                    "present phase exceeded budget"
7527                );
7528            }
7529        } else {
7530            debug!(
7531                degradation = self.budget.degradation().as_str(),
7532                elapsed_ms = self.budget.elapsed().as_millis() as u32,
7533                "frame present skipped: budget exhausted after render"
7534            );
7535        }
7536
7537        if let Some(ref frame_timing) = self.frame_timing {
7538            let update_us = self.last_update_us.unwrap_or(0);
7539            let render_us = render_elapsed.as_micros() as u64;
7540            let present_us = present_elapsed.as_micros() as u64;
7541            let diff_us = if presented {
7542                self.presenter
7543                    .take_last_present_timings()
7544                    .map(|timings| timings.diff_us)
7545                    .unwrap_or(0)
7546            } else {
7547                let _ = self.presenter.take_last_present_timings();
7548                0
7549            };
7550            let total_us = update_us
7551                .saturating_add(render_us)
7552                .saturating_add(present_us);
7553            let timing = FrameTiming {
7554                frame_idx,
7555                update_us,
7556                render_us,
7557                diff_us,
7558                present_us,
7559                total_us,
7560            };
7561            frame_timing.sink.record_frame(&timing);
7562        }
7563
7564        let frame_time = render_elapsed.saturating_add(present_elapsed);
7565        self.budget.record_frame_time(frame_time);
7566        let frame_time_us = frame_time.as_secs_f64() * 1_000_000.0;
7567
7568        if let (Some(predictor), Some(prediction)) = (
7569            self.conformal_predictor.as_mut(),
7570            conformal_prediction.as_ref(),
7571        ) {
7572            let diff_strategy = self
7573                .presenter
7574                .last_diff_strategy()
7575                .unwrap_or(DiffStrategy::Full);
7576            let key = BucketKey::from_context(
7577                self.presenter.screen_mode(),
7578                diff_strategy,
7579                self.width,
7580                frame_height,
7581            );
7582            predictor.observe(key, prediction.y_hat, frame_time_us);
7583        }
7584        self.last_frame_time_us = Some(frame_time_us);
7585        let load_snapshot = self.update_load_governor_snapshot(
7586            frame_idx,
7587            frame_time_us,
7588            conformal_prediction.as_ref(),
7589        );
7590        self.emit_budget_evidence(
7591            frame_idx,
7592            degradation_start,
7593            frame_time_us,
7594            conformal_prediction.as_ref(),
7595            &load_snapshot,
7596        );
7597
7598        // Only clear dirty when the frame was actually presented.
7599        // If present was skipped (budget exhausted after render), the UI
7600        // update was never shown and must be retried on the next frame.
7601        if presented {
7602            self.dirty = false;
7603        }
7604
7605        // Deliver the accessibility hook after the dirty reset so a model
7606        // that changes state in response gets one more frame.
7607        if self.a11y_changed {
7608            self.a11y_changed = false;
7609            self.deliver_a11y_frame()?;
7610        }
7611
7612        Ok(())
7613    }
7614
7615    fn update_load_governor_snapshot(
7616        &mut self,
7617        _frame_idx: u64,
7618        frame_time_us: f64,
7619        conformal_prediction: Option<&ConformalPrediction>,
7620    ) -> LoadGovernorSnapshot {
7621        let budget_us = conformal_prediction
7622            .map(|prediction| prediction.budget_us)
7623            .unwrap_or_else(|| self.budget.total().as_secs_f64() * 1_000_000.0);
7624        let resize_stats = self.resize_coalescer.stats();
7625        self.load_governor.observe(LoadGovernorObservation {
7626            frame_time_us,
7627            budget_us,
7628            degradation: self.budget.degradation(),
7629            queue: crate::effect_system::queue_telemetry(),
7630            // Only meaningful when the coalescer actually runs: in legacy
7631            // Immediate mode `tick_at` never fires, so a single Burst entry
7632            // would otherwise pin the governor at SoftOverload forever.
7633            resize_coalescing_active: self.resize_behavior.uses_coalescer()
7634                && (resize_stats.has_pending
7635                    || !matches!(resize_stats.regime, crate::resize_coalescer::Regime::Steady)),
7636            strict_semantics_violation: false,
7637        })
7638    }
7639
7640    fn emit_budget_evidence(
7641        &self,
7642        frame_idx: u64,
7643        degradation_start: DegradationLevel,
7644        frame_time_us: f64,
7645        conformal_prediction: Option<&ConformalPrediction>,
7646        load_snapshot: &LoadGovernorSnapshot,
7647    ) {
7648        let Some(telemetry) = self.budget.telemetry() else {
7649            set_budget_snapshot(None);
7650            return;
7651        };
7652
7653        let budget_us = conformal_prediction
7654            .map(|prediction| prediction.budget_us)
7655            .unwrap_or_else(|| self.budget.total().as_secs_f64() * 1_000_000.0);
7656        let conformal = conformal_prediction.map(ConformalEvidence::from_prediction);
7657        let degradation_after = self.budget.degradation();
7658
7659        let evidence = BudgetDecisionEvidence {
7660            frame_idx,
7661            decision: BudgetDecisionEvidence::decision_from_levels(
7662                degradation_start,
7663                degradation_after,
7664            ),
7665            controller_decision: telemetry.last_decision,
7666            degradation_before: degradation_start,
7667            degradation_after,
7668            frame_time_us,
7669            budget_us,
7670            pid_output: telemetry.pid_output,
7671            pid_p: telemetry.pid_p,
7672            pid_i: telemetry.pid_i,
7673            pid_d: telemetry.pid_d,
7674            e_value: telemetry.e_value,
7675            frames_observed: telemetry.frames_observed,
7676            frames_since_change: telemetry.frames_since_change,
7677            in_warmup: telemetry.in_warmup,
7678            recovery_streak: telemetry.recovery_streak,
7679            total_degrades: telemetry.total_degrades,
7680            total_recoveries: telemetry.total_recoveries,
7681            controller_reason: telemetry.decision_reason,
7682            load_governor: *load_snapshot,
7683            resize_detector: self.resize_coalescer.last_detector().as_str(),
7684            conformal,
7685        };
7686
7687        let conformal_snapshot = evidence
7688            .conformal
7689            .as_ref()
7690            .map(|snapshot| ConformalSnapshot {
7691                bucket_key: snapshot.bucket_key.clone(),
7692                sample_count: snapshot.n_b,
7693                upper_us: snapshot.upper_us,
7694                risk: snapshot.risk,
7695                status: snapshot.status,
7696                required_rank: snapshot.required_rank,
7697            });
7698        set_budget_snapshot(Some(BudgetDecisionSnapshot {
7699            frame_idx: evidence.frame_idx,
7700            decision: evidence.decision,
7701            controller_decision: evidence.controller_decision,
7702            degradation_before: evidence.degradation_before,
7703            degradation_after: evidence.degradation_after,
7704            frame_time_us: evidence.frame_time_us,
7705            budget_us: evidence.budget_us,
7706            pid_output: evidence.pid_output,
7707            e_value: evidence.e_value,
7708            frames_observed: evidence.frames_observed,
7709            frames_since_change: evidence.frames_since_change,
7710            in_warmup: evidence.in_warmup,
7711            conformal: conformal_snapshot,
7712        }));
7713
7714        if let Some(ref sink) = self.evidence_sink {
7715            let _ = sink.write_jsonl(&evidence.to_jsonl());
7716        }
7717    }
7718
7719    fn update_widget_refresh_plan(&mut self, frame_idx: u64) {
7720        if !self.widget_refresh_config.enabled {
7721            self.widget_refresh_plan.clear();
7722            return;
7723        }
7724
7725        let budget_us = self.budget.phase_budgets().render.as_secs_f64() * 1_000_000.0;
7726        let degradation = self.budget.degradation();
7727        self.widget_refresh_plan.recompute(
7728            frame_idx,
7729            budget_us,
7730            degradation,
7731            &self.widget_signals,
7732            &self.widget_refresh_config,
7733        );
7734
7735        if let Some(ref sink) = self.evidence_sink {
7736            let _ = sink.write_jsonl(&self.widget_refresh_plan.to_jsonl());
7737        }
7738    }
7739
7740    fn render_buffer(&mut self, frame_height: u16) -> (Buffer, Option<(u16, u16)>, bool) {
7741        // Reset the per-frame arena so widgets get fresh scratch space.
7742        self.frame_arena.reset();
7743
7744        // Pin the successful presentation baseline before registering this
7745        // frame's URLs. Also retire links from any abandoned render, since a
7746        // budget decision can skip presentation after model.view has run.
7747        self.presenter.begin_link_frame();
7748
7749        // Note: Frame borrows the pool and links from presenter.
7750        // We scope it so it drops before we call present_ui (which needs exclusive presenter access).
7751        let buffer = self.presenter.take_render_buffer(self.width, frame_height);
7752        let mut a11y_builder = self.a11y_policy.map(|_| A11yTreeBuilder::new());
7753        let (pool, links) = self.presenter.pool_and_links_mut();
7754        let mut frame = Frame::from_buffer(buffer, pool);
7755        frame.set_degradation(self.budget.degradation());
7756        frame.set_links(links);
7757        frame.set_widget_budget(self.widget_refresh_plan.as_budget());
7758        frame.set_arena(&self.frame_arena);
7759        frame.text_direction = self.locale_context.direction().into();
7760        if let Some(builder) = a11y_builder.as_mut() {
7761            frame.set_a11y(builder);
7762        }
7763
7764        let view_start = Instant::now();
7765        let _view_span = debug_span!(
7766            crate::telemetry_schema::span::PROGRAM_VIEW,
7767            duration_us = tracing::field::Empty,
7768            widget_count = tracing::field::Empty
7769        )
7770        .entered();
7771        self.model.view(&mut frame);
7772        self.widget_signals = frame.take_widget_signals();
7773        frame.finish_a11y();
7774        let a11y_order = frame.take_a11y_order();
7775        tracing::Span::current().record("duration_us", view_start.elapsed().as_micros() as u64);
7776        // widget_count would require tracking in Frame
7777
7778        let output = (frame.buffer, frame.cursor_position, frame.cursor_visible);
7779        // `frame` is not used past this point, which releases its borrow of
7780        // the builder so the tree can be built.
7781        self.a11y_pending = a11y_builder.map(|builder| (builder.build(), a11y_order));
7782        output
7783    }
7784
7785    /// Diff the accessibility tree collected by the last `render_buffer`
7786    /// against the previous frame's tree, derive screen-reader
7787    /// announcements, and export their metadata. Full text stays local unless
7788    /// explicitly included in the evidence sink; tracing never contains it.
7789    ///
7790    /// No-op unless `ProgramConfig::accessibility` is set.
7791    fn process_a11y_frame(&mut self) {
7792        let Some(policy) = self.a11y_policy else {
7793            return;
7794        };
7795        let Some((tree, order)) = self.a11y_pending.take() else {
7796            return;
7797        };
7798        let previous = self
7799            .a11y_tree
7800            .take()
7801            .unwrap_or_else(|| A11yTreeBuilder::new().build());
7802        let diff = tree.diff(&previous);
7803        let announcements = diff.screen_reader_announcements(&tree, policy);
7804
7805        if !diff.is_empty() {
7806            tracing::debug!(
7807                target: crate::telemetry_schema::TARGET_A11Y,
7808                frame_idx = self.frame_idx,
7809                nodes = tree.node_count(),
7810                added = diff.added.len(),
7811                removed = diff.removed.len(),
7812                changed = diff.changed.len(),
7813                focus_changed = diff.focus_changed.is_some(),
7814                announcements = announcements.announcements.len(),
7815                dropped = announcements.dropped_count,
7816                "a11y tree changed"
7817            );
7818            if let Some(ref sink) = self.evidence_sink {
7819                let focus = match diff.focus_changed {
7820                    Some((_, Some(id))) => id.to_string(),
7821                    Some((_, None)) | None => "null".to_string(),
7822                };
7823                let _ = sink.write_jsonl(&format!(
7824                    r#"{{"event":"a11y_tree","frame_idx":{},"nodes":{},"added":{},"removed":{},"changed":{},"focus":{},"announcements":{},"dropped":{}}}"#,
7825                    self.frame_idx,
7826                    tree.node_count(),
7827                    diff.added.len(),
7828                    diff.removed.len(),
7829                    diff.changed.len(),
7830                    focus,
7831                    announcements.announcements.len(),
7832                    announcements.dropped_count,
7833                ));
7834                for announcement in &announcements.announcements {
7835                    let node_id = announcement
7836                        .node_id
7837                        .map_or_else(|| "null".to_string(), |id| id.to_string());
7838                    let text = if self.a11y_evidence_text {
7839                        format!(
7840                            "\"{}\"",
7841                            crate::queueing_scheduler::escape_json(&announcement.text)
7842                        )
7843                    } else {
7844                        "null".to_string()
7845                    };
7846                    let _ = sink.write_jsonl(&format!(
7847                        r#"{{"event":"a11y_announcement","frame_idx":{},"node_id":{},"urgency":"{}","reason":"{:?}","text":{},"text_chars":{}}}"#,
7848                        self.frame_idx,
7849                        node_id,
7850                        announcement.urgency,
7851                        announcement.reason,
7852                        text,
7853                        announcement.text.chars().count(),
7854                    ));
7855                }
7856            }
7857        }
7858        for announcement in &announcements.announcements {
7859            tracing::info!(
7860                target: crate::telemetry_schema::TARGET_A11Y,
7861                frame_idx = self.frame_idx,
7862                node_id = announcement.node_id,
7863                urgency = %announcement.urgency,
7864                reason = ?announcement.reason,
7865                text_chars = announcement.text.chars().count(),
7866                "screen reader announcement"
7867            );
7868        }
7869
7870        self.a11y_changed = !diff.is_empty();
7871        self.a11y_dropped = announcements.dropped_count;
7872        self.a11y_announcements = announcements.announcements;
7873        self.a11y_tree = Some(tree);
7874        self.a11y_order = order;
7875    }
7876
7877    /// Hand the last frame's tree to [`Model::on_accessibility`] (called by
7878    /// `render_frame` when `process_a11y_frame` saw a change) and schedule
7879    /// one more frame so state the hook changed gets rendered.
7880    fn deliver_a11y_frame(&mut self) -> io::Result<()> {
7881        let Some(tree) = self.a11y_tree.as_ref() else {
7882            return Ok(());
7883        };
7884        let cmd = {
7885            let _span = debug_span!(
7886                crate::telemetry_schema::span::PROGRAM_UPDATE,
7887                msg_type = "accessibility"
7888            )
7889            .entered();
7890            self.model.on_accessibility(AccessibilityFrame {
7891                frame_idx: self.frame_idx,
7892                tree,
7893                order: &self.a11y_order,
7894                announcements: &self.a11y_announcements,
7895                dropped: self.a11y_dropped,
7896            })
7897        };
7898        self.mark_dirty();
7899        self.execute_cmd(cmd)?;
7900        if self.running {
7901            self.reconcile_subscriptions();
7902        }
7903        Ok(())
7904    }
7905
7906    /// The accessibility tree built from the last rendered frame, or `None`
7907    /// when [`ProgramConfig::accessibility`] is unset or nothing has been
7908    /// rendered yet.
7909    #[must_use]
7910    pub fn accessibility_tree(&self) -> Option<&A11yTree> {
7911        self.a11y_tree.as_ref()
7912    }
7913
7914    /// Reading order (node IDs in widget push order) of the last
7915    /// accessibility tree; empty when accessibility is off.
7916    #[must_use]
7917    pub fn accessibility_order(&self) -> &[u64] {
7918        &self.a11y_order
7919    }
7920
7921    /// Screen-reader announcements derived from the last frame's tree diff
7922    /// (bounded by the configured [`ScreenReaderPolicy`]); empty when the
7923    /// tree did not change in an announceable way.
7924    #[must_use]
7925    pub fn accessibility_announcements(&self) -> &[ScreenReaderAnnouncement] {
7926        &self.a11y_announcements
7927    }
7928
7929    /// Indented, one-node-per-line dump of the last accessibility tree in
7930    /// reading order (see [`A11yTree::dump_text`]); `None` when off.
7931    #[must_use]
7932    pub fn accessibility_dump(&self) -> Option<String> {
7933        self.a11y_tree
7934            .as_ref()
7935            .map(|tree| tree.dump_text(&self.a11y_order))
7936    }
7937
7938    fn emit_fairness_evidence(&mut self, decision: &FairnessDecision, dominance_count: u32) {
7939        let Some(ref sink) = self.evidence_sink else {
7940            return;
7941        };
7942
7943        let config = self.fairness_guard.config();
7944        if !self.fairness_config_logged {
7945            let config_entry = FairnessConfigEvidence {
7946                enabled: config.enabled,
7947                input_priority_threshold_ms: config.input_priority_threshold.as_millis() as u64,
7948                dominance_threshold: config.dominance_threshold,
7949                fairness_threshold: config.fairness_threshold,
7950            };
7951            let _ = sink.write_jsonl(&config_entry.to_jsonl());
7952            self.fairness_config_logged = true;
7953        }
7954
7955        let evidence = FairnessDecisionEvidence {
7956            frame_idx: self.frame_idx,
7957            decision: if decision.should_process {
7958                "allow"
7959            } else {
7960                "yield"
7961            },
7962            reason: decision.reason.as_str(),
7963            pending_input_latency_ms: decision
7964                .pending_input_latency
7965                .map(|latency| latency.as_millis() as u64),
7966            jain_index: decision.jain_index,
7967            resize_dominance_count: dominance_count,
7968            dominance_threshold: config.dominance_threshold,
7969            fairness_threshold: config.fairness_threshold,
7970            input_priority_threshold_ms: config.input_priority_threshold.as_millis() as u64,
7971        };
7972
7973        let _ = sink.write_jsonl(&evidence.to_jsonl());
7974    }
7975
7976    fn render_measure_buffer(&mut self, frame_height: u16) -> (Buffer, Option<(u16, u16)>) {
7977        // Reset the per-frame arena for measurement pass.
7978        self.frame_arena.reset();
7979
7980        let pool = self.presenter.pool_mut();
7981        let mut frame = Frame::new(self.width, frame_height, pool);
7982        frame.set_degradation(self.budget.degradation());
7983        frame.set_arena(&self.frame_arena);
7984        frame.text_direction = self.locale_context.direction().into();
7985
7986        let view_start = Instant::now();
7987        let _view_span = debug_span!(
7988            crate::telemetry_schema::span::PROGRAM_VIEW,
7989            duration_us = tracing::field::Empty,
7990            widget_count = tracing::field::Empty
7991        )
7992        .entered();
7993        self.model.view(&mut frame);
7994        tracing::Span::current().record("duration_us", view_start.elapsed().as_micros() as u64);
7995
7996        (frame.buffer, frame.cursor_position)
7997    }
7998
7999    /// Calculate the effective poll timeout.
8000    fn effective_timeout(&self) -> Duration {
8001        // A full subscription batch may leave a FIFO suffix queued. Poll input
8002        // without sleeping before the next batch, while still returning through
8003        // the normal input, tick, and render work on every iteration.
8004        if self.subscriptions.may_have_pending_messages() {
8005            return Duration::ZERO;
8006        }
8007        if let Some(tick_rate) = self.tick_rate {
8008            let elapsed = self.last_tick.elapsed();
8009            let mut timeout = tick_rate.saturating_sub(elapsed);
8010            if self.resize_behavior.uses_coalescer()
8011                && let Some(resize_timeout) = self.resize_coalescer.time_until_apply(Instant::now())
8012            {
8013                timeout = timeout.min(resize_timeout);
8014            }
8015            timeout
8016        } else {
8017            let mut timeout = self.poll_timeout;
8018            if self.resize_behavior.uses_coalescer()
8019                && let Some(resize_timeout) = self.resize_coalescer.time_until_apply(Instant::now())
8020            {
8021                timeout = timeout.min(resize_timeout);
8022            }
8023            timeout
8024        }
8025    }
8026
8027    /// Check if we should send a tick.
8028    fn should_tick(&mut self) -> bool {
8029        if let Some(tick_rate) = self.tick_rate
8030            && self.last_tick.elapsed() >= tick_rate
8031        {
8032            self.last_tick = Instant::now();
8033            return true;
8034        }
8035        false
8036    }
8037
8038    fn process_resize_coalescer(&mut self) -> io::Result<()> {
8039        if !self.resize_behavior.uses_coalescer() {
8040            return Ok(());
8041        }
8042
8043        // Check fairness: if input is starving, skip resize application this cycle.
8044        // This ensures input events are processed before resize is finalized.
8045        let dominance_count = self.fairness_guard.resize_dominance_count();
8046        let fairness_decision = self.fairness_guard.check_fairness(Instant::now());
8047        self.emit_fairness_evidence(&fairness_decision, dominance_count);
8048        if !fairness_decision.should_process {
8049            debug!(
8050                reason = ?fairness_decision.reason,
8051                pending_latency_ms = fairness_decision.pending_input_latency.map(|d| d.as_millis() as u64),
8052                "Resize yielding to input for fairness"
8053            );
8054            // Skip resize application this cycle to allow input processing.
8055            return Ok(());
8056        }
8057
8058        let action = self.resize_coalescer.tick();
8059        let resize_snapshot =
8060            self.resize_coalescer
8061                .logs()
8062                .last()
8063                .map(|entry| ResizeDecisionSnapshot {
8064                    event_idx: entry.event_idx,
8065                    action: entry.action,
8066                    dt_ms: entry.dt_ms,
8067                    event_rate: entry.event_rate,
8068                    regime: entry.regime,
8069                    pending_size: entry.pending_size,
8070                    applied_size: entry.applied_size,
8071                    time_since_render_ms: entry.time_since_render_ms,
8072                    bocpd: self
8073                        .resize_coalescer
8074                        .bocpd()
8075                        .and_then(|detector| detector.last_evidence().cloned()),
8076                });
8077        set_resize_snapshot(resize_snapshot);
8078
8079        match action {
8080            CoalesceAction::ApplyResize {
8081                width,
8082                height,
8083                coalesce_time,
8084                forced_by_deadline,
8085            } => self.apply_resize(width, height, coalesce_time, forced_by_deadline),
8086            _ => Ok(()),
8087        }
8088    }
8089
8090    fn apply_resize(
8091        &mut self,
8092        width: u16,
8093        height: u16,
8094        coalesce_time: Duration,
8095        forced_by_deadline: bool,
8096    ) -> io::Result<()> {
8097        // Clamp to minimum 1 to prevent Buffer::new panic on zero dimensions
8098        let width = width.max(1);
8099        let height = height.max(1);
8100        self.width = width;
8101        self.height = height;
8102        self.presenter.resize(width, height);
8103        info!(
8104            width = width,
8105            height = height,
8106            coalesce_ms = coalesce_time.as_millis() as u64,
8107            forced = forced_by_deadline,
8108            "Resize applied"
8109        );
8110
8111        let msg = M::Message::from(Event::Resize { width, height });
8112        let start = Instant::now();
8113        let cmd = self.model.update(msg);
8114        let elapsed_us = start.elapsed().as_micros() as u64;
8115        self.last_update_us = Some(elapsed_us);
8116        self.mark_dirty();
8117        self.execute_cmd(cmd)?;
8118        if self.running && self.dirty {
8119            self.reconcile_subscriptions();
8120        }
8121        Ok(())
8122    }
8123
8124    // removed: resize placeholder rendering (continuous reflow preferred)
8125
8126    /// Get a reference to the model.
8127    pub fn model(&self) -> &M {
8128        &self.model
8129    }
8130
8131    /// Get a mutable reference to the model.
8132    pub fn model_mut(&mut self) -> &mut M {
8133        &mut self.model
8134    }
8135
8136    /// Check if the program is running.
8137    pub fn is_running(&self) -> bool {
8138        self.running
8139    }
8140
8141    /// Get the current tick rate, if one has been installed.
8142    #[must_use]
8143    pub const fn tick_rate(&self) -> Option<Duration> {
8144        self.tick_rate
8145    }
8146
8147    /// Get the number of commands actually executed by the runtime.
8148    #[must_use]
8149    pub const fn executed_cmd_count(&self) -> usize {
8150        self.executed_cmd_count
8151    }
8152
8153    /// Request a quit.
8154    pub fn quit(&mut self) {
8155        self.running = false;
8156    }
8157
8158    /// Get a reference to the state registry, if configured.
8159    pub fn state_registry(&self) -> Option<&std::sync::Arc<StateRegistry>> {
8160        self.state_registry.as_ref()
8161    }
8162
8163    /// Check if state persistence is enabled.
8164    pub fn has_persistence(&self) -> bool {
8165        self.state_registry.is_some()
8166    }
8167
8168    /// Query the current tick strategy's debug statistics.
8169    ///
8170    /// Returns key-value pairs describing the strategy's internal state
8171    /// (e.g. strategy name, divisors, confidence, transition counts).
8172    /// Returns an empty vec if no tick strategy is configured.
8173    #[must_use]
8174    pub fn tick_strategy_stats(&self) -> Vec<(String, String)> {
8175        self.tick_strategy
8176            .as_ref()
8177            .map(|s| s.debug_stats())
8178            .unwrap_or_default()
8179    }
8180
8181    /// Trigger a manual save of widget state.
8182    ///
8183    /// Returns the result of the flush operation, or `Ok(false)` if
8184    /// persistence is not configured.
8185    pub fn trigger_save(&mut self) -> StorageResult<bool> {
8186        if let Some(registry) = &self.state_registry {
8187            registry.flush()
8188        } else {
8189            Ok(false)
8190        }
8191    }
8192
8193    /// Trigger a manual load of widget state.
8194    ///
8195    /// Returns the number of entries loaded, or `Ok(0)` if persistence
8196    /// is not configured.
8197    pub fn trigger_load(&mut self) -> StorageResult<usize> {
8198        if let Some(registry) = &self.state_registry {
8199            registry.load()
8200        } else {
8201            Ok(0)
8202        }
8203    }
8204
8205    fn mark_dirty(&mut self) {
8206        self.dirty = true;
8207    }
8208
8209    fn check_locale_change(&mut self) {
8210        let version = self.locale_context.version();
8211        if version != self.locale_version {
8212            self.locale_version = version;
8213            self.mark_dirty();
8214        }
8215    }
8216
8217    /// Mark the UI as needing redraw.
8218    pub fn request_redraw(&mut self) {
8219        self.mark_dirty();
8220    }
8221
8222    /// Request a re-measure of inline auto UI height on next render.
8223    pub fn request_ui_height_remeasure(&mut self) {
8224        if self.presenter.inline_auto_bounds().is_some() {
8225            self.presenter.clear_auto_ui_height();
8226            if let Some(state) = self.inline_auto_remeasure.as_mut() {
8227                state.reset();
8228            }
8229            crate::voi_telemetry::clear_inline_auto_voi_snapshot();
8230            self.mark_dirty();
8231        }
8232    }
8233
8234    /// Start recording events into a macro.
8235    ///
8236    /// If already recording, the current recording is discarded and a new one starts.
8237    /// The current terminal size is captured as metadata.
8238    pub fn start_recording(&mut self, name: impl Into<String>) {
8239        let mut recorder = EventRecorder::new(name).with_terminal_size(self.width, self.height);
8240        recorder.start();
8241        self.event_recorder = Some(recorder);
8242    }
8243
8244    /// Stop recording and return the recorded macro, if any.
8245    ///
8246    /// Returns `None` if not currently recording.
8247    pub fn stop_recording(&mut self) -> Option<InputMacro> {
8248        self.event_recorder.take().map(EventRecorder::finish)
8249    }
8250
8251    /// Check if event recording is active.
8252    pub fn is_recording(&self) -> bool {
8253        self.event_recorder
8254            .as_ref()
8255            .is_some_and(EventRecorder::is_recording)
8256    }
8257}
8258
8259/// Builder for creating and running programs.
8260pub struct App;
8261
8262impl App {
8263    /// Create a new app builder with the given model.
8264    #[allow(clippy::new_ret_no_self)] // App is a namespace for builder methods
8265    pub fn new<M: Model>(model: M) -> AppBuilder<M> {
8266        AppBuilder {
8267            model,
8268            config: ProgramConfig::default(),
8269        }
8270    }
8271
8272    /// Create a fullscreen app.
8273    pub fn fullscreen<M: Model>(model: M) -> AppBuilder<M> {
8274        AppBuilder {
8275            model,
8276            config: ProgramConfig::fullscreen(),
8277        }
8278    }
8279
8280    /// Create an inline app with the given height.
8281    pub fn inline<M: Model>(model: M, height: u16) -> AppBuilder<M> {
8282        AppBuilder {
8283            model,
8284            config: ProgramConfig::inline(height),
8285        }
8286    }
8287
8288    /// Create an inline app with automatic UI height.
8289    pub fn inline_auto<M: Model>(model: M, min_height: u16, max_height: u16) -> AppBuilder<M> {
8290        AppBuilder {
8291            model,
8292            config: ProgramConfig::inline_auto(min_height, max_height),
8293        }
8294    }
8295
8296    /// Create a fullscreen app from a [`StringModel`](crate::string_model::StringModel).
8297    ///
8298    /// This wraps the string model in a [`StringModelAdapter`](crate::string_model::StringModelAdapter)
8299    /// so that `view_string()` output is rendered through the standard kernel pipeline.
8300    pub fn string_model<S: crate::string_model::StringModel>(
8301        model: S,
8302    ) -> AppBuilder<crate::string_model::StringModelAdapter<S>> {
8303        AppBuilder {
8304            model: crate::string_model::StringModelAdapter::new(model),
8305            config: ProgramConfig::fullscreen(),
8306        }
8307    }
8308}
8309
8310/// Builder for configuring and running programs.
8311#[must_use]
8312pub struct AppBuilder<M: Model> {
8313    model: M,
8314    config: ProgramConfig,
8315}
8316
8317impl<M: Model> AppBuilder<M> {
8318    /// Bound hyperlinks per frame and retire URLs no longer displayed.
8319    /// See [`ProgramConfig::hyperlink_limit`] for the ID lifetime contract.
8320    pub fn with_hyperlink_limit(mut self, limit: usize) -> Self {
8321        self.config.hyperlink_limit = Some(limit);
8322        self
8323    }
8324
8325    /// Set the screen mode.
8326    pub fn screen_mode(mut self, mode: ScreenMode) -> Self {
8327        self.config.screen_mode = mode;
8328        self
8329    }
8330
8331    /// Set the UI anchor.
8332    pub fn anchor(mut self, anchor: UiAnchor) -> Self {
8333        self.config.ui_anchor = anchor;
8334        self
8335    }
8336
8337    /// Force mouse capture on.
8338    pub fn with_mouse(mut self) -> Self {
8339        self.config.mouse_capture_policy = MouseCapturePolicy::On;
8340        self
8341    }
8342
8343    /// Set mouse capture policy for this app.
8344    pub fn with_mouse_capture_policy(mut self, policy: MouseCapturePolicy) -> Self {
8345        self.config.mouse_capture_policy = policy;
8346        self
8347    }
8348
8349    /// Force mouse capture enabled/disabled for this app.
8350    pub fn with_mouse_enabled(mut self, enabled: bool) -> Self {
8351        self.config.mouse_capture_policy = if enabled {
8352            MouseCapturePolicy::On
8353        } else {
8354            MouseCapturePolicy::Off
8355        };
8356        self
8357    }
8358
8359    /// Set the frame budget configuration.
8360    pub fn with_budget(mut self, budget: FrameBudgetConfig) -> Self {
8361        self.config.budget = budget;
8362        self
8363    }
8364
8365    /// Set the runtime load-governor configuration.
8366    pub fn with_load_governor(mut self, config: LoadGovernorConfig) -> Self {
8367        self.config.load_governor = config;
8368        self
8369    }
8370
8371    /// Disable the adaptive load governor for this app.
8372    pub fn without_load_governor(mut self) -> Self {
8373        self.config.load_governor = LoadGovernorConfig::disabled();
8374        self
8375    }
8376
8377    /// Set the evidence JSONL sink configuration.
8378    pub fn with_evidence_sink(mut self, config: EvidenceSinkConfig) -> Self {
8379        self.config.evidence_sink = config;
8380        self
8381    }
8382
8383    /// Set the render-trace recorder configuration.
8384    pub fn with_render_trace(mut self, config: RenderTraceConfig) -> Self {
8385        self.config.render_trace = config;
8386        self
8387    }
8388
8389    /// Set the widget refresh selection configuration.
8390    pub fn with_widget_refresh(mut self, config: WidgetRefreshConfig) -> Self {
8391        self.config.widget_refresh = config;
8392        self
8393    }
8394
8395    /// Set the effect queue scheduling configuration.
8396    pub fn with_effect_queue(mut self, config: EffectQueueConfig) -> Self {
8397        self.config.effect_queue = config;
8398        self
8399    }
8400
8401    /// Enable inline auto UI height remeasurement.
8402    pub fn with_inline_auto_remeasure(mut self, config: InlineAutoRemeasureConfig) -> Self {
8403        self.config.inline_auto_remeasure = Some(config);
8404        self
8405    }
8406
8407    /// Disable inline auto UI height remeasurement.
8408    pub fn without_inline_auto_remeasure(mut self) -> Self {
8409        self.config.inline_auto_remeasure = None;
8410        self
8411    }
8412
8413    /// Set the locale context used for rendering.
8414    pub fn with_locale_context(mut self, locale_context: LocaleContext) -> Self {
8415        self.config.locale_context = locale_context;
8416        self
8417    }
8418
8419    /// Set the base locale used for rendering.
8420    pub fn with_locale(mut self, locale: impl Into<crate::locale::Locale>) -> Self {
8421        self.config.locale_context = LocaleContext::new(locale);
8422        self
8423    }
8424
8425    /// Set the resize coalescer configuration.
8426    pub fn resize_coalescer(mut self, config: CoalescerConfig) -> Self {
8427        self.config.resize_coalescer = config;
8428        self
8429    }
8430
8431    /// Set the resize handling behavior.
8432    pub fn resize_behavior(mut self, behavior: ResizeBehavior) -> Self {
8433        self.config.resize_behavior = behavior;
8434        self
8435    }
8436
8437    /// Toggle legacy immediate-resize behavior for migration.
8438    pub fn legacy_resize(mut self, enabled: bool) -> Self {
8439        if enabled {
8440            self.config.resize_behavior = ResizeBehavior::Immediate;
8441        }
8442        self
8443    }
8444
8445    /// Set the tick strategy for selective background screen ticking.
8446    pub fn tick_strategy(mut self, strategy: crate::tick_strategy::TickStrategyKind) -> Self {
8447        self.config.tick_strategy = Some(strategy);
8448        self
8449    }
8450
8451    /// Run the application on the default backend for this build.
8452    ///
8453    /// Selects the native TTY backend on Unix when `native-backend` is
8454    /// compiled, otherwise the Crossterm backend when `crossterm-compat` is
8455    /// compiled (see [`DEFAULT_BACKEND`]). When neither backend feature was
8456    /// compiled this returns an [`io::ErrorKind::Unsupported`] error whose
8457    /// message names the feature to enable ([`NO_BACKEND_MESSAGE`]).
8458    ///
8459    /// A termination signal that ends the run exits the process with
8460    /// `128 + signal` after the terminal has been restored, matching the
8461    /// behavior of [`AppBuilder::run_native`] and [`AppBuilder::run_crossterm`].
8462    pub fn run(self) -> io::Result<()>
8463    where
8464        M::Message: Send + 'static,
8465    {
8466        self.run_default_backend()
8467    }
8468
8469    #[cfg(all(feature = "native-backend", unix))]
8470    fn run_default_backend(self) -> io::Result<()>
8471    where
8472        M::Message: Send + 'static,
8473    {
8474        self.run_native()
8475    }
8476
8477    #[cfg(all(
8478        feature = "crossterm-compat",
8479        not(all(feature = "native-backend", unix))
8480    ))]
8481    fn run_default_backend(self) -> io::Result<()>
8482    where
8483        M::Message: Send + 'static,
8484    {
8485        self.run_crossterm()
8486    }
8487
8488    #[cfg(not(any(all(feature = "native-backend", unix), feature = "crossterm-compat")))]
8489    fn run_default_backend(self) -> io::Result<()>
8490    where
8491        M::Message: Send + 'static,
8492    {
8493        let _ = (self.model, self.config);
8494        Err(io::Error::new(
8495            io::ErrorKind::Unsupported,
8496            NO_BACKEND_MESSAGE,
8497        ))
8498    }
8499
8500    /// Run the application using the Crossterm backend.
8501    #[cfg(feature = "crossterm-compat")]
8502    pub fn run_crossterm(self) -> io::Result<()>
8503    where
8504        M::Message: Send + 'static,
8505    {
8506        finish_run(Program::with_config(self.model, self.config)?)
8507    }
8508
8509    /// Run the application using the Crossterm backend.
8510    ///
8511    /// This build did not enable `crossterm-compat`; use [`AppBuilder::run`]
8512    /// for the default backend.
8513    #[cfg(not(feature = "crossterm-compat"))]
8514    pub fn run_crossterm(self) -> io::Result<()>
8515    where
8516        M::Message: Send + 'static,
8517    {
8518        let _ = (self.model, self.config);
8519        Err(io::Error::new(
8520            io::ErrorKind::Unsupported,
8521            "enable `crossterm-compat` feature to use AppBuilder::run_crossterm()",
8522        ))
8523    }
8524
8525    /// Run the application using the native TTY backend.
8526    #[cfg(all(feature = "native-backend", unix))]
8527    pub fn run_native(self) -> io::Result<()>
8528    where
8529        M::Message: Send + 'static,
8530    {
8531        finish_run(Program::with_native_backend(self.model, self.config)?)
8532    }
8533
8534    /// Run the application using the native TTY backend.
8535    ///
8536    /// On non-Unix targets the native backend is unavailable; call
8537    /// [`AppBuilder::run`] (which selects Crossterm there) instead.
8538    #[cfg(any(not(feature = "native-backend"), not(unix)))]
8539    pub fn run_native(self) -> io::Result<()>
8540    where
8541        M::Message: Send + 'static,
8542    {
8543        let _ = (self.model, self.config);
8544        // Prefer the platform-level message: a Windows user without
8545        // `native-backend` enabled would otherwise be told to enable the
8546        // feature, only to discover after rebuilding that it's still
8547        // Unix-only. Pointing them at run() up front avoids the two-step debug.
8548        #[cfg(not(unix))]
8549        let msg = "AppBuilder::run_native() is Unix-only; use AppBuilder::run() on this platform";
8550        #[cfg(all(unix, not(feature = "native-backend")))]
8551        let msg = "enable `native-backend` feature to use AppBuilder::run_native()";
8552        Err(io::Error::new(io::ErrorKind::Unsupported, msg))
8553    }
8554}
8555
8556// =============================================================================
8557// Adaptive Batch Window: Queueing Model (bd-4kq0.8.1)
8558// =============================================================================
8559//
8560// # M/G/1 Queueing Model for Event Batching
8561//
8562// ## Problem
8563//
8564// The event loop must balance two objectives:
8565// 1. **Low latency**: Process events quickly (small batch window ฯ„).
8566// 2. **Efficiency**: Batch multiple events to amortize render cost (large ฯ„).
8567//
8568// ## Model
8569//
8570// We model the event loop as an M/G/1 queue:
8571// - Events arrive at rate ฮป (Poisson process, reasonable for human input).
8572// - Service time S has mean E[S] and variance Var[S] (render + present).
8573// - Utilization ฯ = ฮปยทE[S] must be < 1 for stability.
8574//
8575// ## Pollaczekโ€“Khinchine Mean Waiting Time
8576//
8577// For M/G/1: E[W] = (ฮปยทE[Sยฒ]) / (2ยท(1 โˆ’ ฯ))
8578// where E[Sยฒ] = Var[S] + E[S]ยฒ.
8579//
8580// ## Optimal Batch Window ฯ„
8581//
8582// With batching window ฯ„, we collect ~(ฮปยทฯ„) events per batch, amortizing
8583// the per-frame render cost. The effective per-event latency is:
8584//
8585//   L(ฯ„) = ฯ„/2 + E[S]
8586//         (waiting in batch)  (service)
8587//
8588// The batch reduces arrival rate to ฮป_eff = 1/ฯ„ (one batch per window),
8589// giving utilization ฯ_eff = E[S]/ฯ„.
8590//
8591// Minimizing L(ฯ„) subject to ฯ_eff < 1:
8592//   L(ฯ„) = ฯ„/2 + E[S]
8593//   dL/dฯ„ = 1/2  (always positive, so smaller ฯ„ is always better for latency)
8594//
8595// But we need ฯ_eff < 1, so ฯ„ > E[S].
8596//
8597// The practical rule: ฯ„ = max(E[S] ยท headroom_factor, ฯ„_min)
8598// where headroom_factor provides margin (typically 1.5โ€“2.0).
8599//
8600// For high arrival rates: ฯ„ = max(E[S] ยท headroom, 1/ฮป_target)
8601// where ฮป_target is the max frame rate we want to sustain.
8602//
8603// ## Failure Modes
8604//
8605// 1. **Overload (ฯ โ‰ฅ 1)**: Queue grows unbounded. Mitigation: increase ฯ„
8606//    (degrade to lower frame rate), or drop stale events.
8607// 2. **Bursty arrivals**: Real input is bursty (typing, mouse drag). The
8608//    exponential moving average of ฮป smooths this; high burst periods
8609//    temporarily increase ฯ„.
8610// 3. **Variable service time**: Render complexity varies per frame. Using
8611//    EMA of E[S] tracks this adaptively.
8612//
8613// ## Observable Telemetry
8614//
8615// - ฮป_est: Exponential moving average of inter-arrival times.
8616// - es_est: Exponential moving average of service (render) times.
8617// - ฯ_est: ฮป_est ร— es_est (estimated utilization).
8618
8619/// Adaptive batch window controller based on M/G/1 queueing model.
8620///
8621/// Estimates arrival rate ฮป and service time `E[S]` from observations,
8622/// then computes the optimal batch window ฯ„ to maintain stability
8623/// (ฯ < 1) while minimizing latency.
8624#[derive(Debug, Clone)]
8625pub struct BatchController {
8626    /// Exponential moving average of inter-arrival time (seconds).
8627    ema_inter_arrival_s: f64,
8628    /// Exponential moving average of service time (seconds).
8629    ema_service_s: f64,
8630    /// EMA smoothing factor (0..1). Higher = more responsive.
8631    alpha: f64,
8632    /// Minimum batch window (floor).
8633    tau_min_s: f64,
8634    /// Maximum batch window (cap for responsiveness).
8635    tau_max_s: f64,
8636    /// Headroom factor: ฯ„ >= E[S] ร— headroom to keep ฯ < 1.
8637    headroom: f64,
8638    /// Last event arrival timestamp.
8639    last_arrival: Option<Instant>,
8640    /// Number of observations.
8641    observations: u64,
8642}
8643
8644impl BatchController {
8645    /// Create a new controller with sensible defaults.
8646    ///
8647    /// - `alpha`: EMA smoothing (default 0.2)
8648    /// - `tau_min`: minimum batch window (default 1ms)
8649    /// - `tau_max`: maximum batch window (default 50ms)
8650    /// - `headroom`: stability margin (default 2.0, keeps ฯ โ‰ค 0.5)
8651    pub fn new() -> Self {
8652        Self {
8653            ema_inter_arrival_s: 0.1, // assume 10 events/sec initially
8654            ema_service_s: 0.002,     // assume 2ms render initially
8655            alpha: 0.2,
8656            tau_min_s: 0.001, // 1ms floor
8657            tau_max_s: 0.050, // 50ms cap
8658            headroom: 2.0,
8659            last_arrival: None,
8660            observations: 0,
8661        }
8662    }
8663
8664    /// Record an event arrival, updating the inter-arrival estimate.
8665    pub fn observe_arrival(&mut self, now: Instant) {
8666        if let Some(last) = self.last_arrival {
8667            let dt = now.saturating_duration_since(last).as_secs_f64();
8668            if dt > 0.0 && dt < 10.0 {
8669                // Guard against stale gaps (e.g., app was suspended)
8670                self.ema_inter_arrival_s =
8671                    self.alpha * dt + (1.0 - self.alpha) * self.ema_inter_arrival_s;
8672                self.observations += 1;
8673            }
8674        }
8675        self.last_arrival = Some(now);
8676    }
8677
8678    /// Record a service (render) time observation.
8679    pub fn observe_service(&mut self, duration: Duration) {
8680        let dt = duration.as_secs_f64();
8681        if (0.0..10.0).contains(&dt) {
8682            self.ema_service_s = self.alpha * dt + (1.0 - self.alpha) * self.ema_service_s;
8683        }
8684    }
8685
8686    /// Estimated arrival rate ฮป (events/second).
8687    #[inline]
8688    pub fn lambda_est(&self) -> f64 {
8689        if self.ema_inter_arrival_s > 0.0 {
8690            1.0 / self.ema_inter_arrival_s
8691        } else {
8692            0.0
8693        }
8694    }
8695
8696    /// Estimated service time `E[S]` (seconds).
8697    #[inline]
8698    pub fn service_est_s(&self) -> f64 {
8699        self.ema_service_s
8700    }
8701
8702    /// Estimated utilization ฯ = ฮป ร— `E[S]`.
8703    #[inline]
8704    pub fn rho_est(&self) -> f64 {
8705        self.lambda_est() * self.ema_service_s
8706    }
8707
8708    /// Compute the optimal batch window ฯ„ (seconds).
8709    ///
8710    /// ฯ„ = clamp(`E[S]` ร— headroom, ฯ„_min, ฯ„_max)
8711    ///
8712    /// When ฯ approaches 1, ฯ„ increases to maintain stability.
8713    pub fn tau_s(&self) -> f64 {
8714        let base = self.ema_service_s * self.headroom;
8715        base.clamp(self.tau_min_s, self.tau_max_s)
8716    }
8717
8718    /// Compute the optimal batch window as a Duration.
8719    pub fn tau(&self) -> Duration {
8720        Duration::from_secs_f64(self.tau_s())
8721    }
8722
8723    /// Check if the system is stable (ฯ < 1).
8724    #[inline]
8725    pub fn is_stable(&self) -> bool {
8726        self.rho_est() < 1.0
8727    }
8728
8729    /// Number of observations recorded.
8730    #[inline]
8731    pub fn observations(&self) -> u64 {
8732        self.observations
8733    }
8734}
8735
8736impl Default for BatchController {
8737    fn default() -> Self {
8738        Self::new()
8739    }
8740}
8741
8742#[cfg(test)]
8743mod tests {
8744    use super::*;
8745    use ftui_core::terminal_capabilities::TerminalCapabilities;
8746    use ftui_layout::PaneDragResizeEffect;
8747    use ftui_render::buffer::Buffer;
8748    use ftui_render::cell::Cell;
8749    use ftui_render::diff_strategy::DiffStrategy;
8750    use ftui_render::frame::CostEstimateSource;
8751    use ftui_render::frame_guardrails::{MemoryBudgetConfig, QueueConfig};
8752    use serde_json::Value;
8753    use std::collections::{HashMap, VecDeque};
8754    use std::io::Write;
8755    use std::path::PathBuf;
8756    use std::sync::mpsc;
8757    use std::sync::{
8758        Arc,
8759        atomic::{AtomicUsize, Ordering},
8760    };
8761
8762    // Simple test model
8763    struct TestModel {
8764        value: i32,
8765    }
8766
8767    #[derive(Debug)]
8768    enum TestMsg {
8769        Increment,
8770        Decrement,
8771        Quit,
8772    }
8773
8774    impl From<Event> for TestMsg {
8775        fn from(_event: Event) -> Self {
8776            TestMsg::Increment
8777        }
8778    }
8779
8780    impl Model for TestModel {
8781        type Message = TestMsg;
8782
8783        fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
8784            match msg {
8785                TestMsg::Increment => {
8786                    self.value += 1;
8787                    Cmd::none()
8788                }
8789                TestMsg::Decrement => {
8790                    self.value -= 1;
8791                    Cmd::none()
8792                }
8793                TestMsg::Quit => Cmd::quit(),
8794            }
8795        }
8796
8797        fn view(&self, _frame: &mut Frame) {
8798            // No-op for tests
8799        }
8800    }
8801
8802    #[test]
8803    fn cmd_none() {
8804        let cmd: Cmd<TestMsg> = Cmd::none();
8805        assert!(matches!(cmd, Cmd::None));
8806    }
8807
8808    #[test]
8809    fn cmd_quit() {
8810        let cmd: Cmd<TestMsg> = Cmd::quit();
8811        assert!(matches!(cmd, Cmd::Quit));
8812    }
8813
8814    #[test]
8815    fn cmd_msg() {
8816        let cmd: Cmd<TestMsg> = Cmd::msg(TestMsg::Increment);
8817        assert!(matches!(cmd, Cmd::Msg(TestMsg::Increment)));
8818    }
8819
8820    #[test]
8821    fn cmd_batch_empty() {
8822        let cmd: Cmd<TestMsg> = Cmd::batch(vec![]);
8823        assert!(matches!(cmd, Cmd::None));
8824    }
8825
8826    #[test]
8827    fn cmd_batch_single() {
8828        let cmd: Cmd<TestMsg> = Cmd::batch(vec![Cmd::quit()]);
8829        assert!(matches!(cmd, Cmd::Quit));
8830    }
8831
8832    #[test]
8833    fn cmd_batch_multiple() {
8834        let cmd: Cmd<TestMsg> = Cmd::batch(vec![Cmd::none(), Cmd::quit()]);
8835        assert!(matches!(cmd, Cmd::Batch(_)));
8836    }
8837
8838    #[test]
8839    fn cmd_sequence_empty() {
8840        let cmd: Cmd<TestMsg> = Cmd::sequence(vec![]);
8841        assert!(matches!(cmd, Cmd::None));
8842    }
8843
8844    #[test]
8845    fn cmd_tick() {
8846        let cmd: Cmd<TestMsg> = Cmd::tick(Duration::from_millis(100));
8847        assert!(matches!(cmd, Cmd::Tick(_)));
8848    }
8849
8850    #[test]
8851    fn cmd_task() {
8852        let cmd: Cmd<TestMsg> = Cmd::task(|| TestMsg::Increment);
8853        assert!(matches!(cmd, Cmd::Task(..)));
8854    }
8855
8856    #[test]
8857    fn cmd_debug_format() {
8858        let cmd: Cmd<TestMsg> = Cmd::task(|| TestMsg::Increment);
8859        let debug = format!("{cmd:?}");
8860        assert_eq!(
8861            debug,
8862            "Task { spec: TaskSpec { weight: 1.0, estimate_ms: 10.0, name: None } }"
8863        );
8864    }
8865
8866    #[test]
8867    fn model_subscriptions_default_empty() {
8868        let model = TestModel { value: 0 };
8869        let subs = model.subscriptions();
8870        assert!(subs.is_empty());
8871    }
8872
8873    #[test]
8874    fn program_config_default() {
8875        let config = ProgramConfig::default();
8876        assert!(matches!(config.screen_mode, ScreenMode::Inline { .. }));
8877        assert_eq!(config.mouse_capture_policy, MouseCapturePolicy::Auto);
8878        assert!(!config.resolved_mouse_capture());
8879        assert!(config.bracketed_paste);
8880        assert_eq!(config.resize_behavior, ResizeBehavior::Throttled);
8881        assert!(config.inline_auto_remeasure.is_none());
8882        let conformal = config
8883            .conformal_config
8884            .as_ref()
8885            .expect("conformal frame-time gating is on by default");
8886        assert_eq!(conformal.min_samples, 20, "warm-up before any gating");
8887        assert!(
8888            ProgramConfig::default()
8889                .without_conformal()
8890                .conformal_config
8891                .is_none()
8892        );
8893        assert!(config.diff_config.bayesian_enabled);
8894        assert!(config.diff_config.dirty_rows_enabled);
8895        assert!(
8896            !config.resize_coalescer.enable_bocpd,
8897            "the rate heuristic is the default resize regime detector (bd-h8l3d)"
8898        );
8899        assert!(config.resize_coalescer.heuristic_fallback);
8900        assert!(!config.effect_queue.enabled);
8901        assert_eq!(config.immediate_drain.max_zero_timeout_polls_per_burst, 64);
8902        assert_eq!(
8903            config.immediate_drain.max_burst_duration,
8904            Duration::from_millis(2)
8905        );
8906        assert_eq!(
8907            config.immediate_drain.backoff_timeout,
8908            Duration::from_millis(1)
8909        );
8910        assert_eq!(
8911            config.resize_coalescer.steady_delay_ms,
8912            CoalescerConfig::default().steady_delay_ms
8913        );
8914    }
8915
8916    #[test]
8917    fn program_config_with_immediate_drain() {
8918        let custom = ImmediateDrainConfig {
8919            max_zero_timeout_polls_per_burst: 7,
8920            max_burst_duration: Duration::from_millis(9),
8921            backoff_timeout: Duration::from_millis(3),
8922        };
8923        let config = ProgramConfig::default().with_immediate_drain(custom.clone());
8924        assert_eq!(
8925            config.immediate_drain.max_zero_timeout_polls_per_burst,
8926            custom.max_zero_timeout_polls_per_burst
8927        );
8928        assert_eq!(
8929            config.immediate_drain.max_burst_duration,
8930            custom.max_burst_duration
8931        );
8932        assert_eq!(
8933            config.immediate_drain.backoff_timeout,
8934            custom.backoff_timeout
8935        );
8936    }
8937
8938    #[test]
8939    fn program_config_fullscreen() {
8940        let config = ProgramConfig::fullscreen();
8941        assert!(matches!(config.screen_mode, ScreenMode::AltScreen));
8942    }
8943
8944    #[test]
8945    fn program_config_inline() {
8946        let config = ProgramConfig::inline(10);
8947        assert!(matches!(
8948            config.screen_mode,
8949            ScreenMode::Inline { ui_height: 10 }
8950        ));
8951    }
8952
8953    #[test]
8954    fn program_config_inline_auto() {
8955        let config = ProgramConfig::inline_auto(3, 9);
8956        assert!(matches!(
8957            config.screen_mode,
8958            ScreenMode::InlineAuto {
8959                min_height: 3,
8960                max_height: 9
8961            }
8962        ));
8963        assert!(config.inline_auto_remeasure.is_some());
8964    }
8965
8966    #[test]
8967    fn program_config_with_mouse() {
8968        let config = ProgramConfig::default().with_mouse();
8969        assert_eq!(config.mouse_capture_policy, MouseCapturePolicy::On);
8970        assert!(config.resolved_mouse_capture());
8971    }
8972
8973    #[cfg(feature = "native-backend")]
8974    #[test]
8975    fn sanitize_backend_features_disables_unsupported_features() {
8976        let requested = BackendFeatures {
8977            mouse_capture: true,
8978            bracketed_paste: true,
8979            focus_events: true,
8980            kitty_keyboard: true,
8981        };
8982        let sanitized =
8983            sanitize_backend_features_for_capabilities(requested, &TerminalCapabilities::basic());
8984        assert_eq!(sanitized, BackendFeatures::default());
8985    }
8986
8987    #[cfg(feature = "native-backend")]
8988    #[test]
8989    fn sanitize_backend_features_is_conservative_in_wezterm_mux() {
8990        let requested = BackendFeatures {
8991            mouse_capture: true,
8992            bracketed_paste: true,
8993            focus_events: true,
8994            kitty_keyboard: true,
8995        };
8996        let caps = TerminalCapabilities::builder()
8997            .mouse_sgr(true)
8998            .bracketed_paste(true)
8999            .focus_events(true)
9000            .kitty_keyboard(true)
9001            .in_wezterm_mux(true)
9002            .build();
9003        let sanitized = sanitize_backend_features_for_capabilities(requested, &caps);
9004
9005        assert!(sanitized.mouse_capture);
9006        assert!(sanitized.bracketed_paste);
9007        assert!(!sanitized.focus_events);
9008        assert!(!sanitized.kitty_keyboard);
9009    }
9010
9011    #[cfg(feature = "native-backend")]
9012    #[test]
9013    fn sanitize_backend_features_is_conservative_in_tmux() {
9014        let requested = BackendFeatures {
9015            mouse_capture: true,
9016            bracketed_paste: true,
9017            focus_events: true,
9018            kitty_keyboard: true,
9019        };
9020        let caps = TerminalCapabilities::builder()
9021            .mouse_sgr(true)
9022            .bracketed_paste(true)
9023            .focus_events(true)
9024            .kitty_keyboard(true)
9025            .in_tmux(true)
9026            .build();
9027        let sanitized = sanitize_backend_features_for_capabilities(requested, &caps);
9028
9029        assert!(sanitized.mouse_capture);
9030        assert!(sanitized.bracketed_paste);
9031        assert!(!sanitized.focus_events);
9032        assert!(!sanitized.kitty_keyboard);
9033    }
9034
9035    #[test]
9036    fn program_config_mouse_policy_auto_altscreen() {
9037        let config = ProgramConfig::fullscreen();
9038        assert_eq!(config.mouse_capture_policy, MouseCapturePolicy::Auto);
9039        assert!(config.resolved_mouse_capture());
9040    }
9041
9042    #[test]
9043    fn program_config_mouse_policy_force_off() {
9044        let config = ProgramConfig::fullscreen().with_mouse_capture_policy(MouseCapturePolicy::Off);
9045        assert_eq!(config.mouse_capture_policy, MouseCapturePolicy::Off);
9046        assert!(!config.resolved_mouse_capture());
9047    }
9048
9049    #[test]
9050    fn program_config_mouse_policy_force_on_inline() {
9051        let config = ProgramConfig::inline(6).with_mouse_enabled(true);
9052        assert_eq!(config.mouse_capture_policy, MouseCapturePolicy::On);
9053        assert!(config.resolved_mouse_capture());
9054    }
9055
9056    fn pane_target(axis: SplitAxis) -> PaneResizeTarget {
9057        PaneResizeTarget {
9058            split_id: ftui_layout::PaneId::MIN,
9059            axis,
9060        }
9061    }
9062
9063    fn pane_id(raw: u64) -> ftui_layout::PaneId {
9064        ftui_layout::PaneId::new(raw).expect("test pane id must be non-zero")
9065    }
9066
9067    fn nested_pane_tree() -> ftui_layout::PaneTree {
9068        let root = pane_id(1);
9069        let left = pane_id(2);
9070        let right_split = pane_id(3);
9071        let right_top = pane_id(4);
9072        let right_bottom = pane_id(5);
9073        let snapshot = ftui_layout::PaneTreeSnapshot {
9074            schema_version: ftui_layout::PANE_TREE_SCHEMA_VERSION,
9075            root,
9076            next_id: pane_id(6),
9077            nodes: vec![
9078                ftui_layout::PaneNodeRecord::split(
9079                    root,
9080                    None,
9081                    ftui_layout::PaneSplit {
9082                        axis: SplitAxis::Horizontal,
9083                        ratio: ftui_layout::PaneSplitRatio::new(1, 1).expect("valid ratio"),
9084                        first: left,
9085                        second: right_split,
9086                    },
9087                ),
9088                ftui_layout::PaneNodeRecord::leaf(
9089                    left,
9090                    Some(root),
9091                    ftui_layout::PaneLeaf::new("left"),
9092                ),
9093                ftui_layout::PaneNodeRecord::split(
9094                    right_split,
9095                    Some(root),
9096                    ftui_layout::PaneSplit {
9097                        axis: SplitAxis::Vertical,
9098                        ratio: ftui_layout::PaneSplitRatio::new(1, 1).expect("valid ratio"),
9099                        first: right_top,
9100                        second: right_bottom,
9101                    },
9102                ),
9103                ftui_layout::PaneNodeRecord::leaf(
9104                    right_top,
9105                    Some(right_split),
9106                    ftui_layout::PaneLeaf::new("right_top"),
9107                ),
9108                ftui_layout::PaneNodeRecord::leaf(
9109                    right_bottom,
9110                    Some(right_split),
9111                    ftui_layout::PaneLeaf::new("right_bottom"),
9112                ),
9113            ],
9114            extensions: std::collections::BTreeMap::new(),
9115        };
9116        ftui_layout::PaneTree::from_snapshot(snapshot).expect("valid nested pane tree")
9117    }
9118
9119    /// First-child share (in basis points) of a split node's ratio.
9120    fn root_first_share_bps(tree: &ftui_layout::PaneTree, split: ftui_layout::PaneId) -> u32 {
9121        match &tree.node(split).expect("split node present").kind {
9122            PaneNodeKind::Split(node) => {
9123                node.ratio.numerator() * 10_000
9124                    / (node.ratio.numerator() + node.ratio.denominator())
9125            }
9126            other => panic!("expected split node, got {other:?}"),
9127        }
9128    }
9129
9130    /// A fixed, timing-independent pressure-snap profile for deterministic tests.
9131    fn fixed_neutral_pressure() -> PanePressureSnapProfile {
9132        PanePressureSnapProfile {
9133            strength_bps: 5_000,
9134            hysteresis_bps: 100,
9135        }
9136    }
9137
9138    /// Apply a terminal dispatch's geometry-bearing transition to the live tree
9139    /// using a fixed, caller-supplied pressure profile.
9140    ///
9141    /// Unlike the realistic path (which derives pressure from pointer motion and
9142    /// therefore from wall-clock `speed`), this helper always uses `pressure`, so
9143    /// repeated runs of the same scripted event sequence are byte-for-byte
9144    /// deterministic. Returns the number of operations applied.
9145    fn apply_dispatch_fixed(
9146        tree: &mut ftui_layout::PaneTree,
9147        layout: &ftui_layout::PaneLayout,
9148        dispatch: &PaneTerminalDispatch,
9149        pressure: PanePressureSnapProfile,
9150        seed: &mut u64,
9151    ) -> usize {
9152        let Some(transition) = dispatch.primary_transition.as_ref() else {
9153            return 0;
9154        };
9155        let ops = tree.operations_for_transition(transition, layout, pressure);
9156        let applied = ops.len();
9157        for op in ops {
9158            tree.apply_operation(*seed, op).expect("operation applies");
9159            *seed += 1;
9160        }
9161        applied
9162    }
9163
9164    /// Drive a full scripted horizontal splitter drag through the live
9165    /// adapter -> bridge -> tree path with a fixed pressure profile. Press at
9166    /// `down_x`, then send Drag events for every position in `drag_xs` except the
9167    /// last, which is sent as the release (Up). Pointer x must increase across
9168    /// samples (the adapter tracks magnitude via saturating deltas). Returns the
9169    /// number of operations applied.
9170    #[allow(clippy::too_many_arguments)]
9171    fn drive_horizontal_drag_fixed(
9172        adapter: &mut PaneTerminalAdapter,
9173        tree: &mut ftui_layout::PaneTree,
9174        layout: &ftui_layout::PaneLayout,
9175        target: PaneResizeTarget,
9176        down_x: u16,
9177        y: u16,
9178        drag_xs: &[u16],
9179        pressure: PanePressureSnapProfile,
9180        seed: &mut u64,
9181    ) -> usize {
9182        let down = Event::Mouse(MouseEvent::new(
9183            MouseEventKind::Down(MouseButton::Left),
9184            down_x,
9185            y,
9186        ));
9187        let mut applied = apply_dispatch_fixed(
9188            tree,
9189            layout,
9190            &adapter.translate(&down, Some(target)),
9191            pressure,
9192            seed,
9193        );
9194
9195        let last = drag_xs.len().saturating_sub(1);
9196        for (idx, &x) in drag_xs.iter().enumerate() {
9197            let kind = if idx == last {
9198                MouseEventKind::Up(MouseButton::Left)
9199            } else {
9200                MouseEventKind::Drag(MouseButton::Left)
9201            };
9202            let event = Event::Mouse(MouseEvent::new(kind, x, y));
9203            applied += apply_dispatch_fixed(
9204                tree,
9205                layout,
9206                &adapter.translate(&event, None),
9207                pressure,
9208                seed,
9209            );
9210        }
9211        applied
9212    }
9213
9214    #[test]
9215    fn pane_terminal_splitter_resolution_is_deterministic() {
9216        let tree = nested_pane_tree();
9217        let layout = tree
9218            .solve_layout(Rect::new(0, 0, 50, 20))
9219            .expect("layout should solve");
9220        let handles = pane_terminal_splitter_handles(&tree, &layout, 3);
9221        assert_eq!(handles.len(), 2);
9222
9223        // Intersection between root vertical splitter and right-side horizontal
9224        // splitter deterministically resolves to smaller split ID.
9225        let overlap = pane_terminal_resolve_splitter_target(&handles, 25, 10)
9226            .expect("overlap cell should resolve");
9227        assert_eq!(overlap.split_id, pane_id(1));
9228        assert_eq!(overlap.axis, SplitAxis::Horizontal);
9229
9230        let right_only = pane_terminal_resolve_splitter_target(&handles, 40, 10)
9231            .expect("right split should resolve");
9232        assert_eq!(right_only.split_id, pane_id(3));
9233        assert_eq!(right_only.axis, SplitAxis::Vertical);
9234    }
9235
9236    #[test]
9237    fn pane_terminal_splitter_hits_register_and_decode_target() {
9238        let tree = nested_pane_tree();
9239        let layout = tree
9240            .solve_layout(Rect::new(0, 0, 50, 20))
9241            .expect("layout should solve");
9242        let handles = pane_terminal_splitter_handles(&tree, &layout, 3);
9243
9244        let mut pool = ftui_render::grapheme_pool::GraphemePool::new();
9245        let mut frame = Frame::with_hit_grid(50, 20, &mut pool);
9246        let registered = register_pane_terminal_splitter_hits(&mut frame, &handles, 9_000);
9247        assert_eq!(registered, handles.len());
9248
9249        let root_hit = frame
9250            .hit_test(25, 2)
9251            .expect("root splitter should be hittable");
9252        assert_eq!(root_hit.1, HitRegion::Handle);
9253        let root_target = pane_terminal_target_from_hit(root_hit).expect("target from hit");
9254        assert_eq!(root_target.split_id, pane_id(1));
9255        assert_eq!(root_target.axis, SplitAxis::Horizontal);
9256
9257        let right_hit = frame
9258            .hit_test(40, 10)
9259            .expect("right splitter should be hittable");
9260        assert_eq!(right_hit.1, HitRegion::Handle);
9261        let right_target = pane_terminal_target_from_hit(right_hit).expect("target from hit");
9262        assert_eq!(right_target.split_id, pane_id(3));
9263        assert_eq!(right_target.axis, SplitAxis::Vertical);
9264    }
9265
9266    #[test]
9267    fn pane_terminal_adapter_maps_basic_drag_lifecycle() {
9268        let mut adapter =
9269            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
9270        let target = pane_target(SplitAxis::Horizontal);
9271
9272        let down = Event::Mouse(MouseEvent::new(
9273            MouseEventKind::Down(MouseButton::Left),
9274            10,
9275            4,
9276        ));
9277        let down_dispatch = adapter.translate(&down, Some(target));
9278        let down_event = down_dispatch
9279            .primary_event
9280            .as_ref()
9281            .expect("pointer down semantic event");
9282        assert_eq!(down_event.sequence, 1);
9283        assert!(matches!(
9284            down_event.kind,
9285            PaneSemanticInputEventKind::PointerDown {
9286                target: actual_target,
9287                pointer_id: 1,
9288                button: PanePointerButton::Primary,
9289                position
9290            } if actual_target == target && position == PanePointerPosition::new(10, 4)
9291        ));
9292        assert!(down_event.validate().is_ok());
9293
9294        let drag = Event::Mouse(MouseEvent::new(
9295            MouseEventKind::Drag(MouseButton::Left),
9296            14,
9297            4,
9298        ));
9299        let drag_dispatch = adapter.translate(&drag, None);
9300        let drag_event = drag_dispatch
9301            .primary_event
9302            .as_ref()
9303            .expect("pointer move semantic event");
9304        assert_eq!(drag_event.sequence, 2);
9305        assert!(matches!(
9306            drag_event.kind,
9307            PaneSemanticInputEventKind::PointerMove {
9308                target: actual_target,
9309                pointer_id: 1,
9310                position,
9311                delta_x: 4,
9312                delta_y: 0
9313            } if actual_target == target && position == PanePointerPosition::new(14, 4)
9314        ));
9315        let drag_motion = drag_dispatch
9316            .motion
9317            .expect("drag should emit motion metadata");
9318        assert_eq!(drag_motion.delta_x, 4);
9319        assert_eq!(drag_motion.delta_y, 0);
9320        assert_eq!(drag_motion.direction_changes, 0);
9321        assert!(drag_motion.speed > 0.0);
9322        assert!(drag_dispatch.pressure_snap_profile().is_some());
9323
9324        let up = Event::Mouse(MouseEvent::new(
9325            MouseEventKind::Up(MouseButton::Left),
9326            14,
9327            4,
9328        ));
9329        let up_dispatch = adapter.translate(&up, None);
9330        let up_event = up_dispatch
9331            .primary_event
9332            .as_ref()
9333            .expect("pointer up semantic event");
9334        assert_eq!(up_event.sequence, 3);
9335        assert!(matches!(
9336            up_event.kind,
9337            PaneSemanticInputEventKind::PointerUp {
9338                target: actual_target,
9339                pointer_id: 1,
9340                button: PanePointerButton::Primary,
9341                position
9342            } if actual_target == target && position == PanePointerPosition::new(14, 4)
9343        ));
9344        let up_motion = up_dispatch
9345            .motion
9346            .expect("up should emit final motion metadata");
9347        assert_eq!(up_motion.delta_x, 4);
9348        assert_eq!(up_motion.delta_y, 0);
9349        assert_eq!(up_motion.direction_changes, 0);
9350        let inertial_throw = up_dispatch
9351            .inertial_throw
9352            .expect("up should emit inertial throw metadata");
9353        assert_eq!(
9354            up_dispatch.projected_position,
9355            Some(inertial_throw.projected_pointer(PanePointerPosition::new(14, 4)))
9356        );
9357        assert_eq!(adapter.active_pointer_id(), None);
9358        assert!(matches!(adapter.machine_state(), PaneDragResizeState::Idle));
9359    }
9360
9361    #[test]
9362    fn pane_terminal_adapter_drives_live_tree_mutation() {
9363        // End-to-end proof that the terminal adapter actually mutates the live
9364        // pane tree. Raw crossterm events flow through PaneTerminalAdapter into
9365        // PaneDragResizeTransition values, the layout bridge
9366        // (PaneTree::operations_for_transition) turns each geometry-bearing
9367        // transition into PaneOperation values, and apply_operation moves the
9368        // live root split ratio. This closes the historical gap where the
9369        // adapter emitted transitions that no production path consumed.
9370        fn apply_dispatch(
9371            tree: &mut ftui_layout::PaneTree,
9372            layout: &ftui_layout::PaneLayout,
9373            dispatch: &PaneTerminalDispatch,
9374            neutral: PanePressureSnapProfile,
9375            seed: &mut u64,
9376        ) -> usize {
9377            let Some(transition) = dispatch.primary_transition.as_ref() else {
9378                return 0;
9379            };
9380            let pressure = dispatch.pressure_snap_profile().unwrap_or(neutral);
9381            let ops = tree.operations_for_transition(transition, layout, pressure);
9382            let applied = ops.len();
9383            for op in ops {
9384                tree.apply_operation(*seed, op).expect("operation applies");
9385                *seed += 1;
9386            }
9387            applied
9388        }
9389
9390        let mut tree = nested_pane_tree();
9391        // The root split's own rectangle spans the whole viewport regardless of
9392        // its ratio, so a single solve is sufficient for targeting it.
9393        let layout = tree
9394            .solve_layout(Rect::new(0, 0, 50, 20))
9395            .expect("layout should solve");
9396        let root_split = pane_id(1);
9397        let target = PaneResizeTarget {
9398            split_id: root_split,
9399            axis: SplitAxis::Horizontal,
9400        };
9401        let neutral = PanePressureSnapProfile {
9402            strength_bps: 5_000,
9403            hysteresis_bps: 100,
9404        };
9405
9406        let before_share = root_first_share_bps(&tree, root_split);
9407
9408        let mut adapter =
9409            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
9410        let mut op_seed = 7_000u64;
9411        let mut geometry_transitions = 0usize;
9412
9413        // Press on the splitter (arms the machine; no geometry yet).
9414        let down = Event::Mouse(MouseEvent::new(
9415            MouseEventKind::Down(MouseButton::Left),
9416            25,
9417            10,
9418        ));
9419        let down_dispatch = adapter.translate(&down, Some(target));
9420        geometry_transitions +=
9421            apply_dispatch(&mut tree, &layout, &down_dispatch, neutral, &mut op_seed);
9422
9423        // Drag rightward across cells, applying each transition to the tree.
9424        for x in [30u16, 36, 42] {
9425            let drag = Event::Mouse(MouseEvent::new(
9426                MouseEventKind::Drag(MouseButton::Left),
9427                x,
9428                10,
9429            ));
9430            let dispatch = adapter.translate(&drag, None);
9431            geometry_transitions +=
9432                apply_dispatch(&mut tree, &layout, &dispatch, neutral, &mut op_seed);
9433        }
9434
9435        // Release.
9436        let up = Event::Mouse(MouseEvent::new(
9437            MouseEventKind::Up(MouseButton::Left),
9438            42,
9439            10,
9440        ));
9441        let up_dispatch = adapter.translate(&up, None);
9442        geometry_transitions +=
9443            apply_dispatch(&mut tree, &layout, &up_dispatch, neutral, &mut op_seed);
9444
9445        assert!(
9446            geometry_transitions > 0,
9447            "drag lifecycle should yield at least one geometry-bearing transition"
9448        );
9449        let after_share = root_first_share_bps(&tree, root_split);
9450        assert!(
9451            after_share > before_share,
9452            "rightward splitter drag should grow the first child: after={after_share} before={before_share}"
9453        );
9454        assert!(matches!(adapter.machine_state(), PaneDragResizeState::Idle));
9455    }
9456
9457    #[test]
9458    fn pane_terminal_adapter_resize_interrupt_cancels_drag_and_preserves_tree() {
9459        // Edge interruption: a terminal resize (SIGWINCH) arrives mid-drag. With
9460        // the default config (cancel_on_resize = true) the adapter must cancel the
9461        // in-flight gesture cleanly, leave the live tree valid and unmutated by the
9462        // interrupt itself, and remain reusable for a fresh gesture afterwards.
9463        let mut tree = nested_pane_tree();
9464        let layout = tree
9465            .solve_layout(Rect::new(0, 0, 50, 20))
9466            .expect("layout should solve");
9467        let root_split = pane_id(1);
9468        let target = PaneResizeTarget {
9469            split_id: root_split,
9470            axis: SplitAxis::Horizontal,
9471        };
9472        let pressure = fixed_neutral_pressure();
9473        let mut seed = 4_100u64;
9474
9475        let initial_hash = tree.state_hash();
9476
9477        let mut adapter =
9478            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
9479
9480        // Arm + drag (without releasing) so a gesture is genuinely in flight.
9481        let _ = apply_dispatch_fixed(
9482            &mut tree,
9483            &layout,
9484            &adapter.translate(
9485                &Event::Mouse(MouseEvent::new(
9486                    MouseEventKind::Down(MouseButton::Left),
9487                    25,
9488                    10,
9489                )),
9490                Some(target),
9491            ),
9492            pressure,
9493            &mut seed,
9494        );
9495        for x in [30u16, 36] {
9496            let _ = apply_dispatch_fixed(
9497                &mut tree,
9498                &layout,
9499                &adapter.translate(
9500                    &Event::Mouse(MouseEvent::new(
9501                        MouseEventKind::Drag(MouseButton::Left),
9502                        x,
9503                        10,
9504                    )),
9505                    None,
9506                ),
9507                pressure,
9508                &mut seed,
9509            );
9510        }
9511        let mid_drag_hash = tree.state_hash();
9512        assert_ne!(
9513            mid_drag_hash, initial_hash,
9514            "drag should have mutated the tree before the interrupt"
9515        );
9516        assert!(tree.validate().is_ok());
9517        assert_eq!(adapter.active_pointer_id(), Some(1));
9518
9519        // Resize interrupt mid-drag.
9520        let resize_dispatch = adapter.translate(
9521            &Event::Resize {
9522                width: 60,
9523                height: 24,
9524            },
9525            None,
9526        );
9527        let cancel = resize_dispatch
9528            .primary_event
9529            .as_ref()
9530            .expect("resize interrupt should emit a cancel semantic event");
9531        assert!(matches!(
9532            cancel.kind,
9533            PaneSemanticInputEventKind::Cancel {
9534                target: Some(actual),
9535                reason: PaneCancelReason::Programmatic
9536            } if actual == target
9537        ));
9538        assert_eq!(
9539            resize_dispatch.log.phase,
9540            PaneTerminalLifecyclePhase::ResizeInterrupt
9541        );
9542        assert_eq!(
9543            resize_dispatch.log.outcome,
9544            PaneTerminalLogOutcome::SemanticForwarded
9545        );
9546
9547        // The cancel transition carries no geometry, so the bridge yields no ops
9548        // and the tree is left exactly as the last drag sample left it.
9549        let cancel_transition = resize_dispatch
9550            .primary_transition
9551            .as_ref()
9552            .expect("cancel transition present");
9553        let cancel_ops = tree.operations_for_transition(cancel_transition, &layout, pressure);
9554        assert!(
9555            cancel_ops.is_empty(),
9556            "cancel transition must not mutate the live tree"
9557        );
9558        assert_eq!(tree.state_hash(), mid_drag_hash);
9559        assert!(tree.validate().is_ok());
9560
9561        // Adapter is back to idle with no active pointer.
9562        assert_eq!(adapter.active_pointer_id(), None);
9563        assert!(matches!(adapter.machine_state(), PaneDragResizeState::Idle));
9564
9565        // Reusable: a fresh gesture at the new viewport mutates the tree again.
9566        let new_layout = tree
9567            .solve_layout(Rect::new(0, 0, 60, 24))
9568            .expect("layout should solve at new size");
9569        let before_reuse = tree.state_hash();
9570        let applied = drive_horizontal_drag_fixed(
9571            &mut adapter,
9572            &mut tree,
9573            &new_layout,
9574            target,
9575            30,
9576            12,
9577            &[36, 42, 48],
9578            pressure,
9579            &mut seed,
9580        );
9581        assert!(applied > 0, "fresh gesture should apply operations");
9582        assert_ne!(
9583            tree.state_hash(),
9584            before_reuse,
9585            "adapter must remain usable after a resize interrupt"
9586        );
9587        assert!(tree.validate().is_ok());
9588        assert!(matches!(adapter.machine_state(), PaneDragResizeState::Idle));
9589    }
9590
9591    #[test]
9592    fn pane_terminal_adapter_survives_resize_storm_and_is_deterministic() {
9593        // Resize-storm stability at the live-tree level. The default config
9594        // cancels in-flight gestures on resize (matching real SIGWINCH behavior),
9595        // so a storm rapidly re-grabs the splitter and re-drags across many
9596        // viewport sizes. After every step the tree must stay structurally valid
9597        // and within ratio bounds, and the whole scripted storm must be
9598        // byte-for-byte deterministic across repeated runs.
9599        fn run_storm() -> u64 {
9600            let mut adapter = PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default())
9601                .expect("valid adapter");
9602            let mut tree = nested_pane_tree();
9603            let root_split = pane_id(1);
9604            let target = PaneResizeTarget {
9605                split_id: root_split,
9606                axis: SplitAxis::Horizontal,
9607            };
9608            let pressure = fixed_neutral_pressure();
9609            let mut seed = 5_200u64;
9610
9611            // Sizes the "window manager" cycles through during the storm.
9612            let sizes: [(u16, u16); 6] =
9613                [(50, 20), (80, 24), (40, 16), (120, 40), (30, 12), (100, 30)];
9614
9615            for (idx, &(w, h)) in sizes.iter().enumerate() {
9616                let layout = tree
9617                    .solve_layout(Rect::new(0, 0, w, h))
9618                    .expect("layout should solve under storm");
9619
9620                // Re-grab near 1/5 width and drag rightward to 3/5 width (always
9621                // increasing x, comfortably mid-rail to avoid child minimums).
9622                let down_x = (w / 5).max(2);
9623                let drag_x = (3 * w / 5).max(down_x + 2);
9624                let _ = apply_dispatch_fixed(
9625                    &mut tree,
9626                    &layout,
9627                    &adapter.translate(
9628                        &Event::Mouse(MouseEvent::new(
9629                            MouseEventKind::Down(MouseButton::Left),
9630                            down_x,
9631                            h / 2,
9632                        )),
9633                        Some(target),
9634                    ),
9635                    pressure,
9636                    &mut seed,
9637                );
9638                let _ = apply_dispatch_fixed(
9639                    &mut tree,
9640                    &layout,
9641                    &adapter.translate(
9642                        &Event::Mouse(MouseEvent::new(
9643                            MouseEventKind::Drag(MouseButton::Left),
9644                            drag_x,
9645                            h / 2,
9646                        )),
9647                        None,
9648                    ),
9649                    pressure,
9650                    &mut seed,
9651                );
9652                assert!(
9653                    tree.validate().is_ok(),
9654                    "tree invalid after drag at step {idx}"
9655                );
9656                let share = root_first_share_bps(&tree, root_split);
9657                assert!(
9658                    share > 0 && share < 10_000,
9659                    "split ratio escaped bounds at step {idx}: {share}"
9660                );
9661
9662                // Storm: a resize arrives mid-gesture and cancels it cleanly.
9663                let resize = adapter.translate(
9664                    &Event::Resize {
9665                        width: w,
9666                        height: h,
9667                    },
9668                    None,
9669                );
9670                if let Some(cancel_transition) = resize.primary_transition.as_ref() {
9671                    let cancel_ops =
9672                        tree.operations_for_transition(cancel_transition, &layout, pressure);
9673                    assert!(
9674                        cancel_ops.is_empty(),
9675                        "resize cancel must not mutate the tree at step {idx}"
9676                    );
9677                }
9678                assert!(matches!(adapter.machine_state(), PaneDragResizeState::Idle));
9679                assert_eq!(adapter.active_pointer_id(), None);
9680                assert!(
9681                    tree.validate().is_ok(),
9682                    "tree invalid after resize at step {idx}"
9683                );
9684            }
9685
9686            // A final complete gesture (with a real release) settles the tree.
9687            let (w, h) = (90u16, 30u16);
9688            let layout = tree
9689                .solve_layout(Rect::new(0, 0, w, h))
9690                .expect("final layout should solve");
9691            let _ = drive_horizontal_drag_fixed(
9692                &mut adapter,
9693                &mut tree,
9694                &layout,
9695                target,
9696                (w / 5).max(2),
9697                h / 2,
9698                &[w / 2, 3 * w / 5],
9699                pressure,
9700                &mut seed,
9701            );
9702            assert!(matches!(adapter.machine_state(), PaneDragResizeState::Idle));
9703            assert!(tree.validate().is_ok());
9704
9705            tree.state_hash()
9706        }
9707
9708        let first = run_storm();
9709        let second = run_storm();
9710        assert_eq!(
9711            first, second,
9712            "resize storm with repeated re-grabs must be deterministic"
9713        );
9714    }
9715
9716    #[test]
9717    fn pane_terminal_adapter_geometry_is_capability_invariant() {
9718        // Capability variance: the terminal adapter consumes already-parsed
9719        // `Event` values and makes no terminal-capability queries, so the same
9720        // logical drag must produce identical live-tree geometry whether the host
9721        // is a dumb terminal, a modern emulator, or tmux. We assert both halves:
9722        // (1) the capability profiles genuinely differ (non-vacuous), and (2) the
9723        // resulting tree state is identical across all three. This locks the
9724        // invariant that pane resize is capability-independent and would catch any
9725        // future regression that silently couples geometry to terminal caps.
9726        fn drag_under(
9727            over: ftui_core::capability_override::CapabilityOverride,
9728        ) -> (bool, bool, bool, u64) {
9729            ftui_core::capability_override::with_capability_override(over, || {
9730                let caps = ftui_core::capability_override::current_capabilities();
9731                let mut tree = nested_pane_tree();
9732                let layout = tree
9733                    .solve_layout(Rect::new(0, 0, 50, 20))
9734                    .expect("layout should solve");
9735                let target = PaneResizeTarget {
9736                    split_id: pane_id(1),
9737                    axis: SplitAxis::Horizontal,
9738                };
9739                let pressure = fixed_neutral_pressure();
9740                let mut seed = 6_300u64;
9741                let mut adapter = PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default())
9742                    .expect("valid adapter");
9743                let applied = drive_horizontal_drag_fixed(
9744                    &mut adapter,
9745                    &mut tree,
9746                    &layout,
9747                    target,
9748                    25,
9749                    10,
9750                    &[30, 36, 42],
9751                    pressure,
9752                    &mut seed,
9753                );
9754                assert!(
9755                    applied > 0,
9756                    "drag should apply operations under every profile"
9757                );
9758                (
9759                    caps.mouse_sgr,
9760                    caps.supports_true_color(),
9761                    caps.in_tmux,
9762                    tree.state_hash(),
9763                )
9764            })
9765        }
9766
9767        let (dumb_sgr, dumb_truecolor, _dumb_tmux, dumb_hash) =
9768            drag_under(ftui_core::capability_override::CapabilityOverride::dumb());
9769        let (modern_sgr, modern_truecolor, modern_tmux, modern_hash) =
9770            drag_under(ftui_core::capability_override::CapabilityOverride::modern());
9771        let (_tmux_sgr, _tmux_truecolor, tmux_tmux, tmux_hash) =
9772            drag_under(ftui_core::capability_override::CapabilityOverride::tmux());
9773
9774        // Non-vacuous: the three profiles really do present different caps.
9775        assert!(
9776            dumb_sgr != modern_sgr || dumb_truecolor != modern_truecolor,
9777            "dumb and modern profiles must differ in capabilities"
9778        );
9779        assert!(
9780            modern_tmux != tmux_tmux,
9781            "modern and tmux profiles must differ in the in_tmux flag"
9782        );
9783
9784        // Invariant: identical geometry regardless of terminal capabilities.
9785        assert_eq!(
9786            dumb_hash, modern_hash,
9787            "geometry must not depend on terminal capabilities"
9788        );
9789        assert_eq!(
9790            modern_hash, tmux_hash,
9791            "geometry must not depend on terminal capabilities"
9792        );
9793    }
9794
9795    #[test]
9796    fn pane_terminal_adapter_dispatch_log_traces_routing_and_failures() {
9797        // Diagnostic logs must capture event routing (the lifecycle phase of each
9798        // translated event) and failure context (deterministic ignore reasons), so
9799        // operators can reconstruct what the adapter did from the dispatch log
9800        // alone. This exercises both the happy routing path and two failure paths.
9801        let mut adapter =
9802            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
9803        let target = pane_target(SplitAxis::Horizontal);
9804
9805        // Failure path 1: wrong activation button is ignored with a precise reason.
9806        let wrong_button = adapter.translate(
9807            &Event::Mouse(MouseEvent::new(
9808                MouseEventKind::Down(MouseButton::Right),
9809                5,
9810                5,
9811            )),
9812            Some(target),
9813        );
9814        assert_eq!(
9815            wrong_button.log.phase,
9816            PaneTerminalLifecyclePhase::MouseDown
9817        );
9818        assert_eq!(
9819            wrong_button.log.outcome,
9820            PaneTerminalLogOutcome::Ignored(PaneTerminalIgnoredReason::ActivationButtonRequired)
9821        );
9822        assert!(wrong_button.primary_event.is_none());
9823        assert_eq!(adapter.active_pointer_id(), None);
9824
9825        // Routing: a real gesture progresses MouseDown -> MouseDrag -> MouseUp,
9826        // each forwarded with a monotonically increasing sequence number.
9827        let down = adapter.translate(
9828            &Event::Mouse(MouseEvent::new(
9829                MouseEventKind::Down(MouseButton::Left),
9830                25,
9831                10,
9832            )),
9833            Some(target),
9834        );
9835        assert_eq!(down.log.phase, PaneTerminalLifecyclePhase::MouseDown);
9836        assert_eq!(down.log.outcome, PaneTerminalLogOutcome::SemanticForwarded);
9837        assert_eq!(down.log.target, Some(target));
9838        assert_eq!(down.log.pointer_id, Some(1));
9839        let down_seq = down.log.sequence.expect("down sequence");
9840
9841        let drag = adapter.translate(
9842            &Event::Mouse(MouseEvent::new(
9843                MouseEventKind::Drag(MouseButton::Left),
9844                31,
9845                10,
9846            )),
9847            None,
9848        );
9849        assert_eq!(drag.log.phase, PaneTerminalLifecyclePhase::MouseDrag);
9850        assert_eq!(drag.log.outcome, PaneTerminalLogOutcome::SemanticForwarded);
9851        let drag_seq = drag.log.sequence.expect("drag sequence");
9852        assert!(drag_seq > down_seq, "sequence numbers must be monotonic");
9853
9854        let up = adapter.translate(
9855            &Event::Mouse(MouseEvent::new(
9856                MouseEventKind::Up(MouseButton::Left),
9857                31,
9858                10,
9859            )),
9860            None,
9861        );
9862        assert_eq!(up.log.phase, PaneTerminalLifecyclePhase::MouseUp);
9863        assert_eq!(up.log.outcome, PaneTerminalLogOutcome::SemanticForwarded);
9864        assert!(up.log.sequence.expect("up sequence") > drag_seq);
9865
9866        // Failure path 2: a resize with no active gesture is a clean no-op with a
9867        // precise reason rather than a spurious cancel.
9868        let idle_resize = adapter.translate(
9869            &Event::Resize {
9870                width: 80,
9871                height: 24,
9872            },
9873            None,
9874        );
9875        assert_eq!(
9876            idle_resize.log.phase,
9877            PaneTerminalLifecyclePhase::ResizeInterrupt
9878        );
9879        assert_eq!(
9880            idle_resize.log.outcome,
9881            PaneTerminalLogOutcome::Ignored(PaneTerminalIgnoredReason::ResizeNoop)
9882        );
9883        assert!(idle_resize.primary_event.is_none());
9884    }
9885
9886    #[test]
9887    fn pane_terminal_adapter_resize_preserves_gesture_when_cancel_disabled() {
9888        // Edge interruption, opposite branch: with cancel_on_resize disabled a
9889        // resize event is a deterministic no-op that leaves the active gesture
9890        // intact, so the drag can continue to completion afterwards.
9891        let config = PaneTerminalAdapterConfig {
9892            cancel_on_resize: false,
9893            ..PaneTerminalAdapterConfig::default()
9894        };
9895        let mut adapter = PaneTerminalAdapter::new(config).expect("valid adapter");
9896        let mut tree = nested_pane_tree();
9897        let layout = tree
9898            .solve_layout(Rect::new(0, 0, 50, 20))
9899            .expect("layout should solve");
9900        let root_split = pane_id(1);
9901        let target = PaneResizeTarget {
9902            split_id: root_split,
9903            axis: SplitAxis::Horizontal,
9904        };
9905        let pressure = fixed_neutral_pressure();
9906        let mut seed = 7_700u64;
9907
9908        // Arm + first drag sample.
9909        let _ = apply_dispatch_fixed(
9910            &mut tree,
9911            &layout,
9912            &adapter.translate(
9913                &Event::Mouse(MouseEvent::new(
9914                    MouseEventKind::Down(MouseButton::Left),
9915                    20,
9916                    10,
9917                )),
9918                Some(target),
9919            ),
9920            pressure,
9921            &mut seed,
9922        );
9923        let _ = apply_dispatch_fixed(
9924            &mut tree,
9925            &layout,
9926            &adapter.translate(
9927                &Event::Mouse(MouseEvent::new(
9928                    MouseEventKind::Drag(MouseButton::Left),
9929                    26,
9930                    10,
9931                )),
9932                None,
9933            ),
9934            pressure,
9935            &mut seed,
9936        );
9937        assert_eq!(adapter.active_pointer_id(), Some(1));
9938
9939        // Resize arrives mid-drag: ignored as a no-op, gesture survives.
9940        let resize = adapter.translate(
9941            &Event::Resize {
9942                width: 50,
9943                height: 20,
9944            },
9945            None,
9946        );
9947        assert!(resize.primary_event.is_none());
9948        assert!(resize.primary_transition.is_none());
9949        assert_eq!(
9950            resize.log.outcome,
9951            PaneTerminalLogOutcome::Ignored(PaneTerminalIgnoredReason::ResizeNoop)
9952        );
9953        assert_eq!(
9954            adapter.active_pointer_id(),
9955            Some(1),
9956            "gesture must survive the resize when cancel_on_resize is disabled"
9957        );
9958
9959        // The drag continues and a release commits cleanly.
9960        let before_finish = tree.state_hash();
9961        for x in [32u16, 38] {
9962            let _ = apply_dispatch_fixed(
9963                &mut tree,
9964                &layout,
9965                &adapter.translate(
9966                    &Event::Mouse(MouseEvent::new(
9967                        MouseEventKind::Drag(MouseButton::Left),
9968                        x,
9969                        10,
9970                    )),
9971                    None,
9972                ),
9973                pressure,
9974                &mut seed,
9975            );
9976        }
9977        let _ = apply_dispatch_fixed(
9978            &mut tree,
9979            &layout,
9980            &adapter.translate(
9981                &Event::Mouse(MouseEvent::new(
9982                    MouseEventKind::Up(MouseButton::Left),
9983                    38,
9984                    10,
9985                )),
9986                None,
9987            ),
9988            pressure,
9989            &mut seed,
9990        );
9991        assert_ne!(
9992            tree.state_hash(),
9993            before_finish,
9994            "the surviving gesture should keep mutating the tree"
9995        );
9996        assert!(matches!(adapter.machine_state(), PaneDragResizeState::Idle));
9997        assert!(tree.validate().is_ok());
9998    }
9999
10000    #[test]
10001    fn pane_terminal_adapter_focus_loss_emits_cancel() {
10002        let mut adapter =
10003            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
10004        let target = pane_target(SplitAxis::Vertical);
10005
10006        let down = Event::Mouse(MouseEvent::new(
10007            MouseEventKind::Down(MouseButton::Left),
10008            3,
10009            9,
10010        ));
10011        let _ = adapter.translate(&down, Some(target));
10012        assert_eq!(adapter.active_pointer_id(), Some(1));
10013
10014        let cancel_dispatch = adapter.translate(&Event::Focus(false), None);
10015        let cancel_event = cancel_dispatch
10016            .primary_event
10017            .as_ref()
10018            .expect("focus-loss cancel event");
10019        assert!(matches!(
10020            cancel_event.kind,
10021            PaneSemanticInputEventKind::Cancel {
10022                target: Some(actual_target),
10023                reason: PaneCancelReason::FocusLost
10024            } if actual_target == target
10025        ));
10026        assert_eq!(adapter.active_pointer_id(), None);
10027        assert!(matches!(adapter.machine_state(), PaneDragResizeState::Idle));
10028    }
10029
10030    #[test]
10031    fn pane_terminal_adapter_recovers_missing_mouse_up() {
10032        let mut adapter =
10033            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
10034        let first_target = pane_target(SplitAxis::Horizontal);
10035        let second_target = pane_target(SplitAxis::Vertical);
10036
10037        let first_down = Event::Mouse(MouseEvent::new(
10038            MouseEventKind::Down(MouseButton::Left),
10039            5,
10040            5,
10041        ));
10042        let _ = adapter.translate(&first_down, Some(first_target));
10043
10044        let second_down = Event::Mouse(MouseEvent::new(
10045            MouseEventKind::Down(MouseButton::Left),
10046            8,
10047            11,
10048        ));
10049        let dispatch = adapter.translate(&second_down, Some(second_target));
10050        let recovery = dispatch
10051            .recovery_event
10052            .as_ref()
10053            .expect("recovery cancel expected");
10054        assert!(matches!(
10055            recovery.kind,
10056            PaneSemanticInputEventKind::Cancel {
10057                target: Some(actual_target),
10058                reason: PaneCancelReason::PointerCancel
10059            } if actual_target == first_target
10060        ));
10061        let primary = dispatch
10062            .primary_event
10063            .as_ref()
10064            .expect("second pointer down expected");
10065        assert!(matches!(
10066            primary.kind,
10067            PaneSemanticInputEventKind::PointerDown {
10068                target: actual_target,
10069                pointer_id: 1,
10070                button: PanePointerButton::Primary,
10071                position
10072            } if actual_target == second_target && position == PanePointerPosition::new(8, 11)
10073        ));
10074        assert_eq!(recovery.sequence, 2);
10075        assert_eq!(primary.sequence, 3);
10076        assert!(matches!(
10077            dispatch.log.outcome,
10078            PaneTerminalLogOutcome::SemanticForwardedAfterRecovery
10079        ));
10080        assert_eq!(dispatch.log.recovery_cancel_sequence, Some(2));
10081    }
10082
10083    #[test]
10084    fn pane_terminal_adapter_modifier_parity() {
10085        let mut adapter =
10086            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
10087        let target = pane_target(SplitAxis::Horizontal);
10088
10089        let mouse = MouseEvent::new(MouseEventKind::Down(MouseButton::Left), 1, 2)
10090            .with_modifiers(Modifiers::SHIFT | Modifiers::ALT | Modifiers::CTRL | Modifiers::SUPER);
10091        let dispatch = adapter.translate(&Event::Mouse(mouse), Some(target));
10092        let event = dispatch.primary_event.expect("semantic event");
10093        assert!(event.modifiers.shift);
10094        assert!(event.modifiers.alt);
10095        assert!(event.modifiers.ctrl);
10096        assert!(event.modifiers.meta);
10097    }
10098
10099    #[test]
10100    fn pane_terminal_adapter_keyboard_resize_mapping() {
10101        let mut adapter =
10102            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
10103        let target = pane_target(SplitAxis::Horizontal);
10104
10105        let key = KeyEvent::new(KeyCode::Right);
10106        let dispatch = adapter.translate(&Event::Key(key), Some(target));
10107        let event = dispatch.primary_event.expect("keyboard resize event");
10108        assert!(matches!(
10109            event.kind,
10110            PaneSemanticInputEventKind::KeyboardResize {
10111                target: actual_target,
10112                direction: PaneResizeDirection::Increase,
10113                units: 1
10114            } if actual_target == target
10115        ));
10116
10117        let shifted = KeyEvent::new(KeyCode::Right).with_modifiers(Modifiers::SHIFT);
10118        let shifted_dispatch = adapter.translate(&Event::Key(shifted), Some(target));
10119        let shifted_event = shifted_dispatch
10120            .primary_event
10121            .expect("shifted resize event");
10122        assert!(matches!(
10123            shifted_event.kind,
10124            PaneSemanticInputEventKind::KeyboardResize {
10125                direction: PaneResizeDirection::Increase,
10126                units: 5,
10127                ..
10128            }
10129        ));
10130        assert!(shifted_event.modifiers.shift);
10131    }
10132
10133    #[test]
10134    fn pane_terminal_adapter_keyboard_resize_requires_focus() {
10135        let mut adapter =
10136            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
10137        let target = pane_target(SplitAxis::Horizontal);
10138
10139        let _ = adapter.translate(&Event::Focus(false), None);
10140        assert!(!adapter.window_focused());
10141
10142        let unfocused = adapter.translate(&Event::Key(KeyEvent::new(KeyCode::Right)), Some(target));
10143        assert!(unfocused.primary_event.is_none());
10144        assert!(matches!(
10145            unfocused.log.outcome,
10146            PaneTerminalLogOutcome::Ignored(PaneTerminalIgnoredReason::WindowNotFocused)
10147        ));
10148
10149        let _ = adapter.translate(&Event::Focus(true), None);
10150        assert!(adapter.window_focused());
10151
10152        let focused = adapter.translate(&Event::Key(KeyEvent::new(KeyCode::Right)), Some(target));
10153        assert!(focused.primary_event.is_some());
10154    }
10155
10156    #[test]
10157    fn pane_terminal_adapter_drag_updates_are_coalesced() {
10158        let mut adapter = PaneTerminalAdapter::new(PaneTerminalAdapterConfig {
10159            drag_update_coalesce_distance: 2,
10160            ..PaneTerminalAdapterConfig::default()
10161        })
10162        .expect("valid adapter");
10163        let target = pane_target(SplitAxis::Horizontal);
10164
10165        let down = Event::Mouse(MouseEvent::new(
10166            MouseEventKind::Down(MouseButton::Left),
10167            10,
10168            4,
10169        ));
10170        let _ = adapter.translate(&down, Some(target));
10171
10172        let drag_start = Event::Mouse(MouseEvent::new(
10173            MouseEventKind::Drag(MouseButton::Left),
10174            14,
10175            4,
10176        ));
10177        let started = adapter.translate(&drag_start, None);
10178        assert!(started.primary_event.is_some());
10179        assert!(matches!(
10180            adapter.machine_state(),
10181            PaneDragResizeState::Dragging { .. }
10182        ));
10183
10184        let coalesced = Event::Mouse(MouseEvent::new(
10185            MouseEventKind::Drag(MouseButton::Left),
10186            15,
10187            4,
10188        ));
10189        let coalesced_dispatch = adapter.translate(&coalesced, None);
10190        assert!(coalesced_dispatch.primary_event.is_none());
10191        assert!(matches!(
10192            coalesced_dispatch.log.outcome,
10193            PaneTerminalLogOutcome::Ignored(PaneTerminalIgnoredReason::DragCoalesced)
10194        ));
10195
10196        let forwarded = Event::Mouse(MouseEvent::new(
10197            MouseEventKind::Drag(MouseButton::Left),
10198            16,
10199            4,
10200        ));
10201        let forwarded_dispatch = adapter.translate(&forwarded, None);
10202        let forwarded_event = forwarded_dispatch
10203            .primary_event
10204            .as_ref()
10205            .expect("coalesced movement should flush once threshold reached");
10206        assert!(matches!(
10207            forwarded_event.kind,
10208            PaneSemanticInputEventKind::PointerMove {
10209                delta_x: 2,
10210                delta_y: 0,
10211                ..
10212            }
10213        ));
10214    }
10215
10216    #[test]
10217    fn pane_terminal_adapter_motion_tracks_direction_changes() {
10218        let mut adapter =
10219            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
10220        let target = pane_target(SplitAxis::Horizontal);
10221
10222        let down = Event::Mouse(MouseEvent::new(
10223            MouseEventKind::Down(MouseButton::Left),
10224            10,
10225            4,
10226        ));
10227        let _ = adapter.translate(&down, Some(target));
10228
10229        let drag_forward = Event::Mouse(MouseEvent::new(
10230            MouseEventKind::Drag(MouseButton::Left),
10231            14,
10232            4,
10233        ));
10234        let forward_dispatch = adapter.translate(&drag_forward, None);
10235        let forward_motion = forward_dispatch
10236            .motion
10237            .expect("forward drag should emit motion metadata");
10238        assert_eq!(forward_motion.direction_changes, 0);
10239
10240        let drag_reverse = Event::Mouse(MouseEvent::new(
10241            MouseEventKind::Drag(MouseButton::Left),
10242            12,
10243            4,
10244        ));
10245        let reverse_dispatch = adapter.translate(&drag_reverse, None);
10246        let reverse_motion = reverse_dispatch
10247            .motion
10248            .expect("reverse drag should emit motion metadata");
10249        assert_eq!(reverse_motion.direction_changes, 1);
10250
10251        let up = Event::Mouse(MouseEvent::new(
10252            MouseEventKind::Up(MouseButton::Left),
10253            12,
10254            4,
10255        ));
10256        let up_dispatch = adapter.translate(&up, None);
10257        let up_motion = up_dispatch
10258            .motion
10259            .expect("release should include cumulative motion metadata");
10260        assert_eq!(up_motion.direction_changes, 1);
10261    }
10262
10263    #[test]
10264    fn pane_terminal_adapter_drag_and_moved_share_motion_bookkeeping() {
10265        // `Drag` and `Moved` forward identical `PointerMove` semantics through
10266        // the same `apply_pointer_motion` path; only the lifecycle phase differs.
10267        // Driving the identical motion sequence through each arm must therefore
10268        // produce identical motion metadata at every step (the extraction's
10269        // equivalence guarantee).
10270        let run = |moved: bool| {
10271            let mut adapter = PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default())
10272                .expect("valid adapter");
10273            let target = pane_target(SplitAxis::Horizontal);
10274            let down = Event::Mouse(MouseEvent::new(
10275                MouseEventKind::Down(MouseButton::Left),
10276                10,
10277                4,
10278            ));
10279            let _ = adapter.translate(&down, Some(target));
10280            let mut motions = Vec::new();
10281            for (x, y) in [(14u16, 4u16), (12, 4), (16, 4)] {
10282                let kind = if moved {
10283                    MouseEventKind::Moved
10284                } else {
10285                    MouseEventKind::Drag(MouseButton::Left)
10286                };
10287                let dispatch = adapter.translate(&Event::Mouse(MouseEvent::new(kind, x, y)), None);
10288                assert!(dispatch.primary_event.is_some());
10289                motions.push(dispatch.motion.expect("motion metadata present"));
10290            }
10291            motions
10292        };
10293
10294        let via_drag = run(false);
10295        let via_moved = run(true);
10296        assert_eq!(via_drag, via_moved);
10297        // Sanity: the reverse step (14->12) registered a direction change in both.
10298        assert_eq!(via_drag[1].direction_changes, 1);
10299    }
10300
10301    #[test]
10302    fn pane_terminal_adapter_translate_with_handles_resolves_target() {
10303        let tree = nested_pane_tree();
10304        let layout = tree
10305            .solve_layout(Rect::new(0, 0, 50, 20))
10306            .expect("layout should solve");
10307        let handles =
10308            pane_terminal_splitter_handles(&tree, &layout, PANE_TERMINAL_DEFAULT_HIT_THICKNESS);
10309        let mut adapter =
10310            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
10311
10312        let down = Event::Mouse(MouseEvent::new(
10313            MouseEventKind::Down(MouseButton::Left),
10314            25,
10315            10,
10316        ));
10317        let dispatch = adapter.translate_with_handles(&down, &handles);
10318        let event = dispatch
10319            .primary_event
10320            .as_ref()
10321            .expect("pointer down should be routed from handles");
10322        assert!(matches!(
10323            event.kind,
10324            PaneSemanticInputEventKind::PointerDown {
10325                target:
10326                    PaneResizeTarget {
10327                        split_id,
10328                        axis: SplitAxis::Horizontal
10329                    },
10330                ..
10331            } if split_id == pane_id(1)
10332        ));
10333    }
10334
10335    #[test]
10336    fn model_update() {
10337        let mut model = TestModel { value: 0 };
10338        model.update(TestMsg::Increment);
10339        assert_eq!(model.value, 1);
10340        model.update(TestMsg::Decrement);
10341        assert_eq!(model.value, 0);
10342        assert!(matches!(model.update(TestMsg::Quit), Cmd::Quit));
10343    }
10344
10345    #[test]
10346    fn model_init_default() {
10347        let mut model = TestModel { value: 0 };
10348        let cmd = model.init();
10349        assert!(matches!(cmd, Cmd::None));
10350    }
10351
10352    // Resize coalescer behavior is covered by resize_coalescer.rs tests.
10353
10354    // =========================================================================
10355    // DETERMINISM TESTS - Program loop determinism (bd-2nu8.10.1)
10356    // =========================================================================
10357
10358    #[test]
10359    fn cmd_sequence_executes_in_order() {
10360        // Verify that Cmd::Sequence executes commands in declared order
10361        use crate::simulator::ProgramSimulator;
10362
10363        struct SeqModel {
10364            trace: Vec<i32>,
10365        }
10366
10367        #[derive(Debug)]
10368        enum SeqMsg {
10369            Append(i32),
10370            TriggerSequence,
10371        }
10372
10373        impl From<Event> for SeqMsg {
10374            fn from(_: Event) -> Self {
10375                SeqMsg::Append(0)
10376            }
10377        }
10378
10379        impl Model for SeqModel {
10380            type Message = SeqMsg;
10381
10382            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
10383                match msg {
10384                    SeqMsg::Append(n) => {
10385                        self.trace.push(n);
10386                        Cmd::none()
10387                    }
10388                    SeqMsg::TriggerSequence => Cmd::sequence(vec![
10389                        Cmd::msg(SeqMsg::Append(1)),
10390                        Cmd::msg(SeqMsg::Append(2)),
10391                        Cmd::msg(SeqMsg::Append(3)),
10392                    ]),
10393                }
10394            }
10395
10396            fn view(&self, _frame: &mut Frame) {}
10397        }
10398
10399        let mut sim = ProgramSimulator::new(SeqModel { trace: vec![] });
10400        sim.init();
10401        sim.send(SeqMsg::TriggerSequence);
10402
10403        assert_eq!(sim.model().trace, vec![1, 2, 3]);
10404    }
10405
10406    #[test]
10407    fn cmd_batch_executes_all_regardless_of_order() {
10408        // Verify that Cmd::Batch executes all commands
10409        use crate::simulator::ProgramSimulator;
10410
10411        struct BatchModel {
10412            values: Vec<i32>,
10413        }
10414
10415        #[derive(Debug)]
10416        enum BatchMsg {
10417            Add(i32),
10418            TriggerBatch,
10419        }
10420
10421        impl From<Event> for BatchMsg {
10422            fn from(_: Event) -> Self {
10423                BatchMsg::Add(0)
10424            }
10425        }
10426
10427        impl Model for BatchModel {
10428            type Message = BatchMsg;
10429
10430            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
10431                match msg {
10432                    BatchMsg::Add(n) => {
10433                        self.values.push(n);
10434                        Cmd::none()
10435                    }
10436                    BatchMsg::TriggerBatch => Cmd::batch(vec![
10437                        Cmd::msg(BatchMsg::Add(10)),
10438                        Cmd::msg(BatchMsg::Add(20)),
10439                        Cmd::msg(BatchMsg::Add(30)),
10440                    ]),
10441                }
10442            }
10443
10444            fn view(&self, _frame: &mut Frame) {}
10445        }
10446
10447        let mut sim = ProgramSimulator::new(BatchModel { values: vec![] });
10448        sim.init();
10449        sim.send(BatchMsg::TriggerBatch);
10450
10451        // All values should be present
10452        assert_eq!(sim.model().values.len(), 3);
10453        assert!(sim.model().values.contains(&10));
10454        assert!(sim.model().values.contains(&20));
10455        assert!(sim.model().values.contains(&30));
10456    }
10457
10458    #[test]
10459    fn cmd_sequence_stops_on_quit() {
10460        // Verify that Cmd::Sequence stops processing after Quit
10461        use crate::simulator::ProgramSimulator;
10462
10463        struct SeqQuitModel {
10464            trace: Vec<i32>,
10465        }
10466
10467        #[derive(Debug)]
10468        enum SeqQuitMsg {
10469            Append(i32),
10470            TriggerSequenceWithQuit,
10471        }
10472
10473        impl From<Event> for SeqQuitMsg {
10474            fn from(_: Event) -> Self {
10475                SeqQuitMsg::Append(0)
10476            }
10477        }
10478
10479        impl Model for SeqQuitModel {
10480            type Message = SeqQuitMsg;
10481
10482            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
10483                match msg {
10484                    SeqQuitMsg::Append(n) => {
10485                        self.trace.push(n);
10486                        Cmd::none()
10487                    }
10488                    SeqQuitMsg::TriggerSequenceWithQuit => Cmd::sequence(vec![
10489                        Cmd::msg(SeqQuitMsg::Append(1)),
10490                        Cmd::quit(),
10491                        Cmd::msg(SeqQuitMsg::Append(2)), // Should not execute
10492                    ]),
10493                }
10494            }
10495
10496            fn view(&self, _frame: &mut Frame) {}
10497        }
10498
10499        let mut sim = ProgramSimulator::new(SeqQuitModel { trace: vec![] });
10500        sim.init();
10501        sim.send(SeqQuitMsg::TriggerSequenceWithQuit);
10502
10503        assert_eq!(sim.model().trace, vec![1]);
10504        assert!(!sim.is_running());
10505    }
10506
10507    #[test]
10508    fn identical_input_produces_identical_state() {
10509        // Verify deterministic state transitions
10510        use crate::simulator::ProgramSimulator;
10511
10512        fn run_scenario() -> Vec<i32> {
10513            struct DetModel {
10514                values: Vec<i32>,
10515            }
10516
10517            #[derive(Debug, Clone)]
10518            enum DetMsg {
10519                Add(i32),
10520                Double,
10521            }
10522
10523            impl From<Event> for DetMsg {
10524                fn from(_: Event) -> Self {
10525                    DetMsg::Add(1)
10526                }
10527            }
10528
10529            impl Model for DetModel {
10530                type Message = DetMsg;
10531
10532                fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
10533                    match msg {
10534                        DetMsg::Add(n) => {
10535                            self.values.push(n);
10536                            Cmd::none()
10537                        }
10538                        DetMsg::Double => {
10539                            if let Some(&last) = self.values.last() {
10540                                self.values.push(last * 2);
10541                            }
10542                            Cmd::none()
10543                        }
10544                    }
10545                }
10546
10547                fn view(&self, _frame: &mut Frame) {}
10548            }
10549
10550            let mut sim = ProgramSimulator::new(DetModel { values: vec![] });
10551            sim.init();
10552            sim.send(DetMsg::Add(5));
10553            sim.send(DetMsg::Double);
10554            sim.send(DetMsg::Add(3));
10555            sim.send(DetMsg::Double);
10556
10557            sim.model().values.clone()
10558        }
10559
10560        // Run the same scenario multiple times
10561        let run1 = run_scenario();
10562        let run2 = run_scenario();
10563        let run3 = run_scenario();
10564
10565        assert_eq!(run1, run2);
10566        assert_eq!(run2, run3);
10567        assert_eq!(run1, vec![5, 10, 3, 6]);
10568    }
10569
10570    #[test]
10571    fn identical_state_produces_identical_render() {
10572        // Verify consistent render outputs for identical inputs
10573        use crate::simulator::ProgramSimulator;
10574
10575        struct RenderModel {
10576            counter: i32,
10577        }
10578
10579        #[derive(Debug)]
10580        enum RenderMsg {
10581            Set(i32),
10582        }
10583
10584        impl From<Event> for RenderMsg {
10585            fn from(_: Event) -> Self {
10586                RenderMsg::Set(0)
10587            }
10588        }
10589
10590        impl Model for RenderModel {
10591            type Message = RenderMsg;
10592
10593            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
10594                match msg {
10595                    RenderMsg::Set(n) => {
10596                        self.counter = n;
10597                        Cmd::none()
10598                    }
10599                }
10600            }
10601
10602            fn view(&self, frame: &mut Frame) {
10603                let text = format!("Value: {}", self.counter);
10604                for (i, c) in text.chars().enumerate() {
10605                    if (i as u16) < frame.width() {
10606                        use ftui_render::cell::Cell;
10607                        frame.buffer.set_raw(i as u16, 0, Cell::from_char(c));
10608                    }
10609                }
10610            }
10611        }
10612
10613        // Create two simulators with the same state
10614        let mut sim1 = ProgramSimulator::new(RenderModel { counter: 42 });
10615        let mut sim2 = ProgramSimulator::new(RenderModel { counter: 42 });
10616
10617        let buf1 = sim1.capture_frame(80, 24);
10618        let buf2 = sim2.capture_frame(80, 24);
10619
10620        // Compare buffer contents
10621        for y in 0..24 {
10622            for x in 0..80 {
10623                let cell1 = buf1.get(x, y).unwrap();
10624                let cell2 = buf2.get(x, y).unwrap();
10625                assert_eq!(
10626                    cell1.content.as_char(),
10627                    cell2.content.as_char(),
10628                    "Mismatch at ({}, {})",
10629                    x,
10630                    y
10631                );
10632            }
10633        }
10634    }
10635
10636    // Resize coalescer timing invariants are covered in resize_coalescer.rs tests.
10637
10638    #[test]
10639    fn cmd_log_creates_log_command() {
10640        let cmd: Cmd<TestMsg> = Cmd::log("test message");
10641        assert!(
10642            matches!(cmd, Cmd::Log { text, mode: SanitizeMode::Strip } if text == "test message")
10643        );
10644    }
10645
10646    #[test]
10647    fn cmd_log_from_string() {
10648        let msg = String::from("dynamic message");
10649        let cmd: Cmd<TestMsg> = Cmd::log(msg);
10650        assert!(
10651            matches!(cmd, Cmd::Log { text, mode: SanitizeMode::Strip } if text == "dynamic message")
10652        );
10653    }
10654
10655    #[test]
10656    fn cmd_log_markers_keep_the_explicit_policy() {
10657        for (marker, expected) in [
10658            (Text::sanitized("hello"), SanitizeMode::Strip),
10659            (Text::sgr_only("\x1b[31mhello"), SanitizeMode::SgrOnly),
10660            (Text::trusted("\x1b[2Jhello"), SanitizeMode::Raw),
10661        ] {
10662            let expected_text = marker.as_str().to_owned();
10663            let cmd: Cmd<TestMsg> = Cmd::log_text(marker);
10664            assert_eq!(cmd.type_name(), "Log");
10665            assert!(
10666                matches!(cmd, Cmd::Log { text, mode } if text == expected_text && mode == expected)
10667            );
10668        }
10669    }
10670
10671    #[test]
10672    fn program_simulator_logs_jsonl_with_seed_and_run_id() {
10673        // Ensure ProgramSimulator captures JSONL log lines with run_id/seed.
10674        use crate::simulator::ProgramSimulator;
10675
10676        struct LogModel {
10677            run_id: &'static str,
10678            seed: u64,
10679        }
10680
10681        #[derive(Debug)]
10682        enum LogMsg {
10683            Emit,
10684        }
10685
10686        impl From<Event> for LogMsg {
10687            fn from(_: Event) -> Self {
10688                LogMsg::Emit
10689            }
10690        }
10691
10692        impl Model for LogModel {
10693            type Message = LogMsg;
10694
10695            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
10696                let line = format!(
10697                    r#"{{"event":"test","run_id":"{}","seed":{}}}"#,
10698                    self.run_id, self.seed
10699                );
10700                Cmd::log(line)
10701            }
10702
10703            fn view(&self, _frame: &mut Frame) {}
10704        }
10705
10706        let mut sim = ProgramSimulator::new(LogModel {
10707            run_id: "test-run-001",
10708            seed: 4242,
10709        });
10710        sim.init();
10711        sim.send(LogMsg::Emit);
10712
10713        let logs = sim.logs();
10714        assert_eq!(logs.len(), 1);
10715        assert!(logs[0].contains(r#""run_id":"test-run-001""#));
10716        assert!(logs[0].contains(r#""seed":4242"#));
10717    }
10718
10719    #[test]
10720    fn cmd_sequence_single_unwraps() {
10721        let cmd: Cmd<TestMsg> = Cmd::sequence(vec![Cmd::quit()]);
10722        // Single element sequence should unwrap to the inner command
10723        assert!(matches!(cmd, Cmd::Quit));
10724    }
10725
10726    #[test]
10727    fn cmd_sequence_multiple() {
10728        let cmd: Cmd<TestMsg> = Cmd::sequence(vec![Cmd::none(), Cmd::quit()]);
10729        assert!(matches!(cmd, Cmd::Sequence(_)));
10730    }
10731
10732    #[test]
10733    fn cmd_default_is_none() {
10734        let cmd: Cmd<TestMsg> = Cmd::default();
10735        assert!(matches!(cmd, Cmd::None));
10736    }
10737
10738    #[test]
10739    fn cmd_debug_all_variants() {
10740        // Test Debug impl for all variants
10741        let none: Cmd<TestMsg> = Cmd::none();
10742        assert_eq!(format!("{none:?}"), "None");
10743
10744        let quit: Cmd<TestMsg> = Cmd::quit();
10745        assert_eq!(format!("{quit:?}"), "Quit");
10746
10747        let msg: Cmd<TestMsg> = Cmd::msg(TestMsg::Increment);
10748        assert!(format!("{msg:?}").starts_with("Msg("));
10749
10750        let batch: Cmd<TestMsg> = Cmd::batch(vec![Cmd::none(), Cmd::none()]);
10751        assert!(format!("{batch:?}").starts_with("Batch("));
10752
10753        let seq: Cmd<TestMsg> = Cmd::sequence(vec![Cmd::none(), Cmd::none()]);
10754        assert!(format!("{seq:?}").starts_with("Sequence("));
10755
10756        let tick: Cmd<TestMsg> = Cmd::tick(Duration::from_secs(1));
10757        assert!(format!("{tick:?}").starts_with("Tick("));
10758
10759        let log: Cmd<TestMsg> = Cmd::log("test");
10760        assert!(format!("{log:?}").starts_with("Log("));
10761    }
10762
10763    #[test]
10764    fn program_config_with_budget() {
10765        let budget = FrameBudgetConfig {
10766            total: Duration::from_millis(50),
10767            ..Default::default()
10768        };
10769        let config = ProgramConfig::default().with_budget(budget);
10770        assert_eq!(config.budget.total, Duration::from_millis(50));
10771    }
10772
10773    #[test]
10774    fn load_governor_default_is_enabled() {
10775        let config = LoadGovernorConfig::default();
10776        assert!(config.enabled);
10777        assert_eq!(
10778            config.budget_controller.degradation_floor,
10779            DegradationLevel::SimpleBorders
10780        );
10781    }
10782
10783    #[test]
10784    fn program_config_load_governor_builders() {
10785        let governor = LoadGovernorConfig::disabled().with_enabled(true);
10786        let config = ProgramConfig::default().with_load_governor(governor);
10787        assert!(config.load_governor.enabled);
10788
10789        let config = config.without_load_governor();
10790        assert!(!config.load_governor.enabled);
10791    }
10792
10793    fn governor_observation(
10794        frame_time_ms: f64,
10795        in_flight: u64,
10796        dropped: u64,
10797        degradation: DegradationLevel,
10798        resize_coalescing_active: bool,
10799        strict_semantics_violation: bool,
10800    ) -> LoadGovernorObservation {
10801        LoadGovernorObservation {
10802            frame_time_us: frame_time_ms * 1_000.0,
10803            budget_us: 16_000.0,
10804            degradation,
10805            queue: crate::effect_system::QueueTelemetry {
10806                // Invariant: in_flight = enqueued - processed (drops are
10807                // rejected before ever being counted as enqueued).
10808                enqueued: in_flight,
10809                processed: 0,
10810                dropped,
10811                high_water: in_flight,
10812                in_flight,
10813            },
10814            resize_coalescing_active,
10815            strict_semantics_violation,
10816        }
10817    }
10818
10819    fn test_load_governor(max_queue_depth: usize, recovery_intervals: u8) -> LoadGovernorState {
10820        let policy = LoadGovernorPolicy {
10821            recovery_intervals,
10822            ..Default::default()
10823        };
10824        LoadGovernorState::new(
10825            LoadGovernorConfig::enabled().with_policy(policy),
10826            max_queue_depth,
10827        )
10828    }
10829
10830    #[test]
10831    fn load_governor_policy_defaults_match_runtime_contract() {
10832        let policy = LoadGovernorPolicy::default().normalized();
10833
10834        assert_eq!(policy.stressed_queue_watermark, 0.5);
10835        assert_eq!(policy.degraded_queue_watermark, 0.8);
10836        assert_eq!(policy.recovery_queue_watermark, 0.25);
10837        assert_eq!(policy.recovery_intervals, 3);
10838        assert_eq!(policy.budget_overrun_soft_ratio, 1.0);
10839    }
10840
10841    #[test]
10842    fn load_governor_classifies_queue_watermarks_and_recovery() {
10843        let mut governor = test_load_governor(100, 2);
10844
10845        let steady = governor.observe(governor_observation(
10846            8.0,
10847            0,
10848            0,
10849            DegradationLevel::Full,
10850            false,
10851            false,
10852        ));
10853        assert_eq!(steady.mode, RuntimeLoadMode::Healthy);
10854        assert_eq!(steady.pressure_class, RuntimePressureClass::SteadyState);
10855        assert_eq!(steady.disposition, RuntimeWorkDisposition::AdmitAll);
10856
10857        let stressed = governor.observe(governor_observation(
10858            8.0,
10859            50,
10860            0,
10861            DegradationLevel::Full,
10862            false,
10863            false,
10864        ));
10865        assert_eq!(stressed.mode, RuntimeLoadMode::Stressed);
10866        assert_eq!(stressed.pressure_class, RuntimePressureClass::SoftOverload);
10867        assert_eq!(
10868            stressed.disposition,
10869            RuntimeWorkDisposition::CoalesceVisibleDeferBackground
10870        );
10871        assert_eq!(stressed.reason_code, "queue_stressed_watermark");
10872
10873        let degraded = governor.observe(governor_observation(
10874            8.0,
10875            80,
10876            0,
10877            DegradationLevel::Full,
10878            false,
10879            false,
10880        ));
10881        assert_eq!(degraded.mode, RuntimeLoadMode::Degraded);
10882        assert_eq!(degraded.pressure_class, RuntimePressureClass::HardOverload);
10883        assert_eq!(
10884            degraded.disposition,
10885            RuntimeWorkDisposition::DeferBackgroundDropBestEffort
10886        );
10887        assert_eq!(degraded.reason_code, "queue_degraded_watermark");
10888
10889        let recovery_pending = governor.observe(governor_observation(
10890            8.0,
10891            10,
10892            0,
10893            DegradationLevel::Full,
10894            false,
10895            false,
10896        ));
10897        assert_eq!(recovery_pending.mode, RuntimeLoadMode::Degraded);
10898        assert_eq!(recovery_pending.reason_code, "recovery_hysteresis_pending");
10899        assert_eq!(recovery_pending.recovery_intervals_observed, 1);
10900
10901        let recovered = governor.observe(governor_observation(
10902            8.0,
10903            10,
10904            0,
10905            DegradationLevel::Full,
10906            false,
10907            false,
10908        ));
10909        assert_eq!(recovered.mode, RuntimeLoadMode::Recovered);
10910        assert_eq!(recovered.reason_code, "recovery_hysteresis_satisfied");
10911        assert_eq!(
10912            recovered.disposition,
10913            RuntimeWorkDisposition::ReadmitAfterHysteresis
10914        );
10915
10916        let healthy = governor.observe(governor_observation(
10917            8.0,
10918            10,
10919            0,
10920            DegradationLevel::Full,
10921            false,
10922            false,
10923        ));
10924        assert_eq!(healthy.mode, RuntimeLoadMode::Healthy);
10925        assert_eq!(healthy.reason_code, "recovered_interval_closed");
10926    }
10927
10928    #[test]
10929    fn load_governor_uses_uncapped_budget_pressure_fallback() {
10930        let mut governor = test_load_governor(0, 2);
10931
10932        let stressed = governor.observe(governor_observation(
10933            20.0,
10934            0,
10935            0,
10936            DegradationLevel::Full,
10937            false,
10938            false,
10939        ));
10940        assert_eq!(stressed.mode, RuntimeLoadMode::Stressed);
10941        assert_eq!(stressed.reason_code, "frame_budget_overrun");
10942        assert_eq!(stressed.queue_max_depth, None);
10943
10944        let degraded = governor.observe(governor_observation(
10945            8.0,
10946            0,
10947            0,
10948            DegradationLevel::SimpleBorders,
10949            false,
10950            false,
10951        ));
10952        assert_eq!(degraded.mode, RuntimeLoadMode::Degraded);
10953        assert_eq!(degraded.reason_code, "budget_degradation_active");
10954    }
10955
10956    #[test]
10957    fn load_governor_strict_semantics_failure_is_terminal() {
10958        let mut governor = test_load_governor(100, 2);
10959
10960        let unsafe_snapshot = governor.observe(governor_observation(
10961            8.0,
10962            0,
10963            0,
10964            DegradationLevel::Full,
10965            false,
10966            true,
10967        ));
10968
10969        assert_eq!(unsafe_snapshot.mode, RuntimeLoadMode::Unsafe);
10970        assert_eq!(unsafe_snapshot.pressure_class, RuntimePressureClass::Unsafe);
10971        assert_eq!(
10972            unsafe_snapshot.disposition,
10973            RuntimeWorkDisposition::FailFastStrictGuarantee
10974        );
10975        assert!(!unsafe_snapshot.strict_semantics_preserved);
10976        assert_eq!(unsafe_snapshot.reason_code, "strict_semantics_violation");
10977    }
10978
10979    #[test]
10980    fn load_governor_unsafe_latches_through_later_pressure() {
10981        let mut governor = test_load_governor(100, 2);
10982
10983        // Enter Unsafe via a strict-semantics violation.
10984        let entered = governor.observe(governor_observation(
10985            8.0,
10986            0,
10987            0,
10988            DegradationLevel::Full,
10989            false,
10990            true,
10991        ));
10992        assert_eq!(entered.mode, RuntimeLoadMode::Unsafe);
10993
10994        // A later hard-overload interval (queue ratio >= degraded watermark) with
10995        // NO fresh violation must not downgrade the terminal Unsafe state.
10996        let hard = governor.observe(governor_observation(
10997            8.0,
10998            90,
10999            0,
11000            DegradationLevel::SimpleBorders,
11001            false,
11002            false,
11003        ));
11004        assert_eq!(hard.mode, RuntimeLoadMode::Unsafe);
11005        assert_eq!(
11006            hard.disposition,
11007            RuntimeWorkDisposition::FailFastStrictGuarantee
11008        );
11009        assert!(!hard.strict_semantics_preserved);
11010        assert_eq!(hard.reason_code, "strict_semantics_violation");
11011
11012        // A soft-overload interval (would otherwise classify as Stressed) must
11013        // also keep Unsafe latched rather than escaping downward.
11014        let soft = governor.observe(governor_observation(
11015            8.0,
11016            60,
11017            0,
11018            DegradationLevel::Full,
11019            true,
11020            false,
11021        ));
11022        assert_eq!(soft.mode, RuntimeLoadMode::Unsafe);
11023
11024        // And a fully steady interval never recovers out of Unsafe.
11025        let steady = governor.observe(governor_observation(
11026            8.0,
11027            0,
11028            0,
11029            DegradationLevel::Full,
11030            false,
11031            false,
11032        ));
11033        assert_eq!(steady.mode, RuntimeLoadMode::Unsafe);
11034        assert!(!steady.strict_semantics_preserved);
11035    }
11036
11037    #[test]
11038    fn load_governor_hysteresis_prevents_single_sample_recovery() {
11039        let mut governor = test_load_governor(100, 3);
11040
11041        governor.observe(governor_observation(
11042            8.0,
11043            90,
11044            0,
11045            DegradationLevel::Full,
11046            false,
11047            false,
11048        ));
11049
11050        for expected in 1..=2 {
11051            let snapshot = governor.observe(governor_observation(
11052                8.0,
11053                0,
11054                0,
11055                DegradationLevel::Full,
11056                false,
11057                false,
11058            ));
11059            assert_eq!(snapshot.mode, RuntimeLoadMode::Degraded);
11060            assert_eq!(snapshot.recovery_intervals_observed, expected);
11061            assert_eq!(snapshot.reason_code, "recovery_hysteresis_pending");
11062        }
11063
11064        let recovered = governor.observe(governor_observation(
11065            8.0,
11066            0,
11067            0,
11068            DegradationLevel::Full,
11069            false,
11070            false,
11071        ));
11072        assert_eq!(recovered.mode, RuntimeLoadMode::Recovered);
11073    }
11074
11075    #[test]
11076    fn load_governor_stress_e2e_evidence_shows_degraded_and_recovery() {
11077        let mut governor = test_load_governor(50, 2);
11078        let scenario = [
11079            governor_observation(8.0, 0, 0, DegradationLevel::Full, false, false),
11080            governor_observation(18.0, 25, 0, DegradationLevel::Full, true, false),
11081            governor_observation(22.0, 45, 1, DegradationLevel::SimpleBorders, true, false),
11082            governor_observation(8.0, 5, 1, DegradationLevel::Full, false, false),
11083            governor_observation(8.0, 5, 1, DegradationLevel::Full, false, false),
11084            governor_observation(8.0, 5, 1, DegradationLevel::Full, false, false),
11085        ];
11086
11087        let mut modes = Vec::new();
11088        for observation in scenario {
11089            let snapshot = governor.observe(observation);
11090            modes.push(snapshot.mode);
11091            println!(
11092                "{{\"test\":\"load_governor_stress_e2e\",\"mode\":\"{}\",\"pressure_class\":\"{}\",\"work_disposition\":\"{}\",\"reason\":\"{}\",\"transition\":{},\"deferred\":{},\"coalesced\":{},\"dropped\":{}}}",
11093                snapshot.mode.as_str(),
11094                snapshot.pressure_class.as_str(),
11095                snapshot.disposition.as_str(),
11096                snapshot.reason_code,
11097                snapshot.transition,
11098                snapshot.deferred_work_total,
11099                snapshot.coalesced_work_total,
11100                snapshot.dropped_work_total
11101            );
11102        }
11103
11104        assert!(modes.contains(&RuntimeLoadMode::Stressed));
11105        assert!(modes.contains(&RuntimeLoadMode::Degraded));
11106        assert!(modes.contains(&RuntimeLoadMode::Recovered));
11107        assert_eq!(modes.last(), Some(&RuntimeLoadMode::Healthy));
11108    }
11109
11110    #[test]
11111    fn headless_program_default_load_governor_attaches_controller() {
11112        let program =
11113            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
11114        assert!(program.budget.controller().is_some());
11115    }
11116
11117    #[test]
11118    fn headless_program_load_governor_target_tracks_frame_budget() {
11119        let config = ProgramConfig::default().with_budget(FrameBudgetConfig {
11120            total: Duration::from_millis(50),
11121            ..Default::default()
11122        });
11123        let program = headless_program_with_config(TestModel { value: 0 }, config);
11124        assert_eq!(
11125            program.budget.controller().unwrap().config().target,
11126            Duration::from_millis(50)
11127        );
11128    }
11129
11130    #[test]
11131    fn headless_program_without_load_governor_uses_legacy_budget() {
11132        let program = headless_program_with_config(
11133            TestModel { value: 0 },
11134            ProgramConfig::default().without_load_governor(),
11135        );
11136        assert!(program.budget.controller().is_none());
11137    }
11138
11139    #[test]
11140    fn app_builder_without_load_governor_sets_config() {
11141        let builder = App::new(TestModel { value: 0 }).without_load_governor();
11142        assert!(!builder.config.load_governor.enabled);
11143    }
11144
11145    #[test]
11146    fn program_config_with_conformal() {
11147        let config = ProgramConfig::default().with_conformal_config(ConformalConfig {
11148            alpha: 0.2,
11149            ..Default::default()
11150        });
11151        assert!(config.conformal_config.is_some());
11152        assert!((config.conformal_config.as_ref().unwrap().alpha - 0.2).abs() < 1e-6);
11153    }
11154
11155    #[test]
11156    fn program_rejects_invalid_conformal_configuration() {
11157        let features = BackendFeatures::default();
11158        let events = HeadlessEventSource::new(80, 24, features);
11159        let writer = TerminalWriter::new(
11160            Vec::<u8>::new(),
11161            ScreenMode::AltScreen,
11162            UiAnchor::Bottom,
11163            TerminalCapabilities::default(),
11164        );
11165        let result = Program::with_event_source(
11166            TestModel { value: 0 },
11167            events,
11168            features,
11169            TerminalPresenter::new(writer),
11170            ProgramConfig::default()
11171                .with_signal_interception(false)
11172                .with_conformal_config(ConformalConfig {
11173                    alpha: f64::NAN,
11174                    ..Default::default()
11175                }),
11176        );
11177        let error = result.err().expect("invalid configuration must fail");
11178        assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
11179        assert!(error.to_string().contains("alpha"));
11180    }
11181
11182    #[test]
11183    fn program_config_forced_size_clamps_minimums() {
11184        let config = ProgramConfig::default().with_forced_size(0, 0);
11185        assert_eq!(config.forced_size, Some((1, 1)));
11186
11187        let cleared = config.without_forced_size();
11188        assert!(cleared.forced_size.is_none());
11189    }
11190
11191    #[test]
11192    fn effect_queue_config_defaults_are_safe() {
11193        let config = EffectQueueConfig::default();
11194        assert!(!config.enabled);
11195        assert_eq!(config.backend, TaskExecutorBackend::Spawned);
11196        assert!(config.scheduler.smith_enabled);
11197        assert!(!config.scheduler.preemptive);
11198        assert_eq!(config.scheduler.aging_factor, 0.0);
11199        assert_eq!(config.scheduler.wait_starve_ms, 0.0);
11200    }
11201
11202    #[test]
11203    fn handle_effect_command_enqueues_or_executes_inline() {
11204        let (result_tx, result_rx) = mpsc::channel::<u32>();
11205        let mut scheduler = QueueingScheduler::new(EffectQueueConfig::default().scheduler);
11206        let mut tasks: HashMap<u64, Box<dyn FnOnce() -> u32 + Send>> = HashMap::new();
11207
11208        let ran = Arc::new(AtomicUsize::new(0));
11209        let ran_task = ran.clone();
11210        let cmd = EffectCommand::Enqueue(
11211            TaskSpec::default(),
11212            Box::new(move || {
11213                ran_task.fetch_add(1, Ordering::SeqCst);
11214                7
11215            }),
11216        );
11217
11218        let shutdown = handle_effect_command(cmd, &mut scheduler, &mut tasks, &result_tx, None, 0);
11219        assert_eq!(shutdown, EffectLoopControl::Continue);
11220        assert_eq!(ran.load(Ordering::SeqCst), 0);
11221        assert_eq!(tasks.len(), 1);
11222        assert!(result_rx.try_recv().is_err());
11223
11224        let mut full_scheduler = QueueingScheduler::new(SchedulerConfig {
11225            max_queue_size: 0,
11226            ..Default::default()
11227        });
11228        let mut full_tasks: HashMap<u64, Box<dyn FnOnce() -> u32 + Send>> = HashMap::new();
11229        let ran_full = Arc::new(AtomicUsize::new(0));
11230        let ran_full_task = ran_full.clone();
11231        let cmd_full = EffectCommand::Enqueue(
11232            TaskSpec::default(),
11233            Box::new(move || {
11234                ran_full_task.fetch_add(1, Ordering::SeqCst);
11235                42
11236            }),
11237        );
11238
11239        let shutdown_full = handle_effect_command(
11240            cmd_full,
11241            &mut full_scheduler,
11242            &mut full_tasks,
11243            &result_tx,
11244            None,
11245            0,
11246        );
11247        assert_eq!(shutdown_full, EffectLoopControl::Continue);
11248        assert!(full_tasks.is_empty());
11249        assert_eq!(ran_full.load(Ordering::SeqCst), 1);
11250        assert_eq!(
11251            result_rx.recv_timeout(Duration::from_millis(200)).unwrap(),
11252            42
11253        );
11254
11255        let shutdown = handle_effect_command(
11256            EffectCommand::Shutdown,
11257            &mut full_scheduler,
11258            &mut full_tasks,
11259            &result_tx,
11260            None,
11261            0,
11262        );
11263        assert_eq!(shutdown, EffectLoopControl::ShutdownRequested);
11264    }
11265
11266    #[test]
11267    fn handle_effect_command_inline_fallback_writes_backpressure_evidence() {
11268        let evidence_path = temp_evidence_path("task_executor_backpressure");
11269        let sink_config = EvidenceSinkConfig::enabled_file(&evidence_path);
11270        let sink = EvidenceSink::from_config(&sink_config)
11271            .expect("evidence sink config")
11272            .expect("evidence sink enabled");
11273        let (result_tx, result_rx) = mpsc::channel::<u32>();
11274        let mut scheduler = QueueingScheduler::new(SchedulerConfig {
11275            max_queue_size: 0,
11276            ..Default::default()
11277        });
11278        let mut tasks: HashMap<u64, Box<dyn FnOnce() -> u32 + Send>> = HashMap::new();
11279
11280        let shutdown = handle_effect_command(
11281            EffectCommand::Enqueue(TaskSpec::default(), Box::new(|| 7)),
11282            &mut scheduler,
11283            &mut tasks,
11284            &result_tx,
11285            Some(&sink),
11286            0,
11287        );
11288
11289        assert_eq!(shutdown, EffectLoopControl::Continue);
11290        assert!(tasks.is_empty());
11291        assert_eq!(
11292            result_rx.recv_timeout(Duration::from_millis(200)).unwrap(),
11293            7
11294        );
11295
11296        let backpressure_line = read_evidence_event(&evidence_path, "task_executor_backpressure");
11297        assert_eq!(backpressure_line["backend"], "queued");
11298        assert_eq!(backpressure_line["action"], "inline_fallback");
11299        assert_eq!(backpressure_line["max_queue_size"], 0);
11300        assert_eq!(backpressure_line["total_rejected"], 1);
11301
11302        let completion_line = read_evidence_event(&evidence_path, "task_executor_complete");
11303        assert_eq!(completion_line["backend"], "queued-inline-fallback");
11304        assert!(completion_line["duration_us"].is_number());
11305    }
11306
11307    #[test]
11308    fn effect_queue_loop_executes_tasks_and_shutdowns() {
11309        let (cmd_tx, cmd_rx) = mpsc::channel::<EffectCommand<u32>>();
11310        let (result_tx, result_rx) = mpsc::channel::<u32>();
11311        let config = EffectQueueConfig {
11312            enabled: true,
11313            backend: TaskExecutorBackend::EffectQueue,
11314            scheduler: SchedulerConfig {
11315                preemptive: false,
11316                ..Default::default()
11317            },
11318            explicit_backend: true,
11319            ..Default::default()
11320        };
11321
11322        let handle = std::thread::spawn(move || {
11323            effect_queue_loop(
11324                config,
11325                cmd_rx,
11326                result_tx,
11327                None,
11328                &std::sync::atomic::AtomicUsize::new(0),
11329            );
11330        });
11331
11332        cmd_tx
11333            .send(EffectCommand::Enqueue(TaskSpec::default(), Box::new(|| 10)))
11334            .unwrap();
11335        cmd_tx
11336            .send(EffectCommand::Enqueue(
11337                TaskSpec::new(2.0, 5.0).with_name("second"),
11338                Box::new(|| 20),
11339            ))
11340            .unwrap();
11341
11342        let mut results = vec![
11343            result_rx.recv_timeout(Duration::from_millis(500)).unwrap(),
11344            result_rx.recv_timeout(Duration::from_millis(500)).unwrap(),
11345        ];
11346        results.sort_unstable();
11347        assert_eq!(results, vec![10, 20]);
11348
11349        cmd_tx.send(EffectCommand::Shutdown).unwrap();
11350        let _ = handle.join();
11351    }
11352
11353    #[test]
11354    fn effect_queue_loop_drains_queued_tasks_after_shutdown_request() {
11355        let (cmd_tx, cmd_rx) = mpsc::channel::<EffectCommand<u32>>();
11356        let (result_tx, result_rx) = mpsc::channel::<u32>();
11357        let config = EffectQueueConfig {
11358            enabled: true,
11359            backend: TaskExecutorBackend::EffectQueue,
11360            scheduler: SchedulerConfig {
11361                preemptive: false,
11362                ..Default::default()
11363            },
11364            explicit_backend: true,
11365            ..Default::default()
11366        };
11367
11368        let handle = std::thread::spawn(move || {
11369            effect_queue_loop(
11370                config,
11371                cmd_rx,
11372                result_tx,
11373                None,
11374                &std::sync::atomic::AtomicUsize::new(0),
11375            );
11376        });
11377
11378        cmd_tx
11379            .send(EffectCommand::Enqueue(
11380                TaskSpec::default().with_name("slow"),
11381                Box::new(|| {
11382                    std::thread::sleep(Duration::from_millis(20));
11383                    10
11384                }),
11385            ))
11386            .unwrap();
11387        cmd_tx
11388            .send(EffectCommand::Enqueue(
11389                TaskSpec::new(2.0, 5.0).with_name("fast"),
11390                Box::new(|| 20),
11391            ))
11392            .unwrap();
11393        cmd_tx.send(EffectCommand::Shutdown).unwrap();
11394
11395        let mut results = vec![
11396            result_rx.recv_timeout(Duration::from_millis(500)).unwrap(),
11397            result_rx.recv_timeout(Duration::from_millis(500)).unwrap(),
11398        ];
11399        results.sort_unstable();
11400        assert_eq!(results, vec![10, 20]);
11401
11402        handle
11403            .join()
11404            .expect("effect queue thread joins after draining");
11405    }
11406
11407    #[test]
11408    fn effect_queue_loop_survives_panicking_task_and_runs_later_work() {
11409        let (cmd_tx, cmd_rx) = mpsc::channel::<EffectCommand<u32>>();
11410        let (result_tx, result_rx) = mpsc::channel::<u32>();
11411        let config = EffectQueueConfig {
11412            enabled: true,
11413            backend: TaskExecutorBackend::EffectQueue,
11414            scheduler: SchedulerConfig {
11415                preemptive: false,
11416                ..Default::default()
11417            },
11418            explicit_backend: true,
11419            ..Default::default()
11420        };
11421
11422        let handle = std::thread::spawn(move || {
11423            effect_queue_loop(
11424                config,
11425                cmd_rx,
11426                result_tx,
11427                None,
11428                &std::sync::atomic::AtomicUsize::new(0),
11429            );
11430        });
11431
11432        cmd_tx
11433            .send(EffectCommand::Enqueue(
11434                TaskSpec::new(3.0, 1.0).with_name("panic"),
11435                Box::new(|| panic!("queued panic")),
11436            ))
11437            .unwrap();
11438        cmd_tx
11439            .send(EffectCommand::Enqueue(
11440                TaskSpec::new(1.0, 5.0).with_name("after"),
11441                Box::new(|| 99),
11442            ))
11443            .unwrap();
11444
11445        assert_eq!(
11446            result_rx.recv_timeout(Duration::from_millis(500)).unwrap(),
11447            99
11448        );
11449
11450        cmd_tx.send(EffectCommand::Shutdown).unwrap();
11451        handle
11452            .join()
11453            .expect("effect queue thread survives task panic");
11454    }
11455
11456    #[test]
11457    fn effect_queue_loop_rejects_tasks_submitted_after_shutdown_request() {
11458        let (cmd_tx, cmd_rx) = mpsc::channel::<EffectCommand<u32>>();
11459        let (result_tx, result_rx) = mpsc::channel::<u32>();
11460        let config = EffectQueueConfig {
11461            enabled: true,
11462            backend: TaskExecutorBackend::EffectQueue,
11463            scheduler: SchedulerConfig {
11464                preemptive: false,
11465                ..Default::default()
11466            },
11467            explicit_backend: true,
11468            ..Default::default()
11469        };
11470
11471        let handle = std::thread::spawn(move || {
11472            effect_queue_loop(
11473                config,
11474                cmd_rx,
11475                result_tx,
11476                None,
11477                &std::sync::atomic::AtomicUsize::new(0),
11478            );
11479        });
11480
11481        cmd_tx
11482            .send(EffectCommand::Enqueue(
11483                TaskSpec::default().with_name("slow"),
11484                Box::new(|| {
11485                    std::thread::sleep(Duration::from_millis(20));
11486                    10
11487                }),
11488            ))
11489            .unwrap();
11490        cmd_tx.send(EffectCommand::Shutdown).unwrap();
11491        cmd_tx
11492            .send(EffectCommand::Enqueue(
11493                TaskSpec::new(1.0, 1.0).with_name("late"),
11494                Box::new(|| 99),
11495            ))
11496            .unwrap();
11497
11498        assert_eq!(
11499            result_rx.recv_timeout(Duration::from_millis(500)).unwrap(),
11500            10
11501        );
11502        assert!(
11503            result_rx.recv_timeout(Duration::from_millis(100)).is_err(),
11504            "post-shutdown enqueue should not execute"
11505        );
11506
11507        handle
11508            .join()
11509            .expect("effect queue thread joins after rejecting post-shutdown work");
11510    }
11511
11512    #[test]
11513    fn effect_queue_enqueue_after_shutdown_records_drop() {
11514        let (tx, rx) = mpsc::channel::<EffectCommand<u32>>();
11515        drop(rx);
11516
11517        let queue = EffectQueue {
11518            sender: tx,
11519            handle: None,
11520            closed: true,
11521            depth: Arc::new(AtomicUsize::new(0)),
11522        };
11523        let runs = Arc::new(AtomicUsize::new(0));
11524        let before = crate::effect_system::effects_queue_dropped();
11525
11526        queue.enqueue(
11527            TaskSpec::default(),
11528            Box::new({
11529                let runs = Arc::clone(&runs);
11530                move || {
11531                    runs.fetch_add(1, Ordering::SeqCst);
11532                    7
11533                }
11534            }),
11535        );
11536
11537        let after = crate::effect_system::effects_queue_dropped();
11538        assert_eq!(runs.load(Ordering::SeqCst), 0);
11539        assert!(
11540            after > before,
11541            "enqueue after shutdown should increment dropped counter"
11542        );
11543    }
11544
11545    #[test]
11546    fn effect_queue_enqueue_with_closed_channel_records_drop() {
11547        let (tx, rx) = mpsc::channel::<EffectCommand<u32>>();
11548        drop(rx);
11549
11550        let queue = EffectQueue {
11551            sender: tx,
11552            handle: None,
11553            closed: false,
11554            depth: Arc::new(AtomicUsize::new(0)),
11555        };
11556        let runs = Arc::new(AtomicUsize::new(0));
11557        let before = crate::effect_system::effects_queue_dropped();
11558
11559        queue.enqueue(
11560            TaskSpec::default(),
11561            Box::new({
11562                let runs = Arc::clone(&runs);
11563                move || {
11564                    runs.fetch_add(1, Ordering::SeqCst);
11565                    9
11566                }
11567            }),
11568        );
11569
11570        let after = crate::effect_system::effects_queue_dropped();
11571        assert_eq!(runs.load(Ordering::SeqCst), 0);
11572        assert!(
11573            after > before,
11574            "enqueue into a closed queue channel should increment dropped counter"
11575        );
11576    }
11577
11578    // =========================================================================
11579    // Backpressure tests (bd-2zd0a)
11580    // =========================================================================
11581
11582    #[test]
11583    fn backpressure_drops_tasks_beyond_max_depth() {
11584        let (result_tx, _result_rx) = mpsc::channel::<u32>();
11585        let mut scheduler = QueueingScheduler::new(SchedulerConfig::default());
11586        let mut tasks: HashMap<u64, Box<dyn FnOnce() -> u32 + Send>> = HashMap::new();
11587        let in_flight_before = crate::effect_system::queue_telemetry().in_flight;
11588
11589        // Enqueue 2 tasks with max_depth=2 โ€” should succeed
11590        let r1 = handle_effect_command(
11591            EffectCommand::Enqueue(TaskSpec::default(), Box::new(|| 1)),
11592            &mut scheduler,
11593            &mut tasks,
11594            &result_tx,
11595            None,
11596            2,
11597        );
11598        assert_eq!(r1, EffectLoopControl::Continue);
11599        assert_eq!(tasks.len(), 1);
11600
11601        let r2 = handle_effect_command(
11602            EffectCommand::Enqueue(TaskSpec::default(), Box::new(|| 2)),
11603            &mut scheduler,
11604            &mut tasks,
11605            &result_tx,
11606            None,
11607            2,
11608        );
11609        assert_eq!(r2, EffectLoopControl::Continue);
11610        assert_eq!(tasks.len(), 2);
11611
11612        // 3rd task should be dropped (depth=2 >= max_depth=2)
11613        let dropped_before = crate::effect_system::effects_queue_dropped();
11614        let r3 = handle_effect_command(
11615            EffectCommand::Enqueue(TaskSpec::default(), Box::new(|| 3)),
11616            &mut scheduler,
11617            &mut tasks,
11618            &result_tx,
11619            None,
11620            2,
11621        );
11622        assert_eq!(r3, EffectLoopControl::Continue);
11623        assert_eq!(
11624            tasks.len(),
11625            2,
11626            "task should have been dropped, not enqueued"
11627        );
11628        assert!(
11629            crate::effect_system::effects_queue_dropped() > dropped_before,
11630            "dropped counter should increment"
11631        );
11632        release_unrun_queued_tasks(in_flight_before);
11633    }
11634
11635    #[test]
11636    fn backpressure_zero_depth_means_unbounded() {
11637        let (result_tx, _result_rx) = mpsc::channel::<u32>();
11638        let mut scheduler = QueueingScheduler::new(SchedulerConfig::default());
11639        let mut tasks: HashMap<u64, Box<dyn FnOnce() -> u32 + Send>> = HashMap::new();
11640
11641        // With max_depth=0, can enqueue many tasks
11642        let in_flight_before = crate::effect_system::queue_telemetry().in_flight;
11643        for i in 0..20 {
11644            let r = handle_effect_command(
11645                EffectCommand::Enqueue(TaskSpec::default(), Box::new(move || i)),
11646                &mut scheduler,
11647                &mut tasks,
11648                &result_tx,
11649                None,
11650                0,
11651            );
11652            assert_eq!(r, EffectLoopControl::Continue);
11653        }
11654        // All should be enqueued (some may have been inlined by scheduler, but none dropped)
11655        release_unrun_queued_tasks(in_flight_before);
11656    }
11657
11658    /// The enqueue counters are process-global and `in_flight` feeds the
11659    /// frame guardrail of every `Program` in this process. A unit test that
11660    /// queues tasks into a bare task map never runs them, so it must hand the
11661    /// accounting back or later headless render tests see a phantom backlog
11662    /// and drop their frames.
11663    fn release_unrun_queued_tasks(in_flight_before: u64) {
11664        let leaked = crate::effect_system::queue_telemetry()
11665            .in_flight
11666            .saturating_sub(in_flight_before);
11667        for _ in 0..leaked {
11668            crate::effect_system::record_queue_processed();
11669        }
11670    }
11671
11672    #[test]
11673    fn inline_auto_remeasure_reset_clears_decision() {
11674        let mut state = InlineAutoRemeasureState::new(InlineAutoRemeasureConfig::default());
11675        state.sampler.decide(Instant::now());
11676        assert!(state.sampler.last_decision().is_some());
11677
11678        state.reset();
11679        assert!(state.sampler.last_decision().is_none());
11680    }
11681
11682    #[test]
11683    fn budget_decision_jsonl_contains_required_fields() {
11684        let evidence = BudgetDecisionEvidence {
11685            frame_idx: 7,
11686            decision: BudgetDecision::Degrade,
11687            controller_decision: BudgetDecision::Hold,
11688            degradation_before: DegradationLevel::Full,
11689            degradation_after: DegradationLevel::NoStyling,
11690            frame_time_us: 12_345.678,
11691            budget_us: 16_000.0,
11692            pid_output: 1.25,
11693            pid_p: 0.5,
11694            pid_i: 0.25,
11695            pid_d: 0.5,
11696            e_value: 2.0,
11697            frames_observed: 42,
11698            frames_since_change: 3,
11699            in_warmup: false,
11700            recovery_streak: 5,
11701            total_degrades: 2,
11702            total_recoveries: 1,
11703            controller_reason: BudgetDecisionReason::OverloadEvidencePassed,
11704            resize_detector: "bocpd",
11705            load_governor: LoadGovernorSnapshot {
11706                mode: RuntimeLoadMode::Degraded,
11707                mode_before: RuntimeLoadMode::Stressed,
11708                pressure_class: RuntimePressureClass::HardOverload,
11709                disposition: RuntimeWorkDisposition::DeferBackgroundDropBestEffort,
11710                reason_code: "budget_degradation_active",
11711                transition: true,
11712                strict_semantics_preserved: true,
11713                queue_in_flight: 8,
11714                queue_max_depth: Some(10),
11715                queue_dropped_delta: 0,
11716                resize_coalescing_active: false,
11717                recovery_intervals_observed: 0,
11718                recovery_intervals_required: 3,
11719                deferred_work_total: 2,
11720                coalesced_work_total: 1,
11721                dropped_work_total: 0,
11722            },
11723            conformal: Some(ConformalEvidence {
11724                bucket_key: "inline:dirty:10".to_string(),
11725                n_b: 32,
11726                alpha: 0.05,
11727                q_b: Some(1000.0),
11728                y_hat: 12_000.0,
11729                upper_us: Some(13_000.0),
11730                risk: true,
11731                status: ConformalStatus::Calibrated,
11732                required_rank: 32,
11733                fallback_level: 1,
11734                window_size: 256,
11735                reset_count: 2,
11736            }),
11737        };
11738
11739        let jsonl = evidence.to_jsonl();
11740        assert!(jsonl.contains("\"event\":\"budget_decision\""));
11741        assert!(jsonl.contains("\"decision\":\"degrade\""));
11742        assert!(jsonl.contains("\"decision_controller\":\"stay\""));
11743        assert!(jsonl.contains("\"decision_controller_reason\":\"overload_evidence_passed\""));
11744        assert!(jsonl.contains("\"degradation_before\":\"Full\""));
11745        assert!(jsonl.contains("\"degradation_after\":\"NoStyling\""));
11746        assert!(jsonl.contains("\"frame_time_us\":12345.678000"));
11747        assert!(jsonl.contains("\"budget_us\":16000.000000"));
11748        assert!(jsonl.contains("\"pid_output\":1.250000"));
11749        assert!(jsonl.contains("\"e_value\":2.000000"));
11750        assert!(jsonl.contains("\"recovery_streak\":5"));
11751        assert!(jsonl.contains("\"total_degrades\":2"));
11752        assert!(jsonl.contains("\"total_recoveries\":1"));
11753        assert!(jsonl.contains("\"runtime_mode\":\"degraded\""));
11754        assert!(jsonl.contains("\"runtime_mode_before\":\"stressed\""));
11755        assert!(jsonl.contains("\"pressure_class\":\"hard_overload\""));
11756        assert!(jsonl.contains("\"work_disposition\":\"defer_background_drop_best_effort\""));
11757        assert!(jsonl.contains("\"governor_reason\":\"budget_degradation_active\""));
11758        assert!(jsonl.contains("\"governor_transition\":true"));
11759        assert!(jsonl.contains("\"strict_semantics_preserved\":true"));
11760        assert!(jsonl.contains("\"queue_in_flight\":8"));
11761        assert!(jsonl.contains("\"queue_max_depth\":10"));
11762        assert!(jsonl.contains("\"resize_detector\":\"bocpd\""));
11763        assert!(jsonl.contains("\"deferred_work_total\":2"));
11764        assert!(jsonl.contains("\"bucket_key\":\"inline:dirty:10\""));
11765        assert!(jsonl.contains("\"n_b\":32"));
11766        assert!(jsonl.contains("\"alpha\":0.050000"));
11767        assert!(jsonl.contains("\"q_b\":1000.000000"));
11768        assert!(jsonl.contains("\"y_hat\":12000.000000"));
11769        assert!(jsonl.contains("\"upper_us\":13000.000000"));
11770        assert!(jsonl.contains("\"risk\":true"));
11771        assert!(jsonl.contains("\"fallback_level\":1"));
11772        assert!(jsonl.contains("\"window_size\":256"));
11773        assert!(jsonl.contains("\"reset_count\":2"));
11774    }
11775
11776    fn make_signal(
11777        widget_id: u64,
11778        essential: bool,
11779        priority: f32,
11780        staleness_ms: u64,
11781        cost_us: f32,
11782    ) -> WidgetSignal {
11783        WidgetSignal {
11784            widget_id,
11785            essential,
11786            priority,
11787            staleness_ms,
11788            focus_boost: 0.0,
11789            interaction_boost: 0.0,
11790            area_cells: 1,
11791            cost_estimate_us: cost_us,
11792            recent_cost_us: 0.0,
11793            estimate_source: CostEstimateSource::FixedDefault,
11794        }
11795    }
11796
11797    fn signal_value_cost(signal: &WidgetSignal, config: &WidgetRefreshConfig) -> (f32, f32, bool) {
11798        let starved = config.starve_ms > 0 && signal.staleness_ms >= config.starve_ms;
11799        let staleness_window = config.staleness_window_ms.max(1) as f32;
11800        let staleness_score = (signal.staleness_ms as f32 / staleness_window).min(1.0);
11801        let mut value = config.weight_priority * signal.priority
11802            + config.weight_staleness * staleness_score
11803            + config.weight_focus * signal.focus_boost
11804            + config.weight_interaction * signal.interaction_boost;
11805        if starved {
11806            value += config.starve_boost;
11807        }
11808        let raw_cost = if signal.recent_cost_us > 0.0 {
11809            signal.recent_cost_us
11810        } else {
11811            signal.cost_estimate_us
11812        };
11813        let cost_us = raw_cost.max(config.min_cost_us);
11814        (value, cost_us, starved)
11815    }
11816
11817    fn fifo_select(
11818        signals: &[WidgetSignal],
11819        budget_us: f64,
11820        config: &WidgetRefreshConfig,
11821    ) -> (Vec<u64>, f64, usize) {
11822        let mut selected = Vec::new();
11823        let mut total_value = 0.0f64;
11824        let mut starved_selected = 0usize;
11825        let mut remaining = budget_us;
11826
11827        for signal in signals {
11828            if !signal.essential {
11829                continue;
11830            }
11831            let (value, cost_us, starved) = signal_value_cost(signal, config);
11832            remaining -= cost_us as f64;
11833            total_value += value as f64;
11834            if starved {
11835                starved_selected = starved_selected.saturating_add(1);
11836            }
11837            selected.push(signal.widget_id);
11838        }
11839        for signal in signals {
11840            if signal.essential {
11841                continue;
11842            }
11843            let (value, cost_us, starved) = signal_value_cost(signal, config);
11844            if remaining >= cost_us as f64 {
11845                remaining -= cost_us as f64;
11846                total_value += value as f64;
11847                if starved {
11848                    starved_selected = starved_selected.saturating_add(1);
11849                }
11850                selected.push(signal.widget_id);
11851            }
11852        }
11853
11854        (selected, total_value, starved_selected)
11855    }
11856
11857    fn rotate_signals(signals: &[WidgetSignal], offset: usize) -> Vec<WidgetSignal> {
11858        if signals.is_empty() {
11859            return Vec::new();
11860        }
11861        let mut rotated = Vec::with_capacity(signals.len());
11862        for idx in 0..signals.len() {
11863            rotated.push(signals[(idx + offset) % signals.len()].clone());
11864        }
11865        rotated
11866    }
11867
11868    #[test]
11869    fn widget_refresh_selects_essentials_first() {
11870        let signals = vec![
11871            make_signal(1, true, 0.6, 0, 5.0),
11872            make_signal(2, false, 0.9, 0, 4.0),
11873        ];
11874        let mut plan = WidgetRefreshPlan::new();
11875        let config = WidgetRefreshConfig::default();
11876        plan.recompute(1, 6.0, DegradationLevel::Full, &signals, &config);
11877        let selected: Vec<u64> = plan.selected.iter().map(|e| e.widget_id).collect();
11878        assert_eq!(selected, vec![1]);
11879        assert!(!plan.over_budget);
11880    }
11881
11882    #[test]
11883    fn widget_refresh_degradation_essential_only_skips_nonessential() {
11884        let signals = vec![
11885            make_signal(1, true, 0.5, 0, 2.0),
11886            make_signal(2, false, 1.0, 0, 1.0),
11887        ];
11888        let mut plan = WidgetRefreshPlan::new();
11889        let config = WidgetRefreshConfig::default();
11890        plan.recompute(3, 10.0, DegradationLevel::EssentialOnly, &signals, &config);
11891        let selected: Vec<u64> = plan.selected.iter().map(|e| e.widget_id).collect();
11892        assert_eq!(selected, vec![1]);
11893        assert_eq!(plan.skipped_count, 1);
11894    }
11895
11896    #[test]
11897    fn widget_refresh_starvation_guard_forces_one_starved() {
11898        let signals = vec![make_signal(7, false, 0.1, 10_000, 8.0)];
11899        let mut plan = WidgetRefreshPlan::new();
11900        let config = WidgetRefreshConfig {
11901            starve_ms: 1_000,
11902            max_starved_per_frame: 1,
11903            ..Default::default()
11904        };
11905        plan.recompute(5, 0.0, DegradationLevel::Full, &signals, &config);
11906        assert_eq!(plan.selected.len(), 1);
11907        assert!(plan.selected[0].starved);
11908        assert!(plan.over_budget);
11909    }
11910
11911    #[test]
11912    fn widget_refresh_budget_blocks_when_no_selection() {
11913        let signals = vec![make_signal(42, false, 0.2, 0, 10.0)];
11914        let mut plan = WidgetRefreshPlan::new();
11915        let config = WidgetRefreshConfig {
11916            starve_ms: 0,
11917            max_starved_per_frame: 0,
11918            ..Default::default()
11919        };
11920        plan.recompute(8, 0.0, DegradationLevel::Full, &signals, &config);
11921        let budget = plan.as_budget();
11922        assert!(!budget.allows(42, false));
11923    }
11924
11925    #[test]
11926    fn widget_refresh_max_drop_fraction_forces_minimum_refresh() {
11927        let signals = vec![
11928            make_signal(1, false, 0.4, 0, 10.0),
11929            make_signal(2, false, 0.4, 0, 10.0),
11930            make_signal(3, false, 0.4, 0, 10.0),
11931            make_signal(4, false, 0.4, 0, 10.0),
11932        ];
11933        let mut plan = WidgetRefreshPlan::new();
11934        let config = WidgetRefreshConfig {
11935            starve_ms: 0,
11936            max_starved_per_frame: 0,
11937            max_drop_fraction: 0.5,
11938            ..Default::default()
11939        };
11940        plan.recompute(12, 0.0, DegradationLevel::Full, &signals, &config);
11941        let selected: Vec<u64> = plan.selected.iter().map(|e| e.widget_id).collect();
11942        assert_eq!(selected, vec![1, 2]);
11943    }
11944
11945    #[test]
11946    fn widget_refresh_greedy_beats_fifo_and_round_robin() {
11947        let signals = vec![
11948            make_signal(1, false, 0.1, 0, 6.0),
11949            make_signal(2, false, 0.2, 0, 6.0),
11950            make_signal(3, false, 1.0, 0, 4.0),
11951            make_signal(4, false, 0.9, 0, 3.0),
11952            make_signal(5, false, 0.8, 0, 3.0),
11953            make_signal(6, false, 0.1, 4_000, 2.0),
11954        ];
11955        let budget_us = 10.0;
11956        let config = WidgetRefreshConfig::default();
11957
11958        let mut plan = WidgetRefreshPlan::new();
11959        plan.recompute(21, budget_us, DegradationLevel::Full, &signals, &config);
11960        let greedy_value = plan.selected_value;
11961        let greedy_selected: Vec<u64> = plan.selected.iter().map(|e| e.widget_id).collect();
11962
11963        let (fifo_selected, fifo_value, _fifo_starved) = fifo_select(&signals, budget_us, &config);
11964        let rotated = rotate_signals(&signals, 2);
11965        let (rr_selected, rr_value, _rr_starved) = fifo_select(&rotated, budget_us, &config);
11966
11967        assert!(
11968            greedy_value > fifo_value,
11969            "greedy_value={greedy_value:.3} <= fifo_value={fifo_value:.3}; greedy={:?}, fifo={:?}",
11970            greedy_selected,
11971            fifo_selected
11972        );
11973        assert!(
11974            greedy_value > rr_value,
11975            "greedy_value={greedy_value:.3} <= rr_value={rr_value:.3}; greedy={:?}, rr={:?}",
11976            greedy_selected,
11977            rr_selected
11978        );
11979        assert!(
11980            plan.starved_selected > 0,
11981            "greedy did not select starved widget; greedy={:?}",
11982            greedy_selected
11983        );
11984    }
11985
11986    #[test]
11987    fn widget_refresh_jsonl_contains_required_fields() {
11988        let signals = vec![make_signal(7, true, 0.2, 0, 2.0)];
11989        let mut plan = WidgetRefreshPlan::new();
11990        let config = WidgetRefreshConfig::default();
11991        plan.recompute(9, 4.0, DegradationLevel::Full, &signals, &config);
11992        let jsonl = plan.to_jsonl();
11993        assert!(jsonl.contains("\"event\":\"widget_refresh\""));
11994        assert!(jsonl.contains("\"frame_idx\":9"));
11995        assert!(jsonl.contains("\"selected_count\":1"));
11996        assert!(jsonl.contains("\"id\":7"));
11997    }
11998
11999    #[test]
12000    fn program_config_with_resize_coalescer() {
12001        let config = ProgramConfig::default().with_resize_coalescer(CoalescerConfig {
12002            steady_delay_ms: 8,
12003            burst_delay_ms: 20,
12004            hard_deadline_ms: 80,
12005            burst_enter_rate: 12.0,
12006            burst_exit_rate: 6.0,
12007            cooldown_frames: 2,
12008            rate_window_size: 6,
12009            enable_logging: true,
12010            enable_bocpd: false,
12011            heuristic_fallback: true,
12012            bocpd_config: None,
12013        });
12014        assert_eq!(config.resize_coalescer.steady_delay_ms, 8);
12015        assert!(config.resize_coalescer.enable_logging);
12016    }
12017
12018    #[test]
12019    fn program_config_with_resize_behavior() {
12020        let config = ProgramConfig::default().with_resize_behavior(ResizeBehavior::Immediate);
12021        assert_eq!(config.resize_behavior, ResizeBehavior::Immediate);
12022    }
12023
12024    #[test]
12025    fn program_config_with_legacy_resize_enabled() {
12026        let config = ProgramConfig::default().with_legacy_resize(true);
12027        assert_eq!(config.resize_behavior, ResizeBehavior::Immediate);
12028    }
12029
12030    #[test]
12031    fn program_config_with_legacy_resize_disabled_keeps_default() {
12032        let config = ProgramConfig::default().with_legacy_resize(false);
12033        assert_eq!(config.resize_behavior, ResizeBehavior::Throttled);
12034    }
12035
12036    fn diff_strategy_trace(bayesian_enabled: bool) -> Vec<DiffStrategy> {
12037        let config = RuntimeDiffConfig::default().with_bayesian_enabled(bayesian_enabled);
12038        let mut writer = TerminalWriter::with_diff_config(
12039            Vec::<u8>::new(),
12040            ScreenMode::AltScreen,
12041            UiAnchor::Bottom,
12042            TerminalCapabilities::basic(),
12043            config,
12044        );
12045        writer.set_size(8, 4);
12046
12047        let mut buffer = Buffer::new(8, 4);
12048        let mut trace = Vec::new();
12049
12050        writer.present_ui(&buffer, None, false).unwrap();
12051        trace.push(
12052            writer
12053                .last_diff_strategy()
12054                .unwrap_or(DiffStrategy::FullRedraw),
12055        );
12056
12057        buffer.set_raw(0, 0, Cell::from_char('A'));
12058        writer.present_ui(&buffer, None, false).unwrap();
12059        trace.push(
12060            writer
12061                .last_diff_strategy()
12062                .unwrap_or(DiffStrategy::FullRedraw),
12063        );
12064
12065        buffer.set_raw(1, 1, Cell::from_char('B'));
12066        writer.present_ui(&buffer, None, false).unwrap();
12067        trace.push(
12068            writer
12069                .last_diff_strategy()
12070                .unwrap_or(DiffStrategy::FullRedraw),
12071        );
12072
12073        trace
12074    }
12075
12076    fn coalescer_checksum(enable_bocpd: bool) -> String {
12077        let mut config = CoalescerConfig::default().with_logging(true);
12078        config = if enable_bocpd {
12079            config.with_bocpd()
12080        } else {
12081            config.without_bocpd()
12082        };
12083
12084        let base = Instant::now();
12085        let mut coalescer = ResizeCoalescer::new(config, (80, 24)).with_last_render(base);
12086
12087        let events = [
12088            (0_u64, (82_u16, 24_u16)),
12089            (10, (83, 25)),
12090            (20, (84, 26)),
12091            (35, (90, 28)),
12092            (55, (92, 30)),
12093        ];
12094
12095        let mut idx = 0usize;
12096        for t_ms in (0_u64..=160).step_by(8) {
12097            let now = base + Duration::from_millis(t_ms);
12098            while idx < events.len() && events[idx].0 == t_ms {
12099                let (w, h) = events[idx].1;
12100                coalescer.handle_resize_at(w, h, now);
12101                idx += 1;
12102            }
12103            coalescer.tick_at(now);
12104        }
12105
12106        coalescer.decision_checksum_hex()
12107    }
12108
12109    fn conformal_trace(enabled: bool) -> Vec<(Option<f64>, bool)> {
12110        if !enabled {
12111            return Vec::new();
12112        }
12113
12114        let mut predictor =
12115            ConformalPredictor::new(ConformalConfig::default()).expect("valid config");
12116        let key = BucketKey::from_context(ScreenMode::AltScreen, DiffStrategy::Full, 80, 24);
12117        let mut trace = Vec::new();
12118
12119        for i in 0..30 {
12120            let y_hat = 16_000.0 + (i as f64) * 15.0;
12121            let observed = y_hat + (i % 7) as f64 * 120.0;
12122            predictor.observe(key, y_hat, observed);
12123            let prediction = predictor.predict(key, y_hat, 20_000.0);
12124            trace.push((prediction.upper_us, prediction.risk));
12125        }
12126
12127        trace
12128    }
12129
12130    #[test]
12131    fn policy_toggle_matrix_determinism() {
12132        for &bayesian in &[false, true] {
12133            for &bocpd in &[false, true] {
12134                for &conformal in &[false, true] {
12135                    let diff_a = diff_strategy_trace(bayesian);
12136                    let diff_b = diff_strategy_trace(bayesian);
12137                    assert_eq!(diff_a, diff_b, "diff strategy not deterministic");
12138
12139                    let checksum_a = coalescer_checksum(bocpd);
12140                    let checksum_b = coalescer_checksum(bocpd);
12141                    assert_eq!(checksum_a, checksum_b, "coalescer checksum mismatch");
12142
12143                    let conf_a = conformal_trace(conformal);
12144                    let conf_b = conformal_trace(conformal);
12145                    assert_eq!(conf_a, conf_b, "conformal predictor not deterministic");
12146
12147                    if conformal {
12148                        assert!(!conf_a.is_empty(), "conformal trace should be populated");
12149                    } else {
12150                        assert!(conf_a.is_empty(), "conformal trace should be empty");
12151                    }
12152                }
12153            }
12154        }
12155    }
12156
12157    #[test]
12158    fn resize_behavior_uses_coalescer_flag() {
12159        assert!(ResizeBehavior::Throttled.uses_coalescer());
12160        assert!(!ResizeBehavior::Immediate.uses_coalescer());
12161    }
12162
12163    #[test]
12164    fn nested_cmd_msg_executes_recursively() {
12165        // Verify that Cmd::Msg triggers recursive update
12166        use crate::simulator::ProgramSimulator;
12167
12168        struct NestedModel {
12169            depth: usize,
12170        }
12171
12172        #[derive(Debug)]
12173        enum NestedMsg {
12174            Nest(usize),
12175        }
12176
12177        impl From<Event> for NestedMsg {
12178            fn from(_: Event) -> Self {
12179                NestedMsg::Nest(0)
12180            }
12181        }
12182
12183        impl Model for NestedModel {
12184            type Message = NestedMsg;
12185
12186            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
12187                match msg {
12188                    NestedMsg::Nest(n) => {
12189                        self.depth += 1;
12190                        if n > 0 {
12191                            Cmd::msg(NestedMsg::Nest(n - 1))
12192                        } else {
12193                            Cmd::none()
12194                        }
12195                    }
12196                }
12197            }
12198
12199            fn view(&self, _frame: &mut Frame) {}
12200        }
12201
12202        let mut sim = ProgramSimulator::new(NestedModel { depth: 0 });
12203        sim.init();
12204        sim.send(NestedMsg::Nest(3));
12205
12206        // Should have recursed 4 times (3, 2, 1, 0)
12207        assert_eq!(sim.model().depth, 4);
12208    }
12209
12210    #[test]
12211    fn task_executes_synchronously_in_simulator() {
12212        // In simulator, tasks execute synchronously
12213        use crate::simulator::ProgramSimulator;
12214
12215        struct TaskModel {
12216            completed: bool,
12217        }
12218
12219        #[derive(Debug)]
12220        enum TaskMsg {
12221            Complete,
12222            SpawnTask,
12223        }
12224
12225        impl From<Event> for TaskMsg {
12226            fn from(_: Event) -> Self {
12227                TaskMsg::Complete
12228            }
12229        }
12230
12231        impl Model for TaskModel {
12232            type Message = TaskMsg;
12233
12234            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
12235                match msg {
12236                    TaskMsg::Complete => {
12237                        self.completed = true;
12238                        Cmd::none()
12239                    }
12240                    TaskMsg::SpawnTask => Cmd::task(|| TaskMsg::Complete),
12241                }
12242            }
12243
12244            fn view(&self, _frame: &mut Frame) {}
12245        }
12246
12247        let mut sim = ProgramSimulator::new(TaskModel { completed: false });
12248        sim.init();
12249        sim.send(TaskMsg::SpawnTask);
12250
12251        // Task should have completed synchronously
12252        assert!(sim.model().completed);
12253    }
12254
12255    #[test]
12256    fn multiple_updates_accumulate_correctly() {
12257        // Verify state accumulates correctly across multiple updates
12258        use crate::simulator::ProgramSimulator;
12259
12260        struct AccumModel {
12261            sum: i32,
12262        }
12263
12264        #[derive(Debug)]
12265        enum AccumMsg {
12266            Add(i32),
12267            Multiply(i32),
12268        }
12269
12270        impl From<Event> for AccumMsg {
12271            fn from(_: Event) -> Self {
12272                AccumMsg::Add(1)
12273            }
12274        }
12275
12276        impl Model for AccumModel {
12277            type Message = AccumMsg;
12278
12279            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
12280                match msg {
12281                    AccumMsg::Add(n) => {
12282                        self.sum += n;
12283                        Cmd::none()
12284                    }
12285                    AccumMsg::Multiply(n) => {
12286                        self.sum *= n;
12287                        Cmd::none()
12288                    }
12289                }
12290            }
12291
12292            fn view(&self, _frame: &mut Frame) {}
12293        }
12294
12295        let mut sim = ProgramSimulator::new(AccumModel { sum: 0 });
12296        sim.init();
12297
12298        // (0 + 5) * 2 + 3 = 13
12299        sim.send(AccumMsg::Add(5));
12300        sim.send(AccumMsg::Multiply(2));
12301        sim.send(AccumMsg::Add(3));
12302
12303        assert_eq!(sim.model().sum, 13);
12304    }
12305
12306    #[test]
12307    fn init_command_executes_before_first_update() {
12308        // Verify init() command executes before any update
12309        use crate::simulator::ProgramSimulator;
12310
12311        struct InitModel {
12312            initialized: bool,
12313            updates: usize,
12314        }
12315
12316        #[derive(Debug)]
12317        enum InitMsg {
12318            Update,
12319            MarkInit,
12320        }
12321
12322        impl From<Event> for InitMsg {
12323            fn from(_: Event) -> Self {
12324                InitMsg::Update
12325            }
12326        }
12327
12328        impl Model for InitModel {
12329            type Message = InitMsg;
12330
12331            fn init(&mut self) -> Cmd<Self::Message> {
12332                Cmd::msg(InitMsg::MarkInit)
12333            }
12334
12335            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
12336                match msg {
12337                    InitMsg::MarkInit => {
12338                        self.initialized = true;
12339                        Cmd::none()
12340                    }
12341                    InitMsg::Update => {
12342                        self.updates += 1;
12343                        Cmd::none()
12344                    }
12345                }
12346            }
12347
12348            fn view(&self, _frame: &mut Frame) {}
12349        }
12350
12351        let mut sim = ProgramSimulator::new(InitModel {
12352            initialized: false,
12353            updates: 0,
12354        });
12355        sim.init();
12356
12357        assert!(sim.model().initialized);
12358        sim.send(InitMsg::Update);
12359        assert_eq!(sim.model().updates, 1);
12360    }
12361
12362    // =========================================================================
12363    // INLINE MODE FRAME SIZING TESTS (bd-20vg)
12364    // =========================================================================
12365
12366    #[test]
12367    fn ui_height_returns_correct_value_inline_mode() {
12368        // Verify TerminalWriter.ui_height() returns ui_height in inline mode
12369        use crate::terminal_writer::{ScreenMode, TerminalWriter, UiAnchor};
12370        use ftui_core::terminal_capabilities::TerminalCapabilities;
12371
12372        let output = Vec::new();
12373        let writer = TerminalWriter::new(
12374            output,
12375            ScreenMode::Inline { ui_height: 10 },
12376            UiAnchor::Bottom,
12377            TerminalCapabilities::basic(),
12378        );
12379        assert_eq!(writer.ui_height(), 10);
12380    }
12381
12382    #[test]
12383    fn ui_height_returns_term_height_altscreen_mode() {
12384        // Verify TerminalWriter.ui_height() returns full terminal height in alt-screen mode
12385        use crate::terminal_writer::{ScreenMode, TerminalWriter, UiAnchor};
12386        use ftui_core::terminal_capabilities::TerminalCapabilities;
12387
12388        let output = Vec::new();
12389        let mut writer = TerminalWriter::new(
12390            output,
12391            ScreenMode::AltScreen,
12392            UiAnchor::Bottom,
12393            TerminalCapabilities::basic(),
12394        );
12395        writer.set_size(80, 24);
12396        assert_eq!(writer.ui_height(), 24);
12397    }
12398
12399    #[test]
12400    fn inline_mode_frame_uses_ui_height_not_terminal_height() {
12401        // Verify that in inline mode, the model receives a frame with ui_height,
12402        // not the full terminal height. This is the core fix for bd-20vg.
12403        use crate::simulator::ProgramSimulator;
12404        use std::cell::Cell as StdCell;
12405
12406        thread_local! {
12407            static CAPTURED_HEIGHT: StdCell<u16> = const { StdCell::new(0) };
12408        }
12409
12410        struct FrameSizeTracker;
12411
12412        #[derive(Debug)]
12413        enum SizeMsg {
12414            Check,
12415        }
12416
12417        impl From<Event> for SizeMsg {
12418            fn from(_: Event) -> Self {
12419                SizeMsg::Check
12420            }
12421        }
12422
12423        impl Model for FrameSizeTracker {
12424            type Message = SizeMsg;
12425
12426            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
12427                Cmd::none()
12428            }
12429
12430            fn view(&self, frame: &mut Frame) {
12431                // Capture the frame height we receive
12432                CAPTURED_HEIGHT.with(|h| h.set(frame.height()));
12433            }
12434        }
12435
12436        // Use simulator to verify frame dimension handling
12437        let mut sim = ProgramSimulator::new(FrameSizeTracker);
12438        sim.init();
12439
12440        // Capture with specific dimensions (simulates inline mode ui_height=10)
12441        let buf = sim.capture_frame(80, 10);
12442        assert_eq!(buf.height(), 10);
12443        assert_eq!(buf.width(), 80);
12444
12445        // Verify the frame has the correct dimensions
12446        // In inline mode with ui_height=10, the frame should be 10 rows tall,
12447        // NOT the full terminal height (e.g., 24).
12448    }
12449
12450    #[test]
12451    fn managed_hyperlinks_survive_changed_targets_abandoned_frames_and_resizes() {
12452        use ftui_render::cell::{Cell, CellAttrs, StyleFlags};
12453
12454        struct LinkModel {
12455            targets: [String; 2],
12456        }
12457
12458        impl Model for LinkModel {
12459            type Message = Event;
12460
12461            fn update(&mut self, _event: Event) -> Cmd<Event> {
12462                Cmd::none()
12463            }
12464
12465            fn view(&self, frame: &mut Frame) {
12466                for (x, (label, target)) in ['L', 'R'].iter().zip(&self.targets).enumerate() {
12467                    let id = frame.register_link(target);
12468                    frame.buffer.set_raw(
12469                        x as u16,
12470                        0,
12471                        Cell::from_char(*label).with_attrs(CellAttrs::new(StyleFlags::empty(), id)),
12472                    );
12473                }
12474            }
12475        }
12476
12477        for limit in [0, 1, 2] {
12478            let model = LinkModel {
12479                targets: Default::default(),
12480            };
12481            // Use the public constructor and App configuration, rather than
12482            // the test helper that assembles Program fields directly.
12483            let builder = App::new(model).with_hyperlink_limit(limit);
12484            let config = builder
12485                .config
12486                .with_forced_size(2, 1)
12487                .with_signal_interception(false)
12488                .without_load_governor()
12489                .without_conformal()
12490                .with_budget(FrameBudgetConfig::with_total(Duration::from_secs(5)));
12491            let mut caps = TerminalCapabilities::basic();
12492            caps.osc8_hyperlinks = true;
12493            let writer =
12494                TerminalWriter::new(Vec::new(), ScreenMode::AltScreen, UiAnchor::Bottom, caps);
12495            let events = HeadlessEventSource::new(2, 1, BackendFeatures::default());
12496            let mut program = Program::with_event_source(
12497                builder.model,
12498                events,
12499                BackendFeatures::default(),
12500                TerminalPresenter::new(writer),
12501                config,
12502            )
12503            .expect("construct actual program");
12504            let mut expected_links = Vec::new();
12505            for index in 0..256 {
12506                if index % 3 == 0 {
12507                    program.model.targets = [
12508                        format!("https://abandoned.test/{index}/left"),
12509                        format!("https://abandoned.test/{index}/right"),
12510                    ];
12511                    // A render that never reaches present must not consume
12512                    // admission or unpin the last successful frame next time.
12513                    let _abandoned = program.render_buffer(1);
12514                }
12515                if index % 64 == 0 {
12516                    program
12517                        .apply_resize(2 + (index / 64) % 2, 1, Duration::ZERO, false)
12518                        .expect("resize between link frames");
12519                }
12520                program.model.targets = [
12521                    format!("https://shown.test/{index}/left"),
12522                    format!("https://shown.test/{index}/right"),
12523                ];
12524                expected_links.extend(program.model.targets.iter().take(limit).cloned());
12525                program
12526                    .render_frame()
12527                    .expect("render and present changed URLs");
12528                assert!(program.presenter.writer.links().len() <= 2 * limit);
12529                assert!(program.presenter.writer.links().slot_count() <= 2 * limit);
12530            }
12531            let output = String::from_utf8(program.presenter.into_inner().unwrap()).unwrap();
12532            let actual_links: Vec<_> = output
12533                .split("\x1b]8;;")
12534                .skip(1)
12535                .filter_map(|part| part.split_once('\x07'))
12536                .map(|(url, _)| url)
12537                .filter(|url| !url.is_empty())
12538                .collect();
12539            assert_eq!(actual_links, expected_links, "per-frame limit {limit}");
12540            assert!(!output.contains("abandoned.test"));
12541            assert!(output.contains('L') && output.contains('R'));
12542        }
12543    }
12544
12545    #[test]
12546    fn inline_mode_program_frames_clamp_to_terminal_height_through_resizes() {
12547        use std::cell::RefCell;
12548
12549        #[derive(Default)]
12550        struct FrameSizeTracker {
12551            frame_sizes: RefCell<Vec<(u16, u16)>>,
12552        }
12553
12554        impl Model for FrameSizeTracker {
12555            type Message = Event;
12556
12557            fn update(&mut self, _event: Self::Message) -> Cmd<Self::Message> {
12558                Cmd::none()
12559            }
12560
12561            fn view(&self, frame: &mut Frame) {
12562                self.frame_sizes
12563                    .borrow_mut()
12564                    .push((frame.width(), frame.height()));
12565            }
12566        }
12567
12568        // Exercise Program's actual sizing path without supplying a model
12569        // frame size. The headless backend does not establish PTY behavior.
12570        let mut program = headless_program_with_config(
12571            FrameSizeTracker::default(),
12572            ProgramConfig {
12573                screen_mode: ScreenMode::Inline { ui_height: 64 },
12574                ..ProgramConfig::default()
12575            },
12576        );
12577        program.render_frame().expect("render initial inline frame");
12578        assert_eq!(program.model().frame_sizes.borrow().as_slice(), &[(80, 24)]);
12579        assert_eq!(program.presenter.ui_height(), 64);
12580
12581        for (width, height, expected_height) in [
12582            (40, 3, 3),
12583            (96, 18, 18),
12584            (120, 90, 64),
12585            (90, 70, 64),
12586            (80, 24, 24),
12587            (0, 0, 1),
12588        ] {
12589            program
12590                .apply_resize(width, height, Duration::ZERO, false)
12591                .expect("apply inline terminal resize");
12592            program.render_frame().expect("render resized inline frame");
12593            assert_eq!(
12594                program.model().frame_sizes.borrow().last(),
12595                Some(&(width.max(1), expected_height)),
12596                "terminal resize to {width}x{height}"
12597            );
12598            assert_eq!(
12599                program.presenter.ui_height(),
12600                64,
12601                "resizing must retain the configured inline height"
12602            );
12603        }
12604        assert_eq!(
12605            program.model().frame_sizes.borrow().as_slice(),
12606            &[
12607                (80, 24),
12608                (40, 3),
12609                (96, 18),
12610                (120, 64),
12611                (90, 64),
12612                (80, 24),
12613                (1, 1)
12614            ]
12615        );
12616    }
12617
12618    #[test]
12619    fn altscreen_frame_uses_full_terminal_height() {
12620        // Regression test: in alt-screen mode, frame should use full terminal height.
12621        use crate::terminal_writer::{ScreenMode, TerminalWriter, UiAnchor};
12622        use ftui_core::terminal_capabilities::TerminalCapabilities;
12623
12624        let output = Vec::new();
12625        let mut writer = TerminalWriter::new(
12626            output,
12627            ScreenMode::AltScreen,
12628            UiAnchor::Bottom,
12629            TerminalCapabilities::basic(),
12630        );
12631        writer.set_size(80, 40);
12632
12633        // In alt-screen, ui_height equals terminal height
12634        assert_eq!(writer.ui_height(), 40);
12635    }
12636
12637    #[test]
12638    fn ui_height_clamped_to_terminal_height() {
12639        // Verify ui_height doesn't exceed terminal height
12640        // (This is handled in present_inline, but ui_height() returns the configured value)
12641        use crate::terminal_writer::{ScreenMode, TerminalWriter, UiAnchor};
12642        use ftui_core::terminal_capabilities::TerminalCapabilities;
12643
12644        let output = Vec::new();
12645        let mut writer = TerminalWriter::new(
12646            output,
12647            ScreenMode::Inline { ui_height: 100 },
12648            UiAnchor::Bottom,
12649            TerminalCapabilities::basic(),
12650        );
12651        writer.set_size(80, 10);
12652
12653        // ui_height() retains the configured value. render_height_hint() and
12654        // present_inline clamp the model frame and visible region separately.
12655        assert_eq!(writer.ui_height(), 100);
12656    }
12657
12658    // =========================================================================
12659    // TICK DELIVERY TESTS (bd-3ufh)
12660    // =========================================================================
12661
12662    #[test]
12663    fn tick_event_delivered_to_model_update() {
12664        // Verify that Event::Tick is delivered to model.update()
12665        // This is the core fix: ticks now flow through the update pipeline.
12666        use crate::simulator::ProgramSimulator;
12667
12668        struct TickTracker {
12669            tick_count: usize,
12670        }
12671
12672        #[derive(Debug)]
12673        enum TickMsg {
12674            Tick,
12675            Other,
12676        }
12677
12678        impl From<Event> for TickMsg {
12679            fn from(event: Event) -> Self {
12680                match event {
12681                    Event::Tick => TickMsg::Tick,
12682                    _ => TickMsg::Other,
12683                }
12684            }
12685        }
12686
12687        impl Model for TickTracker {
12688            type Message = TickMsg;
12689
12690            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
12691                match msg {
12692                    TickMsg::Tick => {
12693                        self.tick_count += 1;
12694                        Cmd::none()
12695                    }
12696                    TickMsg::Other => Cmd::none(),
12697                }
12698            }
12699
12700            fn view(&self, _frame: &mut Frame) {}
12701        }
12702
12703        let mut sim = ProgramSimulator::new(TickTracker { tick_count: 0 });
12704        sim.init();
12705
12706        // Manually inject tick event to simulate what the runtime does
12707        sim.inject_event(Event::Tick);
12708        assert_eq!(sim.model().tick_count, 1);
12709
12710        sim.inject_event(Event::Tick);
12711        sim.inject_event(Event::Tick);
12712        assert_eq!(sim.model().tick_count, 3);
12713    }
12714
12715    #[test]
12716    fn tick_command_sets_tick_rate() {
12717        // Verify Cmd::tick() sets the tick rate in the simulator
12718        use crate::simulator::{CmdRecord, ProgramSimulator};
12719
12720        struct TickModel;
12721
12722        #[derive(Debug)]
12723        enum Msg {
12724            SetTick,
12725            Noop,
12726        }
12727
12728        impl From<Event> for Msg {
12729            fn from(_: Event) -> Self {
12730                Msg::Noop
12731            }
12732        }
12733
12734        impl Model for TickModel {
12735            type Message = Msg;
12736
12737            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
12738                match msg {
12739                    Msg::SetTick => Cmd::tick(Duration::from_millis(100)),
12740                    Msg::Noop => Cmd::none(),
12741                }
12742            }
12743
12744            fn view(&self, _frame: &mut Frame) {}
12745        }
12746
12747        let mut sim = ProgramSimulator::new(TickModel);
12748        sim.init();
12749        sim.send(Msg::SetTick);
12750
12751        // Check that tick was recorded
12752        let commands = sim.command_log();
12753        assert!(
12754            commands
12755                .iter()
12756                .any(|c| matches!(c, CmdRecord::Tick(d) if *d == Duration::from_millis(100)))
12757        );
12758    }
12759
12760    #[test]
12761    fn tick_can_trigger_further_commands() {
12762        // Verify that tick handling can return commands that are executed
12763        use crate::simulator::ProgramSimulator;
12764
12765        struct ChainModel {
12766            stage: usize,
12767        }
12768
12769        #[derive(Debug)]
12770        enum ChainMsg {
12771            Tick,
12772            Advance,
12773            Noop,
12774        }
12775
12776        impl From<Event> for ChainMsg {
12777            fn from(event: Event) -> Self {
12778                match event {
12779                    Event::Tick => ChainMsg::Tick,
12780                    _ => ChainMsg::Noop,
12781                }
12782            }
12783        }
12784
12785        impl Model for ChainModel {
12786            type Message = ChainMsg;
12787
12788            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
12789                match msg {
12790                    ChainMsg::Tick => {
12791                        self.stage += 1;
12792                        // Return another message to be processed
12793                        Cmd::msg(ChainMsg::Advance)
12794                    }
12795                    ChainMsg::Advance => {
12796                        self.stage += 10;
12797                        Cmd::none()
12798                    }
12799                    ChainMsg::Noop => Cmd::none(),
12800                }
12801            }
12802
12803            fn view(&self, _frame: &mut Frame) {}
12804        }
12805
12806        let mut sim = ProgramSimulator::new(ChainModel { stage: 0 });
12807        sim.init();
12808        sim.inject_event(Event::Tick);
12809
12810        // Tick increments by 1, then Advance increments by 10
12811        assert_eq!(sim.model().stage, 11);
12812    }
12813
12814    #[test]
12815    fn tick_disabled_with_zero_duration() {
12816        // Verify that Duration::ZERO disables ticks (no busy loop)
12817        use crate::simulator::ProgramSimulator;
12818
12819        struct ZeroTickModel {
12820            disabled: bool,
12821        }
12822
12823        #[derive(Debug)]
12824        enum ZeroMsg {
12825            DisableTick,
12826            Noop,
12827        }
12828
12829        impl From<Event> for ZeroMsg {
12830            fn from(_: Event) -> Self {
12831                ZeroMsg::Noop
12832            }
12833        }
12834
12835        impl Model for ZeroTickModel {
12836            type Message = ZeroMsg;
12837
12838            fn init(&mut self) -> Cmd<Self::Message> {
12839                // Start with a tick enabled
12840                Cmd::tick(Duration::from_millis(100))
12841            }
12842
12843            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
12844                match msg {
12845                    ZeroMsg::DisableTick => {
12846                        self.disabled = true;
12847                        // Setting tick to ZERO should effectively disable
12848                        Cmd::tick(Duration::ZERO)
12849                    }
12850                    ZeroMsg::Noop => Cmd::none(),
12851                }
12852            }
12853
12854            fn view(&self, _frame: &mut Frame) {}
12855        }
12856
12857        let mut sim = ProgramSimulator::new(ZeroTickModel { disabled: false });
12858        sim.init();
12859
12860        // Verify initial tick rate is set
12861        assert!(sim.tick_rate().is_some());
12862        assert_eq!(sim.tick_rate(), Some(Duration::from_millis(100)));
12863
12864        // Disable ticks
12865        sim.send(ZeroMsg::DisableTick);
12866        assert!(sim.model().disabled);
12867
12868        // Note: The simulator still records the ZERO tick, but the runtime's
12869        // should_tick() handles ZERO duration appropriately
12870        assert_eq!(sim.tick_rate(), Some(Duration::ZERO));
12871    }
12872
12873    #[test]
12874    fn tick_event_distinguishable_from_other_events() {
12875        // Verify Event::Tick can be distinguished in pattern matching
12876        let tick = Event::Tick;
12877        let key = Event::Key(ftui_core::event::KeyEvent::new(
12878            ftui_core::event::KeyCode::Char('a'),
12879        ));
12880
12881        assert!(matches!(tick, Event::Tick));
12882        assert!(!matches!(key, Event::Tick));
12883    }
12884
12885    #[test]
12886    fn tick_event_clone_and_eq() {
12887        // Verify Event::Tick implements Clone and Eq correctly
12888        let tick1 = Event::Tick;
12889        let tick2 = tick1.clone();
12890        assert_eq!(tick1, tick2);
12891    }
12892
12893    #[test]
12894    fn model_receives_tick_and_input_events() {
12895        // Verify model can handle both tick and input events correctly
12896        use crate::simulator::ProgramSimulator;
12897
12898        struct MixedModel {
12899            ticks: usize,
12900            keys: usize,
12901        }
12902
12903        #[derive(Debug)]
12904        enum MixedMsg {
12905            Tick,
12906            Key,
12907        }
12908
12909        impl From<Event> for MixedMsg {
12910            fn from(event: Event) -> Self {
12911                match event {
12912                    Event::Tick => MixedMsg::Tick,
12913                    _ => MixedMsg::Key,
12914                }
12915            }
12916        }
12917
12918        impl Model for MixedModel {
12919            type Message = MixedMsg;
12920
12921            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
12922                match msg {
12923                    MixedMsg::Tick => {
12924                        self.ticks += 1;
12925                        Cmd::none()
12926                    }
12927                    MixedMsg::Key => {
12928                        self.keys += 1;
12929                        Cmd::none()
12930                    }
12931                }
12932            }
12933
12934            fn view(&self, _frame: &mut Frame) {}
12935        }
12936
12937        let mut sim = ProgramSimulator::new(MixedModel { ticks: 0, keys: 0 });
12938        sim.init();
12939
12940        // Interleave tick and input events
12941        sim.inject_event(Event::Tick);
12942        sim.inject_event(Event::Key(ftui_core::event::KeyEvent::new(
12943            ftui_core::event::KeyCode::Char('a'),
12944        )));
12945        sim.inject_event(Event::Tick);
12946        sim.inject_event(Event::Key(ftui_core::event::KeyEvent::new(
12947            ftui_core::event::KeyCode::Char('b'),
12948        )));
12949        sim.inject_event(Event::Tick);
12950
12951        assert_eq!(sim.model().ticks, 3);
12952        assert_eq!(sim.model().keys, 2);
12953    }
12954
12955    // =========================================================================
12956    // HEADLESS PROGRAM TESTS (bd-1av4o.2)
12957    // =========================================================================
12958
12959    fn headless_program_with_resolved_config<M: Model>(
12960        model: M,
12961        config: ProgramConfig,
12962    ) -> Program<M, HeadlessEventSource, TerminalPresenter<Vec<u8>>>
12963    where
12964        M::Message: Send + 'static,
12965    {
12966        let effect_queue_config =
12967            config.resolved_effect_queue_config(config.runtime_lane.resolve());
12968        let capabilities = TerminalCapabilities::basic();
12969        let mut writer = TerminalWriter::with_diff_config(
12970            Vec::new(),
12971            config.screen_mode,
12972            config.ui_anchor,
12973            capabilities,
12974            config.diff_config.clone(),
12975        );
12976        if let Some(limit) = config.hyperlink_limit {
12977            writer.set_hyperlink_limit(limit);
12978        }
12979        let frame_timing = config.frame_timing.clone();
12980        writer.set_timing_enabled(frame_timing.is_some());
12981
12982        let (width, height) = config.forced_size.unwrap_or((80, 24));
12983        let width = width.max(1);
12984        let height = height.max(1);
12985        writer.set_size(width, height);
12986
12987        let mouse_capture = config.resolved_mouse_capture();
12988        let initial_features = BackendFeatures {
12989            mouse_capture,
12990            bracketed_paste: config.bracketed_paste,
12991            focus_events: config.focus_reporting,
12992            kitty_keyboard: config.kitty_keyboard,
12993        };
12994        let events = HeadlessEventSource::new(width, height, initial_features);
12995        let evidence_sink = EvidenceSink::from_config(&config.evidence_sink)
12996            .expect("headless evidence sink config");
12997
12998        let budget = render_budget_from_program_config(&config);
12999        let load_governor = LoadGovernorState::new(
13000            config.load_governor.clone(),
13001            effect_queue_config.max_queue_depth,
13002        );
13003        let conformal_predictor = config
13004            .conformal_config
13005            .clone()
13006            .map(ConformalPredictor::new)
13007            .transpose()
13008            .expect("valid headless conformal config");
13009        let locale_context = config.locale_context.clone();
13010        let locale_version = locale_context.version();
13011        let mut resize_coalescer =
13012            ResizeCoalescer::new(config.resize_coalescer.clone(), (width, height));
13013        if let Some(ref sink) = evidence_sink {
13014            resize_coalescer = resize_coalescer.with_evidence_sink(sink.clone());
13015        }
13016        let subscriptions = SubscriptionManager::new();
13017        let (task_sender, task_receiver) = std::sync::mpsc::channel();
13018        let inline_auto_remeasure = config
13019            .inline_auto_remeasure
13020            .clone()
13021            .map(InlineAutoRemeasureState::new);
13022        let gesture_recognizer = config
13023            .gestures
13024            .clone()
13025            .map(ftui_core::gesture::GestureRecognizer::new);
13026        let event_coalescer = if config.event_coalescing {
13027            Some(ftui_core::event_coalescer::EventCoalescer::new())
13028        } else {
13029            None
13030        };
13031        let guardrails = FrameGuardrails::new(config.guardrails);
13032        let task_executor = TaskExecutor::new(
13033            &effect_queue_config,
13034            task_sender.clone(),
13035            evidence_sink.clone(),
13036        )
13037        .expect("task executor");
13038
13039        Program {
13040            model,
13041            presenter: TerminalPresenter::new(writer),
13042            events,
13043            backend_features: initial_features,
13044            running: true,
13045            shutdown_complete: false,
13046            tick_rate: None,
13047            executed_cmd_count: 0,
13048            last_tick: Instant::now(),
13049            dirty: true,
13050            frame_idx: 0,
13051            tick_count: 0,
13052            widget_signals: Vec::new(),
13053            a11y_policy: config.accessibility,
13054            a11y_evidence_text: config.accessibility_evidence_text,
13055            a11y_tree: None,
13056            a11y_order: Vec::new(),
13057            a11y_announcements: Vec::new(),
13058            a11y_pending: None,
13059            a11y_changed: false,
13060            a11y_dropped: 0,
13061            startup_events: Vec::new(),
13062            startup_parser: ftui_core::input_parser::InputParser::new(),
13063            widget_refresh_config: config.widget_refresh,
13064            widget_refresh_plan: WidgetRefreshPlan::new(),
13065            width,
13066            height,
13067            forced_size: config.forced_size,
13068            poll_timeout: config.poll_timeout,
13069            intercept_signals: config.intercept_signals,
13070            pending_signal: Arc::new(std::sync::atomic::AtomicI32::new(0)),
13071            // Headless test programs never install an OS signal handler, so
13072            // they must not read (or clear) the process-global slot: that is
13073            // exactly the cross-test race that used to hang this binary.
13074            global_signal_slot: false,
13075            // Headless: no terminal to release and no OS handler, so stop
13076            // requests are ignored; tests that need the sequence build a
13077            // program over an event source that supports suspend.
13078            pending_suspend: Arc::new(std::sync::atomic::AtomicI32::new(0)),
13079            suspend_enabled: false,
13080            ctrl_z_suspends: config.ctrl_z_suspends,
13081            job_control_claim: None,
13082            stop_process: ftui_core::job_control::stop_process,
13083            immediate_drain_config: config.immediate_drain,
13084            immediate_drain_stats: ImmediateDrainStats::default(),
13085            budget,
13086            load_governor,
13087            conformal_predictor,
13088            last_frame_time_us: None,
13089            last_update_us: None,
13090            frame_timing,
13091            locale_context,
13092            locale_version,
13093            resize_coalescer,
13094            evidence_sink,
13095            fairness_config_logged: false,
13096            resize_behavior: config.resize_behavior,
13097            fairness_guard: InputFairnessGuard::new(),
13098            event_recorder: None,
13099            subscriptions,
13100            #[cfg(test)]
13101            task_sender,
13102            task_receiver,
13103            task_executor,
13104            state_registry: config.persistence.registry.clone(),
13105            persistence_config: config.persistence,
13106            last_checkpoint: Instant::now(),
13107            inline_auto_remeasure,
13108            gesture_recognizer,
13109            event_coalescer,
13110            frame_arena: FrameArena::default(),
13111            guardrails,
13112            last_soft_trim_frame: None,
13113            tick_strategy: config
13114                .tick_strategy
13115                .map(|strategy| Box::new(strategy) as Box<dyn crate::tick_strategy::TickStrategy>),
13116            last_active_screen_for_strategy: None,
13117        }
13118    }
13119
13120    fn headless_program_with_config<M: Model>(
13121        model: M,
13122        config: ProgramConfig,
13123    ) -> Program<M, HeadlessEventSource, TerminalPresenter<Vec<u8>>>
13124    where
13125        M::Message: Send + 'static,
13126    {
13127        // Headless unit tests should not observe process-global shutdown state
13128        // unless they explicitly opt into signal interception.
13129        headless_program_with_resolved_config(model, config.with_signal_interception(false))
13130    }
13131
13132    fn headless_signal_program_with_config<M: Model>(
13133        model: M,
13134        config: ProgramConfig,
13135    ) -> Program<M, HeadlessEventSource, TerminalPresenter<Vec<u8>>>
13136    where
13137        M::Message: Send + 'static,
13138    {
13139        headless_program_with_resolved_config(model, config)
13140    }
13141
13142    fn temp_evidence_path(label: &str) -> PathBuf {
13143        // Retain evidence even if the test panics, with a fresh directory per run.
13144        let dir = tempfile::Builder::new()
13145            .prefix(&format!("ftui-program-{label}-"))
13146            .disable_cleanup(true)
13147            .tempdir()
13148            .expect("create retained evidence directory");
13149        dir.path().join("evidence.jsonl")
13150    }
13151
13152    fn read_evidence_event(path: &PathBuf, event: &str) -> Value {
13153        let jsonl = std::fs::read_to_string(path).expect("read evidence jsonl");
13154        let needle = format!("\"event\":\"{event}\"");
13155        let missing_msg = format!("missing {event} line");
13156        let line = jsonl
13157            .lines()
13158            .find(|line| line.contains(&needle))
13159            .expect(&missing_msg);
13160        serde_json::from_str(line).expect("valid evidence json")
13161    }
13162
13163    #[test]
13164    fn startup_emits_capability_decision_per_capability() {
13165        use ftui_core::caps_probe::{CapabilityDecision, ProbeOutcome, ProbeableCapability};
13166
13167        let evidence_path = temp_evidence_path("startup_emits_capability_decision");
13168        let sink = EvidenceSink::from_config(
13169            &crate::evidence_sink::EvidenceSinkConfig::enabled_file(&evidence_path),
13170        )
13171        .expect("sink config")
13172        .expect("sink enabled");
13173
13174        let decisions: Vec<CapabilityDecision> = ProbeableCapability::ALL
13175            .iter()
13176            .map(|&cap| {
13177                CapabilityDecision::build(cap, false, ProbeOutcome::Confirmed, None, false, true)
13178            })
13179            .collect();
13180
13181        assert_eq!(decisions.len(), ProbeableCapability::ALL.len());
13182
13183        let writer = TerminalWriter::new(
13184            Vec::new(),
13185            ScreenMode::Inline { ui_height: 5 },
13186            UiAnchor::Bottom,
13187            TerminalCapabilities::basic(),
13188        )
13189        .with_evidence_sink(sink)
13190        .with_capability_decisions(decisions);
13191        drop(writer);
13192
13193        let contents = std::fs::read_to_string(&evidence_path).expect("evidence file written");
13194        let cap_lines: Vec<&str> = contents
13195            .lines()
13196            .filter(|l| l.contains(r#""event":"capability_decision""#))
13197            .collect();
13198        assert_eq!(
13199            cap_lines.len(),
13200            ProbeableCapability::ALL.len(),
13201            "expected {} capability_decision lines, got {}",
13202            ProbeableCapability::ALL.len(),
13203            cap_lines.len()
13204        );
13205        for cap in ProbeableCapability::ALL {
13206            let cap_str = cap.as_str();
13207            assert!(
13208                cap_lines
13209                    .iter()
13210                    .any(|l| l.contains(&format!(r#""capability":"{cap_str}""#))),
13211                "missing capability_decision line for {cap_str}"
13212            );
13213        }
13214    }
13215
13216    #[test]
13217    fn headless_apply_resize_updates_model_and_dimensions() {
13218        struct ResizeModel {
13219            last_size: Option<(u16, u16)>,
13220        }
13221
13222        #[derive(Debug)]
13223        enum ResizeMsg {
13224            Resize(u16, u16),
13225            Other,
13226        }
13227
13228        impl From<Event> for ResizeMsg {
13229            fn from(event: Event) -> Self {
13230                match event {
13231                    Event::Resize { width, height } => ResizeMsg::Resize(width, height),
13232                    _ => ResizeMsg::Other,
13233                }
13234            }
13235        }
13236
13237        impl Model for ResizeModel {
13238            type Message = ResizeMsg;
13239
13240            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
13241                if let ResizeMsg::Resize(w, h) = msg {
13242                    self.last_size = Some((w, h));
13243                }
13244                Cmd::none()
13245            }
13246
13247            fn view(&self, _frame: &mut Frame) {}
13248        }
13249
13250        let mut program =
13251            headless_program_with_config(ResizeModel { last_size: None }, ProgramConfig::default());
13252        program.dirty = false;
13253
13254        program
13255            .apply_resize(0, 0, Duration::ZERO, false)
13256            .expect("resize");
13257
13258        assert_eq!(program.width, 1);
13259        assert_eq!(program.height, 1);
13260        assert_eq!(program.model().last_size, Some((1, 1)));
13261        assert!(program.dirty);
13262    }
13263
13264    #[test]
13265    fn headless_apply_resize_reconciles_subscriptions() {
13266        use crate::subscription::{StopSignal, SubId, Subscription, SubscriptionSender};
13267
13268        struct ResizeSubModel {
13269            subscribed: bool,
13270        }
13271
13272        #[derive(Debug)]
13273        enum ResizeSubMsg {
13274            Resize,
13275            Other,
13276        }
13277
13278        impl From<Event> for ResizeSubMsg {
13279            fn from(event: Event) -> Self {
13280                match event {
13281                    Event::Resize { .. } => Self::Resize,
13282                    _ => Self::Other,
13283                }
13284            }
13285        }
13286
13287        impl Model for ResizeSubModel {
13288            type Message = ResizeSubMsg;
13289
13290            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
13291                if matches!(msg, ResizeSubMsg::Resize) {
13292                    self.subscribed = true;
13293                }
13294                Cmd::none()
13295            }
13296
13297            fn view(&self, _frame: &mut Frame) {}
13298
13299            fn subscriptions(&self) -> Vec<Box<dyn Subscription<Self::Message>>> {
13300                if self.subscribed {
13301                    vec![Box::new(ResizeSubscription)]
13302                } else {
13303                    vec![]
13304                }
13305            }
13306        }
13307
13308        struct ResizeSubscription;
13309
13310        impl Subscription<ResizeSubMsg> for ResizeSubscription {
13311            fn id(&self) -> SubId {
13312                1
13313            }
13314
13315            fn run(&self, _sender: SubscriptionSender<ResizeSubMsg>, _stop: StopSignal) {}
13316        }
13317
13318        let mut program = headless_program_with_config(
13319            ResizeSubModel { subscribed: false },
13320            ProgramConfig::default(),
13321        );
13322
13323        assert_eq!(program.subscriptions.active_count(), 0);
13324        program
13325            .apply_resize(120, 40, Duration::ZERO, false)
13326            .expect("resize");
13327
13328        assert!(program.model().subscribed);
13329        assert_eq!(program.subscriptions.active_count(), 1);
13330    }
13331
13332    #[test]
13333    fn headless_execute_cmd_log_writes_output() {
13334        let mut program =
13335            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
13336        program.execute_cmd(Cmd::log("hello world")).expect("log");
13337
13338        let bytes = program.presenter.into_inner().expect("writer output");
13339        let output = String::from_utf8_lossy(&bytes);
13340        assert!(output.contains("hello world"));
13341    }
13342
13343    #[test]
13344    fn headless_process_task_results_updates_model() {
13345        struct TaskModel {
13346            updates: usize,
13347        }
13348
13349        #[derive(Debug)]
13350        enum TaskMsg {
13351            Done,
13352        }
13353
13354        impl From<Event> for TaskMsg {
13355            fn from(_: Event) -> Self {
13356                TaskMsg::Done
13357            }
13358        }
13359
13360        impl Model for TaskModel {
13361            type Message = TaskMsg;
13362
13363            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
13364                self.updates += 1;
13365                Cmd::none()
13366            }
13367
13368            fn view(&self, _frame: &mut Frame) {}
13369        }
13370
13371        let mut program =
13372            headless_program_with_config(TaskModel { updates: 0 }, ProgramConfig::default());
13373        program.dirty = false;
13374        program.task_sender.send(TaskMsg::Done).unwrap();
13375
13376        program
13377            .process_task_results()
13378            .expect("process task results");
13379        assert_eq!(program.model().updates, 1);
13380        assert!(program.dirty);
13381    }
13382
13383    #[test]
13384    fn run_invokes_on_shutdown_after_quit() {
13385        use std::sync::{
13386            Arc,
13387            atomic::{AtomicUsize, Ordering},
13388        };
13389
13390        struct ShutdownModel {
13391            shutdowns: Arc<AtomicUsize>,
13392        }
13393
13394        #[derive(Debug, Clone, Copy)]
13395        enum ShutdownMsg {
13396            Quit,
13397            ShutdownRan,
13398        }
13399
13400        impl From<Event> for ShutdownMsg {
13401            fn from(_: Event) -> Self {
13402                ShutdownMsg::Quit
13403            }
13404        }
13405
13406        impl Model for ShutdownModel {
13407            type Message = ShutdownMsg;
13408
13409            fn init(&mut self) -> Cmd<Self::Message> {
13410                Cmd::quit()
13411            }
13412
13413            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
13414                match msg {
13415                    ShutdownMsg::Quit => Cmd::quit(),
13416                    ShutdownMsg::ShutdownRan => {
13417                        self.shutdowns.fetch_add(1, Ordering::SeqCst);
13418                        Cmd::none()
13419                    }
13420                }
13421            }
13422
13423            fn view(&self, _frame: &mut Frame) {}
13424
13425            fn on_shutdown(&mut self) -> Cmd<Self::Message> {
13426                Cmd::msg(ShutdownMsg::ShutdownRan)
13427            }
13428        }
13429
13430        let shutdowns = Arc::new(AtomicUsize::new(0));
13431        let mut program = headless_program_with_config(
13432            ShutdownModel {
13433                shutdowns: Arc::clone(&shutdowns),
13434            },
13435            ProgramConfig::default(),
13436        );
13437
13438        program.run().expect("program run");
13439
13440        assert_eq!(shutdowns.load(Ordering::SeqCst), 1);
13441    }
13442
13443    #[test]
13444    fn run_processes_shutdown_task_results_before_exit() {
13445        use std::sync::{
13446            Arc,
13447            atomic::{AtomicUsize, Ordering},
13448        };
13449
13450        struct ShutdownTaskModel {
13451            shutdowns: Arc<AtomicUsize>,
13452        }
13453
13454        #[derive(Debug, Clone, Copy)]
13455        enum ShutdownTaskMsg {
13456            Quit,
13457            ShutdownRan,
13458        }
13459
13460        impl From<Event> for ShutdownTaskMsg {
13461            fn from(_: Event) -> Self {
13462                ShutdownTaskMsg::Quit
13463            }
13464        }
13465
13466        impl Model for ShutdownTaskModel {
13467            type Message = ShutdownTaskMsg;
13468
13469            fn init(&mut self) -> Cmd<Self::Message> {
13470                Cmd::quit()
13471            }
13472
13473            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
13474                match msg {
13475                    ShutdownTaskMsg::Quit => Cmd::quit(),
13476                    ShutdownTaskMsg::ShutdownRan => {
13477                        self.shutdowns.fetch_add(1, Ordering::SeqCst);
13478                        Cmd::none()
13479                    }
13480                }
13481            }
13482
13483            fn view(&self, _frame: &mut Frame) {}
13484
13485            fn on_shutdown(&mut self) -> Cmd<Self::Message> {
13486                Cmd::task(|| ShutdownTaskMsg::ShutdownRan)
13487            }
13488        }
13489
13490        let shutdowns = Arc::new(AtomicUsize::new(0));
13491        let mut program = headless_program_with_config(
13492            ShutdownTaskModel {
13493                shutdowns: Arc::clone(&shutdowns),
13494            },
13495            ProgramConfig::default(),
13496        );
13497
13498        program.run().expect("program run");
13499
13500        assert_eq!(shutdowns.load(Ordering::SeqCst), 1);
13501    }
13502
13503    #[test]
13504    fn run_processes_shutdown_task_results_with_effect_queue_backend() {
13505        use std::sync::{
13506            Arc,
13507            atomic::{AtomicUsize, Ordering},
13508        };
13509
13510        struct ShutdownTaskModel {
13511            shutdowns: Arc<AtomicUsize>,
13512        }
13513
13514        #[derive(Debug, Clone, Copy)]
13515        enum ShutdownTaskMsg {
13516            Quit,
13517            ShutdownRan,
13518        }
13519
13520        impl From<Event> for ShutdownTaskMsg {
13521            fn from(_: Event) -> Self {
13522                ShutdownTaskMsg::Quit
13523            }
13524        }
13525
13526        impl Model for ShutdownTaskModel {
13527            type Message = ShutdownTaskMsg;
13528
13529            fn init(&mut self) -> Cmd<Self::Message> {
13530                Cmd::quit()
13531            }
13532
13533            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
13534                match msg {
13535                    ShutdownTaskMsg::Quit => Cmd::quit(),
13536                    ShutdownTaskMsg::ShutdownRan => {
13537                        self.shutdowns.fetch_add(1, Ordering::SeqCst);
13538                        Cmd::none()
13539                    }
13540                }
13541            }
13542
13543            fn view(&self, _frame: &mut Frame) {}
13544
13545            fn on_shutdown(&mut self) -> Cmd<Self::Message> {
13546                Cmd::task(|| ShutdownTaskMsg::ShutdownRan)
13547            }
13548        }
13549
13550        let shutdowns = Arc::new(AtomicUsize::new(0));
13551        let mut program = headless_program_with_config(
13552            ShutdownTaskModel {
13553                shutdowns: Arc::clone(&shutdowns),
13554            },
13555            ProgramConfig::default().with_effect_queue(
13556                EffectQueueConfig::default().with_backend(TaskExecutorBackend::EffectQueue),
13557            ),
13558        );
13559
13560        program.run().expect("program run");
13561
13562        assert_eq!(shutdowns.load(Ordering::SeqCst), 1);
13563    }
13564
13565    #[test]
13566    fn shutdown_task_results_do_not_spawn_follow_up_tasks_after_executor_shutdown() {
13567        use std::sync::{
13568            Arc,
13569            atomic::{AtomicUsize, Ordering},
13570        };
13571
13572        struct ShutdownTaskModel {
13573            shutdowns: Arc<AtomicUsize>,
13574            follow_up_runs: Arc<AtomicUsize>,
13575        }
13576
13577        #[derive(Debug, Clone, Copy)]
13578        enum ShutdownTaskMsg {
13579            Quit,
13580            ShutdownRan,
13581            FollowUp,
13582        }
13583
13584        impl From<Event> for ShutdownTaskMsg {
13585            fn from(_: Event) -> Self {
13586                ShutdownTaskMsg::Quit
13587            }
13588        }
13589
13590        impl Model for ShutdownTaskModel {
13591            type Message = ShutdownTaskMsg;
13592
13593            fn init(&mut self) -> Cmd<Self::Message> {
13594                Cmd::quit()
13595            }
13596
13597            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
13598                match msg {
13599                    ShutdownTaskMsg::Quit => Cmd::quit(),
13600                    ShutdownTaskMsg::ShutdownRan => {
13601                        self.shutdowns.fetch_add(1, Ordering::SeqCst);
13602                        let follow_up_runs = Arc::clone(&self.follow_up_runs);
13603                        Cmd::task(move || {
13604                            follow_up_runs.fetch_add(1, Ordering::SeqCst);
13605                            ShutdownTaskMsg::FollowUp
13606                        })
13607                    }
13608                    ShutdownTaskMsg::FollowUp => {
13609                        self.follow_up_runs.fetch_add(1, Ordering::SeqCst);
13610                        Cmd::none()
13611                    }
13612                }
13613            }
13614
13615            fn view(&self, _frame: &mut Frame) {}
13616
13617            fn on_shutdown(&mut self) -> Cmd<Self::Message> {
13618                Cmd::task(|| ShutdownTaskMsg::ShutdownRan)
13619            }
13620        }
13621
13622        let shutdowns = Arc::new(AtomicUsize::new(0));
13623        let follow_up_runs = Arc::new(AtomicUsize::new(0));
13624        let mut program = headless_program_with_config(
13625            ShutdownTaskModel {
13626                shutdowns: Arc::clone(&shutdowns),
13627                follow_up_runs: Arc::clone(&follow_up_runs),
13628            },
13629            ProgramConfig::default(),
13630        );
13631
13632        program.run().expect("program run");
13633
13634        assert_eq!(shutdowns.load(Ordering::SeqCst), 1);
13635        assert_eq!(follow_up_runs.load(Ordering::SeqCst), 0);
13636    }
13637
13638    #[test]
13639    fn run_quit_from_init_skips_initial_render_and_subscription_start() {
13640        use crate::subscription::{StopSignal, SubId, Subscription, SubscriptionSender};
13641
13642        struct InitQuitModel {
13643            render_calls: Arc<AtomicUsize>,
13644            subscription_starts: Arc<AtomicUsize>,
13645        }
13646
13647        #[derive(Debug, Clone, Copy)]
13648        enum InitQuitMsg {
13649            Noop,
13650        }
13651
13652        impl From<Event> for InitQuitMsg {
13653            fn from(_: Event) -> Self {
13654                Self::Noop
13655            }
13656        }
13657
13658        impl Model for InitQuitModel {
13659            type Message = InitQuitMsg;
13660
13661            fn init(&mut self) -> Cmd<Self::Message> {
13662                Cmd::quit()
13663            }
13664
13665            fn update(&mut self, _: Self::Message) -> Cmd<Self::Message> {
13666                Cmd::none()
13667            }
13668
13669            fn view(&self, _frame: &mut Frame) {
13670                self.render_calls.fetch_add(1, Ordering::SeqCst);
13671            }
13672
13673            fn subscriptions(&self) -> Vec<Box<dyn Subscription<Self::Message>>> {
13674                vec![Box::new(InitQuitSubscription {
13675                    starts: Arc::clone(&self.subscription_starts),
13676                })]
13677            }
13678        }
13679
13680        struct InitQuitSubscription {
13681            starts: Arc<AtomicUsize>,
13682        }
13683
13684        impl Subscription<InitQuitMsg> for InitQuitSubscription {
13685            fn id(&self) -> SubId {
13686                1
13687            }
13688
13689            fn run(&self, _sender: SubscriptionSender<InitQuitMsg>, stop: StopSignal) {
13690                self.starts.fetch_add(1, Ordering::SeqCst);
13691                let _ = stop.wait_timeout(Duration::from_millis(10));
13692            }
13693        }
13694
13695        let render_calls = Arc::new(AtomicUsize::new(0));
13696        let subscription_starts = Arc::new(AtomicUsize::new(0));
13697        let mut program = headless_program_with_config(
13698            InitQuitModel {
13699                render_calls: Arc::clone(&render_calls),
13700                subscription_starts: Arc::clone(&subscription_starts),
13701            },
13702            ProgramConfig::default(),
13703        );
13704
13705        program.run().expect("program run");
13706
13707        assert_eq!(render_calls.load(Ordering::SeqCst), 0);
13708        assert_eq!(subscription_starts.load(Ordering::SeqCst), 0);
13709    }
13710
13711    #[test]
13712    fn run_invokes_on_shutdown_before_returning_signal_error() {
13713        use std::sync::{
13714            Arc,
13715            atomic::{AtomicUsize, Ordering},
13716        };
13717
13718        struct ShutdownModel {
13719            shutdowns: Arc<AtomicUsize>,
13720        }
13721
13722        #[derive(Debug, Clone, Copy)]
13723        enum ShutdownMsg {
13724            Noop,
13725            ShutdownRan,
13726        }
13727
13728        impl From<Event> for ShutdownMsg {
13729            fn from(_: Event) -> Self {
13730                ShutdownMsg::Noop
13731            }
13732        }
13733
13734        impl Model for ShutdownModel {
13735            type Message = ShutdownMsg;
13736
13737            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
13738                match msg {
13739                    ShutdownMsg::Noop => Cmd::none(),
13740                    ShutdownMsg::ShutdownRan => {
13741                        self.shutdowns.fetch_add(1, Ordering::SeqCst);
13742                        Cmd::none()
13743                    }
13744                }
13745            }
13746
13747            fn view(&self, _frame: &mut Frame) {}
13748
13749            fn on_shutdown(&mut self) -> Cmd<Self::Message> {
13750                Cmd::msg(ShutdownMsg::ShutdownRan)
13751            }
13752        }
13753
13754        let shutdowns = Arc::new(AtomicUsize::new(0));
13755        let mut program = headless_signal_program_with_config(
13756            ShutdownModel {
13757                shutdowns: Arc::clone(&shutdowns),
13758            },
13759            ProgramConfig::default().with_signal_interception(true),
13760        );
13761
13762        program.inject_termination_signal(2);
13763        let err = program.run().expect_err("signal should stop runtime");
13764
13765        assert_eq!(shutdowns.load(Ordering::SeqCst), 1);
13766        assert_eq!(signal_termination_from_error(&err), Some(2));
13767        assert_eq!(program.pending_termination_signal(), None);
13768    }
13769
13770    /// Regression test for the cross-test signal race: two headless programs
13771    /// running concurrently, each with its own injected signal, must both
13772    /// terminate with their own signal. Before the per-program slot existed,
13773    /// any other test constructing or finishing a headless program cleared
13774    /// the process-global slot and left the loop waiting forever.
13775    #[test]
13776    fn two_concurrent_headless_programs_with_independent_pending_signals_both_terminate() {
13777        fn run_with_signal(signal: i32) -> Option<i32> {
13778            let mut program = headless_signal_program_with_config(
13779                TestModel { value: 0 },
13780                ProgramConfig::default().with_signal_interception(true),
13781            );
13782            program.inject_termination_signal(signal);
13783            let err = program.run().expect_err("signal should stop runtime");
13784            assert_eq!(program.pending_termination_signal(), None);
13785            signal_termination_from_error(&err)
13786        }
13787
13788        let sigint = std::thread::spawn(|| run_with_signal(2));
13789        let sigterm = std::thread::spawn(|| run_with_signal(15));
13790        // A third program without a pending signal must not observe either.
13791        let clean = std::thread::spawn(|| {
13792            let program = headless_signal_program_with_config(
13793                TestModel { value: 0 },
13794                ProgramConfig::default().with_signal_interception(true),
13795            );
13796            program.observed_termination_signal()
13797        });
13798
13799        assert_eq!(sigint.join().expect("sigint thread"), Some(2));
13800        assert_eq!(sigterm.join().expect("sigterm thread"), Some(15));
13801        assert_eq!(clean.join().expect("clean thread"), None);
13802    }
13803
13804    /// `DEFAULT_BACKEND` must agree with the cfg predicates that select the
13805    /// `AppBuilder::run` dispatch, so consumers can trust it to describe what
13806    /// `run()` will do in their build.
13807    #[test]
13808    fn default_backend_constant_matches_cfg() {
13809        let expected = if cfg!(all(feature = "native-backend", unix)) {
13810            "native"
13811        } else if cfg!(feature = "crossterm-compat") {
13812            "crossterm"
13813        } else {
13814            "none"
13815        };
13816        assert_eq!(DEFAULT_BACKEND, expected);
13817        assert!(NO_BACKEND_MESSAGE.contains("native-backend"));
13818        assert!(NO_BACKEND_MESSAGE.contains("crossterm-compat"));
13819    }
13820
13821    /// Without a compiled backend, `run()` must fail up front with an error
13822    /// that names the features to enable instead of pretending to run.
13823    #[cfg(not(any(all(feature = "native-backend", unix), feature = "crossterm-compat")))]
13824    #[test]
13825    fn run_without_backend_reports_missing_features() {
13826        let err = App::new(TestModel { value: 0 })
13827            .run()
13828            .expect_err("no backend compiled");
13829        assert_eq!(err.kind(), io::ErrorKind::Unsupported);
13830        assert_eq!(err.to_string(), NO_BACKEND_MESSAGE);
13831        let err = App::new(TestModel { value: 0 })
13832            .run_crossterm()
13833            .expect_err("crossterm not compiled");
13834        assert_eq!(err.kind(), io::ErrorKind::Unsupported);
13835        assert!(err.to_string().contains("crossterm-compat"));
13836    }
13837
13838    #[test]
13839    fn inject_termination_signal_first_signal_wins() {
13840        let program = headless_signal_program_with_config(
13841            TestModel { value: 0 },
13842            ProgramConfig::default().with_signal_interception(true),
13843        );
13844        assert_eq!(program.pending_termination_signal(), None);
13845        program.inject_termination_signal(15);
13846        program.inject_termination_signal(2);
13847        assert_eq!(program.pending_termination_signal(), Some(15));
13848        assert_eq!(program.observed_termination_signal(), Some(15));
13849
13850        // Interception disabled: the slot is still recorded but not observed.
13851        let quiet = headless_signal_program_with_config(
13852            TestModel { value: 0 },
13853            ProgramConfig::default().with_signal_interception(false),
13854        );
13855        quiet.inject_termination_signal(2);
13856        assert_eq!(quiet.pending_termination_signal(), Some(2));
13857        assert_eq!(quiet.observed_termination_signal(), None);
13858    }
13859
13860    #[test]
13861    fn run_pending_signal_skips_initial_render_and_subscription_start() {
13862        use crate::subscription::{StopSignal, SubId, Subscription, SubscriptionSender};
13863
13864        struct SignalStopModel {
13865            render_calls: Arc<AtomicUsize>,
13866            subscription_starts: Arc<AtomicUsize>,
13867        }
13868
13869        #[derive(Debug, Clone, Copy)]
13870        enum SignalStopMsg {
13871            Noop,
13872        }
13873
13874        impl From<Event> for SignalStopMsg {
13875            fn from(_: Event) -> Self {
13876                Self::Noop
13877            }
13878        }
13879
13880        impl Model for SignalStopModel {
13881            type Message = SignalStopMsg;
13882
13883            fn update(&mut self, _: Self::Message) -> Cmd<Self::Message> {
13884                Cmd::none()
13885            }
13886
13887            fn view(&self, _frame: &mut Frame) {
13888                self.render_calls.fetch_add(1, Ordering::SeqCst);
13889            }
13890
13891            fn subscriptions(&self) -> Vec<Box<dyn Subscription<Self::Message>>> {
13892                vec![Box::new(SignalStopSubscription {
13893                    starts: Arc::clone(&self.subscription_starts),
13894                })]
13895            }
13896        }
13897
13898        struct SignalStopSubscription {
13899            starts: Arc<AtomicUsize>,
13900        }
13901
13902        impl Subscription<SignalStopMsg> for SignalStopSubscription {
13903            fn id(&self) -> SubId {
13904                11
13905            }
13906
13907            fn run(&self, _sender: SubscriptionSender<SignalStopMsg>, stop: StopSignal) {
13908                self.starts.fetch_add(1, Ordering::SeqCst);
13909                let _ = stop.wait_timeout(Duration::from_millis(10));
13910            }
13911        }
13912
13913        let render_calls = Arc::new(AtomicUsize::new(0));
13914        let subscription_starts = Arc::new(AtomicUsize::new(0));
13915        let mut program = headless_signal_program_with_config(
13916            SignalStopModel {
13917                render_calls: Arc::clone(&render_calls),
13918                subscription_starts: Arc::clone(&subscription_starts),
13919            },
13920            ProgramConfig::default().with_signal_interception(true),
13921        );
13922
13923        program.inject_termination_signal(15);
13924        let err = program.run().expect_err("signal should stop runtime");
13925
13926        assert_eq!(signal_termination_from_error(&err), Some(15));
13927        assert_eq!(render_calls.load(Ordering::SeqCst), 0);
13928        assert_eq!(subscription_starts.load(Ordering::SeqCst), 0);
13929        assert_eq!(program.pending_termination_signal(), None);
13930    }
13931
13932    #[test]
13933    fn headless_should_tick_and_timeout_behaviors() {
13934        let mut program =
13935            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
13936        program.tick_rate = Some(Duration::from_millis(5));
13937        program.last_tick = Instant::now() - Duration::from_millis(10);
13938
13939        assert!(program.should_tick());
13940        assert!(!program.should_tick());
13941
13942        let timeout = program.effective_timeout();
13943        assert!(timeout <= Duration::from_millis(5));
13944
13945        program.tick_rate = None;
13946        program.poll_timeout = Duration::from_millis(33);
13947        assert_eq!(program.effective_timeout(), Duration::from_millis(33));
13948    }
13949
13950    #[test]
13951    fn headless_effective_timeout_respects_resize_coalescer() {
13952        let mut config = ProgramConfig::default().with_resize_behavior(ResizeBehavior::Throttled);
13953        config.resize_coalescer.steady_delay_ms = 0;
13954        config.resize_coalescer.burst_delay_ms = 0;
13955
13956        let mut program = headless_program_with_config(TestModel { value: 0 }, config);
13957        program.tick_rate = Some(Duration::from_millis(50));
13958
13959        program.resize_coalescer.handle_resize(120, 40);
13960        assert!(program.resize_coalescer.has_pending());
13961
13962        let timeout = program.effective_timeout();
13963        assert_eq!(timeout, Duration::ZERO);
13964    }
13965
13966    #[test]
13967    fn headless_ui_height_remeasure_clears_auto_height() {
13968        let mut config = ProgramConfig::inline_auto(2, 6);
13969        config.inline_auto_remeasure = Some(InlineAutoRemeasureConfig::default());
13970
13971        let mut program = headless_program_with_config(TestModel { value: 0 }, config);
13972        program.dirty = false;
13973        program.presenter.set_auto_ui_height(5);
13974
13975        assert_eq!(program.presenter.auto_ui_height(), Some(5));
13976        program.request_ui_height_remeasure();
13977
13978        assert_eq!(program.presenter.auto_ui_height(), None);
13979        assert!(program.dirty);
13980    }
13981
13982    #[test]
13983    fn headless_recording_lifecycle_and_locale_change() {
13984        let mut program =
13985            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
13986        program.dirty = false;
13987
13988        program.start_recording("demo");
13989        assert!(program.is_recording());
13990        let recorded = program.stop_recording();
13991        assert!(recorded.is_some());
13992        assert!(!program.is_recording());
13993
13994        let prev_dirty = program.dirty;
13995        program.locale_context.set_locale("fr");
13996        program.check_locale_change();
13997        assert!(program.dirty || prev_dirty);
13998    }
13999
14000    #[test]
14001    fn frame_text_direction_follows_locale_context() {
14002        use std::cell::RefCell;
14003        use std::rc::Rc;
14004
14005        struct DirectionModel {
14006            directions: Rc<RefCell<Vec<ftui_render::TextDirection>>>,
14007        }
14008
14009        #[derive(Debug)]
14010        enum DirectionMsg {
14011            Noop,
14012        }
14013
14014        impl From<Event> for DirectionMsg {
14015            fn from(_: Event) -> Self {
14016                DirectionMsg::Noop
14017            }
14018        }
14019
14020        impl Model for DirectionModel {
14021            type Message = DirectionMsg;
14022
14023            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
14024                Cmd::none()
14025            }
14026
14027            fn view(&self, frame: &mut Frame) {
14028                self.directions.borrow_mut().push(frame.text_direction);
14029            }
14030        }
14031
14032        let directions = Rc::new(RefCell::new(Vec::new()));
14033        let model = DirectionModel {
14034            directions: Rc::clone(&directions),
14035        };
14036        let config = ProgramConfig::default().with_locale("ar");
14037        let mut program = headless_program_with_config(model, config);
14038
14039        program.render_frame().expect("render initial frame");
14040        assert_eq!(program.frame_idx, 1);
14041        assert_eq!(
14042            directions.borrow().as_slice(),
14043            &[ftui_render::TextDirection::Rtl]
14044        );
14045        assert!(!program.dirty);
14046
14047        program.locale_context.set_locale("en");
14048        program.check_locale_change();
14049        assert!(
14050            program.dirty,
14051            "check_locale_change must trigger redraw on locale switch"
14052        );
14053
14054        program
14055            .render_frame()
14056            .expect("render frame after locale change");
14057        assert_eq!(program.frame_idx, 2);
14058        assert_eq!(
14059            directions.borrow().as_slice(),
14060            &[
14061                ftui_render::TextDirection::Rtl,
14062                ftui_render::TextDirection::Ltr,
14063            ]
14064        );
14065    }
14066
14067    #[test]
14068    fn headless_render_frame_marks_clean_and_sets_diff() {
14069        struct RenderModel;
14070
14071        #[derive(Debug)]
14072        enum RenderMsg {
14073            Noop,
14074        }
14075
14076        impl From<Event> for RenderMsg {
14077            fn from(_: Event) -> Self {
14078                RenderMsg::Noop
14079            }
14080        }
14081
14082        impl Model for RenderModel {
14083            type Message = RenderMsg;
14084
14085            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
14086                Cmd::none()
14087            }
14088
14089            fn view(&self, frame: &mut Frame) {
14090                frame.buffer.set_raw(0, 0, Cell::from_char('X'));
14091            }
14092        }
14093
14094        let mut program = headless_program_with_config(RenderModel, ProgramConfig::default());
14095        program.render_frame().expect("render frame");
14096
14097        assert!(!program.dirty);
14098        assert!(program.presenter.last_diff_strategy().is_some());
14099        assert_eq!(program.frame_idx, 1);
14100    }
14101
14102    /// CONTRACT (bd-1za0z F2): when a guardrail alert fires during
14103    /// render_frame, a `guardrail_snapshot` evidence row is exported through
14104    /// the configured sink โ€” GuardrailSnapshot::to_jsonl is live production
14105    /// observability, not dead code.
14106    #[test]
14107    fn headless_render_frame_emits_guardrail_snapshot_evidence_on_alert() {
14108        struct AlertModel;
14109
14110        #[derive(Debug)]
14111        enum AlertMsg {
14112            Noop,
14113        }
14114
14115        impl From<Event> for AlertMsg {
14116            fn from(_: Event) -> Self {
14117                AlertMsg::Noop
14118            }
14119        }
14120
14121        impl Model for AlertModel {
14122            type Message = AlertMsg;
14123
14124            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
14125                Cmd::none()
14126            }
14127
14128            fn view(&self, frame: &mut Frame) {
14129                frame.buffer.set_raw(0, 0, Cell::from_char('X'));
14130            }
14131        }
14132
14133        let evidence_path = temp_evidence_path("guardrail_snapshot");
14134        let config = ProgramConfig {
14135            guardrails: GuardrailsConfig {
14136                // Soft limit of one byte: the very first frame alerts, so
14137                // no memory pressure needs to be manufactured.
14138                memory: MemoryBudgetConfig {
14139                    soft_limit_bytes: 1,
14140                    ..MemoryBudgetConfig::default()
14141                },
14142                queue: QueueConfig::default(),
14143                ..Default::default()
14144            },
14145            evidence_sink: EvidenceSinkConfig::enabled_file(&evidence_path),
14146            ..Default::default()
14147        };
14148
14149        let mut program = headless_program_with_config(AlertModel, config);
14150        program.dirty = true;
14151        program.render_frame().expect("render frame with alert");
14152
14153        let contents =
14154            std::fs::read_to_string(&evidence_path).expect("guardrail evidence file written");
14155        assert!(
14156            contents.contains(r#""event":"guardrail_snapshot""#),
14157            "alerting frame must export a guardrail_snapshot row; got: {contents}"
14158        );
14159        assert!(
14160            contents.contains(r#""mem_soft_violations":"#),
14161            "snapshot row must carry the violation counters"
14162        );
14163    }
14164
14165    #[test]
14166    fn headless_render_frame_emits_guardrail_snapshot_on_leak_alert() {
14167        let evidence_path = temp_evidence_path("allocation_leak_retained");
14168        let config = ProgramConfig {
14169            evidence_sink: EvidenceSinkConfig::enabled_file(&evidence_path),
14170            ..Default::default()
14171        };
14172        let mut program = headless_program_with_config(TestModel { value: 0 }, config);
14173        for _ in 0..200 {
14174            program.render_frame().expect("stationary render");
14175            assert!(!program.guardrails.snapshot().leak_alert);
14176        }
14177
14178        // Exercise the real retained-capacity sensor, not an injected verdict.
14179        let before = program.frame_arena.allocated_bytes();
14180        program
14181            .frame_arena
14182            .alloc_slice(&vec![0u8; before + 64 * 1024]);
14183        assert!(program.frame_arena.allocated_bytes() > before);
14184        program.render_frame().expect("render with capacity growth");
14185        let contents = std::fs::read_to_string(&evidence_path).expect("retained leak evidence");
14186        let snapshots: Vec<Value> = contents
14187            .lines()
14188            .map(|line| serde_json::from_str::<Value>(line).expect("valid evidence JSON"))
14189            .filter(|row| row["event"] == "guardrail_snapshot")
14190            .collect();
14191        assert_eq!(snapshots.len(), 1, "only the capacity jump should alert");
14192        let snapshot = &snapshots[0]["snapshot"];
14193        assert_eq!(snapshot["leak_alert"], true);
14194        assert!(snapshot["leak_cusum_upper"].as_f64().unwrap() > 8.0);
14195        assert!(snapshot["leak_e_value"].as_f64().unwrap().is_finite());
14196        assert!(snapshot["leak_mean_bytes"].as_f64().unwrap() > 0.0);
14197        assert_eq!(snapshot["mem_soft_violations"], 0);
14198        // Keep the evidence file for inspection (AGENTS.md Rule 1).
14199    }
14200
14201    #[test]
14202    fn headless_emergency_shed_resets_leak_baseline() {
14203        let config = ProgramConfig {
14204            guardrails: GuardrailsConfig {
14205                memory: MemoryBudgetConfig {
14206                    soft_limit_bytes: 1,
14207                    hard_limit_bytes: 1,
14208                    emergency_limit_bytes: 1,
14209                },
14210                ..Default::default()
14211            },
14212            ..Default::default()
14213        };
14214        let mut program = headless_program_with_config(TestModel { value: 0 }, config);
14215        program.frame_arena.alloc_slice(&[0u8; 1024]);
14216        program.render_frame().expect("emergency shed");
14217        let snapshot = program.guardrails.snapshot();
14218        assert_eq!(snapshot.memory_emergency_violations, 1);
14219        assert_eq!(snapshot.frames_checked, 1);
14220        assert_eq!(snapshot.leak_mean_bytes, 0.0);
14221        assert!(!snapshot.leak_alert);
14222    }
14223
14224    /// The inline-auto VOI sampler's decision is exported through the evidence
14225    /// sink (`voi_decision`), not only through the in-process telemetry
14226    /// snapshot, so operators can grep why a remeasure did or did not happen.
14227    #[test]
14228    fn headless_inline_auto_exports_voi_decision_evidence() {
14229        struct TallModel;
14230
14231        #[derive(Debug)]
14232        enum TallMsg {
14233            Noop,
14234        }
14235
14236        impl From<Event> for TallMsg {
14237            fn from(_: Event) -> Self {
14238                TallMsg::Noop
14239            }
14240        }
14241
14242        impl Model for TallModel {
14243            type Message = TallMsg;
14244
14245            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
14246                Cmd::none()
14247            }
14248
14249            fn view(&self, frame: &mut Frame) {
14250                frame.buffer.set_raw(0, 0, Cell::from_char('V'));
14251            }
14252        }
14253
14254        let evidence_path = temp_evidence_path("voi_decision");
14255        let config = ProgramConfig::inline_auto(1, 6)
14256            .with_evidence_sink(EvidenceSinkConfig::enabled_file(&evidence_path));
14257        assert!(config.inline_auto_remeasure.is_some());
14258
14259        let mut program = headless_program_with_config(TallModel, config);
14260        for _ in 0..3 {
14261            program.dirty = true;
14262            program.render_frame().expect("render inline-auto frame");
14263        }
14264
14265        let contents = std::fs::read_to_string(&evidence_path).expect("evidence file written");
14266        assert!(
14267            contents.contains(r#""event":"voi_decision""#),
14268            "inline-auto frames must export the VOI decision; got: {contents}"
14269        );
14270        assert!(
14271            contents.contains(r#""should_sample":"#) && contents.contains(r#""voi_gain":"#),
14272            "voi_decision row must carry the sampler reasoning"
14273        );
14274    }
14275
14276    #[test]
14277    fn voi_sample_written_for_inline_auto() {
14278        headless_inline_auto_exports_voi_decision_evidence();
14279    }
14280
14281    #[test]
14282    fn voi_sample_not_written_without_auto_bounds() {
14283        struct NoAutoModel;
14284
14285        #[derive(Debug)]
14286        enum NoAutoMsg {}
14287
14288        impl From<Event> for NoAutoMsg {
14289            fn from(_: Event) -> Self {
14290                unreachable!()
14291            }
14292        }
14293
14294        impl Model for NoAutoModel {
14295            type Message = NoAutoMsg;
14296
14297            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
14298                Cmd::none()
14299            }
14300
14301            fn view(&self, frame: &mut Frame) {
14302                frame.buffer.set_raw(0, 0, Cell::from_char('N'));
14303            }
14304        }
14305
14306        let evidence_path = temp_evidence_path("voi_no_auto");
14307        let config = ProgramConfig::default()
14308            .with_evidence_sink(EvidenceSinkConfig::enabled_file(&evidence_path));
14309        assert!(config.inline_auto_remeasure.is_none());
14310
14311        let mut program = headless_program_with_config(NoAutoModel, config);
14312        for _ in 0..3 {
14313            program.dirty = true;
14314            program.render_frame().expect("render frame");
14315        }
14316
14317        let contents = std::fs::read_to_string(&evidence_path).unwrap_or_default();
14318        assert!(
14319            !contents.contains(r#""event":"voi_decision""#)
14320                && !contents.contains(r#""event":"voi_sample""#),
14321            "programs without auto bounds must not emit VOI events; got: {contents}"
14322        );
14323    }
14324
14325    #[test]
14326    fn evidence_lines_all_carry_schema_version() {
14327        use crate::telemetry_schema::ALL_EVIDENCE_EVENTS;
14328
14329        let evidence_path = temp_evidence_path("all_evidence_schema_version");
14330        let config = ProgramConfig::inline_auto(1, 6)
14331            .with_evidence_sink(EvidenceSinkConfig::enabled_file(&evidence_path));
14332
14333        struct EvidenceModel;
14334        #[derive(Debug)]
14335        enum EvMsg {}
14336        impl From<Event> for EvMsg {
14337            fn from(_: Event) -> Self {
14338                unreachable!()
14339            }
14340        }
14341        impl Model for EvidenceModel {
14342            type Message = EvMsg;
14343            fn update(&mut self, _: Self::Message) -> Cmd<Self::Message> {
14344                Cmd::none()
14345            }
14346            fn view(&self, frame: &mut Frame) {
14347                frame.buffer.set_raw(0, 0, Cell::from_char('E'));
14348            }
14349        }
14350
14351        let mut program = headless_program_with_config(EvidenceModel, config);
14352        program.dirty = true;
14353        program.render_frame().expect("render frame");
14354
14355        let contents = std::fs::read_to_string(&evidence_path).expect("evidence file written");
14356        for line in contents.lines() {
14357            let line = line.trim();
14358            if line.is_empty() {
14359                continue;
14360            }
14361            let val: serde_json::Value = serde_json::from_str(line).expect("valid jsonl line");
14362            assert_eq!(
14363                val["schema_version"].as_str(),
14364                Some("ftui-evidence-v1"),
14365                "each evidence line must carry schema_version ftui-evidence-v1: {line}"
14366            );
14367            let event = val["event"].as_str().expect("event string");
14368            assert!(
14369                ALL_EVIDENCE_EVENTS.contains(&event),
14370                "event {event} must be in ALL_EVIDENCE_EVENTS"
14371            );
14372        }
14373    }
14374
14375    /// Bytes the startup probes swallowed (a click and a key sent while the
14376    /// terminal was being probed) are parsed and delivered to the model in
14377    /// order before the main loop; draining twice delivers nothing more.
14378    #[test]
14379    fn startup_input_recovered_from_probes_reaches_the_model() {
14380        use ftui_core::event::{KeyCode, MouseEventKind};
14381
14382        #[derive(Default)]
14383        struct RecorderModel {
14384            seen: Vec<String>,
14385            keys: Vec<KeyEvent>,
14386        }
14387
14388        #[derive(Debug)]
14389        enum RecMsg {
14390            Event(Event),
14391        }
14392
14393        impl From<Event> for RecMsg {
14394            fn from(event: Event) -> Self {
14395                RecMsg::Event(event)
14396            }
14397        }
14398
14399        impl Model for RecorderModel {
14400            type Message = RecMsg;
14401
14402            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
14403                match msg {
14404                    RecMsg::Event(Event::Mouse(mouse)) => {
14405                        self.seen
14406                            .push(format!("mouse:{:?}@{},{}", mouse.kind, mouse.x, mouse.y));
14407                    }
14408                    RecMsg::Event(Event::Key(key)) => {
14409                        self.seen.push(format!("key:{:?}", key.code));
14410                        self.keys.push(key);
14411                    }
14412                    RecMsg::Event(_) => {}
14413                }
14414                Cmd::none()
14415            }
14416
14417            fn view(&self, frame: &mut Frame) {
14418                frame.buffer.set_raw(0, 0, Cell::from_char('R'));
14419            }
14420        }
14421
14422        let mut program =
14423            headless_program_with_config(RecorderModel::default(), ProgramConfig::default());
14424        // SGR mouse press + release at column 2 row 1, then a typed `q`.
14425        program.queue_startup_input(b"\x1b[<0;2;1M\x1b[<0;2;1mq");
14426        assert_eq!(program.startup_events.len(), 3);
14427        program
14428            .drain_startup_events()
14429            .expect("deliver startup events");
14430        assert!(program.startup_events.is_empty());
14431        let seen = program.model().seen.clone();
14432        assert_eq!(seen.len(), 3, "{seen:?}");
14433        assert!(
14434            seen[0].starts_with(&format!(
14435                "mouse:{:?}",
14436                MouseEventKind::Down(ftui_core::event::MouseButton::Left)
14437            )) && seen[0].ends_with("@1,0"),
14438            "{seen:?}"
14439        );
14440        assert!(seen[1].starts_with("mouse:Up"), "{seen:?}");
14441        assert_eq!(seen[2], format!("key:{:?}", KeyCode::Char('q')));
14442
14443        program.drain_startup_events().expect("nothing left");
14444        assert_eq!(program.model().seen.len(), 3);
14445        program.queue_startup_input(b"");
14446        assert!(program.startup_events.is_empty());
14447
14448        // A probe can consume the final lone Escape before timing out. The
14449        // startup handoff must deliver that key, even with no subsequent input.
14450        program.queue_startup_input(b"\x1b[<0;2;1M\x1b");
14451        program
14452            .drain_startup_events()
14453            .expect("deliver trailing ESC");
14454        assert_eq!(program.model().seen.len(), 5);
14455        assert_eq!(program.model().seen[4], "key:Escape");
14456        program.drain_startup_events().expect("no duplicate ESC");
14457        assert_eq!(program.model().seen.len(), 5);
14458
14459        // Recovery may arrive in chunks. A pending prefix is not a key until
14460        // the batch is drained, so arrows and Alt+UTF-8 keep their identity.
14461        program.queue_startup_input(b"\x1b");
14462        program.queue_startup_input(b"[C\x1b\xc3");
14463        program.queue_startup_input(b"\xa9");
14464        program.drain_startup_events().expect("fragmented recovery");
14465        assert_eq!(&program.model().seen[5..], &["key:Right", "key:Char('รฉ')"]);
14466        assert_eq!(
14467            program.model().keys.last(),
14468            Some(
14469                &KeyEvent::new(KeyCode::Char('รฉ')).with_modifiers(ftui_core::event::Modifiers::ALT)
14470            )
14471        );
14472    }
14473
14474    /// With `ProgramConfig::accessibility` set, every rendered frame builds
14475    /// an accessibility tree from the nodes the view pushes, diffs it against
14476    /// the previous frame and exports the resulting announcements as
14477    /// evidence rows; without it nothing is collected.
14478    #[test]
14479    fn headless_accessibility_builds_tree_and_exports_announcements() {
14480        use ftui_a11y::node::{A11yNodeInfo, A11yRole, A11yState, LiveRegion};
14481        use ftui_a11y::tree::AnnouncementReason;
14482        use ftui_core::geometry::Rect;
14483
14484        struct A11yModel {
14485            frames: std::cell::Cell<u32>,
14486            hook_calls: u32,
14487            last_dump: String,
14488        }
14489
14490        #[derive(Debug)]
14491        enum A11yMsg {
14492            Noop,
14493        }
14494
14495        impl From<Event> for A11yMsg {
14496            fn from(_: Event) -> Self {
14497                A11yMsg::Noop
14498            }
14499        }
14500
14501        impl Model for A11yModel {
14502            type Message = A11yMsg;
14503
14504            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
14505                Cmd::none()
14506            }
14507
14508            fn on_accessibility(&mut self, a11y: AccessibilityFrame<'_>) -> Cmd<Self::Message> {
14509                self.hook_calls += 1;
14510                self.last_dump = a11y.dump();
14511                Cmd::none()
14512            }
14513
14514            fn view(&self, frame: &mut Frame) {
14515                let n = self.frames.get();
14516                self.frames.set(n + 1);
14517                frame.buffer.set_raw(0, 0, Cell::from_char('A'));
14518                frame.push_a11y(
14519                    A11yNodeInfo::new(1, A11yRole::Button, Rect::new(0, 0, 10, 1))
14520                        .with_name("OK")
14521                        .with_state(A11yState {
14522                            focused: true,
14523                            ..A11yState::default()
14524                        }),
14525                );
14526                if let Some(builder) = frame.a11y.as_deref_mut() {
14527                    builder.set_focused(Some(1));
14528                }
14529                // The second frame adds a polite live region.
14530                if n >= 1 {
14531                    frame.push_a11y(
14532                        A11yNodeInfo::new(2, A11yRole::Label, Rect::new(0, 1, 10, 1))
14533                            .with_name("Saved")
14534                            .with_live_region(LiveRegion::Polite),
14535                    );
14536                }
14537            }
14538        }
14539
14540        // Off by default: nothing is collected even though the view pushes.
14541        let mut off = headless_program_with_config(
14542            A11yModel {
14543                frames: std::cell::Cell::new(0),
14544                hook_calls: 0,
14545                last_dump: String::new(),
14546            },
14547            ProgramConfig::default(),
14548        );
14549        off.dirty = true;
14550        off.render_frame().expect("render without accessibility");
14551        assert!(off.accessibility_tree().is_none());
14552        assert!(off.accessibility_order().is_empty());
14553        assert!(off.accessibility_announcements().is_empty());
14554        assert!(off.accessibility_dump().is_none());
14555        assert_eq!(off.model.hook_calls, 0);
14556
14557        let evidence_path = temp_evidence_path("a11y");
14558        let config = ProgramConfig::default()
14559            .with_accessibility(ScreenReaderPolicy::default())
14560            .with_evidence_sink(EvidenceSinkConfig::enabled_file(&evidence_path));
14561        let mut program = headless_program_with_config(
14562            A11yModel {
14563                frames: std::cell::Cell::new(0),
14564                hook_calls: 0,
14565                last_dump: String::new(),
14566            },
14567            config,
14568        );
14569
14570        program.dirty = true;
14571        program.render_frame().expect("render first a11y frame");
14572        let tree = program
14573            .accessibility_tree()
14574            .expect("tree after first frame");
14575        assert_eq!(tree.node_count(), 1);
14576        assert_eq!(tree.focused_id(), Some(1));
14577        assert_eq!(program.accessibility_order(), &[1]);
14578        let first: Vec<AnnouncementReason> = program
14579            .accessibility_announcements()
14580            .iter()
14581            .map(|a| a.reason)
14582            .collect();
14583        assert!(
14584            first.contains(&AnnouncementReason::FocusChanged),
14585            "first frame must announce the focused button; got {first:?}"
14586        );
14587
14588        program.dirty = true;
14589        program.render_frame().expect("render second a11y frame");
14590        let tree = program
14591            .accessibility_tree()
14592            .expect("tree after second frame");
14593        assert_eq!(tree.node_count(), 2);
14594        assert_eq!(program.accessibility_order(), &[1, 2]);
14595        let second: Vec<(AnnouncementReason, String)> = program
14596            .accessibility_announcements()
14597            .iter()
14598            .map(|a| (a.reason, a.text.clone()))
14599            .collect();
14600        assert!(
14601            second.iter().any(
14602                |(reason, text)| *reason == AnnouncementReason::LiveRegionAdded
14603                    && text.contains("Saved")
14604            ),
14605            "second frame must announce the new live region; got {second:?}"
14606        );
14607        let dump = program.accessibility_dump().expect("dump when enabled");
14608        assert!(
14609            dump.contains("OK") && dump.contains("Saved"),
14610            "dump: {dump}"
14611        );
14612
14613        // A frame with no tree change produces no announcements.
14614        program.dirty = true;
14615        program.render_frame().expect("render third a11y frame");
14616        assert!(program.accessibility_announcements().is_empty());
14617        // The hook fired for the two changing frames only, saw the dump, and
14618        // requested one more frame each time.
14619        assert_eq!(program.model.hook_calls, 2);
14620        assert!(program.model.last_dump.contains("Saved"));
14621        assert!(
14622            !program.dirty,
14623            "an unchanged frame must not request a redraw"
14624        );
14625
14626        let contents = std::fs::read_to_string(&evidence_path).expect("evidence file written");
14627        assert!(
14628            contents.contains(r#""event":"a11y_tree""#),
14629            "tree changes must be exported; got: {contents}"
14630        );
14631        assert!(
14632            contents.contains(r#""event":"a11y_announcement""#)
14633                && contents.contains(r#""reason":"LiveRegionAdded""#)
14634                && contents.contains(r#""urgency":"polite""#),
14635            "announcements must be exported with reason and urgency; got: {contents}"
14636        );
14637        assert_eq!(
14638            contents.matches(r#""event":"a11y_tree""#).count(),
14639            2,
14640            "only the two changing frames export a11y_tree rows; got: {contents}"
14641        );
14642        assert!(
14643            !contents.contains("Saved"),
14644            "ordinary evidence must not contain accessibility content"
14645        );
14646    }
14647
14648    const A11Y_PRIVACY_CANARY: &str = "A11Y_SECRET_450512_\"รฉ\\\nๆ—ฅ";
14649    // Screen-reader text already normalizes whitespace before delivery.
14650    const A11Y_NORMALIZED_CANARY: &str = "A11Y_SECRET_450512_\"รฉ\\ ๆ—ฅ";
14651
14652    fn exercise_a11y_privacy(config: ProgramConfig) -> (Vec<String>, usize) {
14653        use ftui_a11y::node::{A11yNodeInfo, A11yRole, A11yState, LiveRegion};
14654        use ftui_core::geometry::Rect;
14655
14656        #[derive(Default)]
14657        struct ContentModel {
14658            received: Vec<String>,
14659            dropped: usize,
14660        }
14661
14662        impl Model for ContentModel {
14663            type Message = Event;
14664
14665            fn update(&mut self, _: Event) -> Cmd<Event> {
14666                Cmd::none()
14667            }
14668
14669            fn view(&self, frame: &mut Frame) {
14670                frame.buffer.set_raw(0, 0, Cell::from_char('A'));
14671                for (index, (role, source)) in [
14672                    (A11yRole::TextInput, "input"),
14673                    (A11yRole::TextInput, "textarea"),
14674                    (A11yRole::Label, "label"),
14675                    (A11yRole::Dialog, "modal"),
14676                    (A11yRole::Label, "live-region"),
14677                ]
14678                .into_iter()
14679                .enumerate()
14680                {
14681                    frame.push_a11y(
14682                        A11yNodeInfo::new(
14683                            index as u64 + 1,
14684                            role,
14685                            Rect::new(0, index as u16, 20, 1),
14686                        )
14687                        .with_name(format!("{source}: {A11Y_PRIVACY_CANARY}"))
14688                        .with_state(A11yState {
14689                            focused: index == 0,
14690                            ..A11yState::default()
14691                        })
14692                        .with_live_region(LiveRegion::Polite),
14693                    );
14694                }
14695            }
14696
14697            fn on_accessibility(&mut self, frame: AccessibilityFrame<'_>) -> Cmd<Event> {
14698                self.received
14699                    .extend(frame.announcements.iter().map(|a| a.text.clone()));
14700                self.dropped += frame.dropped;
14701                Cmd::none()
14702            }
14703        }
14704
14705        let mut program = headless_program_with_config(ContentModel::default(), config);
14706        program.render_frame().expect("render private a11y content");
14707        let received = program.model.received.clone();
14708        let dropped = program.model.dropped;
14709        program.render_frame().expect("render unchanged a11y tree");
14710        assert_eq!(
14711            program.model.received, received,
14712            "no duplicate announcements"
14713        );
14714        (received, dropped)
14715    }
14716
14717    #[derive(Clone, Default)]
14718    struct A11yTraceCapture(std::sync::Arc<std::sync::Mutex<String>>);
14719
14720    impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for A11yTraceCapture {
14721        fn on_event(
14722            &self,
14723            event: &tracing::Event<'_>,
14724            _: tracing_subscriber::layer::Context<'_, S>,
14725        ) {
14726            struct Fields<'a>(&'a mut String);
14727            impl tracing::field::Visit for Fields<'_> {
14728                fn record_debug(
14729                    &mut self,
14730                    field: &tracing::field::Field,
14731                    value: &dyn std::fmt::Debug,
14732                ) {
14733                    use std::fmt::Write as _;
14734                    write!(self.0, "{}={value:?};", field.name()).expect("write capture");
14735                }
14736            }
14737            let mut output = self.0.lock().expect("capture lock");
14738            output.push_str(event.metadata().target());
14739            event.record(&mut Fields(&mut output));
14740            output.push('\n');
14741        }
14742    }
14743
14744    #[test]
14745    fn headless_a11y_privacy_preserves_local_content_and_explicit_capture() {
14746        use tracing_subscriber::prelude::*;
14747
14748        for enabled in [false, true] {
14749            for include_text in [false, true] {
14750                for max_announcements in [2, 8] {
14751                    let path = temp_evidence_path("a11y_privacy");
14752                    let capture = A11yTraceCapture::default();
14753                    let subscriber = tracing_subscriber::registry().with(capture.clone());
14754                    let mut config = ProgramConfig::default()
14755                        .with_accessibility_evidence_text(include_text)
14756                        .with_evidence_sink(EvidenceSinkConfig::enabled_file(&path));
14757                    if enabled {
14758                        config = config.with_accessibility(ScreenReaderPolicy {
14759                            max_announcements,
14760                            ..ScreenReaderPolicy::default()
14761                        });
14762                    }
14763                    let (local, dropped) = tracing::subscriber::with_default(subscriber, || {
14764                        exercise_a11y_privacy(config)
14765                    });
14766                    let trace = capture.0.lock().expect("capture lock").clone();
14767                    assert!(
14768                        !trace.contains("A11Y_SECRET_450512"),
14769                        "content entered tracing"
14770                    );
14771                    let contents = std::fs::read_to_string(&path).expect("read evidence");
14772                    let rows: Vec<serde_json::Value> = contents
14773                        .lines()
14774                        .map(|line| serde_json::from_str(line).expect("valid JSONL"))
14775                        .filter(|row: &serde_json::Value| row["event"] == "a11y_announcement")
14776                        .collect();
14777                    assert_eq!(rows.len(), local.len());
14778                    if enabled {
14779                        assert!(!local.is_empty(), "local accessibility received nothing");
14780                        assert!(local.len() <= max_announcements);
14781                        assert!(
14782                            local
14783                                .iter()
14784                                .all(|text| text.contains(A11Y_NORMALIZED_CANARY))
14785                        );
14786                        assert!(trace.contains("screen reader announcement"));
14787                        assert_eq!(dropped > 0, max_announcements == 2);
14788                        for (row, text) in rows.iter().zip(&local) {
14789                            assert_eq!(row["text_chars"], text.chars().count());
14790                            if include_text {
14791                                assert_eq!(row["text"], *text, "explicit content round trip");
14792                            } else {
14793                                assert!(row["text"].is_null());
14794                            }
14795                        }
14796                    } else {
14797                        assert!(local.is_empty());
14798                        assert_eq!(dropped, 0);
14799                        assert!(!trace.contains("screen reader announcement"));
14800                    }
14801                    if !include_text {
14802                        assert!(!contents.contains("A11Y_SECRET_450512"));
14803                    }
14804                }
14805            }
14806        }
14807    }
14808
14809    #[cfg(target_os = "linux")]
14810    #[test]
14811    fn headless_a11y_privacy_preserves_callback_when_evidence_write_fails() {
14812        use tracing_subscriber::prelude::*;
14813
14814        let capture = A11yTraceCapture::default();
14815        let subscriber = tracing_subscriber::registry().with(capture.clone());
14816        let config = ProgramConfig::default()
14817            .with_accessibility(ScreenReaderPolicy::default())
14818            .with_evidence_sink(EvidenceSinkConfig::enabled_file("/dev/full"));
14819        let (local, _) =
14820            tracing::subscriber::with_default(subscriber, || exercise_a11y_privacy(config));
14821        assert!(!local.is_empty());
14822        assert!(
14823            local
14824                .iter()
14825                .all(|text| text.contains(A11Y_NORMALIZED_CANARY))
14826        );
14827        let trace = capture.0.lock().expect("capture lock");
14828        assert!(trace.contains("screen reader announcement"));
14829        assert!(!trace.contains("A11Y_SECRET_450512"));
14830    }
14831
14832    #[cfg(feature = "telemetry")]
14833    #[test]
14834    fn headless_a11y_privacy_through_real_otlp_http_exporter() {
14835        use std::io::{Read as _, Write as _};
14836        use std::net::TcpListener;
14837        use std::sync::Arc;
14838        use std::sync::atomic::{AtomicBool, Ordering};
14839        use tracing_subscriber::prelude::*;
14840
14841        let listener = TcpListener::bind("127.0.0.1:0").expect("bind local collector");
14842        listener.set_nonblocking(true).expect("bounded accept");
14843        let endpoint = format!("http://{}/v1/traces", listener.local_addr().unwrap());
14844        let stop = Arc::new(AtomicBool::new(false));
14845        let collector_stop = stop.clone();
14846        let collector = std::thread::spawn(move || {
14847            let start = std::time::Instant::now();
14848            let mut payloads = Vec::new();
14849            while !collector_stop.load(Ordering::Acquire)
14850                && start.elapsed() < std::time::Duration::from_secs(30)
14851            {
14852                let (mut stream, _) = match listener.accept() {
14853                    Ok(connection) => connection,
14854                    Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
14855                        std::thread::sleep(std::time::Duration::from_millis(5));
14856                        continue;
14857                    }
14858                    Err(error) => panic!("collector accept failed: {error}"),
14859                };
14860                // On BSD/Darwin the accepted socket inherits O_NONBLOCK from
14861                // the listener (Linux does not), and SO_RCVTIMEO is ignored on
14862                // a non-blocking socket. Without this the read timeout below
14863                // is a no-op and `read_exact` fails with EAGAIN whenever
14864                // `accept` wins the race against the client's first bytes -
14865                // which it does under load. `read_exact` cannot be resumed
14866                // after WouldBlock, so the socket has to be blocking rather
14867                // than the read retried.
14868                stream
14869                    .set_nonblocking(false)
14870                    .expect("blocking reads, so the timeout below applies");
14871                stream
14872                    .set_read_timeout(Some(std::time::Duration::from_secs(3)))
14873                    .expect("bounded request read");
14874                let mut request = Vec::new();
14875                let (header_end, content_len) = loop {
14876                    let mut byte = [0];
14877                    stream.read_exact(&mut byte).expect("read HTTP headers");
14878                    request.push(byte[0]);
14879                    assert!(request.len() <= 32_768, "bounded HTTP headers");
14880                    if request.ends_with(b"\r\n\r\n") {
14881                        let headers = std::str::from_utf8(&request).expect("HTTP header text");
14882                        assert!(headers.starts_with("POST /v1/traces "));
14883                        let length: usize = headers
14884                            .lines()
14885                            .filter_map(|line| line.split_once(':'))
14886                            .find(|(name, _)| name.eq_ignore_ascii_case("content-length"))
14887                            .expect("OTLP request content length")
14888                            .1
14889                            .trim()
14890                            .parse()
14891                            .expect("numeric content length");
14892                        assert!(length <= 2 * 1024 * 1024, "bounded request body");
14893                        break (request.len(), length);
14894                    }
14895                };
14896                request.resize(header_end + content_len, 0);
14897                stream
14898                    .read_exact(&mut request[header_end..])
14899                    .expect("read actual OTLP protobuf");
14900                payloads.push(request[header_end..].to_vec());
14901                stream
14902                    .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")
14903                    .expect("acknowledge export");
14904            }
14905            payloads
14906        });
14907
14908        let mut telemetry = crate::telemetry::TelemetryConfig::from_env_with(|key| match key {
14909            "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT" => Some(endpoint.clone()),
14910            "OTEL_TRACES_EXPORTER" => Some("otlp".into()),
14911            _ => None,
14912        });
14913        telemetry.processor = crate::telemetry::SpanProcessorKind::Simple;
14914        telemetry.headers.push((
14915            "User-Agent".into(),
14916            "OpenAI File Downloader, XaiImageApiFetch/1.0".into(),
14917        ));
14918        let (layer, provider) = telemetry.build_layer().expect("real OTLP exporter");
14919        let subscriber = tracing_subscriber::registry().with(layer);
14920        let evidence_path = temp_evidence_path("a11y_otlp_private");
14921        let (local, _) = tracing::subscriber::with_default(subscriber, || {
14922            let _span = tracing::info_span!("a11y_privacy_live_export").entered();
14923            exercise_a11y_privacy(
14924                ProgramConfig::default()
14925                    .with_accessibility(ScreenReaderPolicy::default())
14926                    .with_accessibility_evidence_text(true)
14927                    .with_evidence_sink(EvidenceSinkConfig::enabled_file(&evidence_path)),
14928            )
14929        });
14930        provider.force_flush().expect("flush actual export");
14931        provider.shutdown().expect("shutdown exporter");
14932        stop.store(true, Ordering::Release);
14933        let payloads = collector.join().expect("local collector finished");
14934        assert!(
14935            !local.is_empty(),
14936            "accessibility callback must receive text"
14937        );
14938        assert!(
14939            local
14940                .iter()
14941                .all(|text| text.contains(A11Y_NORMALIZED_CANARY))
14942        );
14943        assert!(!payloads.is_empty(), "zero exports is not a privacy pass");
14944        let exported = payloads.concat();
14945        let exported_text = String::from_utf8_lossy(&exported);
14946        assert!(exported_text.contains("screen reader announcement"));
14947        assert!(!exported_text.contains("A11Y_SECRET_450512"));
14948        let evidence = std::fs::read_to_string(evidence_path).expect("explicit local evidence");
14949        assert!(evidence.contains("A11Y_SECRET_450512"));
14950    }
14951
14952    /// Conformal gating is on by default, so its warm-up must be harmless:
14953    /// until `min_samples` residuals exist the prediction rests on the
14954    /// `q_default` prior, which (10 ms on top of a 16 ms baseline against a
14955    /// 16 ms budget by default; made deliberately huge here) reports `risk`,
14956    /// yet an uncalibrated verdict must never lower the degradation level.
14957    /// The evidence rows must still show that risky, uncalibrated verdict so
14958    /// the warm-up is observable.
14959    #[test]
14960    fn headless_default_config_never_degrades_during_conformal_warmup() {
14961        use ftui_render::budget::DegradationLevel;
14962
14963        struct WarmModel;
14964
14965        #[derive(Debug)]
14966        enum WarmMsg {
14967            Noop,
14968        }
14969
14970        impl From<Event> for WarmMsg {
14971            fn from(_: Event) -> Self {
14972                WarmMsg::Noop
14973            }
14974        }
14975
14976        impl Model for WarmModel {
14977            type Message = WarmMsg;
14978
14979            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
14980                Cmd::none()
14981            }
14982
14983            fn view(&self, frame: &mut Frame) {
14984                frame.buffer.set_raw(0, 0, Cell::from_char('W'));
14985            }
14986        }
14987
14988        let evidence_path = temp_evidence_path("conformal_warmup");
14989        let defaults = ProgramConfig::default()
14990            .conformal_config
14991            .expect("conformal on by default");
14992        let min_samples = defaults.min_samples;
14993        // Load-independent setup: a 5 s frame budget keeps the PID path from
14994        // degrading when the test host is busy, while a 10 s `q_default`
14995        // prior makes every uncalibrated conformal verdict risky, so the only
14996        // thing that could degrade here is the warm-up gate letting the
14997        // prior through.
14998        let config = ProgramConfig::default()
14999            .with_budget(FrameBudgetConfig {
15000                total: Duration::from_secs(5),
15001                ..FrameBudgetConfig::default()
15002            })
15003            .with_conformal_config(ConformalConfig {
15004                q_default: 10_000_000.0,
15005                ..defaults
15006            })
15007            .with_evidence_sink(EvidenceSinkConfig::enabled_file(&evidence_path));
15008        let mut program = headless_program_with_config(WarmModel, config);
15009        assert!(program.conformal_predictor.is_some());
15010
15011        for frame in 0..min_samples + 5 {
15012            program.dirty = true;
15013            program.render_frame().expect("render frame");
15014            assert_eq!(
15015                program.budget.degradation(),
15016                DegradationLevel::Full,
15017                "frame {frame}: an uncalibrated or fast frame must not degrade"
15018            );
15019        }
15020
15021        let contents = std::fs::read_to_string(&evidence_path).expect("evidence written");
15022        let rows: Vec<&str> = contents
15023            .lines()
15024            .filter(|l| l.contains(r#""event":"budget_decision""#))
15025            .collect();
15026        assert!(
15027            rows.len() >= min_samples,
15028            "one budget_decision row per frame: {contents}"
15029        );
15030        assert!(
15031            rows.iter()
15032                .any(|r| r.contains(r#""risk":true"#) && r.contains(r#""n_b":0"#)),
15033            "the cold-start prior must be visible as an uncalibrated risky verdict: {contents}"
15034        );
15035        assert!(
15036            rows.iter()
15037                .all(|r| r.contains(r#""degradation_after":"Full""#)),
15038            "no row may record a degradation: {contents}"
15039        );
15040    }
15041
15042    #[test]
15043    fn headless_unattainable_conformal_rank_keeps_rendering_and_measuring() {
15044        use ftui_render::budget::DegradationLevel;
15045        let path = temp_evidence_path("conformal_unattainable_rank");
15046        let config = ProgramConfig::default()
15047            .with_budget(FrameBudgetConfig::with_total(Duration::from_secs(5)))
15048            .with_conformal_config(ConformalConfig {
15049                alpha: 0.01,
15050                min_samples: 20,
15051                window_size: 128,
15052                q_default: 10_000_000.0,
15053            })
15054            .with_evidence_sink(EvidenceSinkConfig::enabled_file(&path));
15055        let mut program = headless_program_with_config(TestModel { value: 0 }, config);
15056        for _ in 0..105 {
15057            program.dirty = true;
15058            program
15059                .render_frame()
15060                .expect("render while calibration grows");
15061            assert_eq!(program.budget.degradation(), DegradationLevel::Full);
15062            assert!(
15063                !program.dirty,
15064                "unavailable rank must not strand rendering at SkipFrame"
15065            );
15066        }
15067        let contents = std::fs::read_to_string(path).expect("actual runtime evidence");
15068        let rows: Vec<serde_json::Value> = contents
15069            .lines()
15070            .map(|line| serde_json::from_str(line).expect("valid evidence JSON"))
15071            .filter(|row: &serde_json::Value| row["event"] == "budget_decision")
15072            .collect();
15073        let unavailable: Vec<_> = rows
15074            .iter()
15075            .filter(|row| row["conformal_status"] == "unattainable_rank")
15076            .collect();
15077        assert!(
15078            !unavailable.is_empty(),
15079            "must observe the post-warmup missing rank"
15080        );
15081        for row in unavailable {
15082            assert!(row["upper_us"].is_null());
15083            assert!(row["q_b"].is_null());
15084            assert_eq!(row["risk"], true);
15085            assert_eq!(row["degradation_after"], "Full");
15086        }
15087        assert!(
15088            rows.iter()
15089                .any(|row| row["conformal_status"] == "calibrated" && row["upper_us"].is_number()),
15090            "continued measurements must eventually yield an available bound"
15091        );
15092    }
15093
15094    #[test]
15095    fn headless_unavailable_conformal_bound_preserves_controller_degradation() {
15096        use ftui_render::budget::DegradationLevel;
15097        let config = ProgramConfig::default()
15098            .with_budget(FrameBudgetConfig::with_total(Duration::from_secs(5)))
15099            .with_conformal_config(ConformalConfig {
15100                alpha: 0.01,
15101                min_samples: 1,
15102                ..Default::default()
15103            });
15104        let mut program = headless_program_with_config(TestModel { value: 0 }, config);
15105        // Controlled observations exercise the actual budget controller and
15106        // runtime gate. These durations are not live performance measurements.
15107        for _ in 0..15 {
15108            program.budget.record_frame_time(Duration::from_secs(200));
15109            program.dirty = true;
15110            program
15111                .render_frame()
15112                .expect("real runtime/controller path");
15113        }
15114        assert_eq!(
15115            program.budget.degradation(),
15116            DegradationLevel::SimpleBorders
15117        );
15118        let predictor = program.conformal_predictor.as_ref().unwrap();
15119        let prediction = predictor.predict(
15120            BucketKey::from_context(ScreenMode::AltScreen, DiffStrategy::Full, 80, 24),
15121            0.0,
15122            5_000_000.0,
15123        );
15124        assert_eq!(prediction.upper_us, None);
15125        assert!(!predictor.is_calibrated(&prediction));
15126    }
15127
15128    /// With `ProgramConfig::gestures` set, raw mouse events still reach
15129    /// `update()` and every recognized gesture reaches `Model::on_gesture`;
15130    /// without it nothing is recognized.
15131    #[test]
15132    fn headless_program_delivers_recognized_gestures_to_on_gesture() {
15133        use ftui_core::event::{Modifiers, MouseButton, MouseEvent, MouseEventKind};
15134        use ftui_core::gesture::GestureConfig;
15135        use ftui_core::semantic_event::SemanticEvent;
15136        use std::sync::{Arc, Mutex};
15137
15138        struct GestureModel {
15139            raw: usize,
15140            gestures: Arc<Mutex<Vec<SemanticEvent>>>,
15141        }
15142
15143        #[derive(Debug)]
15144        enum GMsg {
15145            Raw,
15146        }
15147
15148        impl From<Event> for GMsg {
15149            fn from(_: Event) -> Self {
15150                GMsg::Raw
15151            }
15152        }
15153
15154        impl Model for GestureModel {
15155            type Message = GMsg;
15156
15157            fn update(&mut self, _msg: GMsg) -> Cmd<GMsg> {
15158                self.raw += 1;
15159                Cmd::none()
15160            }
15161
15162            fn view(&self, _frame: &mut Frame) {}
15163
15164            fn on_gesture(&mut self, gesture: SemanticEvent) -> Cmd<GMsg> {
15165                self.gestures.lock().unwrap().push(gesture);
15166                Cmd::none()
15167            }
15168        }
15169
15170        let mouse = |kind: MouseEventKind, x: u16, y: u16| {
15171            Event::Mouse(MouseEvent {
15172                kind,
15173                x,
15174                y,
15175                modifiers: Modifiers::NONE,
15176            })
15177        };
15178
15179        let log = Arc::new(Mutex::new(Vec::new()));
15180        let config = ProgramConfig::default().with_gestures(GestureConfig::default());
15181        let mut program = headless_program_with_config(
15182            GestureModel {
15183                raw: 0,
15184                gestures: Arc::clone(&log),
15185            },
15186            config,
15187        );
15188        // Click: down and up at the same cell.
15189        program
15190            .handle_event(mouse(MouseEventKind::Down(MouseButton::Left), 4, 2))
15191            .unwrap();
15192        program
15193            .handle_event(mouse(MouseEventKind::Up(MouseButton::Left), 4, 2))
15194            .unwrap();
15195        // Drag: down, move past the 3-cell dead zone, up.
15196        program
15197            .handle_event(mouse(MouseEventKind::Down(MouseButton::Left), 10, 5))
15198            .unwrap();
15199        program
15200            .handle_event(mouse(MouseEventKind::Drag(MouseButton::Left), 16, 5))
15201            .unwrap();
15202        program
15203            .handle_event(mouse(MouseEventKind::Up(MouseButton::Left), 16, 5))
15204            .unwrap();
15205        assert_eq!(program.model.raw, 5, "raw events keep flowing to update()");
15206
15207        let gestures = log.lock().unwrap();
15208        assert!(
15209            matches!(
15210                gestures.first(),
15211                Some(SemanticEvent::Click { pos, button: MouseButton::Left })
15212                    if pos.x == 4 && pos.y == 2
15213            ),
15214            "first gesture is the click: {gestures:?}"
15215        );
15216        assert!(
15217            gestures
15218                .iter()
15219                .any(|g| matches!(g, SemanticEvent::DragStart { .. })),
15220            "drag start recognized: {gestures:?}"
15221        );
15222        assert!(
15223            gestures
15224                .iter()
15225                .any(|g| matches!(g, SemanticEvent::DragEnd { .. })),
15226            "drag end recognized: {gestures:?}"
15227        );
15228        drop(gestures);
15229
15230        // Without the config nothing is recognized and update() is unaffected.
15231        let quiet = Arc::new(Mutex::new(Vec::new()));
15232        let mut program = headless_program_with_config(
15233            GestureModel {
15234                raw: 0,
15235                gestures: Arc::clone(&quiet),
15236            },
15237            ProgramConfig::default(),
15238        );
15239        program
15240            .handle_event(mouse(MouseEventKind::Down(MouseButton::Left), 1, 1))
15241            .unwrap();
15242        program
15243            .handle_event(mouse(MouseEventKind::Up(MouseButton::Left), 1, 1))
15244            .unwrap();
15245        assert!(quiet.lock().unwrap().is_empty());
15246        assert_eq!(program.model.raw, 2);
15247    }
15248
15249    #[test]
15250    fn headless_program_event_coalescing_disabled_by_default() {
15251        use ftui_core::event::{Modifiers, MouseEvent, MouseEventKind};
15252
15253        #[derive(Default)]
15254        struct CoalesceTestModel {
15255            events: Vec<Event>,
15256        }
15257
15258        impl Model for CoalesceTestModel {
15259            type Message = Event;
15260            fn update(&mut self, msg: Event) -> Cmd<Event> {
15261                self.events.push(msg);
15262                Cmd::none()
15263            }
15264            fn view(&self, _frame: &mut Frame) {}
15265        }
15266
15267        let mut program =
15268            headless_program_with_config(CoalesceTestModel::default(), ProgramConfig::default());
15269        assert!(program.event_coalescer().is_none());
15270
15271        for i in 0..5 {
15272            program
15273                .handle_event(Event::Mouse(MouseEvent {
15274                    kind: MouseEventKind::Moved,
15275                    x: i,
15276                    y: i,
15277                    modifiers: Modifiers::NONE,
15278                }))
15279                .unwrap();
15280        }
15281        assert_eq!(program.model.events.len(), 5);
15282    }
15283
15284    #[test]
15285    fn headless_program_event_coalesces_mouse_moves_and_flushes_latest() {
15286        use ftui_core::event::{KeyCode, KeyEvent, Modifiers, MouseEvent, MouseEventKind};
15287
15288        #[derive(Default)]
15289        struct CoalesceTestModel {
15290            events: Vec<Event>,
15291        }
15292
15293        impl Model for CoalesceTestModel {
15294            type Message = Event;
15295            fn update(&mut self, msg: Event) -> Cmd<Event> {
15296                self.events.push(msg);
15297                Cmd::none()
15298            }
15299            fn view(&self, _frame: &mut Frame) {}
15300        }
15301
15302        let config = ProgramConfig::default().with_event_coalescing(true);
15303        let mut program = headless_program_with_config(CoalesceTestModel::default(), config);
15304        assert!(program.event_coalescer().is_some());
15305
15306        // Push 3 mouse move events.
15307        for i in 1..=3 {
15308            program
15309                .handle_event(Event::Mouse(MouseEvent {
15310                    kind: MouseEventKind::Moved,
15311                    x: i,
15312                    y: i * 2,
15313                    modifiers: Modifiers::NONE,
15314                }))
15315                .unwrap();
15316        }
15317
15318        // None should have reached the model yet.
15319        assert_eq!(program.model.events.len(), 0);
15320        assert!(program.event_coalescer().unwrap().has_pending());
15321
15322        // A non-coalescable event (Key) arrives: flushes pending move, then delivers key.
15323        let key_evt = Event::Key(KeyEvent::new(KeyCode::Enter));
15324        program.handle_event(key_evt.clone()).unwrap();
15325
15326        assert_eq!(program.model.events.len(), 2);
15327        match &program.model.events[0] {
15328            Event::Mouse(m) => {
15329                assert_eq!(m.kind, MouseEventKind::Moved);
15330                assert_eq!(m.x, 3);
15331                assert_eq!(m.y, 6);
15332            }
15333            other => panic!("expected Mouse move, got {other:?}"),
15334        }
15335        assert_eq!(program.model.events[1], key_evt);
15336        assert!(!program.event_coalescer().unwrap().has_pending());
15337    }
15338
15339    #[test]
15340    fn headless_program_event_coalesces_scrolls_in_same_direction() {
15341        use ftui_core::event::{Modifiers, MouseEvent, MouseEventKind};
15342
15343        #[derive(Default)]
15344        struct CoalesceTestModel {
15345            events: Vec<Event>,
15346        }
15347
15348        impl Model for CoalesceTestModel {
15349            type Message = Event;
15350            fn update(&mut self, msg: Event) -> Cmd<Event> {
15351                self.events.push(msg);
15352                Cmd::none()
15353            }
15354            fn view(&self, _frame: &mut Frame) {}
15355        }
15356
15357        let config = ProgramConfig::default().with_event_coalescing(true);
15358        let mut program = headless_program_with_config(CoalesceTestModel::default(), config);
15359
15360        for _ in 0..4 {
15361            program
15362                .handle_event(Event::Mouse(MouseEvent {
15363                    kind: MouseEventKind::ScrollUp,
15364                    x: 10,
15365                    y: 20,
15366                    modifiers: Modifiers::NONE,
15367                }))
15368                .unwrap();
15369        }
15370
15371        assert_eq!(program.model.events.len(), 0);
15372        assert!(program.event_coalescer().unwrap().has_pending());
15373
15374        // Four notches in, four notches out - which is the point of the fix:
15375        // collapsing the run made the application scroll a quarter as far as
15376        // the user asked (`bd-minjt`).
15377        //
15378        // Note what the assertion below therefore says about cost. The model
15379        // is updated four times, once per notch, because `MouseEventKind` has
15380        // no notch count and a model is entitled to see each notch. Batching
15381        // scroll defers those updates to flush time; it does not merge them.
15382        // Only mouse-move coalescing removes updates.
15383        program.flush_coalesced_events().unwrap();
15384        assert_eq!(program.model.events.len(), 4);
15385        for event in &program.model.events {
15386            match event {
15387                Event::Mouse(m) => {
15388                    assert_eq!(m.kind, MouseEventKind::ScrollUp);
15389                    assert_eq!(m.x, 10);
15390                    assert_eq!(m.y, 20);
15391                }
15392                other => panic!("expected ScrollUp, got {other:?}"),
15393            }
15394        }
15395    }
15396
15397    #[test]
15398    fn headless_program_event_coalescing_scroll_direction_change_flushes_old() {
15399        use ftui_core::event::{Modifiers, MouseEvent, MouseEventKind};
15400
15401        #[derive(Default)]
15402        struct CoalesceTestModel {
15403            events: Vec<Event>,
15404        }
15405
15406        impl Model for CoalesceTestModel {
15407            type Message = Event;
15408            fn update(&mut self, msg: Event) -> Cmd<Event> {
15409                self.events.push(msg);
15410                Cmd::none()
15411            }
15412            fn view(&self, _frame: &mut Frame) {}
15413        }
15414
15415        let config = ProgramConfig::default().with_event_coalescing(true);
15416        let mut program = headless_program_with_config(CoalesceTestModel::default(), config);
15417
15418        program
15419            .handle_event(Event::Mouse(MouseEvent {
15420                kind: MouseEventKind::ScrollUp,
15421                x: 5,
15422                y: 5,
15423                modifiers: Modifiers::NONE,
15424            }))
15425            .unwrap();
15426        assert_eq!(program.model.events.len(), 0);
15427
15428        // Direction change closes the ScrollUp run and opens a ScrollDown one.
15429        // Neither is dispatched yet: a closed run keeps its notch count, which
15430        // does not fit in the single event `push` can hand back, so it waits
15431        // for the flush that ends the batch.
15432        program
15433            .handle_event(Event::Mouse(MouseEvent {
15434                kind: MouseEventKind::ScrollDown,
15435                x: 6,
15436                y: 6,
15437                modifiers: Modifiers::NONE,
15438            }))
15439            .unwrap();
15440        assert_eq!(program.model.events.len(), 0);
15441
15442        // Both runs arrive in input order.
15443        program.flush_coalesced_events().unwrap();
15444        let kinds: Vec<MouseEventKind> = program
15445            .model
15446            .events
15447            .iter()
15448            .map(|e| match e {
15449                Event::Mouse(m) => m.kind,
15450                other => panic!("expected mouse event, got {other:?}"),
15451            })
15452            .collect();
15453        assert_eq!(
15454            kinds,
15455            vec![MouseEventKind::ScrollUp, MouseEventKind::ScrollDown]
15456        );
15457    }
15458
15459    #[test]
15460    fn headless_program_event_coalescing_flushed_on_tick() {
15461        use ftui_core::event::{Modifiers, MouseEvent, MouseEventKind};
15462
15463        #[derive(Default)]
15464        struct CoalesceTestModel {
15465            events: Vec<Event>,
15466        }
15467
15468        impl Model for CoalesceTestModel {
15469            type Message = Event;
15470            fn update(&mut self, msg: Event) -> Cmd<Event> {
15471                self.events.push(msg);
15472                Cmd::none()
15473            }
15474            fn view(&self, _frame: &mut Frame) {}
15475        }
15476
15477        let config = ProgramConfig::default().with_event_coalescing(true);
15478        let mut program = headless_program_with_config(CoalesceTestModel::default(), config);
15479
15480        program
15481            .handle_event(Event::Mouse(MouseEvent {
15482                kind: MouseEventKind::Moved,
15483                x: 42,
15484                y: 24,
15485                modifiers: Modifiers::NONE,
15486            }))
15487            .unwrap();
15488        assert_eq!(program.model.events.len(), 0);
15489
15490        program.handle_event(Event::Tick).unwrap();
15491        assert_eq!(program.model.events.len(), 2);
15492        match &program.model.events[0] {
15493            Event::Mouse(m) => {
15494                assert_eq!(m.kind, MouseEventKind::Moved);
15495                assert_eq!(m.x, 42);
15496                assert_eq!(m.y, 24);
15497            }
15498            other => panic!("expected Moved before Tick, got {other:?}"),
15499        }
15500        assert_eq!(program.model.events[1], Event::Tick);
15501    }
15502
15503    #[test]
15504    fn headless_program_event_coalescing_cleared_on_resize() {
15505        use ftui_core::event::{Modifiers, MouseEvent, MouseEventKind};
15506
15507        #[derive(Default)]
15508        struct CoalesceTestModel {
15509            events: Vec<Event>,
15510        }
15511
15512        impl Model for CoalesceTestModel {
15513            type Message = Event;
15514            fn update(&mut self, msg: Event) -> Cmd<Event> {
15515                self.events.push(msg);
15516                Cmd::none()
15517            }
15518            fn view(&self, _frame: &mut Frame) {}
15519        }
15520
15521        let config = ProgramConfig::default().with_event_coalescing(true);
15522        let mut program = headless_program_with_config(CoalesceTestModel::default(), config);
15523
15524        program
15525            .handle_event(Event::Mouse(MouseEvent {
15526                kind: MouseEventKind::Moved,
15527                x: 10,
15528                y: 10,
15529                modifiers: Modifiers::NONE,
15530            }))
15531            .unwrap();
15532        assert!(program.event_coalescer().unwrap().has_pending());
15533
15534        program
15535            .handle_event(Event::Resize {
15536                width: 100,
15537                height: 50,
15538            })
15539            .unwrap();
15540        assert!(!program.event_coalescer().unwrap().has_pending());
15541
15542        program.flush_coalesced_events().unwrap();
15543        // Mouse move was cleared, and resize is handled internally by the runtime.
15544        assert_eq!(program.model.events.len(), 0);
15545
15546        // Subsequent input arrives normally without the stale mouse position.
15547        program
15548            .handle_event(Event::Key(KeyEvent::new(KeyCode::Char('a'))))
15549            .unwrap();
15550        assert_eq!(program.model.events.len(), 1);
15551        assert_eq!(
15552            program.model.events[0],
15553            Event::Key(KeyEvent::new(KeyCode::Char('a')))
15554        );
15555    }
15556
15557    /// CONTRACT (bd-1za0z item 3): the queue guardrail sees the live effect
15558    /// backlog (`TaskExecutor::in_flight`), not a hard-coded zero. With a
15559    /// warn depth of one and four tasks in flight, the very first frame must
15560    /// raise a queue alert and export a snapshot carrying that depth.
15561    #[test]
15562    fn headless_render_frame_feeds_live_effect_backlog_to_queue_guardrail() {
15563        struct QueueModel;
15564
15565        #[derive(Debug)]
15566        enum QueueMsg {
15567            Noop,
15568        }
15569
15570        impl From<Event> for QueueMsg {
15571            fn from(_: Event) -> Self {
15572                QueueMsg::Noop
15573            }
15574        }
15575
15576        impl Model for QueueModel {
15577            type Message = QueueMsg;
15578
15579            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
15580                Cmd::none()
15581            }
15582
15583            fn view(&self, frame: &mut Frame) {
15584                frame.buffer.set_raw(0, 0, Cell::from_char('Q'));
15585            }
15586        }
15587
15588        let evidence_path = temp_evidence_path("guardrail_queue_depth");
15589        let config = ProgramConfig {
15590            guardrails: GuardrailsConfig {
15591                memory: MemoryBudgetConfig::default(),
15592                queue: QueueConfig {
15593                    warn_depth: 1,
15594                    ..QueueConfig::default()
15595                },
15596                ..Default::default()
15597            },
15598            evidence_sink: EvidenceSinkConfig::enabled_file(&evidence_path),
15599            ..Default::default()
15600        };
15601
15602        // Hand four real effects to this program's executor (the default
15603        // spawned lane) that are still running when the frame renders: the
15604        // guardrail must count them as the backlog. Drain them afterwards so
15605        // the test leaves no worker threads behind.
15606        const IN_FLIGHT: usize = 4;
15607        let mut program = headless_program_with_config(QueueModel, config);
15608        let release = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
15609        for _ in 0..IN_FLIGHT {
15610            let release = std::sync::Arc::clone(&release);
15611            program
15612                .execute_cmd(Cmd::task(move || {
15613                    while !release.load(std::sync::atomic::Ordering::Acquire) {
15614                        std::thread::sleep(Duration::from_millis(1));
15615                    }
15616                    QueueMsg::Noop
15617                }))
15618                .expect("submit in-flight task");
15619        }
15620        assert_eq!(program.task_executor.in_flight(), IN_FLIGHT);
15621        program.dirty = true;
15622        let rendered = program.render_frame();
15623        release.store(true, std::sync::atomic::Ordering::Release);
15624        let deadline = Instant::now() + Duration::from_secs(5);
15625        while program.task_executor.in_flight() > 0 && Instant::now() <= deadline {
15626            program
15627                .process_task_results()
15628                .expect("process task results");
15629            std::thread::sleep(Duration::from_millis(1));
15630        }
15631        assert_eq!(program.task_executor.in_flight(), 0, "tasks must drain");
15632        rendered.expect("render frame with queue alert");
15633
15634        let contents =
15635            std::fs::read_to_string(&evidence_path).expect("guardrail evidence file written");
15636        assert!(
15637            contents.contains(r#""event":"guardrail_snapshot""#),
15638            "queue backlog above warn_depth must export a guardrail_snapshot row; got: {contents}"
15639        );
15640        let depth = contents
15641            .split(r#""queue_depth":"#)
15642            .nth(1)
15643            .and_then(|rest| rest.split(|c: char| !c.is_ascii_digit()).next())
15644            .and_then(|digits| digits.parse::<u64>().ok())
15645            .expect("snapshot row carries queue_depth");
15646        assert!(
15647            depth >= IN_FLIGHT as u64,
15648            "guardrail must observe the live backlog (>= {IN_FLIGHT}), saw {depth}: {contents}"
15649        );
15650    }
15651
15652    #[test]
15653    fn guardrails_receive_live_queue_depth() {
15654        headless_render_frame_feeds_live_effect_backlog_to_queue_guardrail();
15655    }
15656
15657    #[test]
15658    fn guardrails_queue_depth_zero_without_queue() {
15659        struct ZeroQueueModel;
15660
15661        #[derive(Debug)]
15662        enum ZeroMsg {}
15663
15664        impl From<Event> for ZeroMsg {
15665            fn from(_: Event) -> Self {
15666                unreachable!()
15667            }
15668        }
15669
15670        impl Model for ZeroQueueModel {
15671            type Message = ZeroMsg;
15672
15673            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
15674                Cmd::none()
15675            }
15676
15677            fn view(&self, frame: &mut Frame) {
15678                frame.buffer.set_raw(0, 0, Cell::from_char('Z'));
15679            }
15680        }
15681
15682        let config = ProgramConfig {
15683            guardrails: GuardrailsConfig {
15684                memory: MemoryBudgetConfig::default(),
15685                queue: QueueConfig {
15686                    warn_depth: 1,
15687                    ..QueueConfig::default()
15688                },
15689                ..Default::default()
15690            },
15691            ..Default::default()
15692        };
15693
15694        let mut program = headless_program_with_config(ZeroQueueModel, config);
15695        assert_eq!(program.task_executor.in_flight(), 0);
15696        program.dirty = true;
15697        program.render_frame().expect("render frame with no tasks");
15698        let snapshot = program.guardrails.snapshot();
15699        assert_eq!(snapshot.queue_depth, 0);
15700        assert_eq!(snapshot.frames_with_alerts, 0);
15701    }
15702
15703    /// CONTRACT (bd-1za0z): a soft memory alert must trigger a capacity trim
15704    /// (arena rebuild + pool gc) so the degradation actuator can actually
15705    /// move the sensor โ€” retained capacity alone must not pin alerts forever.
15706    #[test]
15707    fn headless_render_frame_soft_alert_trims_retained_capacity() {
15708        struct AlertModel;
15709
15710        #[derive(Debug)]
15711        enum AlertMsg {
15712            Noop,
15713        }
15714
15715        impl From<Event> for AlertMsg {
15716            fn from(_: Event) -> Self {
15717                AlertMsg::Noop
15718            }
15719        }
15720
15721        impl Model for AlertModel {
15722            type Message = AlertMsg;
15723
15724            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
15725                Cmd::none()
15726            }
15727
15728            fn view(&self, _frame: &mut Frame) {}
15729        }
15730
15731        let config = ProgramConfig {
15732            guardrails: GuardrailsConfig {
15733                memory: MemoryBudgetConfig {
15734                    soft_limit_bytes: 4096,
15735                    ..MemoryBudgetConfig::default()
15736                },
15737                queue: QueueConfig::default(),
15738                ..Default::default()
15739            },
15740            ..Default::default()
15741        };
15742
15743        let mut program = headless_program_with_config(AlertModel, config.clone());
15744
15745        // Control: same config, same render, no injected capacity โ€” its
15746        // post-frame arena size is the floor a successful trim must return
15747        // to (the render itself allocates a deterministic working set).
15748        let mut control = headless_program_with_config(AlertModel, config);
15749        control.dirty = true;
15750        control.render_frame().expect("control render");
15751        let control_bytes = control.frame_arena.allocated_bytes();
15752
15753        // Simulate retained capacity well above the soft limit: 256 KiB of
15754        // arena allocations that a reset-less sensor can never shed.
15755        let filler = vec![0u8; 256 * 1024];
15756        program.frame_arena.alloc_slice(&filler);
15757        assert!(program.frame_arena.allocated_bytes() >= 256 * 1024);
15758
15759        program.dirty = true;
15760        program
15761            .render_frame()
15762            .expect("render frame with soft alert");
15763        assert_eq!(
15764            program.last_soft_trim_frame,
15765            Some(program.frame_idx),
15766            "soft alert must trigger the capacity trim"
15767        );
15768
15769        // The trim released the injected chunk: the arena is back at the
15770        // control's size instead of carrying the extra 256 KiB.
15771        let after = program.frame_arena.allocated_bytes();
15772        assert_eq!(program.guardrails.snapshot().leak_mean_bytes, 0.0);
15773        assert!(!program.guardrails.snapshot().leak_alert);
15774        assert!(
15775            after <= control_bytes + 1024,
15776            "soft alert must trim retained capacity: after={after}, control={control_bytes}"
15777        );
15778    }
15779
15780    #[test]
15781    fn headless_render_frame_skips_when_budget_exhausted() {
15782        let config = ProgramConfig {
15783            budget: FrameBudgetConfig::with_total(Duration::ZERO),
15784            ..Default::default()
15785        };
15786
15787        let mut program = headless_program_with_config(TestModel { value: 0 }, config);
15788        program.dirty = true;
15789        program.render_frame().expect("render frame");
15790
15791        // Dirty state is preserved when frame is skipped โ€” the UI update
15792        // was never presented and must be retried.
15793        assert!(program.dirty);
15794        assert_eq!(program.frame_idx, 1);
15795    }
15796
15797    #[test]
15798    fn headless_render_frame_emits_budget_evidence_with_controller() {
15799        use ftui_render::budget::BudgetControllerConfig;
15800
15801        struct RenderModel;
15802
15803        #[derive(Debug)]
15804        enum RenderMsg {
15805            Noop,
15806        }
15807
15808        impl From<Event> for RenderMsg {
15809            fn from(_: Event) -> Self {
15810                RenderMsg::Noop
15811            }
15812        }
15813
15814        impl Model for RenderModel {
15815            type Message = RenderMsg;
15816
15817            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
15818                Cmd::none()
15819            }
15820
15821            fn view(&self, frame: &mut Frame) {
15822                frame.buffer.set_raw(0, 0, Cell::from_char('E'));
15823            }
15824        }
15825
15826        let config =
15827            ProgramConfig::default().with_evidence_sink(EvidenceSinkConfig::enabled_stdout());
15828        let mut program = headless_program_with_config(RenderModel, config);
15829        program.budget = program
15830            .budget
15831            .with_controller(BudgetControllerConfig::default());
15832
15833        program.render_frame().expect("render frame");
15834        assert!(program.budget.telemetry().is_some());
15835        assert_eq!(program.frame_idx, 1);
15836    }
15837
15838    #[test]
15839    fn headless_handle_event_updates_model() {
15840        struct EventModel {
15841            events: usize,
15842            last_resize: Option<(u16, u16)>,
15843        }
15844
15845        #[derive(Debug)]
15846        enum EventMsg {
15847            Resize(u16, u16),
15848            Other,
15849        }
15850
15851        impl From<Event> for EventMsg {
15852            fn from(event: Event) -> Self {
15853                match event {
15854                    Event::Resize { width, height } => EventMsg::Resize(width, height),
15855                    _ => EventMsg::Other,
15856                }
15857            }
15858        }
15859
15860        impl Model for EventModel {
15861            type Message = EventMsg;
15862
15863            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
15864                self.events += 1;
15865                if let EventMsg::Resize(w, h) = msg {
15866                    self.last_resize = Some((w, h));
15867                }
15868                Cmd::none()
15869            }
15870
15871            fn view(&self, _frame: &mut Frame) {}
15872        }
15873
15874        let mut program = headless_program_with_config(
15875            EventModel {
15876                events: 0,
15877                last_resize: None,
15878            },
15879            ProgramConfig::default().with_resize_behavior(ResizeBehavior::Immediate),
15880        );
15881
15882        program
15883            .handle_event(Event::Key(ftui_core::event::KeyEvent::new(
15884                ftui_core::event::KeyCode::Char('x'),
15885            )))
15886            .expect("handle key");
15887        assert_eq!(program.model().events, 1);
15888
15889        program
15890            .handle_event(Event::Resize {
15891                width: 10,
15892                height: 5,
15893            })
15894            .expect("handle resize");
15895        assert_eq!(program.model().events, 2);
15896        assert_eq!(program.model().last_resize, Some((10, 5)));
15897        assert_eq!(program.width, 10);
15898        assert_eq!(program.height, 5);
15899    }
15900
15901    #[test]
15902    fn headless_handle_event_quit_skips_subscription_reconcile() {
15903        use crate::subscription::{StopSignal, SubId, Subscription, SubscriptionSender};
15904
15905        struct QuitSubModel {
15906            quitting: bool,
15907            subscription_starts: Arc<AtomicUsize>,
15908        }
15909
15910        #[derive(Debug)]
15911        enum QuitSubMsg {
15912            Quit,
15913            Other,
15914        }
15915
15916        impl From<Event> for QuitSubMsg {
15917            fn from(event: Event) -> Self {
15918                match event {
15919                    Event::Key(_) => Self::Quit,
15920                    _ => Self::Other,
15921                }
15922            }
15923        }
15924
15925        impl Model for QuitSubModel {
15926            type Message = QuitSubMsg;
15927
15928            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
15929                match msg {
15930                    QuitSubMsg::Quit => {
15931                        self.quitting = true;
15932                        Cmd::quit()
15933                    }
15934                    QuitSubMsg::Other => Cmd::none(),
15935                }
15936            }
15937
15938            fn view(&self, _frame: &mut Frame) {}
15939
15940            fn subscriptions(&self) -> Vec<Box<dyn Subscription<Self::Message>>> {
15941                if self.quitting {
15942                    vec![Box::new(QuitSubSubscription {
15943                        starts: Arc::clone(&self.subscription_starts),
15944                    })]
15945                } else {
15946                    vec![]
15947                }
15948            }
15949        }
15950
15951        struct QuitSubSubscription {
15952            starts: Arc<AtomicUsize>,
15953        }
15954
15955        impl Subscription<QuitSubMsg> for QuitSubSubscription {
15956            fn id(&self) -> SubId {
15957                7
15958            }
15959
15960            fn run(&self, _sender: SubscriptionSender<QuitSubMsg>, stop: StopSignal) {
15961                self.starts.fetch_add(1, Ordering::SeqCst);
15962                let _ = stop.wait_timeout(Duration::from_millis(10));
15963            }
15964        }
15965
15966        let subscription_starts = Arc::new(AtomicUsize::new(0));
15967        let mut program = headless_program_with_config(
15968            QuitSubModel {
15969                quitting: false,
15970                subscription_starts: Arc::clone(&subscription_starts),
15971            },
15972            ProgramConfig::default(),
15973        );
15974
15975        program
15976            .handle_event(Event::Key(ftui_core::event::KeyEvent::new(
15977                ftui_core::event::KeyCode::Char('q'),
15978            )))
15979            .expect("handle event");
15980
15981        assert!(!program.is_running());
15982        assert_eq!(program.subscriptions.active_count(), 0);
15983        assert_eq!(subscription_starts.load(Ordering::SeqCst), 0);
15984    }
15985
15986    #[test]
15987    fn headless_handle_resize_ignored_when_forced_size() {
15988        struct ResizeModel {
15989            resized: bool,
15990        }
15991
15992        #[derive(Debug)]
15993        enum ResizeMsg {
15994            Resize,
15995            Other,
15996        }
15997
15998        impl From<Event> for ResizeMsg {
15999            fn from(event: Event) -> Self {
16000                match event {
16001                    Event::Resize { .. } => ResizeMsg::Resize,
16002                    _ => ResizeMsg::Other,
16003                }
16004            }
16005        }
16006
16007        impl Model for ResizeModel {
16008            type Message = ResizeMsg;
16009
16010            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
16011                if matches!(msg, ResizeMsg::Resize) {
16012                    self.resized = true;
16013                }
16014                Cmd::none()
16015            }
16016
16017            fn view(&self, _frame: &mut Frame) {}
16018        }
16019
16020        let config = ProgramConfig::default().with_forced_size(80, 24);
16021        let mut program = headless_program_with_config(ResizeModel { resized: false }, config);
16022
16023        program
16024            .handle_event(Event::Resize {
16025                width: 120,
16026                height: 40,
16027            })
16028            .expect("handle resize");
16029
16030        assert_eq!(program.width, 80);
16031        assert_eq!(program.height, 24);
16032        assert!(!program.model().resized);
16033    }
16034
16035    #[test]
16036    fn headless_execute_cmd_batch_sequence_and_quit() {
16037        struct BatchModel {
16038            count: usize,
16039        }
16040
16041        #[derive(Debug)]
16042        enum BatchMsg {
16043            Inc,
16044        }
16045
16046        impl From<Event> for BatchMsg {
16047            fn from(_: Event) -> Self {
16048                BatchMsg::Inc
16049            }
16050        }
16051
16052        impl Model for BatchModel {
16053            type Message = BatchMsg;
16054
16055            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
16056                match msg {
16057                    BatchMsg::Inc => {
16058                        self.count += 1;
16059                        Cmd::none()
16060                    }
16061                }
16062            }
16063
16064            fn view(&self, _frame: &mut Frame) {}
16065        }
16066
16067        let mut program =
16068            headless_program_with_config(BatchModel { count: 0 }, ProgramConfig::default());
16069
16070        program
16071            .execute_cmd(Cmd::Batch(vec![
16072                Cmd::msg(BatchMsg::Inc),
16073                Cmd::Sequence(vec![
16074                    Cmd::msg(BatchMsg::Inc),
16075                    Cmd::quit(),
16076                    Cmd::msg(BatchMsg::Inc),
16077                ]),
16078            ]))
16079            .expect("batch cmd");
16080
16081        assert_eq!(program.model().count, 2);
16082        assert!(!program.running);
16083    }
16084
16085    #[test]
16086    fn headless_execute_cmd_runs_long_msg_chains_without_recursion() {
16087        // One step per `Cmd::Msg`, alternating a bare message with one
16088        // nested in a sequence. This recursed per step and overflowed the
16089        // stack at about 10k steps.
16090        struct Walker {
16091            steps: u32,
16092            order: Vec<&'static str>,
16093        }
16094
16095        #[derive(Debug)]
16096        enum WalkMsg {
16097            Step(u32),
16098            Mark(&'static str),
16099        }
16100
16101        impl From<Event> for WalkMsg {
16102            fn from(_: Event) -> Self {
16103                WalkMsg::Mark("event")
16104            }
16105        }
16106
16107        impl Model for Walker {
16108            type Message = WalkMsg;
16109
16110            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
16111                match msg {
16112                    WalkMsg::Step(0) => Cmd::quit(),
16113                    WalkMsg::Step(n) => {
16114                        self.steps += 1;
16115                        let step = Cmd::msg(WalkMsg::Step(n - 1));
16116                        if n % 2 == 0 {
16117                            step
16118                        } else {
16119                            Cmd::Sequence(vec![step, Cmd::msg(WalkMsg::Mark("after"))])
16120                        }
16121                    }
16122                    WalkMsg::Mark(label) => {
16123                        self.order.push(label);
16124                        Cmd::none()
16125                    }
16126                }
16127            }
16128
16129            fn view(&self, _frame: &mut Frame) {}
16130        }
16131
16132        let mut program = headless_program_with_config(
16133            Walker {
16134                steps: 0,
16135                order: Vec::new(),
16136            },
16137            ProgramConfig::default(),
16138        );
16139        program
16140            .execute_cmd(Cmd::msg(WalkMsg::Step(200_000)))
16141            .expect("chain");
16142        assert_eq!(program.model().steps, 200_000);
16143        // The chain ends in Quit, which stops every pending sequence.
16144        assert!(program.model().order.is_empty());
16145        assert!(!program.running);
16146
16147        // Without a quit, a sequence finishes its nested chain before its
16148        // next command, in the order recursion gave.
16149        program.running = true;
16150        program
16151            .execute_cmd(Cmd::Sequence(vec![
16152                Cmd::Batch(vec![
16153                    Cmd::msg(WalkMsg::Mark("a")),
16154                    Cmd::msg(WalkMsg::Mark("b")),
16155                ]),
16156                Cmd::msg(WalkMsg::Mark("c")),
16157            ]))
16158            .expect("sequence");
16159        assert_eq!(program.model().order, ["a", "b", "c"]);
16160    }
16161
16162    #[test]
16163    fn headless_process_subscription_messages_updates_model() {
16164        use crate::subscription::{StopSignal, SubId, Subscription, SubscriptionSender};
16165
16166        struct SubModel {
16167            pings: usize,
16168            ready_tx: mpsc::Sender<()>,
16169        }
16170
16171        #[derive(Debug)]
16172        enum SubMsg {
16173            Ping,
16174            Other,
16175        }
16176
16177        impl From<Event> for SubMsg {
16178            fn from(_: Event) -> Self {
16179                SubMsg::Other
16180            }
16181        }
16182
16183        impl Model for SubModel {
16184            type Message = SubMsg;
16185
16186            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
16187                if let SubMsg::Ping = msg {
16188                    self.pings += 1;
16189                }
16190                Cmd::none()
16191            }
16192
16193            fn view(&self, _frame: &mut Frame) {}
16194
16195            fn subscriptions(&self) -> Vec<Box<dyn Subscription<Self::Message>>> {
16196                vec![Box::new(TestSubscription {
16197                    ready_tx: self.ready_tx.clone(),
16198                })]
16199            }
16200        }
16201
16202        struct TestSubscription {
16203            ready_tx: mpsc::Sender<()>,
16204        }
16205
16206        impl Subscription<SubMsg> for TestSubscription {
16207            fn id(&self) -> SubId {
16208                1
16209            }
16210
16211            fn run(&self, sender: SubscriptionSender<SubMsg>, _stop: StopSignal) {
16212                let _ = sender.send(SubMsg::Ping);
16213                let _ = self.ready_tx.send(());
16214            }
16215        }
16216
16217        let (ready_tx, ready_rx) = mpsc::channel();
16218        let mut program =
16219            headless_program_with_config(SubModel { pings: 0, ready_tx }, ProgramConfig::default());
16220
16221        program.reconcile_subscriptions();
16222        ready_rx
16223            .recv_timeout(Duration::from_millis(200))
16224            .expect("subscription started");
16225        program
16226            .process_subscription_messages()
16227            .expect("process subscriptions");
16228
16229        assert_eq!(program.model().pings, 1);
16230    }
16231
16232    #[test]
16233    fn subscription_backlog_skips_idle_poll_without_starving_input_or_render() {
16234        use crate::subscription::{StopSignal, SubId, Subscription, SubscriptionSender};
16235        use std::sync::Mutex;
16236
16237        // Two full 64-message batches followed by one partial batch exercise
16238        // both prompt backlog draining and restoration of the normal timeout.
16239        const TOTAL: usize = 129;
16240        const IDLE_TIMEOUT: Duration = Duration::from_millis(100);
16241
16242        #[derive(Default)]
16243        struct Trace {
16244            delivered: usize,
16245            polls: Vec<(usize, Duration)>,
16246            renders: Vec<usize>,
16247        }
16248
16249        enum BurstMsg {
16250            Value(usize),
16251            Event(Event),
16252        }
16253
16254        impl From<Event> for BurstMsg {
16255            fn from(event: Event) -> Self {
16256                Self::Event(event)
16257            }
16258        }
16259
16260        struct BurstSubscription {
16261            ready: mpsc::Sender<()>,
16262        }
16263
16264        impl Subscription<BurstMsg> for BurstSubscription {
16265            fn id(&self) -> SubId {
16266                1
16267            }
16268
16269            fn run(&self, sender: SubscriptionSender<BurstMsg>, _stop: StopSignal) {
16270                for value in 0..TOTAL {
16271                    sender.send(BurstMsg::Value(value)).unwrap();
16272                }
16273                self.ready.send(()).unwrap();
16274            }
16275        }
16276
16277        struct BurstModel {
16278            received: Vec<usize>,
16279            input_at: Vec<usize>,
16280            ready: mpsc::Sender<()>,
16281            trace: Arc<Mutex<Trace>>,
16282        }
16283
16284        impl Model for BurstModel {
16285            type Message = BurstMsg;
16286
16287            fn update(&mut self, message: BurstMsg) -> Cmd<BurstMsg> {
16288                match message {
16289                    BurstMsg::Value(value) => {
16290                        self.received.push(value);
16291                        self.trace.lock().unwrap().delivered = self.received.len();
16292                    }
16293                    BurstMsg::Event(Event::Key(key)) if key.code == KeyCode::Char('q') => {
16294                        return Cmd::quit();
16295                    }
16296                    BurstMsg::Event(Event::Key(_)) => self.input_at.push(self.received.len()),
16297                    BurstMsg::Event(_) => {}
16298                }
16299                Cmd::none()
16300            }
16301
16302            fn view(&self, _frame: &mut Frame) {
16303                self.trace.lock().unwrap().renders.push(self.received.len());
16304            }
16305
16306            fn subscriptions(&self) -> Vec<Box<dyn Subscription<BurstMsg>>> {
16307                vec![Box::new(BurstSubscription {
16308                    ready: self.ready.clone(),
16309                })]
16310            }
16311        }
16312
16313        // The event source observes the real loop's requested timeouts. Its
16314        // initial barrier makes the whole burst pending before the first drain;
16315        // it supplies input between batches and quit only after complete delivery.
16316        struct ObservedSource {
16317            ready: Option<mpsc::Receiver<()>>,
16318            trace: Arc<Mutex<Trace>>,
16319            sent_input: bool,
16320            pending: Option<Event>,
16321        }
16322
16323        impl BackendEventSource for ObservedSource {
16324            type Error = io::Error;
16325
16326            fn size(&self) -> io::Result<(u16, u16)> {
16327                Ok((20, 4))
16328            }
16329
16330            fn set_features(&mut self, _features: BackendFeatures) -> io::Result<()> {
16331                Ok(())
16332            }
16333
16334            fn poll_event(&mut self, timeout: Duration) -> io::Result<bool> {
16335                if let Some(ready) = self.ready.take() {
16336                    ready
16337                        .recv_timeout(Duration::from_secs(2))
16338                        .map_err(io::Error::other)?;
16339                }
16340                let mut trace = self.trace.lock().unwrap();
16341                if trace.polls.len() >= 12 {
16342                    return Err(io::Error::other("subscription burst did not complete"));
16343                }
16344                let delivered = trace.delivered;
16345                trace.polls.push((delivered, timeout));
16346                drop(trace);
16347                if delivered == 64 && !self.sent_input {
16348                    self.sent_input = true;
16349                    self.pending = Some(Event::Key(KeyEvent::new(KeyCode::Char('x'))));
16350                } else if delivered == TOTAL {
16351                    self.pending = Some(Event::Key(KeyEvent::new(KeyCode::Char('q'))));
16352                }
16353                Ok(self.pending.is_some())
16354            }
16355
16356            fn read_event(&mut self) -> io::Result<Option<Event>> {
16357                Ok(self.pending.take())
16358            }
16359        }
16360
16361        let trace = Arc::new(Mutex::new(Trace::default()));
16362        let (ready_tx, ready_rx) = mpsc::channel();
16363        let model = BurstModel {
16364            received: Vec::new(),
16365            input_at: Vec::new(),
16366            ready: ready_tx,
16367            trace: Arc::clone(&trace),
16368        };
16369        let events = ObservedSource {
16370            ready: Some(ready_rx),
16371            trace: Arc::clone(&trace),
16372            sent_input: false,
16373            pending: None,
16374        };
16375        let writer = TerminalWriter::new(
16376            Vec::new(),
16377            ScreenMode::AltScreen,
16378            UiAnchor::Bottom,
16379            TerminalCapabilities::dumb(),
16380        );
16381        let config = ProgramConfig {
16382            poll_timeout: IDLE_TIMEOUT,
16383            ..ProgramConfig::default()
16384                .with_forced_size(20, 4)
16385                .with_signal_interception(false)
16386                .with_budget(FrameBudgetConfig::with_total(Duration::from_secs(5)))
16387        };
16388        let mut program = Program::with_event_source(
16389            model,
16390            events,
16391            BackendFeatures::default(),
16392            TerminalPresenter::new(writer),
16393            config,
16394        )
16395        .expect("program construction");
16396        program
16397            .run()
16398            .expect("burst completes through the real loop");
16399
16400        assert_eq!(program.model().received, (0..TOTAL).collect::<Vec<_>>());
16401        assert_eq!(program.model().input_at, [64]);
16402        let trace = trace.lock().unwrap();
16403        assert_eq!(trace.renders, [0, 64, 128, TOTAL]);
16404        assert_eq!(trace.polls.first(), Some(&(0, IDLE_TIMEOUT)));
16405        assert_eq!(trace.polls.last(), Some(&(TOTAL, IDLE_TIMEOUT)));
16406        for delivered in [64, 128] {
16407            let polls: Vec<_> = trace
16408                .polls
16409                .iter()
16410                .filter(|(count, _)| *count == delivered)
16411                .collect();
16412            assert!(!polls.is_empty(), "input must be polled between batches");
16413            assert!(
16414                polls.iter().all(|(_, timeout)| *timeout == Duration::ZERO),
16415                "queued subscription output must not incur an idle input wait: {polls:?}"
16416            );
16417        }
16418    }
16419
16420    #[test]
16421    fn headless_execute_cmd_task_spawns_and_reaps() {
16422        struct TaskModel {
16423            done: bool,
16424        }
16425
16426        #[derive(Debug)]
16427        enum TaskMsg {
16428            Done,
16429        }
16430
16431        impl From<Event> for TaskMsg {
16432            fn from(_: Event) -> Self {
16433                TaskMsg::Done
16434            }
16435        }
16436
16437        impl Model for TaskModel {
16438            type Message = TaskMsg;
16439
16440            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
16441                match msg {
16442                    TaskMsg::Done => {
16443                        self.done = true;
16444                        Cmd::none()
16445                    }
16446                }
16447            }
16448
16449            fn view(&self, _frame: &mut Frame) {}
16450        }
16451
16452        let mut program =
16453            headless_program_with_config(TaskModel { done: false }, ProgramConfig::default());
16454        program
16455            .execute_cmd(Cmd::task(|| TaskMsg::Done))
16456            .expect("task cmd");
16457
16458        let deadline = Instant::now() + Duration::from_millis(200);
16459        while !program.model().done && Instant::now() <= deadline {
16460            program
16461                .process_task_results()
16462                .expect("process task results");
16463            program.reap_finished_tasks();
16464        }
16465
16466        assert!(program.model().done, "task result did not arrive in time");
16467    }
16468
16469    #[test]
16470    fn headless_default_task_executor_is_spawned_for_structured_lane() {
16471        // Input-lag regression fix (#78): the default Structured lane must use
16472        // per-task `Spawned` execution, NOT the single-worker effect queue.
16473        // Routing every `Cmd::Task` through one serialized `effect_queue_loop`
16474        // worker added per-keystroke head-of-line latency for apps that forward
16475        // PTY output via per-pane polling tasks. Structured cancellation does
16476        // not require the effect queue, so the default backend is `Spawned`
16477        // ("spawned") here, matching v0.2.1 task concurrency.
16478        let program =
16479            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
16480        assert_eq!(program.task_executor.kind_name(), "spawned");
16481    }
16482
16483    #[test]
16484    fn headless_structured_lane_task_executor_writes_spawned_backend_evidence() {
16485        // Input-lag regression fix (#78): the default Structured lane emits the
16486        // "spawned" backend in startup evidence (was "queued"), reflecting the
16487        // restored per-task-thread execution.
16488        let evidence_path = temp_evidence_path("task_executor_spawned_backend");
16489        let sink_config = EvidenceSinkConfig::enabled_file(&evidence_path);
16490        let config = ProgramConfig::default().with_evidence_sink(sink_config);
16491        let _program = headless_program_with_config(TestModel { value: 0 }, config);
16492
16493        let backend_line = read_evidence_event(&evidence_path, "task_executor_backend");
16494        assert_eq!(backend_line["backend"], "spawned");
16495    }
16496
16497    #[test]
16498    fn headless_legacy_lane_task_executor_is_spawned() {
16499        let config = ProgramConfig::default().with_lane(RuntimeLane::Legacy);
16500        let program = headless_program_with_config(TestModel { value: 0 }, config);
16501        assert_eq!(program.task_executor.kind_name(), "spawned");
16502    }
16503
16504    #[test]
16505    fn headless_explicit_spawned_backend_overrides_structured_lane_default() {
16506        let config = ProgramConfig::default().with_effect_queue(
16507            EffectQueueConfig::default().with_backend(TaskExecutorBackend::Spawned),
16508        );
16509        let program = headless_program_with_config(TestModel { value: 0 }, config);
16510        assert_eq!(program.task_executor.kind_name(), "spawned");
16511    }
16512
16513    #[cfg(feature = "asupersync-executor")]
16514    #[test]
16515    fn headless_asupersync_task_executor_is_selected() {
16516        let config = ProgramConfig::default().with_effect_queue(
16517            EffectQueueConfig::default().with_backend(TaskExecutorBackend::Asupersync),
16518        );
16519        let program = headless_program_with_config(TestModel { value: 0 }, config);
16520        assert_eq!(program.task_executor.kind_name(), "asupersync");
16521    }
16522
16523    #[test]
16524    fn headless_persistence_commands_with_registry() {
16525        use crate::state_persistence::{MemoryStorage, StateRegistry};
16526        use std::sync::Arc;
16527
16528        let registry = Arc::new(StateRegistry::new(Box::new(MemoryStorage::new())));
16529        let config = ProgramConfig::default().with_registry(registry.clone());
16530        let mut program = headless_program_with_config(TestModel { value: 0 }, config);
16531
16532        assert!(program.has_persistence());
16533        assert!(program.state_registry().is_some());
16534
16535        program.execute_cmd(Cmd::save_state()).expect("save");
16536        program.execute_cmd(Cmd::restore_state()).expect("restore");
16537
16538        let saved = program.trigger_save().expect("trigger save");
16539        let loaded = program.trigger_load().expect("trigger load");
16540        assert!(!saved);
16541        assert_eq!(loaded, 0);
16542    }
16543
16544    #[test]
16545    fn headless_process_resize_coalescer_applies_pending_resize() {
16546        struct ResizeModel {
16547            last_size: Option<(u16, u16)>,
16548        }
16549
16550        #[derive(Debug)]
16551        enum ResizeMsg {
16552            Resize(u16, u16),
16553            Other,
16554        }
16555
16556        impl From<Event> for ResizeMsg {
16557            fn from(event: Event) -> Self {
16558                match event {
16559                    Event::Resize { width, height } => ResizeMsg::Resize(width, height),
16560                    _ => ResizeMsg::Other,
16561                }
16562            }
16563        }
16564
16565        impl Model for ResizeModel {
16566            type Message = ResizeMsg;
16567
16568            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
16569                if let ResizeMsg::Resize(w, h) = msg {
16570                    self.last_size = Some((w, h));
16571                }
16572                Cmd::none()
16573            }
16574
16575            fn view(&self, _frame: &mut Frame) {}
16576        }
16577
16578        let evidence_path = temp_evidence_path("fairness_allow");
16579        let sink_config = EvidenceSinkConfig::enabled_file(&evidence_path);
16580        let mut config = ProgramConfig::default().with_resize_behavior(ResizeBehavior::Throttled);
16581        config.resize_coalescer.steady_delay_ms = 0;
16582        config.resize_coalescer.burst_delay_ms = 0;
16583        config.resize_coalescer.hard_deadline_ms = 1_000;
16584        config.evidence_sink = sink_config.clone();
16585
16586        let mut program = headless_program_with_config(ResizeModel { last_size: None }, config);
16587        let sink = EvidenceSink::from_config(&sink_config)
16588            .expect("evidence sink config")
16589            .expect("evidence sink enabled");
16590        program.evidence_sink = Some(sink);
16591
16592        program.resize_coalescer.handle_resize(120, 40);
16593        assert!(program.resize_coalescer.has_pending());
16594
16595        program
16596            .process_resize_coalescer()
16597            .expect("process resize coalescer");
16598
16599        assert_eq!(program.width, 120);
16600        assert_eq!(program.height, 40);
16601        assert_eq!(program.model().last_size, Some((120, 40)));
16602
16603        let config_line = read_evidence_event(&evidence_path, "fairness_config");
16604        assert_eq!(config_line["event"], "fairness_config");
16605        assert!(config_line["enabled"].is_boolean());
16606        assert!(config_line["input_priority_threshold_ms"].is_number());
16607        assert!(config_line["dominance_threshold"].is_number());
16608        assert!(config_line["fairness_threshold"].is_number());
16609
16610        let decision_line = read_evidence_event(&evidence_path, "fairness_decision");
16611        assert_eq!(decision_line["event"], "fairness_decision");
16612        assert_eq!(decision_line["decision"], "allow");
16613        assert_eq!(decision_line["reason"], "none");
16614        assert!(decision_line["pending_input_latency_ms"].is_null());
16615        assert!(decision_line["jain_index"].is_number());
16616        assert!(decision_line["resize_dominance_count"].is_number());
16617        assert!(decision_line["dominance_threshold"].is_number());
16618        assert!(decision_line["fairness_threshold"].is_number());
16619        assert!(decision_line["input_priority_threshold_ms"].is_number());
16620    }
16621
16622    #[test]
16623    fn headless_process_resize_coalescer_yields_to_input() {
16624        struct ResizeModel {
16625            last_size: Option<(u16, u16)>,
16626        }
16627
16628        #[derive(Debug)]
16629        enum ResizeMsg {
16630            Resize(u16, u16),
16631            Other,
16632        }
16633
16634        impl From<Event> for ResizeMsg {
16635            fn from(event: Event) -> Self {
16636                match event {
16637                    Event::Resize { width, height } => ResizeMsg::Resize(width, height),
16638                    _ => ResizeMsg::Other,
16639                }
16640            }
16641        }
16642
16643        impl Model for ResizeModel {
16644            type Message = ResizeMsg;
16645
16646            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
16647                if let ResizeMsg::Resize(w, h) = msg {
16648                    self.last_size = Some((w, h));
16649                }
16650                Cmd::none()
16651            }
16652
16653            fn view(&self, _frame: &mut Frame) {}
16654        }
16655
16656        let evidence_path = temp_evidence_path("fairness_yield");
16657        let sink_config = EvidenceSinkConfig::enabled_file(&evidence_path);
16658        let mut config = ProgramConfig::default().with_resize_behavior(ResizeBehavior::Throttled);
16659        config.resize_coalescer.steady_delay_ms = 0;
16660        config.resize_coalescer.burst_delay_ms = 0;
16661        // Use a large hard deadline so elapsed wall-clock time between coalescer
16662        // construction and `handle_resize` never triggers an immediate apply.
16663        config.resize_coalescer.hard_deadline_ms = 10_000;
16664        config.evidence_sink = sink_config.clone();
16665
16666        let mut program = headless_program_with_config(ResizeModel { last_size: None }, config);
16667        let sink = EvidenceSink::from_config(&sink_config)
16668            .expect("evidence sink config")
16669            .expect("evidence sink enabled");
16670        program.evidence_sink = Some(sink);
16671
16672        program.fairness_guard = InputFairnessGuard::with_config(
16673            crate::input_fairness::FairnessConfig::default().with_max_latency(Duration::ZERO),
16674        );
16675        program
16676            .fairness_guard
16677            .input_arrived(Instant::now() - Duration::from_millis(1));
16678
16679        program.resize_coalescer.handle_resize(120, 40);
16680        assert!(program.resize_coalescer.has_pending());
16681
16682        program
16683            .process_resize_coalescer()
16684            .expect("process resize coalescer");
16685
16686        assert_eq!(program.width, 80);
16687        assert_eq!(program.height, 24);
16688        assert_eq!(program.model().last_size, None);
16689        assert!(program.resize_coalescer.has_pending());
16690
16691        let decision_line = read_evidence_event(&evidence_path, "fairness_decision");
16692        assert_eq!(decision_line["event"], "fairness_decision");
16693        assert_eq!(decision_line["decision"], "yield");
16694        assert_eq!(decision_line["reason"], "input_latency");
16695        assert!(decision_line["pending_input_latency_ms"].is_number());
16696        assert!(decision_line["jain_index"].is_number());
16697        assert!(decision_line["resize_dominance_count"].is_number());
16698        assert!(decision_line["dominance_threshold"].is_number());
16699        assert!(decision_line["fairness_threshold"].is_number());
16700        assert!(decision_line["input_priority_threshold_ms"].is_number());
16701    }
16702
16703    #[test]
16704    fn headless_execute_cmd_task_with_effect_queue() {
16705        struct TaskModel {
16706            done: bool,
16707        }
16708
16709        #[derive(Debug)]
16710        enum TaskMsg {
16711            Done,
16712        }
16713
16714        impl From<Event> for TaskMsg {
16715            fn from(_: Event) -> Self {
16716                TaskMsg::Done
16717            }
16718        }
16719
16720        impl Model for TaskModel {
16721            type Message = TaskMsg;
16722
16723            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
16724                match msg {
16725                    TaskMsg::Done => {
16726                        self.done = true;
16727                        Cmd::none()
16728                    }
16729                }
16730            }
16731
16732            fn view(&self, _frame: &mut Frame) {}
16733        }
16734
16735        let effect_queue = EffectQueueConfig {
16736            enabled: true,
16737            backend: TaskExecutorBackend::EffectQueue,
16738            scheduler: SchedulerConfig {
16739                max_queue_size: 0,
16740                ..Default::default()
16741            },
16742            explicit_backend: true,
16743            ..Default::default()
16744        };
16745        let config = ProgramConfig::default().with_effect_queue(effect_queue);
16746        let mut program = headless_program_with_config(TaskModel { done: false }, config);
16747
16748        program
16749            .execute_cmd(Cmd::task(|| TaskMsg::Done))
16750            .expect("task cmd");
16751
16752        let deadline = Instant::now() + Duration::from_millis(200);
16753        while !program.model().done && Instant::now() <= deadline {
16754            program
16755                .process_task_results()
16756                .expect("process task results");
16757        }
16758
16759        assert!(
16760            program.model().done,
16761            "effect queue task result did not arrive in time"
16762        );
16763        assert_eq!(program.task_executor.kind_name(), "queued");
16764    }
16765
16766    #[test]
16767    fn headless_execute_cmd_task_with_spawned_backend_writes_completion_evidence() {
16768        struct TaskModel {
16769            done: bool,
16770        }
16771
16772        #[derive(Debug)]
16773        enum TaskMsg {
16774            Done,
16775        }
16776
16777        impl From<Event> for TaskMsg {
16778            fn from(_: Event) -> Self {
16779                TaskMsg::Done
16780            }
16781        }
16782
16783        impl Model for TaskModel {
16784            type Message = TaskMsg;
16785
16786            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
16787                match msg {
16788                    TaskMsg::Done => {
16789                        self.done = true;
16790                        Cmd::none()
16791                    }
16792                }
16793            }
16794
16795            fn view(&self, _frame: &mut Frame) {}
16796        }
16797
16798        let evidence_path = temp_evidence_path("task_executor_spawned_complete");
16799        let sink_config = EvidenceSinkConfig::enabled_file(&evidence_path);
16800        let config = ProgramConfig::default()
16801            .with_lane(RuntimeLane::Legacy)
16802            .with_evidence_sink(sink_config);
16803        let mut program = headless_program_with_config(TaskModel { done: false }, config);
16804
16805        program
16806            .execute_cmd(Cmd::task(|| TaskMsg::Done))
16807            .expect("task cmd");
16808
16809        let deadline = Instant::now() + Duration::from_millis(200);
16810        while !program.model().done && Instant::now() <= deadline {
16811            program
16812                .process_task_results()
16813                .expect("process task results");
16814            program.reap_finished_tasks();
16815        }
16816
16817        assert!(
16818            program.model().done,
16819            "spawned task result did not arrive in time"
16820        );
16821
16822        let completion_line = read_evidence_event(&evidence_path, "task_executor_complete");
16823        assert_eq!(completion_line["backend"], "spawned");
16824        assert!(completion_line["duration_us"].is_number());
16825    }
16826
16827    #[test]
16828    fn headless_effect_queue_task_panic_writes_panic_evidence_and_continues() {
16829        struct TaskModel {
16830            done: bool,
16831        }
16832
16833        #[derive(Debug)]
16834        enum TaskMsg {
16835            Done,
16836        }
16837
16838        impl From<Event> for TaskMsg {
16839            fn from(_: Event) -> Self {
16840                TaskMsg::Done
16841            }
16842        }
16843
16844        impl Model for TaskModel {
16845            type Message = TaskMsg;
16846
16847            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
16848                match msg {
16849                    TaskMsg::Done => {
16850                        self.done = true;
16851                        Cmd::none()
16852                    }
16853                }
16854            }
16855
16856            fn view(&self, _frame: &mut Frame) {}
16857        }
16858
16859        let evidence_path = temp_evidence_path("task_executor_queued_panic");
16860        let sink_config = EvidenceSinkConfig::enabled_file(&evidence_path);
16861        let config = ProgramConfig::default()
16862            .with_evidence_sink(sink_config)
16863            .with_effect_queue(
16864                EffectQueueConfig::default().with_backend(TaskExecutorBackend::EffectQueue),
16865            );
16866        let mut program = headless_program_with_config(TaskModel { done: false }, config);
16867
16868        program
16869            .execute_cmd(Cmd::task(|| -> TaskMsg { panic!("queued panic evidence") }))
16870            .expect("panic task cmd");
16871        program
16872            .execute_cmd(Cmd::task(|| TaskMsg::Done))
16873            .expect("follow-up task cmd");
16874
16875        let deadline = Instant::now() + Duration::from_millis(500);
16876        while !program.model().done && Instant::now() <= deadline {
16877            program
16878                .process_task_results()
16879                .expect("process task results");
16880        }
16881
16882        assert!(
16883            program.model().done,
16884            "effect queue should continue after a panicking task"
16885        );
16886
16887        let panic_line = read_evidence_event(&evidence_path, "task_executor_panic");
16888        assert_eq!(panic_line["backend"], "queued");
16889        assert_eq!(panic_line["panic_msg"], "queued panic evidence");
16890    }
16891
16892    #[cfg(feature = "asupersync-executor")]
16893    #[test]
16894    fn headless_execute_cmd_task_with_asupersync_backend() {
16895        struct TaskModel {
16896            done: bool,
16897        }
16898
16899        #[derive(Debug)]
16900        enum TaskMsg {
16901            Done,
16902        }
16903
16904        impl From<Event> for TaskMsg {
16905            fn from(_: Event) -> Self {
16906                TaskMsg::Done
16907            }
16908        }
16909
16910        impl Model for TaskModel {
16911            type Message = TaskMsg;
16912
16913            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
16914                match msg {
16915                    TaskMsg::Done => {
16916                        self.done = true;
16917                        Cmd::none()
16918                    }
16919                }
16920            }
16921
16922            fn view(&self, _frame: &mut Frame) {}
16923        }
16924
16925        let config = ProgramConfig::default().with_effect_queue(
16926            EffectQueueConfig::default().with_backend(TaskExecutorBackend::Asupersync),
16927        );
16928        let mut program = headless_program_with_config(TaskModel { done: false }, config);
16929
16930        program
16931            .execute_cmd(Cmd::task(|| TaskMsg::Done))
16932            .expect("task cmd");
16933
16934        let deadline = Instant::now() + Duration::from_millis(200);
16935        while !program.model().done && Instant::now() <= deadline {
16936            program
16937                .process_task_results()
16938                .expect("process task results");
16939            program.reap_finished_tasks();
16940        }
16941
16942        assert!(
16943            program.model().done,
16944            "asupersync task result did not arrive in time"
16945        );
16946        assert_eq!(program.task_executor.kind_name(), "asupersync");
16947    }
16948
16949    #[cfg(feature = "asupersync-executor")]
16950    #[test]
16951    fn headless_asupersync_task_executor_writes_backend_and_completion_evidence() {
16952        struct TaskModel {
16953            done: bool,
16954        }
16955
16956        #[derive(Debug)]
16957        enum TaskMsg {
16958            Done,
16959        }
16960
16961        impl From<Event> for TaskMsg {
16962            fn from(_: Event) -> Self {
16963                TaskMsg::Done
16964            }
16965        }
16966
16967        impl Model for TaskModel {
16968            type Message = TaskMsg;
16969
16970            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
16971                match msg {
16972                    TaskMsg::Done => {
16973                        self.done = true;
16974                        Cmd::none()
16975                    }
16976                }
16977            }
16978
16979            fn view(&self, _frame: &mut Frame) {}
16980        }
16981
16982        let evidence_path = temp_evidence_path("task_executor_asupersync_complete");
16983        let sink_config = EvidenceSinkConfig::enabled_file(&evidence_path);
16984        let config = ProgramConfig::default()
16985            .with_evidence_sink(sink_config)
16986            .with_effect_queue(
16987                EffectQueueConfig::default().with_backend(TaskExecutorBackend::Asupersync),
16988            );
16989        let mut program = headless_program_with_config(TaskModel { done: false }, config);
16990
16991        let backend_line = read_evidence_event(&evidence_path, "task_executor_backend");
16992        assert_eq!(backend_line["backend"], "asupersync");
16993
16994        program
16995            .execute_cmd(Cmd::task(|| TaskMsg::Done))
16996            .expect("task cmd");
16997
16998        let deadline = Instant::now() + Duration::from_millis(200);
16999        while !program.model().done && Instant::now() <= deadline {
17000            program
17001                .process_task_results()
17002                .expect("process task results");
17003            program.reap_finished_tasks();
17004        }
17005
17006        assert!(
17007            program.model().done,
17008            "asupersync task result did not arrive in time"
17009        );
17010
17011        let completion_line = read_evidence_event(&evidence_path, "task_executor_complete");
17012        assert_eq!(completion_line["backend"], "asupersync");
17013        assert!(completion_line["duration_us"].is_number());
17014    }
17015
17016    // =========================================================================
17017    // Asupersync executor: semantic parity, failure, stress, shutdown, and
17018    // backpressure coverage (bd-392ka).
17019    // =========================================================================
17020
17021    /// Run `count` tasks (each emitting its index) through `backend` headlessly
17022    /// and return the sorted multiset of delivered message payloads.
17023    #[cfg(feature = "asupersync-executor")]
17024    fn collect_task_batch(backend: TaskExecutorBackend, count: u32) -> Vec<u32> {
17025        struct CollectModel {
17026            got: Vec<u32>,
17027        }
17028        #[derive(Debug)]
17029        enum CollectMsg {
17030            Got(u32),
17031        }
17032        impl From<Event> for CollectMsg {
17033            fn from(_: Event) -> Self {
17034                CollectMsg::Got(u32::MAX)
17035            }
17036        }
17037        impl Model for CollectModel {
17038            type Message = CollectMsg;
17039            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
17040                match msg {
17041                    CollectMsg::Got(value) => self.got.push(value),
17042                }
17043                Cmd::none()
17044            }
17045            fn view(&self, _frame: &mut Frame) {}
17046        }
17047
17048        let config = ProgramConfig::default()
17049            .with_effect_queue(EffectQueueConfig::default().with_backend(backend));
17050        let mut program = headless_program_with_config(CollectModel { got: Vec::new() }, config);
17051        for index in 0..count {
17052            program
17053                .execute_cmd(Cmd::task(move || CollectMsg::Got(index)))
17054                .expect("task cmd");
17055        }
17056        let deadline = Instant::now() + Duration::from_secs(5);
17057        while program.model().got.len() < count as usize && Instant::now() <= deadline {
17058            program
17059                .process_task_results()
17060                .expect("process task results");
17061            program.reap_finished_tasks();
17062        }
17063        let mut got = program.model().got.clone();
17064        got.sort_unstable();
17065        got
17066    }
17067
17068    #[cfg(feature = "asupersync-executor")]
17069    #[test]
17070    fn asupersync_semantic_parity_with_spawned_backend() {
17071        // The same task batch must deliver an identical message multiset whether
17072        // run through the legacy Spawned backend or the Asupersync backend. This
17073        // is the evidence-backed semantic-parity check (a shadow-run in miniature).
17074        let expected: Vec<u32> = (0..16).collect();
17075        let spawned = collect_task_batch(TaskExecutorBackend::Spawned, 16);
17076        let asupersync = collect_task_batch(TaskExecutorBackend::Asupersync, 16);
17077        assert_eq!(
17078            spawned, expected,
17079            "spawned backend lost or reordered results"
17080        );
17081        assert_eq!(
17082            asupersync, expected,
17083            "asupersync backend diverged from the expected results"
17084        );
17085        assert_eq!(
17086            asupersync, spawned,
17087            "asupersync diverged from spawned (parity)"
17088        );
17089    }
17090
17091    #[cfg(feature = "asupersync-executor")]
17092    #[test]
17093    fn asupersync_stress_delivers_every_task() {
17094        // Under a large burst, every task result must arrive exactly once.
17095        let count: u32 = 200;
17096        let got = collect_task_batch(TaskExecutorBackend::Asupersync, count);
17097        assert_eq!(
17098            got.len(),
17099            count as usize,
17100            "asupersync dropped tasks under load"
17101        );
17102        assert_eq!(got, (0..count).collect::<Vec<_>>());
17103    }
17104
17105    #[cfg(feature = "asupersync-executor")]
17106    #[test]
17107    fn asupersync_task_panic_is_isolated() {
17108        struct PanicModel {
17109            survivor_seen: bool,
17110        }
17111        #[derive(Debug)]
17112        enum PanicMsg {
17113            Survivor,
17114        }
17115        impl From<Event> for PanicMsg {
17116            fn from(_: Event) -> Self {
17117                PanicMsg::Survivor
17118            }
17119        }
17120        impl Model for PanicModel {
17121            type Message = PanicMsg;
17122            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
17123                match msg {
17124                    PanicMsg::Survivor => self.survivor_seen = true,
17125                }
17126                Cmd::none()
17127            }
17128            fn view(&self, _frame: &mut Frame) {}
17129        }
17130
17131        let evidence_path = temp_evidence_path("asupersync_panic");
17132        let sink_config = EvidenceSinkConfig::enabled_file(&evidence_path);
17133        let config = ProgramConfig::default()
17134            .with_evidence_sink(sink_config)
17135            .with_effect_queue(
17136                EffectQueueConfig::default().with_backend(TaskExecutorBackend::Asupersync),
17137            );
17138        let mut program = headless_program_with_config(
17139            PanicModel {
17140                survivor_seen: false,
17141            },
17142            config,
17143        );
17144
17145        // A panicking task must neither crash the executor nor deliver a message...
17146        program
17147            .execute_cmd(Cmd::task(|| -> PanicMsg { panic!("asupersync boom") }))
17148            .expect("panic task cmd");
17149        // ...and a task submitted afterwards must still complete normally.
17150        program
17151            .execute_cmd(Cmd::task(|| PanicMsg::Survivor))
17152            .expect("survivor task cmd");
17153
17154        let deadline = Instant::now() + Duration::from_secs(5);
17155        // The survivor can finish before the other worker records its panic.
17156        // Completed handles also guarantee that their evidence writes finished.
17157        while (!program.model().survivor_seen || program.task_executor.in_flight() > 0)
17158            && Instant::now() <= deadline
17159        {
17160            program
17161                .process_task_results()
17162                .expect("process task results");
17163            program.reap_finished_tasks();
17164        }
17165        assert!(
17166            program.model().survivor_seen,
17167            "executor did not survive a panicking task"
17168        );
17169        assert_eq!(
17170            program.task_executor.in_flight(),
17171            0,
17172            "executor tasks did not finish before evidence was read"
17173        );
17174        let panic_line = read_evidence_event(&evidence_path, "task_executor_panic");
17175        assert_eq!(panic_line["backend"], "asupersync");
17176        assert_eq!(panic_line["panic_msg"], "asupersync boom");
17177    }
17178
17179    #[cfg(feature = "asupersync-executor")]
17180    #[test]
17181    fn asupersync_rejects_tasks_after_shutdown() {
17182        struct ShutdownModel {
17183            seen: bool,
17184        }
17185        #[derive(Debug)]
17186        enum ShutdownMsg {
17187            Seen,
17188        }
17189        impl From<Event> for ShutdownMsg {
17190            fn from(_: Event) -> Self {
17191                ShutdownMsg::Seen
17192            }
17193        }
17194        impl Model for ShutdownModel {
17195            type Message = ShutdownMsg;
17196            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
17197                match msg {
17198                    ShutdownMsg::Seen => self.seen = true,
17199                }
17200                Cmd::none()
17201            }
17202            fn view(&self, _frame: &mut Frame) {}
17203        }
17204
17205        let config = ProgramConfig::default().with_effect_queue(
17206            EffectQueueConfig::default().with_backend(TaskExecutorBackend::Asupersync),
17207        );
17208        let mut program = headless_program_with_config(ShutdownModel { seen: false }, config);
17209
17210        // After shutdown, new submissions are rejected (structured ownership):
17211        // the task never runs, so no message is delivered.
17212        program.task_executor.shutdown();
17213        program
17214            .execute_cmd(Cmd::task(|| ShutdownMsg::Seen))
17215            .expect("post-shutdown task cmd");
17216
17217        let deadline = Instant::now() + Duration::from_millis(200);
17218        while Instant::now() <= deadline {
17219            program
17220                .process_task_results()
17221                .expect("process task results");
17222            program.reap_finished_tasks();
17223        }
17224        assert!(
17225            !program.model().seen,
17226            "a task submitted after shutdown was executed"
17227        );
17228    }
17229
17230    #[test]
17231    fn spawned_executor_enforces_max_queue_depth_and_counts_drops() {
17232        let (result_tx, _result_rx) = mpsc::channel::<u32>();
17233        let (gate_tx, gate_rx) = mpsc::channel::<()>();
17234        let mut executor = SpawnTaskExecutor::new(result_tx, None, 1);
17235
17236        // First task occupies the single in-flight slot until gated.
17237        executor.submit(Box::new(move || {
17238            let _ = gate_rx.recv();
17239            1
17240        }));
17241        assert_eq!(executor.handles.len(), 1);
17242
17243        // Second submit exceeds the bound: shed + counted, no thread spawned.
17244        executor.submit(Box::new(|| 2));
17245        assert_eq!(executor.dropped, 1, "backpressure drop not counted");
17246        assert_eq!(executor.handles.len(), 1, "task spawned past the bound");
17247
17248        // Release the gate; post-shutdown submits are also counted drops.
17249        gate_tx.send(()).expect("release gate");
17250        executor.shutdown();
17251        executor.submit(Box::new(|| 3));
17252        assert_eq!(executor.dropped, 2, "post-shutdown drop not counted");
17253    }
17254
17255    #[cfg(feature = "asupersync-executor")]
17256    #[test]
17257    fn asupersync_backpressure_sheds_excess_in_flight_tasks() {
17258        struct SlowModel {
17259            done: u32,
17260        }
17261        #[derive(Debug)]
17262        enum SlowMsg {
17263            Done,
17264        }
17265        impl From<Event> for SlowMsg {
17266            fn from(_: Event) -> Self {
17267                SlowMsg::Done
17268            }
17269        }
17270        impl Model for SlowModel {
17271            type Message = SlowMsg;
17272            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
17273                match msg {
17274                    SlowMsg::Done => self.done += 1,
17275                }
17276                Cmd::none()
17277            }
17278            fn view(&self, _frame: &mut Frame) {}
17279        }
17280
17281        let evidence_path = temp_evidence_path("asupersync_backpressure");
17282        let sink_config = EvidenceSinkConfig::enabled_file(&evidence_path);
17283        let config = ProgramConfig::default()
17284            .with_evidence_sink(sink_config)
17285            .with_effect_queue(
17286                EffectQueueConfig::default()
17287                    .with_backend(TaskExecutorBackend::Asupersync)
17288                    .with_max_queue_depth(2),
17289            );
17290        let mut program = headless_program_with_config(SlowModel { done: 0 }, config);
17291
17292        // Submit more slow (still in-flight) tasks than the depth cap allows: the
17293        // first two occupy the in-flight slots, the rest are shed by backpressure.
17294        for _ in 0..6 {
17295            program
17296                .execute_cmd(Cmd::task(|| {
17297                    std::thread::sleep(Duration::from_millis(120));
17298                    SlowMsg::Done
17299                }))
17300                .expect("slow task cmd");
17301        }
17302
17303        // Backpressure must have fired with a recorded drop.
17304        let backpressure_line = read_evidence_event(&evidence_path, "task_executor_backpressure");
17305        assert_eq!(backpressure_line["backend"], "asupersync");
17306        assert_eq!(backpressure_line["action"], "drop");
17307
17308        // Drain the accepted tasks so teardown is prompt; no more than the depth
17309        // cap of tasks may complete.
17310        let deadline = Instant::now() + Duration::from_secs(5);
17311        while program.model().done < 2 && Instant::now() <= deadline {
17312            program
17313                .process_task_results()
17314                .expect("process task results");
17315            program.reap_finished_tasks();
17316        }
17317        assert!(
17318            program.model().done <= 2,
17319            "more tasks completed than the in-flight depth cap permits"
17320        );
17321    }
17322
17323    // =========================================================================
17324    // BatchController Tests (bd-4kq0.8.1)
17325    // =========================================================================
17326
17327    #[test]
17328    fn unit_tau_monotone() {
17329        // ฯ„ should decrease (or stay constant) as service time decreases,
17330        // since ฯ„ = E[S] ร— headroom.
17331        let mut bc = BatchController::new();
17332
17333        // High service time โ†’ high ฯ„
17334        bc.observe_service(Duration::from_millis(20));
17335        bc.observe_service(Duration::from_millis(20));
17336        bc.observe_service(Duration::from_millis(20));
17337        let tau_high = bc.tau_s();
17338
17339        // Low service time โ†’ lower ฯ„
17340        for _ in 0..20 {
17341            bc.observe_service(Duration::from_millis(1));
17342        }
17343        let tau_low = bc.tau_s();
17344
17345        assert!(
17346            tau_low <= tau_high,
17347            "ฯ„ should decrease with lower service time: tau_low={tau_low:.6}, tau_high={tau_high:.6}"
17348        );
17349    }
17350
17351    #[test]
17352    fn unit_tau_monotone_lambda() {
17353        // As arrival rate ฮป decreases (longer inter-arrival times),
17354        // ฯ„ should not increase (it's based on service time, not ฮป).
17355        // But ฯ should decrease.
17356        let mut bc = BatchController::new();
17357        let base = Instant::now();
17358
17359        // Fast arrivals (ฮป high)
17360        for i in 0..10 {
17361            bc.observe_arrival(base + Duration::from_millis(i * 10));
17362        }
17363        let rho_fast = bc.rho_est();
17364
17365        // Slow arrivals (ฮป low)
17366        for i in 10..20 {
17367            bc.observe_arrival(base + Duration::from_millis(100 + i * 100));
17368        }
17369        let rho_slow = bc.rho_est();
17370
17371        assert!(
17372            rho_slow < rho_fast,
17373            "ฯ should decrease with slower arrivals: rho_slow={rho_slow:.4}, rho_fast={rho_fast:.4}"
17374        );
17375    }
17376
17377    #[test]
17378    fn unit_stability() {
17379        // With reasonable service times, the controller should keep ฯ < 1.
17380        let mut bc = BatchController::new();
17381        let base = Instant::now();
17382
17383        // Moderate arrival rate: 30 events/sec
17384        for i in 0..30 {
17385            bc.observe_arrival(base + Duration::from_millis(i * 33));
17386            bc.observe_service(Duration::from_millis(5)); // 5ms render
17387        }
17388
17389        assert!(
17390            bc.is_stable(),
17391            "should be stable at 30 events/sec with 5ms service: ฯ={:.4}",
17392            bc.rho_est()
17393        );
17394        assert!(
17395            bc.rho_est() < 1.0,
17396            "utilization should be < 1: ฯ={:.4}",
17397            bc.rho_est()
17398        );
17399
17400        // ฯ„ must be > E[S] (stability requirement)
17401        assert!(
17402            bc.tau_s() > bc.service_est_s(),
17403            "ฯ„ ({:.6}) must exceed E[S] ({:.6}) for stability",
17404            bc.tau_s(),
17405            bc.service_est_s()
17406        );
17407    }
17408
17409    #[test]
17410    fn unit_stability_high_load() {
17411        // Even under high load, ฯ„ keeps the system stable.
17412        let mut bc = BatchController::new();
17413        let base = Instant::now();
17414
17415        // 100 events/sec with 8ms render
17416        for i in 0..50 {
17417            bc.observe_arrival(base + Duration::from_millis(i * 10));
17418            bc.observe_service(Duration::from_millis(8));
17419        }
17420
17421        // ฯ„ ร— ฯ_eff = E[S]/ฯ„ should be < 1
17422        let tau = bc.tau_s();
17423        let rho_eff = bc.service_est_s() / tau;
17424        assert!(
17425            rho_eff < 1.0,
17426            "effective utilization should be < 1: ฯ_eff={rho_eff:.4}, ฯ„={tau:.6}, E[S]={:.6}",
17427            bc.service_est_s()
17428        );
17429    }
17430
17431    #[test]
17432    fn batch_controller_defaults() {
17433        let bc = BatchController::new();
17434        assert!(bc.tau_s() >= bc.tau_min_s);
17435        assert!(bc.tau_s() <= bc.tau_max_s);
17436        assert_eq!(bc.observations(), 0);
17437        assert!(bc.is_stable());
17438    }
17439
17440    #[test]
17441    fn batch_controller_tau_clamped() {
17442        let mut bc = BatchController::new();
17443
17444        // Very fast service โ†’ ฯ„ clamped to tau_min
17445        for _ in 0..20 {
17446            bc.observe_service(Duration::from_micros(10));
17447        }
17448        assert!(
17449            bc.tau_s() >= bc.tau_min_s,
17450            "ฯ„ should be >= tau_min: ฯ„={:.6}, min={:.6}",
17451            bc.tau_s(),
17452            bc.tau_min_s
17453        );
17454
17455        // Very slow service โ†’ ฯ„ clamped to tau_max
17456        for _ in 0..20 {
17457            bc.observe_service(Duration::from_millis(100));
17458        }
17459        assert!(
17460            bc.tau_s() <= bc.tau_max_s,
17461            "ฯ„ should be <= tau_max: ฯ„={:.6}, max={:.6}",
17462            bc.tau_s(),
17463            bc.tau_max_s
17464        );
17465    }
17466
17467    #[test]
17468    fn batch_controller_duration_conversion() {
17469        let bc = BatchController::new();
17470        let tau = bc.tau();
17471        let tau_s = bc.tau_s();
17472        // Duration should match f64 representation
17473        let diff = (tau.as_secs_f64() - tau_s).abs();
17474        assert!(diff < 1e-9, "Duration conversion mismatch: {diff}");
17475    }
17476
17477    #[test]
17478    fn batch_controller_lambda_estimation() {
17479        let mut bc = BatchController::new();
17480        let base = Instant::now();
17481
17482        // 50 events/sec (20ms apart)
17483        for i in 0..20 {
17484            bc.observe_arrival(base + Duration::from_millis(i * 20));
17485        }
17486
17487        // ฮป should converge near 50
17488        let lambda = bc.lambda_est();
17489        assert!(
17490            lambda > 20.0 && lambda < 100.0,
17491            "ฮป should be near 50: got {lambda:.1}"
17492        );
17493    }
17494
17495    // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
17496    // Persistence Config Tests
17497    // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
17498
17499    #[test]
17500    fn cmd_save_state() {
17501        let cmd: Cmd<TestMsg> = Cmd::save_state();
17502        assert!(matches!(cmd, Cmd::SaveState));
17503    }
17504
17505    #[test]
17506    fn cmd_restore_state() {
17507        let cmd: Cmd<TestMsg> = Cmd::restore_state();
17508        assert!(matches!(cmd, Cmd::RestoreState));
17509    }
17510
17511    #[test]
17512    fn persistence_config_default() {
17513        let config = PersistenceConfig::default();
17514        assert!(config.registry.is_none());
17515        assert!(config.checkpoint_interval.is_none());
17516        assert!(config.auto_load);
17517        assert!(config.auto_save);
17518    }
17519
17520    #[test]
17521    fn persistence_config_disabled() {
17522        let config = PersistenceConfig::disabled();
17523        assert!(config.registry.is_none());
17524    }
17525
17526    #[test]
17527    fn persistence_config_with_registry() {
17528        use crate::state_persistence::{MemoryStorage, StateRegistry};
17529        use std::sync::Arc;
17530
17531        let registry = Arc::new(StateRegistry::new(Box::new(MemoryStorage::new())));
17532        let config = PersistenceConfig::with_registry(registry.clone());
17533
17534        assert!(config.registry.is_some());
17535        assert!(config.auto_load);
17536        assert!(config.auto_save);
17537    }
17538
17539    #[test]
17540    fn persistence_config_checkpoint_interval() {
17541        use crate::state_persistence::{MemoryStorage, StateRegistry};
17542        use std::sync::Arc;
17543
17544        let registry = Arc::new(StateRegistry::new(Box::new(MemoryStorage::new())));
17545        let config = PersistenceConfig::with_registry(registry)
17546            .checkpoint_every(Duration::from_secs(30))
17547            .auto_load(false)
17548            .auto_save(true);
17549
17550        assert!(config.checkpoint_interval.is_some());
17551        assert_eq!(config.checkpoint_interval.unwrap(), Duration::from_secs(30));
17552        assert!(!config.auto_load);
17553        assert!(config.auto_save);
17554    }
17555
17556    #[test]
17557    fn program_config_with_persistence() {
17558        use crate::state_persistence::{MemoryStorage, StateRegistry};
17559        use std::sync::Arc;
17560
17561        let registry = Arc::new(StateRegistry::new(Box::new(MemoryStorage::new())));
17562        let config = ProgramConfig::default().with_registry(registry);
17563
17564        assert!(config.persistence.registry.is_some());
17565    }
17566
17567    // =========================================================================
17568    // TaskSpec tests (bd-2yjus)
17569    // =========================================================================
17570
17571    #[test]
17572    fn task_spec_default() {
17573        let spec = TaskSpec::default();
17574        assert_eq!(spec.weight, DEFAULT_TASK_WEIGHT);
17575        assert_eq!(spec.estimate_ms, DEFAULT_TASK_ESTIMATE_MS);
17576        assert!(spec.name.is_none());
17577    }
17578
17579    #[test]
17580    fn task_spec_new() {
17581        let spec = TaskSpec::new(5.0, 20.0);
17582        assert_eq!(spec.weight, 5.0);
17583        assert_eq!(spec.estimate_ms, 20.0);
17584        assert!(spec.name.is_none());
17585    }
17586
17587    #[test]
17588    fn task_spec_with_name() {
17589        let spec = TaskSpec::default().with_name("fetch_data");
17590        assert_eq!(spec.name.as_deref(), Some("fetch_data"));
17591    }
17592
17593    #[test]
17594    fn task_spec_debug() {
17595        let spec = TaskSpec::new(2.0, 15.0).with_name("test");
17596        let debug = format!("{spec:?}");
17597        assert!(debug.contains("2.0"));
17598        assert!(debug.contains("15.0"));
17599        assert!(debug.contains("test"));
17600    }
17601
17602    // =========================================================================
17603    // Cmd::count() tests (bd-2yjus)
17604    // =========================================================================
17605
17606    #[test]
17607    fn cmd_count_none() {
17608        let cmd: Cmd<TestMsg> = Cmd::none();
17609        assert_eq!(cmd.count(), 0);
17610    }
17611
17612    #[test]
17613    fn cmd_count_atomic() {
17614        assert_eq!(Cmd::<TestMsg>::quit().count(), 1);
17615        assert_eq!(Cmd::<TestMsg>::msg(TestMsg::Increment).count(), 1);
17616        assert_eq!(Cmd::<TestMsg>::tick(Duration::from_millis(100)).count(), 1);
17617        assert_eq!(Cmd::<TestMsg>::log("hello").count(), 1);
17618        assert_eq!(Cmd::<TestMsg>::save_state().count(), 1);
17619        assert_eq!(Cmd::<TestMsg>::restore_state().count(), 1);
17620        assert_eq!(Cmd::<TestMsg>::set_mouse_capture(true).count(), 1);
17621    }
17622
17623    #[test]
17624    fn cmd_count_batch() {
17625        let cmd: Cmd<TestMsg> =
17626            Cmd::Batch(vec![Cmd::quit(), Cmd::msg(TestMsg::Increment), Cmd::none()]);
17627        assert_eq!(cmd.count(), 2); // quit + msg, none counts 0
17628    }
17629
17630    #[test]
17631    fn cmd_count_nested() {
17632        let cmd: Cmd<TestMsg> = Cmd::Batch(vec![
17633            Cmd::msg(TestMsg::Increment),
17634            Cmd::Sequence(vec![Cmd::quit(), Cmd::msg(TestMsg::Increment)]),
17635        ]);
17636        assert_eq!(cmd.count(), 3);
17637    }
17638
17639    // =========================================================================
17640    // Cmd::type_name() tests (bd-2yjus)
17641    // =========================================================================
17642
17643    #[test]
17644    fn cmd_type_name_all_variants() {
17645        assert_eq!(Cmd::<TestMsg>::none().type_name(), "None");
17646        assert_eq!(Cmd::<TestMsg>::quit().type_name(), "Quit");
17647        assert_eq!(
17648            Cmd::<TestMsg>::Batch(vec![Cmd::none()]).type_name(),
17649            "Batch"
17650        );
17651        assert_eq!(
17652            Cmd::<TestMsg>::Sequence(vec![Cmd::none()]).type_name(),
17653            "Sequence"
17654        );
17655        assert_eq!(Cmd::<TestMsg>::msg(TestMsg::Increment).type_name(), "Msg");
17656        assert_eq!(
17657            Cmd::<TestMsg>::tick(Duration::from_millis(1)).type_name(),
17658            "Tick"
17659        );
17660        assert_eq!(Cmd::<TestMsg>::log("x").type_name(), "Log");
17661        assert_eq!(
17662            Cmd::<TestMsg>::task(|| TestMsg::Increment).type_name(),
17663            "Task"
17664        );
17665        assert_eq!(Cmd::<TestMsg>::save_state().type_name(), "SaveState");
17666        assert_eq!(Cmd::<TestMsg>::restore_state().type_name(), "RestoreState");
17667        assert_eq!(
17668            Cmd::<TestMsg>::set_mouse_capture(true).type_name(),
17669            "SetMouseCapture"
17670        );
17671    }
17672
17673    // =========================================================================
17674    // Cmd::batch() / Cmd::sequence() edge-case tests (bd-2yjus)
17675    // =========================================================================
17676
17677    #[test]
17678    fn cmd_batch_empty_returns_none() {
17679        let cmd: Cmd<TestMsg> = Cmd::batch(vec![]);
17680        assert!(matches!(cmd, Cmd::None));
17681    }
17682
17683    #[test]
17684    fn cmd_batch_single_unwraps() {
17685        let cmd: Cmd<TestMsg> = Cmd::batch(vec![Cmd::quit()]);
17686        assert!(matches!(cmd, Cmd::Quit));
17687    }
17688
17689    #[test]
17690    fn cmd_batch_multiple_stays_batch() {
17691        let cmd: Cmd<TestMsg> = Cmd::batch(vec![Cmd::quit(), Cmd::msg(TestMsg::Increment)]);
17692        assert!(matches!(cmd, Cmd::Batch(_)));
17693    }
17694
17695    #[test]
17696    fn cmd_sequence_empty_returns_none() {
17697        let cmd: Cmd<TestMsg> = Cmd::sequence(vec![]);
17698        assert!(matches!(cmd, Cmd::None));
17699    }
17700
17701    #[test]
17702    fn cmd_sequence_single_unwraps_to_inner() {
17703        let cmd: Cmd<TestMsg> = Cmd::sequence(vec![Cmd::quit()]);
17704        assert!(matches!(cmd, Cmd::Quit));
17705    }
17706
17707    #[test]
17708    fn cmd_sequence_multiple_stays_sequence() {
17709        let cmd: Cmd<TestMsg> = Cmd::sequence(vec![Cmd::quit(), Cmd::msg(TestMsg::Increment)]);
17710        assert!(matches!(cmd, Cmd::Sequence(_)));
17711    }
17712
17713    // =========================================================================
17714    // Cmd task constructor variants (bd-2yjus)
17715    // =========================================================================
17716
17717    #[test]
17718    fn cmd_task_with_spec() {
17719        let spec = TaskSpec::new(3.0, 25.0).with_name("my_task");
17720        let cmd: Cmd<TestMsg> = Cmd::task_with_spec(spec, || TestMsg::Increment);
17721        match cmd {
17722            Cmd::Task(s, _) => {
17723                assert_eq!(s.weight, 3.0);
17724                assert_eq!(s.estimate_ms, 25.0);
17725                assert_eq!(s.name.as_deref(), Some("my_task"));
17726            }
17727            _ => panic!("expected Task variant"),
17728        }
17729    }
17730
17731    #[test]
17732    fn cmd_task_weighted() {
17733        let cmd: Cmd<TestMsg> = Cmd::task_weighted(2.0, 50.0, || TestMsg::Increment);
17734        match cmd {
17735            Cmd::Task(s, _) => {
17736                assert_eq!(s.weight, 2.0);
17737                assert_eq!(s.estimate_ms, 50.0);
17738                assert!(s.name.is_none());
17739            }
17740            _ => panic!("expected Task variant"),
17741        }
17742    }
17743
17744    #[test]
17745    fn cmd_task_named() {
17746        let cmd: Cmd<TestMsg> = Cmd::task_named("background_fetch", || TestMsg::Increment);
17747        match cmd {
17748            Cmd::Task(s, _) => {
17749                assert_eq!(s.weight, DEFAULT_TASK_WEIGHT);
17750                assert_eq!(s.estimate_ms, DEFAULT_TASK_ESTIMATE_MS);
17751                assert_eq!(s.name.as_deref(), Some("background_fetch"));
17752            }
17753            _ => panic!("expected Task variant"),
17754        }
17755    }
17756
17757    // =========================================================================
17758    // Cmd Debug formatting (bd-2yjus)
17759    // =========================================================================
17760
17761    #[test]
17762    fn cmd_debug_all_variant_strings() {
17763        assert_eq!(format!("{:?}", Cmd::<TestMsg>::none()), "None");
17764        assert_eq!(format!("{:?}", Cmd::<TestMsg>::quit()), "Quit");
17765        assert!(format!("{:?}", Cmd::<TestMsg>::msg(TestMsg::Increment)).starts_with("Msg("));
17766        assert!(
17767            format!("{:?}", Cmd::<TestMsg>::tick(Duration::from_millis(100))).starts_with("Tick(")
17768        );
17769        assert!(format!("{:?}", Cmd::<TestMsg>::log("hi")).starts_with("Log("));
17770        assert!(format!("{:?}", Cmd::<TestMsg>::task(|| TestMsg::Increment)).starts_with("Task"));
17771        assert_eq!(format!("{:?}", Cmd::<TestMsg>::save_state()), "SaveState");
17772        assert_eq!(
17773            format!("{:?}", Cmd::<TestMsg>::restore_state()),
17774            "RestoreState"
17775        );
17776        assert_eq!(
17777            format!("{:?}", Cmd::<TestMsg>::set_mouse_capture(true)),
17778            "SetMouseCapture(true)"
17779        );
17780    }
17781
17782    // =========================================================================
17783    // Cmd::set_mouse_capture headless execution (bd-2yjus)
17784    // =========================================================================
17785
17786    #[test]
17787    fn headless_execute_cmd_set_mouse_capture() {
17788        let mut program =
17789            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
17790        assert!(!program.backend_features.mouse_capture);
17791
17792        program
17793            .execute_cmd(Cmd::set_mouse_capture(true))
17794            .expect("set mouse capture true");
17795        assert!(program.backend_features.mouse_capture);
17796
17797        program
17798            .execute_cmd(Cmd::set_mouse_capture(false))
17799            .expect("set mouse capture false");
17800        assert!(!program.backend_features.mouse_capture);
17801    }
17802
17803    #[test]
17804    fn clipboard_commands_reach_writer_and_reply_reaches_model_once() {
17805        use ftui_core::event::{ClipboardEvent, ClipboardSource};
17806
17807        #[derive(Default)]
17808        struct ClipboardModel(Vec<String>);
17809        impl Model for ClipboardModel {
17810            type Message = Event;
17811            fn update(&mut self, event: Event) -> Cmd<Event> {
17812                match event {
17813                    Event::Tick => {
17814                        Cmd::sequence(vec![Cmd::set_clipboard("hi"), Cmd::get_clipboard()])
17815                    }
17816                    Event::Clipboard(reply) => {
17817                        self.0.push(reply.content);
17818                        Cmd::none()
17819                    }
17820                    _ => Cmd::none(),
17821                }
17822            }
17823            fn view(&self, _: &mut Frame) {}
17824        }
17825
17826        let mut program =
17827            headless_program_with_config(ClipboardModel::default(), ProgramConfig::default());
17828        let mut caps = TerminalCapabilities::basic();
17829        caps.osc52_clipboard = true;
17830        program.presenter = TerminalPresenter::new(TerminalWriter::new(
17831            Vec::new(),
17832            ScreenMode::AltScreen,
17833            UiAnchor::Bottom,
17834            caps,
17835        ));
17836        program.handle_event(Event::Tick).unwrap();
17837        assert!(
17838            program.model.0.is_empty(),
17839            "a query must not synthesize a reply"
17840        );
17841        program
17842            .handle_event(Event::Clipboard(ClipboardEvent::new(
17843                "hi",
17844                ClipboardSource::Osc52,
17845            )))
17846            .unwrap();
17847        assert_eq!(program.model.0, ["hi"]);
17848        let bytes = program.presenter.into_inner().unwrap();
17849        assert!(bytes.starts_with(b"\x1b]52;c;aGk=\x07\x1b]52;c;?\x07"));
17850        assert_eq!(Cmd::<()>::set_clipboard("hi").type_name(), "SetClipboard");
17851        assert_eq!(Cmd::<()>::get_clipboard().type_name(), "GetClipboard");
17852        assert!(
17853            !format!("{:?}", Cmd::<()>::set_clipboard("secret payload")).contains("secret payload")
17854        );
17855    }
17856
17857    #[test]
17858    fn clipboard_flushes_with_frame_or_without_a_future_frame() {
17859        #[derive(Clone, Default)]
17860        struct Capture(std::sync::Arc<std::sync::Mutex<(Vec<u8>, usize)>>);
17861        impl Write for Capture {
17862            fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
17863                let mut state = self.0.lock().unwrap();
17864                state.0.extend_from_slice(bytes);
17865                state.1 += 1;
17866                Ok(bytes.len())
17867            }
17868            fn flush(&mut self) -> io::Result<()> {
17869                Ok(())
17870            }
17871        }
17872        let capture = Capture::default();
17873        let mut caps = TerminalCapabilities::basic();
17874        caps.osc52_clipboard = true;
17875        let writer = TerminalWriter::new(
17876            capture.clone(),
17877            ScreenMode::AltScreen,
17878            UiAnchor::Bottom,
17879            caps,
17880        );
17881        let mut program = Program::with_event_source(
17882            TestModel { value: 0 },
17883            HeadlessEventSource::new(10, 3, BackendFeatures::default()),
17884            BackendFeatures::default(),
17885            TerminalPresenter::new(writer),
17886            ProgramConfig::default(),
17887        )
17888        .unwrap();
17889        program.dirty = true;
17890        program.execute_cmd(Cmd::set_clipboard("hi")).unwrap();
17891        program.execute_cmd(Cmd::get_clipboard()).unwrap();
17892        assert_eq!(capture.0.lock().unwrap().1, 0);
17893        program.render_frame().unwrap();
17894        {
17895            let state = capture.0.lock().unwrap();
17896            assert_eq!(state.1, 1, "controls and frame share the buffered write");
17897            assert!(state.0.starts_with(b"\x1b]52;c;aGk=\x07\x1b]52;c;?\x07"));
17898        }
17899        program.dirty = false;
17900        program.execute_cmd(Cmd::get_clipboard()).unwrap();
17901        assert_eq!(
17902            capture.0.lock().unwrap().1,
17903            2,
17904            "no frame: flush immediately"
17905        );
17906        program.dirty = true;
17907        program.execute_cmd(Cmd::set_clipboard("quit")).unwrap();
17908        program.execute_cmd(Cmd::quit()).unwrap();
17909        assert!(
17910            capture
17911                .0
17912                .lock()
17913                .unwrap()
17914                .0
17915                .ends_with(b"\x1b]52;c;cXVpdA==\x07")
17916        );
17917        program
17918            .execute_lifecycle_cmd(Cmd::set_clipboard("bye"))
17919            .unwrap();
17920        assert!(capture.0.lock().unwrap().0.ends_with(b"\x1b]52;c;Ynll\x07"));
17921        assert!(!program.running);
17922    }
17923
17924    // =========================================================================
17925    // ResizeBehavior tests (bd-2yjus)
17926    // =========================================================================
17927
17928    #[test]
17929    fn resize_behavior_uses_coalescer() {
17930        assert!(ResizeBehavior::Throttled.uses_coalescer());
17931        assert!(!ResizeBehavior::Immediate.uses_coalescer());
17932    }
17933
17934    #[test]
17935    fn resize_behavior_eq_and_debug() {
17936        assert_eq!(ResizeBehavior::Immediate, ResizeBehavior::Immediate);
17937        assert_ne!(ResizeBehavior::Immediate, ResizeBehavior::Throttled);
17938        let debug = format!("{:?}", ResizeBehavior::Throttled);
17939        assert_eq!(debug, "Throttled");
17940    }
17941
17942    // =========================================================================
17943    // WidgetRefreshConfig default values (bd-2yjus)
17944    // =========================================================================
17945
17946    #[test]
17947    fn widget_refresh_config_defaults() {
17948        let config = WidgetRefreshConfig::default();
17949        assert!(config.enabled);
17950        assert_eq!(config.staleness_window_ms, 1_000);
17951        assert_eq!(config.starve_ms, 3_000);
17952        assert_eq!(config.max_starved_per_frame, 2);
17953        assert_eq!(config.max_drop_fraction, 1.0);
17954        assert_eq!(config.weight_priority, 1.0);
17955        assert_eq!(config.weight_staleness, 0.5);
17956        assert_eq!(config.weight_focus, 0.75);
17957        assert_eq!(config.weight_interaction, 0.5);
17958        assert_eq!(config.starve_boost, 1.5);
17959        assert_eq!(config.min_cost_us, 1.0);
17960    }
17961
17962    // =========================================================================
17963    // EffectQueueConfig tests (bd-2yjus)
17964    // =========================================================================
17965
17966    #[test]
17967    fn effect_queue_config_default() {
17968        let config = EffectQueueConfig::default();
17969        assert!(!config.enabled);
17970        assert_eq!(config.backend, TaskExecutorBackend::Spawned);
17971        assert!(!config.explicit_backend);
17972        assert!(config.scheduler.smith_enabled);
17973        assert!(!config.scheduler.force_fifo);
17974        assert!(!config.scheduler.preemptive);
17975    }
17976
17977    #[test]
17978    fn effect_queue_config_with_enabled() {
17979        let config = EffectQueueConfig::default().with_enabled(true);
17980        assert!(config.enabled);
17981        assert_eq!(config.backend, TaskExecutorBackend::EffectQueue);
17982        assert!(config.explicit_backend);
17983    }
17984
17985    #[test]
17986    fn effect_queue_config_with_enabled_false_marks_explicit_spawned_backend() {
17987        let config = EffectQueueConfig::default().with_enabled(false);
17988        assert!(!config.enabled);
17989        assert_eq!(config.backend, TaskExecutorBackend::Spawned);
17990        assert!(config.explicit_backend);
17991    }
17992
17993    #[test]
17994    fn effect_queue_config_with_backend() {
17995        let config = EffectQueueConfig::default().with_backend(TaskExecutorBackend::EffectQueue);
17996        assert!(config.enabled);
17997        assert_eq!(config.backend, TaskExecutorBackend::EffectQueue);
17998        assert!(config.explicit_backend);
17999    }
18000
18001    #[cfg(feature = "asupersync-executor")]
18002    #[test]
18003    fn effect_queue_config_with_asupersync_backend_disables_effect_queue_flag() {
18004        let config = EffectQueueConfig::default().with_backend(TaskExecutorBackend::Asupersync);
18005        assert!(!config.enabled);
18006        assert_eq!(config.backend, TaskExecutorBackend::Asupersync);
18007    }
18008
18009    #[test]
18010    fn effect_queue_config_with_scheduler() {
18011        let sched = SchedulerConfig {
18012            force_fifo: true,
18013            ..Default::default()
18014        };
18015        let config = EffectQueueConfig::default().with_scheduler(sched);
18016        assert!(config.scheduler.force_fifo);
18017    }
18018
18019    // =========================================================================
18020    // InlineAutoRemeasureConfig defaults (bd-2yjus)
18021    // =========================================================================
18022
18023    #[test]
18024    fn inline_auto_remeasure_config_defaults() {
18025        let config = InlineAutoRemeasureConfig::default();
18026        assert_eq!(config.change_threshold_rows, 1);
18027        assert_eq!(config.voi.prior_alpha, 1.0);
18028        assert_eq!(config.voi.prior_beta, 9.0);
18029        assert_eq!(config.voi.max_interval_ms, 1000);
18030        assert_eq!(config.voi.min_interval_ms, 100);
18031        assert_eq!(config.voi.sample_cost, 0.08);
18032    }
18033
18034    // =========================================================================
18035    // HeadlessEventSource direct tests (bd-2yjus)
18036    // =========================================================================
18037
18038    #[test]
18039    fn headless_event_source_size() {
18040        let source = HeadlessEventSource::new(120, 40, BackendFeatures::default());
18041        assert_eq!(source.size().unwrap(), (120, 40));
18042    }
18043
18044    #[test]
18045    fn headless_event_source_poll_always_false() {
18046        let mut source = HeadlessEventSource::new(80, 24, BackendFeatures::default());
18047        assert!(!source.poll_event(Duration::from_millis(100)).unwrap());
18048    }
18049
18050    #[test]
18051    fn headless_event_source_read_always_none() {
18052        let mut source = HeadlessEventSource::new(80, 24, BackendFeatures::default());
18053        assert!(source.read_event().unwrap().is_none());
18054    }
18055
18056    #[test]
18057    fn headless_event_source_set_features() {
18058        let mut source = HeadlessEventSource::new(80, 24, BackendFeatures::default());
18059        let features = BackendFeatures {
18060            mouse_capture: true,
18061            bracketed_paste: true,
18062            focus_events: true,
18063            kitty_keyboard: true,
18064        };
18065        source.set_features(features).unwrap();
18066        assert_eq!(source.features, features);
18067    }
18068
18069    #[test]
18070    fn immediate_drain_budget_adds_backoff_poll_under_burst() {
18071        use ftui_core::event::{KeyCode, KeyEvent};
18072
18073        struct DrainBurstModel {
18074            processed: usize,
18075            quit_after: usize,
18076        }
18077
18078        #[derive(Debug)]
18079        #[allow(dead_code)]
18080        enum DrainBurstMsg {
18081            Event(Event),
18082        }
18083
18084        impl From<Event> for DrainBurstMsg {
18085            fn from(event: Event) -> Self {
18086                DrainBurstMsg::Event(event)
18087            }
18088        }
18089
18090        impl Model for DrainBurstModel {
18091            type Message = DrainBurstMsg;
18092
18093            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
18094                match msg {
18095                    DrainBurstMsg::Event(_) => {
18096                        self.processed = self.processed.saturating_add(1);
18097                        if self.processed >= self.quit_after {
18098                            Cmd::quit()
18099                        } else {
18100                            Cmd::none()
18101                        }
18102                    }
18103                }
18104            }
18105
18106            fn view(&self, _frame: &mut Frame) {}
18107        }
18108
18109        struct DrainBurstEventSource {
18110            queue: VecDeque<Event>,
18111            poll_timeouts: Arc<std::sync::Mutex<Vec<Duration>>>,
18112            size: (u16, u16),
18113        }
18114
18115        impl BackendEventSource for DrainBurstEventSource {
18116            type Error = io::Error;
18117
18118            fn size(&self) -> Result<(u16, u16), Self::Error> {
18119                Ok(self.size)
18120            }
18121
18122            fn set_features(&mut self, _features: BackendFeatures) -> Result<(), Self::Error> {
18123                Ok(())
18124            }
18125
18126            fn poll_event(&mut self, timeout: Duration) -> Result<bool, Self::Error> {
18127                self.poll_timeouts.lock().unwrap().push(timeout);
18128                Ok(!self.queue.is_empty())
18129            }
18130
18131            fn read_event(&mut self) -> Result<Option<Event>, Self::Error> {
18132                Ok(self.queue.pop_front())
18133            }
18134        }
18135
18136        let burst_events = 24usize;
18137        let poll_timeouts = Arc::new(std::sync::Mutex::new(Vec::new()));
18138        let mut queue = VecDeque::new();
18139        for _ in 0..burst_events {
18140            queue.push_back(Event::Key(KeyEvent::new(KeyCode::Char('x'))));
18141        }
18142
18143        let events = DrainBurstEventSource {
18144            queue,
18145            poll_timeouts: poll_timeouts.clone(),
18146            size: (80, 24),
18147        };
18148        let writer = TerminalWriter::new(
18149            Vec::<u8>::new(),
18150            ScreenMode::AltScreen,
18151            UiAnchor::Bottom,
18152            TerminalCapabilities::dumb(),
18153        );
18154        let config = ProgramConfig::default()
18155            .with_forced_size(80, 24)
18156            .with_signal_interception(false)
18157            .with_immediate_drain(ImmediateDrainConfig {
18158                max_zero_timeout_polls_per_burst: 3,
18159                max_burst_duration: Duration::from_secs(1),
18160                backoff_timeout: Duration::from_millis(1),
18161            });
18162
18163        let model = DrainBurstModel {
18164            processed: 0,
18165            quit_after: burst_events,
18166        };
18167        let mut program = Program::with_event_source(
18168            model,
18169            events,
18170            BackendFeatures::default(),
18171            TerminalPresenter::new(writer),
18172            config,
18173        )
18174        .expect("program creation");
18175        program.run().expect("run burst");
18176
18177        assert_eq!(program.model().processed, burst_events);
18178
18179        let stats = program.immediate_drain_stats();
18180        assert_eq!(stats.bursts, 1);
18181        assert!(stats.capped_bursts >= 1);
18182        assert!(stats.backoff_polls >= 1);
18183        assert!(stats.zero_timeout_polls >= 1);
18184        assert!(stats.max_zero_timeout_polls_in_burst <= 3);
18185
18186        let timeouts = poll_timeouts.lock().unwrap();
18187        assert!(timeouts.contains(&Duration::ZERO));
18188        assert!(timeouts.contains(&Duration::from_millis(1)));
18189    }
18190
18191    /// Regression test for frankentui#95: an event source that reports poll
18192    /// readiness but yields no event from `read_event` (spurious readiness,
18193    /// as the Windows console can produce) must not stall or busy-spin the
18194    /// event loop. The runtime must treat `read_event() == Ok(None)` as
18195    /// "nothing decodable", finish the drain burst via its bounded
18196    /// zero-timeout polls, and return to the timed outer poll so ticks and
18197    /// queued messages keep flowing.
18198    #[test]
18199    fn spurious_poll_readiness_does_not_stall_event_loop() {
18200        struct SpuriousModel {
18201            ticks: usize,
18202            quit_after: usize,
18203        }
18204
18205        #[derive(Debug)]
18206        enum SpuriousMsg {
18207            Tick,
18208            Other,
18209        }
18210
18211        impl From<Event> for SpuriousMsg {
18212            fn from(event: Event) -> Self {
18213                match event {
18214                    Event::Tick => SpuriousMsg::Tick,
18215                    _ => SpuriousMsg::Other,
18216                }
18217            }
18218        }
18219
18220        impl Model for SpuriousModel {
18221            type Message = SpuriousMsg;
18222
18223            fn init(&mut self) -> Cmd<Self::Message> {
18224                Cmd::tick(Duration::from_millis(1))
18225            }
18226
18227            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
18228                match msg {
18229                    SpuriousMsg::Tick => {
18230                        self.ticks = self.ticks.saturating_add(1);
18231                        if self.ticks >= self.quit_after {
18232                            Cmd::quit()
18233                        } else {
18234                            Cmd::none()
18235                        }
18236                    }
18237                    SpuriousMsg::Other => Cmd::none(),
18238                }
18239            }
18240
18241            fn view(&self, _frame: &mut Frame) {}
18242        }
18243
18244        struct SpuriousReadySource {
18245            spurious_polls_remaining: usize,
18246            read_calls: Arc<std::sync::atomic::AtomicUsize>,
18247        }
18248
18249        impl BackendEventSource for SpuriousReadySource {
18250            type Error = io::Error;
18251
18252            fn size(&self) -> Result<(u16, u16), Self::Error> {
18253                Ok((80, 24))
18254            }
18255
18256            fn set_features(&mut self, _features: BackendFeatures) -> Result<(), Self::Error> {
18257                Ok(())
18258            }
18259
18260            fn poll_event(&mut self, _timeout: Duration) -> Result<bool, Self::Error> {
18261                if self.spurious_polls_remaining > 0 {
18262                    self.spurious_polls_remaining -= 1;
18263                    Ok(true)
18264                } else {
18265                    Ok(false)
18266                }
18267            }
18268
18269            fn read_event(&mut self) -> Result<Option<Event>, Self::Error> {
18270                // Readiness was spurious: nothing decodable is ever produced.
18271                self.read_calls
18272                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
18273                Ok(None)
18274            }
18275        }
18276
18277        let spurious_polls = 5usize;
18278        let read_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
18279        let events = SpuriousReadySource {
18280            spurious_polls_remaining: spurious_polls,
18281            read_calls: read_calls.clone(),
18282        };
18283        let writer = TerminalWriter::new(
18284            Vec::<u8>::new(),
18285            ScreenMode::AltScreen,
18286            UiAnchor::Bottom,
18287            TerminalCapabilities::dumb(),
18288        );
18289        let config = ProgramConfig::default()
18290            .with_forced_size(80, 24)
18291            .with_signal_interception(false);
18292
18293        let model = SpuriousModel {
18294            ticks: 0,
18295            quit_after: 3,
18296        };
18297        let mut program = Program::with_event_source(
18298            model,
18299            events,
18300            BackendFeatures::default(),
18301            TerminalPresenter::new(writer),
18302            config,
18303        )
18304        .expect("program creation");
18305        // If spurious readiness parked the loop (the frankentui#95 failure
18306        // mode with a blocking read), this would hang instead of returning.
18307        program.run().expect("run with spurious readiness");
18308
18309        assert_eq!(program.model().ticks, 3, "ticks must keep flowing");
18310        // Every `true` poll is followed by exactly one read attempt; a
18311        // spurious-ready source must produce a bounded number of empty reads,
18312        // not an unbounded spin.
18313        assert_eq!(
18314            read_calls.load(std::sync::atomic::Ordering::Relaxed),
18315            spurious_polls
18316        );
18317    }
18318
18319    #[test]
18320    fn immediate_drain_zero_poll_limit_is_clamped() {
18321        use ftui_core::event::{KeyCode, KeyEvent};
18322
18323        struct ClampModel {
18324            processed: usize,
18325            quit_after: usize,
18326        }
18327
18328        #[derive(Debug)]
18329        #[allow(dead_code)]
18330        enum ClampMsg {
18331            Event(Event),
18332        }
18333
18334        impl From<Event> for ClampMsg {
18335            fn from(event: Event) -> Self {
18336                ClampMsg::Event(event)
18337            }
18338        }
18339
18340        impl Model for ClampModel {
18341            type Message = ClampMsg;
18342
18343            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
18344                match msg {
18345                    ClampMsg::Event(_) => {
18346                        self.processed = self.processed.saturating_add(1);
18347                        if self.processed >= self.quit_after {
18348                            Cmd::quit()
18349                        } else {
18350                            Cmd::none()
18351                        }
18352                    }
18353                }
18354            }
18355
18356            fn view(&self, _frame: &mut Frame) {}
18357        }
18358
18359        struct ClampSource {
18360            queue: VecDeque<Event>,
18361        }
18362
18363        impl BackendEventSource for ClampSource {
18364            type Error = io::Error;
18365
18366            fn size(&self) -> Result<(u16, u16), Self::Error> {
18367                Ok((80, 24))
18368            }
18369
18370            fn set_features(&mut self, _features: BackendFeatures) -> Result<(), Self::Error> {
18371                Ok(())
18372            }
18373
18374            fn poll_event(&mut self, _timeout: Duration) -> Result<bool, Self::Error> {
18375                Ok(!self.queue.is_empty())
18376            }
18377
18378            fn read_event(&mut self) -> Result<Option<Event>, Self::Error> {
18379                Ok(self.queue.pop_front())
18380            }
18381        }
18382
18383        let burst_events = 8usize;
18384        let mut queue = VecDeque::new();
18385        for _ in 0..burst_events {
18386            queue.push_back(Event::Key(KeyEvent::new(KeyCode::Char('z'))));
18387        }
18388        let events = ClampSource { queue };
18389
18390        let writer = TerminalWriter::new(
18391            Vec::<u8>::new(),
18392            ScreenMode::AltScreen,
18393            UiAnchor::Bottom,
18394            TerminalCapabilities::dumb(),
18395        );
18396        let config = ProgramConfig::default()
18397            .with_forced_size(80, 24)
18398            .with_signal_interception(false)
18399            .with_immediate_drain(ImmediateDrainConfig {
18400                max_zero_timeout_polls_per_burst: 0,
18401                max_burst_duration: Duration::from_secs(1),
18402                backoff_timeout: Duration::from_millis(1),
18403            });
18404        let model = ClampModel {
18405            processed: 0,
18406            quit_after: burst_events,
18407        };
18408
18409        let mut program = Program::with_event_source(
18410            model,
18411            events,
18412            BackendFeatures::default(),
18413            TerminalPresenter::new(writer),
18414            config,
18415        )
18416        .expect("program creation");
18417        program.run().expect("run clamp");
18418
18419        let stats = program.immediate_drain_stats();
18420        assert!(stats.max_zero_timeout_polls_in_burst <= 1);
18421    }
18422
18423    #[test]
18424    fn quit_stops_draining_remaining_burst_events() {
18425        use ftui_core::event::{KeyCode, KeyEvent};
18426
18427        struct QuitBurstModel {
18428            processed: usize,
18429            quit_after: usize,
18430        }
18431
18432        #[derive(Debug)]
18433        #[allow(dead_code)]
18434        enum QuitBurstMsg {
18435            Event(Event),
18436        }
18437
18438        impl From<Event> for QuitBurstMsg {
18439            fn from(event: Event) -> Self {
18440                Self::Event(event)
18441            }
18442        }
18443
18444        impl Model for QuitBurstModel {
18445            type Message = QuitBurstMsg;
18446
18447            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
18448                match msg {
18449                    QuitBurstMsg::Event(_) => {
18450                        self.processed = self.processed.saturating_add(1);
18451                        if self.processed >= self.quit_after {
18452                            Cmd::quit()
18453                        } else {
18454                            Cmd::none()
18455                        }
18456                    }
18457                }
18458            }
18459
18460            fn view(&self, _frame: &mut Frame) {}
18461        }
18462
18463        struct QuitBurstSource {
18464            queue: VecDeque<Event>,
18465        }
18466
18467        impl BackendEventSource for QuitBurstSource {
18468            type Error = io::Error;
18469
18470            fn size(&self) -> Result<(u16, u16), Self::Error> {
18471                Ok((80, 24))
18472            }
18473
18474            fn set_features(&mut self, _features: BackendFeatures) -> Result<(), Self::Error> {
18475                Ok(())
18476            }
18477
18478            fn poll_event(&mut self, _timeout: Duration) -> Result<bool, Self::Error> {
18479                Ok(!self.queue.is_empty())
18480            }
18481
18482            fn read_event(&mut self) -> Result<Option<Event>, Self::Error> {
18483                Ok(self.queue.pop_front())
18484            }
18485        }
18486
18487        let total_events = 8usize;
18488        let quit_after = 3usize;
18489        let mut queue = VecDeque::new();
18490        for _ in 0..total_events {
18491            queue.push_back(Event::Key(KeyEvent::new(KeyCode::Char('q'))));
18492        }
18493
18494        let writer = TerminalWriter::new(
18495            Vec::<u8>::new(),
18496            ScreenMode::AltScreen,
18497            UiAnchor::Bottom,
18498            TerminalCapabilities::dumb(),
18499        );
18500        let config = ProgramConfig::default()
18501            .with_forced_size(80, 24)
18502            .with_signal_interception(false)
18503            .with_immediate_drain(ImmediateDrainConfig {
18504                max_zero_timeout_polls_per_burst: 64,
18505                max_burst_duration: Duration::from_secs(1),
18506                backoff_timeout: Duration::from_millis(1),
18507            });
18508        let model = QuitBurstModel {
18509            processed: 0,
18510            quit_after,
18511        };
18512        let events = QuitBurstSource { queue };
18513
18514        let mut program = Program::with_event_source(
18515            model,
18516            events,
18517            BackendFeatures::default(),
18518            TerminalPresenter::new(writer),
18519            config,
18520        )
18521        .expect("program creation");
18522        program.run().expect("run burst quit");
18523
18524        assert_eq!(program.model().processed, quit_after);
18525    }
18526
18527    // =========================================================================
18528    // Program helper methods (bd-2yjus)
18529    // =========================================================================
18530
18531    #[test]
18532    fn headless_program_quit_and_is_running() {
18533        let mut program =
18534            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
18535        assert!(program.is_running());
18536
18537        program.quit();
18538        assert!(!program.is_running());
18539    }
18540
18541    #[test]
18542    fn headless_program_model_mut() {
18543        let mut program =
18544            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
18545        assert_eq!(program.model().value, 0);
18546
18547        program.model_mut().value = 42;
18548        assert_eq!(program.model().value, 42);
18549    }
18550
18551    #[test]
18552    fn headless_program_request_redraw() {
18553        let mut program =
18554            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
18555        program.dirty = false;
18556
18557        program.request_redraw();
18558        assert!(program.dirty);
18559    }
18560
18561    #[test]
18562    fn headless_program_last_widget_signals_initially_empty() {
18563        let program =
18564            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
18565        assert!(program.last_widget_signals().is_empty());
18566    }
18567
18568    #[test]
18569    fn headless_program_no_persistence_by_default() {
18570        let program =
18571            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
18572        assert!(!program.has_persistence());
18573        assert!(program.state_registry().is_none());
18574    }
18575
18576    // =========================================================================
18577    // classify_event_for_fairness (bd-2yjus)
18578    // =========================================================================
18579
18580    #[test]
18581    fn classify_event_fairness_key_is_input() {
18582        let event = Event::Key(ftui_core::event::KeyEvent::new(
18583            ftui_core::event::KeyCode::Char('a'),
18584        ));
18585        let classification = DefaultProgram::<TestModel>::classify_event_for_fairness(&event);
18586        assert_eq!(classification, FairnessEventType::Input);
18587    }
18588
18589    #[test]
18590    fn classify_event_fairness_resize_is_resize() {
18591        let event = Event::Resize {
18592            width: 80,
18593            height: 24,
18594        };
18595        let classification = DefaultProgram::<TestModel>::classify_event_for_fairness(&event);
18596        assert_eq!(classification, FairnessEventType::Resize);
18597    }
18598
18599    #[test]
18600    fn classify_event_fairness_tick_is_tick() {
18601        let event = Event::Tick;
18602        let classification = DefaultProgram::<TestModel>::classify_event_for_fairness(&event);
18603        assert_eq!(classification, FairnessEventType::Tick);
18604    }
18605
18606    #[test]
18607    fn classify_event_fairness_paste_is_input() {
18608        let event = Event::Paste(ftui_core::event::PasteEvent::bracketed("hello"));
18609        let classification = DefaultProgram::<TestModel>::classify_event_for_fairness(&event);
18610        assert_eq!(classification, FairnessEventType::Input);
18611    }
18612
18613    #[test]
18614    fn classify_event_fairness_focus_is_input() {
18615        let event = Event::Focus(true);
18616        let classification = DefaultProgram::<TestModel>::classify_event_for_fairness(&event);
18617        assert_eq!(classification, FairnessEventType::Input);
18618    }
18619
18620    // =========================================================================
18621    // ProgramConfig builder methods (bd-2yjus)
18622    // =========================================================================
18623
18624    #[test]
18625    fn program_config_with_diff_config() {
18626        let diff = RuntimeDiffConfig::default();
18627        let config = ProgramConfig::default().with_diff_config(diff.clone());
18628        // Just verify it doesn't panic and the field is set
18629        let _ = format!("{:?}", config);
18630    }
18631
18632    #[test]
18633    fn program_config_with_evidence_sink() {
18634        let config =
18635            ProgramConfig::default().with_evidence_sink(EvidenceSinkConfig::enabled_stdout());
18636        let _ = format!("{:?}", config);
18637    }
18638
18639    #[test]
18640    fn program_config_with_render_trace() {
18641        let config = ProgramConfig::default().with_render_trace(RenderTraceConfig::default());
18642        let _ = format!("{:?}", config);
18643    }
18644
18645    #[test]
18646    fn program_config_with_locale() {
18647        let config = ProgramConfig::default().with_locale("fr");
18648        let _ = format!("{:?}", config);
18649    }
18650
18651    #[test]
18652    fn program_config_with_locale_context() {
18653        let config = ProgramConfig::default().with_locale_context(LocaleContext::new("de"));
18654        let _ = format!("{:?}", config);
18655    }
18656
18657    #[test]
18658    fn program_config_without_forced_size() {
18659        let config = ProgramConfig::default()
18660            .with_forced_size(80, 24)
18661            .without_forced_size();
18662        assert!(config.forced_size.is_none());
18663    }
18664
18665    #[test]
18666    fn program_config_forced_size_clamps_min() {
18667        let config = ProgramConfig::default().with_forced_size(0, 0);
18668        assert_eq!(config.forced_size, Some((1, 1)));
18669    }
18670
18671    #[test]
18672    fn program_config_with_widget_refresh() {
18673        let wrc = WidgetRefreshConfig {
18674            enabled: false,
18675            ..Default::default()
18676        };
18677        let config = ProgramConfig::default().with_widget_refresh(wrc);
18678        assert!(!config.widget_refresh.enabled);
18679    }
18680
18681    #[test]
18682    fn program_config_with_effect_queue() {
18683        let eqc = EffectQueueConfig::default().with_enabled(true);
18684        let config = ProgramConfig::default().with_effect_queue(eqc);
18685        assert!(config.effect_queue.enabled);
18686        assert_eq!(
18687            config.effect_queue.backend,
18688            TaskExecutorBackend::EffectQueue
18689        );
18690    }
18691
18692    #[test]
18693    fn program_config_with_resize_coalescer_custom() {
18694        let cc = CoalescerConfig {
18695            steady_delay_ms: 42,
18696            ..Default::default()
18697        };
18698        let config = ProgramConfig::default().with_resize_coalescer(cc);
18699        assert_eq!(config.resize_coalescer.steady_delay_ms, 42);
18700    }
18701
18702    #[test]
18703    fn program_config_with_inline_auto_remeasure() {
18704        let config = ProgramConfig::default()
18705            .with_inline_auto_remeasure(InlineAutoRemeasureConfig::default());
18706        assert!(config.inline_auto_remeasure.is_some());
18707
18708        let config = config.without_inline_auto_remeasure();
18709        assert!(config.inline_auto_remeasure.is_none());
18710    }
18711
18712    #[test]
18713    fn program_config_with_persistence_full() {
18714        let pc = PersistenceConfig::disabled();
18715        let config = ProgramConfig::default().with_persistence(pc);
18716        assert!(config.persistence.registry.is_none());
18717    }
18718
18719    #[test]
18720    fn program_config_with_conformal_config() {
18721        let config = ProgramConfig::default()
18722            .with_conformal_config(ConformalConfig::default())
18723            .without_conformal();
18724        assert!(config.conformal_config.is_none());
18725    }
18726
18727    // =========================================================================
18728    // Rollout config builder methods (bd-2crbt)
18729    // =========================================================================
18730
18731    #[test]
18732    fn program_config_with_lane() {
18733        let config = ProgramConfig::default().with_lane(RuntimeLane::Asupersync);
18734        assert_eq!(config.runtime_lane, RuntimeLane::Asupersync);
18735    }
18736
18737    #[test]
18738    fn program_config_default_lane_resolves_to_spawned_backend() {
18739        // Input-lag regression fix (#78): the default Structured lane now
18740        // resolves to per-task `Spawned` execution instead of the single-worker
18741        // `EffectQueue`. Structured cancellation is independent of the task
18742        // executor backend, so the lane no longer serializes `Cmd::Task` through
18743        // one `effect_queue_loop` worker (which caused per-keystroke head-of-line
18744        // latency for PTY-forwarding apps). `enabled` is the legacy convenience
18745        // flag mirroring the backend, so it is now false for the default lane.
18746        let config = ProgramConfig::default();
18747        let resolved = config.resolved_effect_queue_config(config.runtime_lane.resolve());
18748        assert!(!resolved.enabled);
18749        assert_eq!(resolved.backend, TaskExecutorBackend::Spawned);
18750    }
18751
18752    #[test]
18753    fn program_config_legacy_lane_resolves_to_spawned_backend() {
18754        let resolved = ProgramConfig::default()
18755            .with_lane(RuntimeLane::Legacy)
18756            .resolved_effect_queue_config(RuntimeLane::Legacy);
18757        assert!(!resolved.enabled);
18758        assert_eq!(resolved.backend, TaskExecutorBackend::Spawned);
18759    }
18760
18761    #[cfg(not(feature = "asupersync-executor"))]
18762    #[test]
18763    fn asupersync_lane_falls_back_to_structured_without_feature() {
18764        use tracing_subscriber::prelude::*;
18765
18766        let capture = A11yTraceCapture::default();
18767        let subscriber = tracing_subscriber::registry().with(capture.clone().with_filter(
18768            tracing_subscriber::filter::filter_fn(|metadata| {
18769                *metadata.level() == tracing::Level::WARN
18770                    && metadata.target() == crate::telemetry_schema::TARGET_RUNTIME
18771            }),
18772        ));
18773        tracing::subscriber::with_default(subscriber, || {
18774            assert_eq!(RuntimeLane::Asupersync.resolve(), RuntimeLane::Structured);
18775        });
18776        let warning = capture.0.lock().expect("capture lock");
18777        assert_eq!(warning.lines().count(), 1, "{warning}");
18778        assert!(warning.contains("missing_feature=\"asupersync-executor\""));
18779        assert!(warning.contains("requested=\"asupersync\""));
18780        assert!(warning.contains("resolved=\"structured\""));
18781    }
18782
18783    #[cfg(not(feature = "asupersync-executor"))]
18784    #[test]
18785    fn public_constructor_reports_fallback_once_and_actual_backend() {
18786        use tracing_subscriber::prelude::*;
18787
18788        for (effect_queue, expected_backend) in [
18789            (EffectQueueConfig::default(), "spawned"),
18790            (
18791                EffectQueueConfig::default().with_backend(TaskExecutorBackend::Spawned),
18792                "spawned",
18793            ),
18794            (
18795                EffectQueueConfig::default().with_backend(TaskExecutorBackend::EffectQueue),
18796                "queued",
18797            ),
18798        ] {
18799            let capture = A11yTraceCapture::default();
18800            let subscriber = tracing_subscriber::registry().with(capture.clone().with_filter(
18801                tracing_subscriber::filter::filter_fn(|metadata| {
18802                    metadata.target() == crate::telemetry_schema::TARGET_RUNTIME
18803                }),
18804            ));
18805            tracing::subscriber::with_default(subscriber, || {
18806                let config = ProgramConfig::default()
18807                    .with_lane(RuntimeLane::Asupersync)
18808                    .with_effect_queue(effect_queue)
18809                    .with_signal_interception(false);
18810                let features = BackendFeatures::default();
18811                let events = HeadlessEventSource::new(80, 24, features);
18812                let writer = TerminalWriter::with_diff_config(
18813                    Vec::new(),
18814                    config.screen_mode,
18815                    config.ui_anchor,
18816                    TerminalCapabilities::basic(),
18817                    config.diff_config.clone(),
18818                );
18819                let program = Program::with_event_source(
18820                    TestModel { value: 0 },
18821                    events,
18822                    features,
18823                    TerminalPresenter::new(writer),
18824                    config,
18825                )
18826                .expect("fallback executor initializes");
18827                assert_eq!(program.task_executor.kind_name(), expected_backend);
18828            });
18829            let output = capture.0.lock().expect("capture lock");
18830            assert_eq!(output.matches("missing_feature=").count(), 1, "{output}");
18831            assert!(output.contains("missing_feature=\"asupersync-executor\""));
18832            assert!(output.contains("requested=\"asupersync\""));
18833            assert!(output.contains("resolved=\"structured\""));
18834            let startup: Vec<_> = output
18835                .lines()
18836                .filter(|line| line.contains("runtime startup:"))
18837                .collect();
18838            assert_eq!(startup.len(), 1, "{output}");
18839            assert!(startup[0].contains("requested_lane=\"asupersync\""));
18840            assert!(startup[0].contains("resolved_lane=\"structured\""));
18841            assert!(startup[0].contains(&format!("task_backend=\"{expected_backend}\"")));
18842        }
18843    }
18844
18845    #[cfg(feature = "asupersync-executor")]
18846    #[test]
18847    fn asupersync_lane_resolves_to_asupersync_backend_when_feature_enabled() {
18848        let resolved_lane = RuntimeLane::Asupersync.resolve();
18849        assert_eq!(resolved_lane, RuntimeLane::Asupersync);
18850        assert_eq!(
18851            resolved_lane.task_executor_backend(),
18852            TaskExecutorBackend::Asupersync
18853        );
18854        let config = ProgramConfig::default()
18855            .with_lane(RuntimeLane::Asupersync)
18856            .with_signal_interception(false);
18857        let resolved = config.resolved_effect_queue_config(resolved_lane);
18858        assert_eq!(resolved.backend, TaskExecutorBackend::Asupersync);
18859        assert!(!resolved.enabled);
18860
18861        // Use the public constructor, not the manually assembled test Program.
18862        let features = BackendFeatures::default();
18863        let events = HeadlessEventSource::new(80, 24, features);
18864        let writer = TerminalWriter::with_diff_config(
18865            Vec::new(),
18866            config.screen_mode,
18867            config.ui_anchor,
18868            TerminalCapabilities::basic(),
18869            config.diff_config.clone(),
18870        );
18871        let mut program = Program::with_event_source(
18872            TestModel { value: 0 },
18873            events,
18874            features,
18875            TerminalPresenter::new(writer),
18876            config,
18877        )
18878        .expect("Asupersync lane initializes its executor");
18879        assert_eq!(program.task_executor.kind_name(), "asupersync");
18880        let executions = Arc::new(AtomicUsize::new(0));
18881        for _ in 0..32 {
18882            let executions = Arc::clone(&executions);
18883            program
18884                .execute_cmd(Cmd::task(move || {
18885                    executions.fetch_add(1, Ordering::SeqCst);
18886                    TestMsg::Increment
18887                }))
18888                .expect("submit through selected lane");
18889        }
18890        let deadline = Instant::now() + Duration::from_secs(5);
18891        while (program.model().value < 32 || program.task_executor.in_flight() > 0)
18892            && Instant::now() < deadline
18893        {
18894            program
18895                .process_task_results()
18896                .expect("deliver task results");
18897            program.reap_finished_tasks();
18898            thread::yield_now();
18899        }
18900        assert_eq!(program.model().value, 32, "every result reaches the model");
18901        assert_eq!(
18902            executions.load(Ordering::SeqCst),
18903            32,
18904            "effects execute once"
18905        );
18906        assert_eq!(program.task_executor.in_flight(), 0);
18907    }
18908
18909    #[test]
18910    fn asupersync_lane_preserves_explicit_task_backend() {
18911        for backend in [
18912            TaskExecutorBackend::Spawned,
18913            TaskExecutorBackend::EffectQueue,
18914        ] {
18915            let config = ProgramConfig::default()
18916                .with_lane(RuntimeLane::Asupersync)
18917                .with_effect_queue(EffectQueueConfig::default().with_backend(backend));
18918            assert_eq!(
18919                config
18920                    .resolved_effect_queue_config(config.runtime_lane.resolve())
18921                    .backend,
18922                backend
18923            );
18924        }
18925    }
18926
18927    #[test]
18928    fn program_config_explicit_spawned_backend_is_preserved() {
18929        let resolved = ProgramConfig::default()
18930            .with_effect_queue(EffectQueueConfig::default().with_enabled(false))
18931            .resolved_effect_queue_config(RuntimeLane::Structured);
18932        assert!(!resolved.enabled);
18933        assert_eq!(resolved.backend, TaskExecutorBackend::Spawned);
18934    }
18935
18936    #[test]
18937    fn program_config_with_rollout_policy() {
18938        let config = ProgramConfig::default().with_rollout_policy(RolloutPolicy::Shadow);
18939        assert_eq!(config.rollout_policy, RolloutPolicy::Shadow);
18940    }
18941
18942    #[test]
18943    fn rollout_policy_labels() {
18944        assert_eq!(RolloutPolicy::Off.label(), "off");
18945        assert_eq!(RolloutPolicy::Shadow.label(), "shadow");
18946        assert_eq!(RolloutPolicy::Enabled.label(), "enabled");
18947        assert_eq!(format!("{}", RolloutPolicy::Shadow), "shadow");
18948    }
18949
18950    #[test]
18951    fn rollout_policy_is_shadow() {
18952        assert!(!RolloutPolicy::Off.is_shadow());
18953        assert!(RolloutPolicy::Shadow.is_shadow());
18954        assert!(!RolloutPolicy::Enabled.is_shadow());
18955    }
18956
18957    #[test]
18958    fn rollout_policy_default_is_off() {
18959        assert_eq!(RolloutPolicy::default(), RolloutPolicy::Off);
18960    }
18961
18962    #[test]
18963    fn runtime_lane_parse_legacy() {
18964        assert_eq!(RuntimeLane::parse("legacy"), Some(RuntimeLane::Legacy));
18965    }
18966
18967    #[test]
18968    fn runtime_lane_parse_structured_case_insensitive() {
18969        assert_eq!(
18970            RuntimeLane::parse("Structured"),
18971            Some(RuntimeLane::Structured)
18972        );
18973    }
18974
18975    #[test]
18976    fn runtime_lane_parse_asupersync_uppercase() {
18977        assert_eq!(
18978            RuntimeLane::parse("ASUPERSYNC"),
18979            Some(RuntimeLane::Asupersync)
18980        );
18981    }
18982
18983    #[test]
18984    fn runtime_lane_parse_unrecognized() {
18985        assert_eq!(RuntimeLane::parse("bogus"), None);
18986    }
18987
18988    #[test]
18989    fn rollout_policy_parse_shadow() {
18990        assert_eq!(RolloutPolicy::parse("shadow"), Some(RolloutPolicy::Shadow));
18991    }
18992
18993    #[test]
18994    fn rollout_policy_parse_enabled() {
18995        assert_eq!(
18996            RolloutPolicy::parse("enabled"),
18997            Some(RolloutPolicy::Enabled)
18998        );
18999    }
19000
19001    #[test]
19002    fn rollout_policy_parse_off() {
19003        assert_eq!(RolloutPolicy::parse("off"), Some(RolloutPolicy::Off));
19004    }
19005
19006    #[test]
19007    fn rollout_policy_parse_unrecognized() {
19008        assert_eq!(RolloutPolicy::parse("bogus"), None);
19009    }
19010
19011    // =========================================================================
19012    // PersistenceConfig Debug (bd-2yjus)
19013    // =========================================================================
19014
19015    #[test]
19016    fn persistence_config_debug() {
19017        let config = PersistenceConfig::default();
19018        let debug = format!("{config:?}");
19019        assert!(debug.contains("PersistenceConfig"));
19020        assert!(debug.contains("auto_load"));
19021        assert!(debug.contains("auto_save"));
19022    }
19023
19024    // =========================================================================
19025    // FrameTimingConfig (bd-2yjus)
19026    // =========================================================================
19027
19028    #[test]
19029    fn frame_timing_config_debug() {
19030        use std::sync::Arc;
19031
19032        struct DummySink;
19033        impl FrameTimingSink for DummySink {
19034            fn record_frame(&self, _timing: &FrameTiming) {}
19035        }
19036
19037        let config = FrameTimingConfig::new(Arc::new(DummySink));
19038        let debug = format!("{config:?}");
19039        assert!(debug.contains("FrameTimingConfig"));
19040    }
19041
19042    #[test]
19043    fn program_config_with_frame_timing() {
19044        use std::sync::Arc;
19045
19046        struct DummySink;
19047        impl FrameTimingSink for DummySink {
19048            fn record_frame(&self, _timing: &FrameTiming) {}
19049        }
19050
19051        let config =
19052            ProgramConfig::default().with_frame_timing(FrameTimingConfig::new(Arc::new(DummySink)));
19053        assert!(config.frame_timing.is_some());
19054    }
19055
19056    // =========================================================================
19057    // BudgetDecisionEvidence helper functions (bd-2yjus)
19058    // =========================================================================
19059
19060    #[test]
19061    fn budget_decision_evidence_decision_from_levels() {
19062        use ftui_render::budget::DegradationLevel;
19063        // Degrade: after > before
19064        assert_eq!(
19065            BudgetDecisionEvidence::decision_from_levels(
19066                DegradationLevel::Full,
19067                DegradationLevel::SimpleBorders
19068            ),
19069            BudgetDecision::Degrade
19070        );
19071        // Upgrade: after < before
19072        assert_eq!(
19073            BudgetDecisionEvidence::decision_from_levels(
19074                DegradationLevel::SimpleBorders,
19075                DegradationLevel::Full
19076            ),
19077            BudgetDecision::Upgrade
19078        );
19079        // Hold: same
19080        assert_eq!(
19081            BudgetDecisionEvidence::decision_from_levels(
19082                DegradationLevel::Full,
19083                DegradationLevel::Full
19084            ),
19085            BudgetDecision::Hold
19086        );
19087    }
19088
19089    // =========================================================================
19090    // WidgetRefreshPlan (bd-2yjus)
19091    // =========================================================================
19092
19093    #[test]
19094    fn widget_refresh_plan_clear() {
19095        let mut plan = WidgetRefreshPlan::new();
19096        plan.frame_idx = 5;
19097        plan.budget_us = 100.0;
19098        plan.signal_count = 3;
19099        plan.over_budget = true;
19100        plan.clear();
19101        assert_eq!(plan.frame_idx, 0);
19102        assert_eq!(plan.budget_us, 0.0);
19103        assert_eq!(plan.signal_count, 0);
19104        assert!(!plan.over_budget);
19105    }
19106
19107    #[test]
19108    fn widget_refresh_plan_as_budget_empty_signals() {
19109        let plan = WidgetRefreshPlan::new();
19110        let budget = plan.as_budget();
19111        // With signal_count == 0, should be allow_all (allows any widget)
19112        assert!(budget.allows(0, false));
19113        assert!(budget.allows(999, false));
19114    }
19115
19116    #[test]
19117    fn widget_refresh_plan_to_jsonl_structure() {
19118        let plan = WidgetRefreshPlan::new();
19119        let jsonl = plan.to_jsonl();
19120        assert!(jsonl.contains("\"event\":\"widget_refresh\""));
19121        assert!(jsonl.contains("\"frame_idx\":0"));
19122        assert!(jsonl.contains("\"selected\":[]"));
19123    }
19124
19125    // =========================================================================
19126    // BatchController Default trait (bd-2yjus)
19127    // =========================================================================
19128
19129    #[test]
19130    fn batch_controller_default_trait() {
19131        let bc = BatchController::default();
19132        let bc2 = BatchController::new();
19133        // Should be equivalent
19134        assert_eq!(bc.tau_s(), bc2.tau_s());
19135        assert_eq!(bc.observations(), bc2.observations());
19136    }
19137
19138    #[test]
19139    fn batch_controller_observe_arrival_stale_gap_ignored() {
19140        let mut bc = BatchController::new();
19141        let base = Instant::now();
19142        // First arrival
19143        bc.observe_arrival(base);
19144        // Stale gap > 10s should be ignored
19145        bc.observe_arrival(base + Duration::from_secs(15));
19146        assert_eq!(bc.observations(), 0);
19147    }
19148
19149    #[test]
19150    fn batch_controller_observe_service_out_of_range() {
19151        let mut bc = BatchController::new();
19152        let original_service = bc.service_est_s();
19153        // Out-of-range (>= 10s) should be ignored
19154        bc.observe_service(Duration::from_secs(15));
19155        assert_eq!(bc.service_est_s(), original_service);
19156    }
19157
19158    #[test]
19159    fn batch_controller_lambda_zero_inter_arrival() {
19160        // When ema_inter_arrival_s is effectively 0, lambda should be 0
19161        let bc = BatchController {
19162            ema_inter_arrival_s: 0.0,
19163            ..BatchController::new()
19164        };
19165        assert_eq!(bc.lambda_est(), 0.0);
19166    }
19167
19168    // =========================================================================
19169    // Headless program: Cmd::Log with and without trailing newline (bd-2yjus)
19170    // =========================================================================
19171
19172    #[test]
19173    fn headless_execute_cmd_log_appends_newline_if_missing() {
19174        let mut program =
19175            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
19176        program.execute_cmd(Cmd::log("no newline")).expect("log");
19177
19178        let bytes = program.presenter.into_inner().expect("writer output");
19179        let output = String::from_utf8_lossy(&bytes);
19180        // The sanitized output should end with a newline
19181        assert!(output.contains("no newline"));
19182    }
19183
19184    #[test]
19185    fn headless_execute_cmd_log_preserves_trailing_newline() {
19186        let mut program =
19187            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
19188        program
19189            .execute_cmd(Cmd::log("with newline\n"))
19190            .expect("log");
19191
19192        let bytes = program.presenter.into_inner().expect("writer output");
19193        let output = String::from_utf8_lossy(&bytes);
19194        assert!(output.contains("with newline"));
19195    }
19196
19197    #[test]
19198    fn model_log_commands_filter_before_line_formatting() {
19199        let mut program =
19200            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
19201        let mut caps = TerminalCapabilities::basic();
19202        caps.scroll_region = true;
19203        program.presenter = TerminalPresenter::new(TerminalWriter::new(
19204            Vec::new(),
19205            ScreenMode::Inline { ui_height: 3 },
19206            UiAnchor::Bottom,
19207            caps,
19208        ));
19209        program.presenter.set_size(80, 24);
19210        program
19211            .presenter
19212            .present_ui(&Buffer::new(80, 3), None, false)
19213            .expect("establish log region");
19214        assert!(program.presenter.writer.scroll_region_active());
19215        for text in ["first\nsecond", "first\r\nsecond\r\n"] {
19216            program.execute_cmd(Cmd::log(text)).expect("log lines");
19217        }
19218        program
19219            .execute_cmd(Cmd::log("joined\r\x00\nnext"))
19220            .expect("filter before normalizing a revealed CRLF");
19221        program
19222            .execute_cmd(Cmd::log("a\x1b]0;hidden\nline\x07b"))
19223            .expect("filter embedded control newline");
19224        program
19225            .execute_cmd(Cmd::log_sgr_only("\x1b[31mred\x1b[2J\nplain"))
19226            .expect("colored command");
19227        let output = String::from_utf8(program.presenter.into_inner().unwrap()).unwrap();
19228        assert_eq!(output.matches("first\r\nsecond\r\n").count(), 2);
19229        assert!(output.contains("joined\r\nnext\r\n"));
19230        assert!(!output.contains("joined\r\r\n"));
19231        // The sanitizer aborts an OSC at LF, preserving that newline and the
19232        // printable suffix, while stripping the OSC prefix and BEL.
19233        assert!(output.contains("a\r\nlineb\r\n"));
19234        assert!(!output.contains("hidden"));
19235        assert!(!output.contains("\x1b[2J"));
19236        assert!(output.contains("\x1b[31mred\x1b[0m\r"));
19237        assert!(output.contains("\x1b[0m\nplain\x1b[0m\r"));
19238    }
19239
19240    #[test]
19241    fn model_log_command_propagates_output_failure() {
19242        struct FailingWriter;
19243        impl Write for FailingWriter {
19244            fn write(&mut self, _: &[u8]) -> io::Result<usize> {
19245                Err(io::Error::new(
19246                    io::ErrorKind::BrokenPipe,
19247                    "log write failed",
19248                ))
19249            }
19250            fn flush(&mut self) -> io::Result<()> {
19251                Ok(())
19252            }
19253        }
19254        struct LoggingModel;
19255        impl Model for LoggingModel {
19256            type Message = Event;
19257            fn init(&mut self) -> Cmd<Event> {
19258                Cmd::sequence(vec![Cmd::log_sgr_only("\x1b[31mvisible"), Cmd::quit()])
19259            }
19260            fn update(&mut self, _: Event) -> Cmd<Event> {
19261                Cmd::none()
19262            }
19263            fn view(&self, _: &mut Frame) {
19264                panic!("log failure must be returned before rendering");
19265            }
19266        }
19267        let features = BackendFeatures::default();
19268        let config = ProgramConfig {
19269            screen_mode: ScreenMode::Inline { ui_height: 3 },
19270            ..ProgramConfig::default()
19271        }
19272        .with_signal_interception(false);
19273        let writer = TerminalWriter::new(
19274            FailingWriter,
19275            config.screen_mode,
19276            config.ui_anchor,
19277            TerminalCapabilities::basic(),
19278        );
19279        let mut program = Program::with_event_source(
19280            LoggingModel,
19281            HeadlessEventSource::new(80, 24, features),
19282            features,
19283            TerminalPresenter::new(writer),
19284            config,
19285        )
19286        .expect("construct real Program");
19287        assert_eq!(program.run().unwrap_err().kind(), io::ErrorKind::BrokenPipe);
19288    }
19289
19290    // =========================================================================
19291    // Headless program: immediate resize behavior (bd-2yjus)
19292    // =========================================================================
19293
19294    #[test]
19295    fn headless_handle_event_immediate_resize() {
19296        struct ResizeModel {
19297            last_size: Option<(u16, u16)>,
19298        }
19299
19300        #[derive(Debug)]
19301        enum ResizeMsg {
19302            Resize(u16, u16),
19303            Other,
19304        }
19305
19306        impl From<Event> for ResizeMsg {
19307            fn from(event: Event) -> Self {
19308                match event {
19309                    Event::Resize { width, height } => ResizeMsg::Resize(width, height),
19310                    _ => ResizeMsg::Other,
19311                }
19312            }
19313        }
19314
19315        impl Model for ResizeModel {
19316            type Message = ResizeMsg;
19317
19318            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
19319                if let ResizeMsg::Resize(w, h) = msg {
19320                    self.last_size = Some((w, h));
19321                }
19322                Cmd::none()
19323            }
19324
19325            fn view(&self, _frame: &mut Frame) {}
19326        }
19327
19328        let config = ProgramConfig::default().with_resize_behavior(ResizeBehavior::Immediate);
19329        let mut program = headless_program_with_config(ResizeModel { last_size: None }, config);
19330
19331        program
19332            .handle_event(Event::Resize {
19333                width: 120,
19334                height: 40,
19335            })
19336            .expect("handle resize");
19337
19338        assert_eq!(program.width, 120);
19339        assert_eq!(program.height, 40);
19340        assert_eq!(program.model().last_size, Some((120, 40)));
19341    }
19342
19343    // =========================================================================
19344    // Headless program: resize clamps zero dimensions (bd-2yjus)
19345    // =========================================================================
19346
19347    #[test]
19348    fn headless_apply_resize_clamps_zero_to_one() {
19349        struct SimpleModel;
19350
19351        #[derive(Debug)]
19352        enum SimpleMsg {
19353            Noop,
19354        }
19355
19356        impl From<Event> for SimpleMsg {
19357            fn from(_: Event) -> Self {
19358                SimpleMsg::Noop
19359            }
19360        }
19361
19362        impl Model for SimpleModel {
19363            type Message = SimpleMsg;
19364
19365            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
19366                Cmd::none()
19367            }
19368
19369            fn view(&self, _frame: &mut Frame) {}
19370        }
19371
19372        let mut program = headless_program_with_config(SimpleModel, ProgramConfig::default());
19373        program
19374            .apply_resize(0, 0, Duration::ZERO, false)
19375            .expect("resize");
19376
19377        // Zero dimensions should be clamped to 1
19378        assert_eq!(program.width, 1);
19379        assert_eq!(program.height, 1);
19380    }
19381
19382    // =========================================================================
19383    // PaneTerminalAdapter::force_cancel_all (bd-24v9m)
19384    // =========================================================================
19385
19386    #[test]
19387    fn force_cancel_all_idle_returns_none() {
19388        let mut adapter =
19389            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
19390        assert!(adapter.force_cancel_all().is_none());
19391    }
19392
19393    #[test]
19394    fn force_cancel_all_after_pointer_down_returns_diagnostics() {
19395        let mut adapter =
19396            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
19397        let target = pane_target(SplitAxis::Horizontal);
19398
19399        let down = Event::Mouse(MouseEvent::new(
19400            MouseEventKind::Down(MouseButton::Left),
19401            5,
19402            5,
19403        ));
19404        let _ = adapter.translate(&down, Some(target));
19405        assert!(adapter.active_pointer_id().is_some());
19406
19407        let diag = adapter
19408            .force_cancel_all()
19409            .expect("should produce diagnostics");
19410        assert!(diag.had_active_pointer);
19411        assert_eq!(diag.active_pointer_id, Some(1));
19412        assert!(diag.machine_transition.is_some());
19413
19414        // Adapter should be fully idle afterwards
19415        assert_eq!(adapter.active_pointer_id(), None);
19416        assert!(matches!(adapter.machine_state(), PaneDragResizeState::Idle));
19417    }
19418
19419    #[test]
19420    fn force_cancel_all_during_drag_returns_diagnostics() {
19421        let mut adapter =
19422            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
19423        let target = pane_target(SplitAxis::Vertical);
19424
19425        // Down โ†’ arm
19426        let down = Event::Mouse(MouseEvent::new(
19427            MouseEventKind::Down(MouseButton::Left),
19428            3,
19429            3,
19430        ));
19431        let _ = adapter.translate(&down, Some(target));
19432
19433        // Drag โ†’ transition to Dragging
19434        let drag = Event::Mouse(MouseEvent::new(
19435            MouseEventKind::Drag(MouseButton::Left),
19436            8,
19437            3,
19438        ));
19439        let _ = adapter.translate(&drag, None);
19440
19441        let diag = adapter
19442            .force_cancel_all()
19443            .expect("should produce diagnostics");
19444        assert!(diag.had_active_pointer);
19445        assert!(diag.machine_transition.is_some());
19446        let transition = diag.machine_transition.unwrap();
19447        assert!(matches!(
19448            transition.effect,
19449            PaneDragResizeEffect::Canceled {
19450                reason: PaneCancelReason::Programmatic,
19451                ..
19452            }
19453        ));
19454    }
19455
19456    #[test]
19457    fn force_cancel_all_is_idempotent() {
19458        let mut adapter =
19459            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
19460        let target = pane_target(SplitAxis::Horizontal);
19461
19462        let down = Event::Mouse(MouseEvent::new(
19463            MouseEventKind::Down(MouseButton::Left),
19464            5,
19465            5,
19466        ));
19467        let _ = adapter.translate(&down, Some(target));
19468
19469        let first = adapter.force_cancel_all();
19470        assert!(first.is_some());
19471
19472        let second = adapter.force_cancel_all();
19473        assert!(second.is_none());
19474    }
19475
19476    // =========================================================================
19477    // PaneInteractionGuard (bd-24v9m)
19478    // =========================================================================
19479
19480    #[test]
19481    fn pane_interaction_guard_finish_when_idle() {
19482        let mut adapter =
19483            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
19484        let guard = PaneInteractionGuard::new(&mut adapter);
19485        let diag = guard.finish();
19486        assert!(diag.is_none());
19487    }
19488
19489    #[test]
19490    fn pane_interaction_guard_finish_returns_diagnostics() {
19491        let mut adapter =
19492            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
19493        let target = pane_target(SplitAxis::Horizontal);
19494
19495        // Start a drag interaction through the adapter directly
19496        let down = Event::Mouse(MouseEvent::new(
19497            MouseEventKind::Down(MouseButton::Left),
19498            5,
19499            5,
19500        ));
19501        let _ = adapter.translate(&down, Some(target));
19502
19503        let guard = PaneInteractionGuard::new(&mut adapter);
19504        let diag = guard.finish().expect("should produce diagnostics");
19505        assert!(diag.had_active_pointer);
19506        assert_eq!(diag.active_pointer_id, Some(1));
19507    }
19508
19509    #[test]
19510    fn pane_interaction_guard_drop_cancels_active_interaction() {
19511        let mut adapter =
19512            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
19513        let target = pane_target(SplitAxis::Vertical);
19514
19515        let down = Event::Mouse(MouseEvent::new(
19516            MouseEventKind::Down(MouseButton::Left),
19517            7,
19518            7,
19519        ));
19520        let _ = adapter.translate(&down, Some(target));
19521        assert!(adapter.active_pointer_id().is_some());
19522
19523        {
19524            let _guard = PaneInteractionGuard::new(&mut adapter);
19525            // guard drops here without finish()
19526        }
19527
19528        // After guard drop, adapter should be idle
19529        assert_eq!(adapter.active_pointer_id(), None);
19530        assert!(matches!(adapter.machine_state(), PaneDragResizeState::Idle));
19531    }
19532
19533    #[test]
19534    fn pane_interaction_guard_adapter_access_works() {
19535        let mut adapter =
19536            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
19537        let target = pane_target(SplitAxis::Horizontal);
19538
19539        let mut guard = PaneInteractionGuard::new(&mut adapter);
19540
19541        // Use the adapter through the guard
19542        let down = Event::Mouse(MouseEvent::new(
19543            MouseEventKind::Down(MouseButton::Left),
19544            5,
19545            5,
19546        ));
19547        let dispatch = guard.adapter().translate(&down, Some(target));
19548        assert!(dispatch.primary_event.is_some());
19549
19550        // finish should clean up the interaction started through the guard
19551        let diag = guard.finish().expect("should produce diagnostics");
19552        assert!(diag.had_active_pointer);
19553    }
19554
19555    #[test]
19556    fn pane_interaction_guard_finish_then_drop_is_safe() {
19557        let mut adapter =
19558            PaneTerminalAdapter::new(PaneTerminalAdapterConfig::default()).expect("valid adapter");
19559        let target = pane_target(SplitAxis::Horizontal);
19560
19561        let down = Event::Mouse(MouseEvent::new(
19562            MouseEventKind::Down(MouseButton::Left),
19563            5,
19564            5,
19565        ));
19566        let _ = adapter.translate(&down, Some(target));
19567
19568        let guard = PaneInteractionGuard::new(&mut adapter);
19569        let _diag = guard.finish();
19570        // guard is consumed by finish(), so drop doesn't double-cancel
19571        // This test proves the API is safe: finish() takes `self` not `&mut self`
19572        assert_eq!(adapter.active_pointer_id(), None);
19573    }
19574
19575    // =========================================================================
19576    // PaneCapabilityMatrix (bd-6u66i)
19577    // =========================================================================
19578
19579    fn caps_modern() -> TerminalCapabilities {
19580        TerminalCapabilities::modern()
19581    }
19582
19583    fn caps_with_mux(
19584        mux: PaneMuxEnvironment,
19585    ) -> ftui_core::terminal_capabilities::TerminalCapabilities {
19586        let mut caps = TerminalCapabilities::modern();
19587        match mux {
19588            PaneMuxEnvironment::Tmux => caps.in_tmux = true,
19589            PaneMuxEnvironment::Screen => caps.in_screen = true,
19590            PaneMuxEnvironment::Zellij => caps.in_zellij = true,
19591            PaneMuxEnvironment::WeztermMux => caps.in_wezterm_mux = true,
19592            PaneMuxEnvironment::None => {}
19593        }
19594        caps
19595    }
19596
19597    #[test]
19598    fn capability_matrix_bare_terminal_modern() {
19599        let caps = caps_modern();
19600        let mat = PaneCapabilityMatrix::from_capabilities(&caps);
19601
19602        assert_eq!(mat.mux, PaneMuxEnvironment::None);
19603        assert!(mat.mouse_sgr);
19604        assert!(mat.mouse_drag_reliable);
19605        assert!(mat.mouse_button_discrimination);
19606        assert!(mat.focus_events);
19607        assert!(mat.unicode_box_drawing);
19608        assert!(mat.true_color);
19609        assert!(!mat.degraded);
19610        assert!(mat.drag_enabled());
19611        assert!(mat.focus_cancel_effective());
19612        assert!(mat.limitations().is_empty());
19613    }
19614
19615    #[test]
19616    fn capability_matrix_tmux() {
19617        let caps = caps_with_mux(PaneMuxEnvironment::Tmux);
19618        let mat = PaneCapabilityMatrix::from_capabilities(&caps);
19619
19620        assert_eq!(mat.mux, PaneMuxEnvironment::Tmux);
19621        // Focus cancel path is conservatively disabled in all muxes.
19622        assert!(mat.mouse_drag_reliable);
19623        assert!(!mat.focus_events);
19624        assert!(mat.drag_enabled());
19625        assert!(!mat.focus_cancel_effective());
19626        assert!(mat.degraded);
19627    }
19628
19629    #[test]
19630    fn capability_matrix_screen_degrades_drag() {
19631        let caps = caps_with_mux(PaneMuxEnvironment::Screen);
19632        let mat = PaneCapabilityMatrix::from_capabilities(&caps);
19633
19634        assert_eq!(mat.mux, PaneMuxEnvironment::Screen);
19635        assert!(!mat.mouse_drag_reliable);
19636        assert!(!mat.focus_events);
19637        assert!(!mat.drag_enabled());
19638        assert!(!mat.focus_cancel_effective());
19639        assert!(mat.degraded);
19640
19641        let lims = mat.limitations();
19642        assert!(lims.iter().any(|l| l.id == "mouse_drag_unreliable"));
19643        assert!(lims.iter().any(|l| l.id == "no_focus_events"));
19644    }
19645
19646    #[test]
19647    fn capability_matrix_zellij() {
19648        let caps = caps_with_mux(PaneMuxEnvironment::Zellij);
19649        let mat = PaneCapabilityMatrix::from_capabilities(&caps);
19650
19651        assert_eq!(mat.mux, PaneMuxEnvironment::Zellij);
19652        assert!(mat.mouse_drag_reliable);
19653        assert!(!mat.focus_events);
19654        assert!(mat.drag_enabled());
19655        assert!(!mat.focus_cancel_effective());
19656        assert!(mat.degraded);
19657    }
19658
19659    #[test]
19660    fn capability_matrix_wezterm_mux_disables_focus_cancel_path() {
19661        let caps = caps_with_mux(PaneMuxEnvironment::WeztermMux);
19662        let mat = PaneCapabilityMatrix::from_capabilities(&caps);
19663
19664        assert_eq!(mat.mux, PaneMuxEnvironment::WeztermMux);
19665        assert!(mat.mouse_drag_reliable);
19666        assert!(!mat.focus_events);
19667        assert!(mat.drag_enabled());
19668        assert!(!mat.focus_cancel_effective());
19669        assert!(mat.degraded);
19670    }
19671
19672    #[test]
19673    fn capability_matrix_no_sgr_mouse() {
19674        let mut caps = caps_modern();
19675        caps.mouse_sgr = false;
19676        let mat = PaneCapabilityMatrix::from_capabilities(&caps);
19677
19678        assert!(!mat.mouse_sgr);
19679        assert!(!mat.mouse_button_discrimination);
19680        assert!(mat.degraded);
19681
19682        let lims = mat.limitations();
19683        assert!(lims.iter().any(|l| l.id == "no_sgr_mouse"));
19684        assert!(lims.iter().any(|l| l.id == "no_button_discrimination"));
19685    }
19686
19687    #[test]
19688    fn capability_matrix_no_focus_events() {
19689        let mut caps = caps_modern();
19690        caps.focus_events = false;
19691        let mat = PaneCapabilityMatrix::from_capabilities(&caps);
19692
19693        assert!(!mat.focus_events);
19694        assert!(!mat.focus_cancel_effective());
19695        assert!(mat.degraded);
19696
19697        let lims = mat.limitations();
19698        assert!(lims.iter().any(|l| l.id == "no_focus_events"));
19699    }
19700
19701    #[test]
19702    fn capability_matrix_dumb_terminal() {
19703        let caps = TerminalCapabilities::dumb();
19704        let mat = PaneCapabilityMatrix::from_capabilities(&caps);
19705
19706        assert_eq!(mat.mux, PaneMuxEnvironment::None);
19707        assert!(!mat.mouse_sgr);
19708        assert!(!mat.focus_events);
19709        assert!(!mat.unicode_box_drawing);
19710        assert!(!mat.true_color);
19711        assert!(mat.degraded);
19712        assert!(mat.limitations().len() >= 3);
19713    }
19714
19715    #[test]
19716    fn capability_matrix_limitations_have_fallbacks() {
19717        let caps = TerminalCapabilities::dumb();
19718        let mat = PaneCapabilityMatrix::from_capabilities(&caps);
19719
19720        for lim in mat.limitations() {
19721            assert!(!lim.id.is_empty());
19722            assert!(!lim.description.is_empty());
19723            assert!(!lim.fallback.is_empty());
19724        }
19725    }
19726
19727    // ========================================================================
19728    // Screen transition detection tests (A.2 + D.3)
19729    // ========================================================================
19730
19731    /// A multi-screen model that implements ScreenTickDispatch, for testing
19732    /// the `check_screen_transition` logic.
19733    struct MultiScreenModel {
19734        active: String,
19735        screens: Vec<String>,
19736        ticked_screens: Vec<(String, u64)>,
19737    }
19738
19739    #[derive(Debug)]
19740    enum MultiScreenMsg {
19741        #[expect(dead_code)]
19742        Event(Event),
19743    }
19744
19745    impl From<Event> for MultiScreenMsg {
19746        fn from(event: Event) -> Self {
19747            MultiScreenMsg::Event(event)
19748        }
19749    }
19750
19751    impl Model for MultiScreenModel {
19752        type Message = MultiScreenMsg;
19753
19754        fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
19755            match msg {
19756                MultiScreenMsg::Event(_) => Cmd::none(),
19757            }
19758        }
19759
19760        fn view(&self, _frame: &mut Frame) {}
19761
19762        fn as_screen_tick_dispatch(
19763            &mut self,
19764        ) -> Option<&mut dyn crate::tick_strategy::ScreenTickDispatch> {
19765            Some(self)
19766        }
19767    }
19768
19769    impl crate::tick_strategy::ScreenTickDispatch for MultiScreenModel {
19770        fn screen_ids(&self) -> Vec<String> {
19771            self.screens.clone()
19772        }
19773
19774        fn active_screen_id(&self) -> String {
19775            self.active.clone()
19776        }
19777
19778        fn tick_screen(&mut self, screen_id: &str, tick_count: u64) {
19779            self.ticked_screens.push((screen_id.to_owned(), tick_count));
19780        }
19781    }
19782
19783    /// Shared log for recording strategy transitions (inspectable after test).
19784    type TransitionLog = Arc<std::sync::Mutex<Vec<(String, String)>>>;
19785
19786    /// A recording tick strategy that logs `on_screen_transition` calls
19787    /// to a shared log that can be inspected from test assertions.
19788    struct RecordingStrategy {
19789        log: TransitionLog,
19790    }
19791
19792    impl RecordingStrategy {
19793        fn new(log: TransitionLog) -> Self {
19794            Self { log }
19795        }
19796    }
19797
19798    impl crate::tick_strategy::TickStrategy for RecordingStrategy {
19799        fn should_tick(
19800            &mut self,
19801            _screen_id: &str,
19802            _tick_count: u64,
19803            _active_screen: &str,
19804        ) -> crate::tick_strategy::TickDecision {
19805            crate::tick_strategy::TickDecision::Skip
19806        }
19807
19808        fn on_screen_transition(&mut self, from: &str, to: &str) {
19809            self.log
19810                .lock()
19811                .unwrap()
19812                .push((from.to_owned(), to.to_owned()));
19813        }
19814
19815        fn name(&self) -> &str {
19816            "Recording"
19817        }
19818
19819        fn debug_stats(&self) -> Vec<(String, String)> {
19820            vec![("strategy".into(), "Recording".into())]
19821        }
19822    }
19823
19824    /// Helper to create a headless Program with a multi-screen model and
19825    /// a recording tick strategy. Returns the program and a shared log of
19826    /// `on_screen_transition` calls for assertions.
19827    fn headless_multi_screen_program(
19828        active: &str,
19829        screens: &[&str],
19830    ) -> (
19831        Program<MultiScreenModel, HeadlessEventSource, TerminalPresenter<Vec<u8>>>,
19832        TransitionLog,
19833    ) {
19834        let model = MultiScreenModel {
19835            active: active.to_owned(),
19836            screens: screens.iter().map(|s| (*s).to_owned()).collect(),
19837            ticked_screens: Vec::new(),
19838        };
19839        let events = HeadlessEventSource::new(80, 24, BackendFeatures::default());
19840        let writer = TerminalWriter::new(
19841            Vec::<u8>::new(),
19842            ScreenMode::AltScreen,
19843            UiAnchor::Bottom,
19844            TerminalCapabilities::dumb(),
19845        );
19846        let config = ProgramConfig {
19847            forced_size: Some((80, 24)),
19848            tick_strategy: Some(crate::tick_strategy::TickStrategyKind::ActiveOnly),
19849            ..ProgramConfig::default()
19850        };
19851        let mut prog = Program::with_event_source(
19852            model,
19853            events,
19854            BackendFeatures::default(),
19855            TerminalPresenter::new(writer),
19856            config,
19857        )
19858        .expect("headless program creation failed");
19859
19860        // Replace the default strategy with our recording strategy.
19861        let log: TransitionLog = Arc::new(std::sync::Mutex::new(Vec::new()));
19862        prog.tick_strategy = Some(Box::new(RecordingStrategy::new(log.clone())));
19863
19864        (prog, log)
19865    }
19866
19867    #[test]
19868    fn check_screen_transition_first_call_records_active() {
19869        let (mut prog, log) = headless_multi_screen_program("A", &["A", "B", "C"]);
19870
19871        assert!(prog.last_active_screen_for_strategy.is_none());
19872        prog.check_screen_transition();
19873        assert_eq!(prog.last_active_screen_for_strategy.as_deref(), Some("A"));
19874
19875        // First observation: no transition event, no force-tick.
19876        assert!(prog.model.ticked_screens.is_empty());
19877        assert!(log.lock().unwrap().is_empty());
19878    }
19879
19880    #[test]
19881    fn check_screen_transition_no_change_is_noop() {
19882        let (mut prog, log) = headless_multi_screen_program("A", &["A", "B", "C"]);
19883
19884        // First call: records.
19885        prog.check_screen_transition();
19886
19887        // Second call with same active screen: no-op.
19888        prog.check_screen_transition();
19889        assert_eq!(prog.last_active_screen_for_strategy.as_deref(), Some("A"));
19890
19891        // No force-tick, no transition notification.
19892        assert!(prog.model.ticked_screens.is_empty());
19893        assert!(log.lock().unwrap().is_empty());
19894    }
19895
19896    #[test]
19897    fn check_screen_transition_detects_switch_and_force_ticks() {
19898        let (mut prog, log) = headless_multi_screen_program("A", &["A", "B", "C"]);
19899
19900        prog.check_screen_transition(); // records "A"
19901
19902        // Simulate model switching to screen "B".
19903        prog.model.active = "B".to_owned();
19904        prog.check_screen_transition();
19905
19906        // D.3: force-tick should have been dispatched for "B".
19907        assert_eq!(prog.model.ticked_screens.len(), 1);
19908        assert_eq!(prog.model.ticked_screens[0].0, "B");
19909
19910        // A.2: strategy should have been notified of A โ†’ B.
19911        let transitions = log.lock().unwrap();
19912        assert_eq!(transitions.len(), 1);
19913        assert_eq!(transitions[0], ("A".to_owned(), "B".to_owned()));
19914
19915        // last_active should now be "B".
19916        assert_eq!(prog.last_active_screen_for_strategy.as_deref(), Some("B"));
19917    }
19918
19919    #[test]
19920    fn check_screen_transition_marks_dirty_on_change() {
19921        let (mut prog, _log) = headless_multi_screen_program("A", &["A", "B"]);
19922
19923        prog.check_screen_transition();
19924        prog.dirty = false;
19925
19926        prog.model.active = "B".to_owned();
19927        prog.check_screen_transition();
19928
19929        assert!(prog.dirty);
19930    }
19931
19932    #[test]
19933    fn check_screen_transition_not_dirty_when_unchanged() {
19934        let (mut prog, _log) = headless_multi_screen_program("A", &["A", "B"]);
19935
19936        prog.check_screen_transition();
19937        prog.dirty = false;
19938
19939        prog.check_screen_transition();
19940
19941        assert!(!prog.dirty);
19942    }
19943
19944    #[test]
19945    fn check_screen_transition_noop_without_strategy() {
19946        let (mut prog, _log) = headless_multi_screen_program("A", &["A", "B"]);
19947
19948        // Remove the tick strategy.
19949        prog.tick_strategy = None;
19950
19951        prog.check_screen_transition();
19952        assert!(prog.last_active_screen_for_strategy.is_none());
19953    }
19954
19955    #[test]
19956    fn check_screen_transition_multiple_switches_notifies_strategy() {
19957        let (mut prog, log) = headless_multi_screen_program("A", &["A", "B", "C"]);
19958
19959        prog.check_screen_transition(); // records "A"
19960
19961        // A โ†’ B
19962        prog.model.active = "B".to_owned();
19963        prog.check_screen_transition();
19964        assert_eq!(prog.model.ticked_screens.len(), 1);
19965        assert_eq!(prog.model.ticked_screens[0].0, "B");
19966
19967        // B โ†’ C
19968        prog.model.active = "C".to_owned();
19969        prog.check_screen_transition();
19970        assert_eq!(prog.model.ticked_screens.len(), 2);
19971        assert_eq!(prog.model.ticked_screens[1].0, "C");
19972
19973        // C โ†’ A
19974        prog.model.active = "A".to_owned();
19975        prog.check_screen_transition();
19976        assert_eq!(prog.model.ticked_screens.len(), 3);
19977        assert_eq!(prog.model.ticked_screens[2].0, "A");
19978
19979        // A.2: strategy should have all three transitions.
19980        let transitions = log.lock().unwrap();
19981        assert_eq!(transitions.len(), 3);
19982        assert_eq!(transitions[0], ("A".to_owned(), "B".to_owned()));
19983        assert_eq!(transitions[1], ("B".to_owned(), "C".to_owned()));
19984        assert_eq!(transitions[2], ("C".to_owned(), "A".to_owned()));
19985    }
19986
19987    #[test]
19988    fn check_screen_transition_uses_current_tick_count() {
19989        let (mut prog, _log) = headless_multi_screen_program("A", &["A", "B"]);
19990        prog.tick_count = 42;
19991
19992        prog.check_screen_transition(); // records "A"
19993
19994        prog.model.active = "B".to_owned();
19995        prog.check_screen_transition();
19996
19997        // Force-tick should use the current tick_count.
19998        assert_eq!(prog.model.ticked_screens[0].1, 42);
19999    }
20000
20001    #[test]
20002    fn check_screen_transition_reconciles_subscriptions_after_force_tick() {
20003        use crate::subscription::{StopSignal, SubId, Subscription, SubscriptionSender};
20004
20005        struct TransitionSubModel {
20006            active: String,
20007            screens: Vec<String>,
20008            subscribed: bool,
20009        }
20010
20011        #[derive(Debug)]
20012        #[allow(dead_code)]
20013        enum TransitionSubMsg {
20014            Event(Event),
20015        }
20016
20017        impl From<Event> for TransitionSubMsg {
20018            fn from(event: Event) -> Self {
20019                Self::Event(event)
20020            }
20021        }
20022
20023        impl Model for TransitionSubModel {
20024            type Message = TransitionSubMsg;
20025
20026            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
20027                Cmd::none()
20028            }
20029
20030            fn view(&self, _frame: &mut Frame) {}
20031
20032            fn subscriptions(&self) -> Vec<Box<dyn Subscription<Self::Message>>> {
20033                if self.subscribed {
20034                    vec![Box::new(TransitionSubscription)]
20035                } else {
20036                    vec![]
20037                }
20038            }
20039
20040            fn as_screen_tick_dispatch(
20041                &mut self,
20042            ) -> Option<&mut dyn crate::tick_strategy::ScreenTickDispatch> {
20043                Some(self)
20044            }
20045        }
20046
20047        impl crate::tick_strategy::ScreenTickDispatch for TransitionSubModel {
20048            fn screen_ids(&self) -> Vec<String> {
20049                self.screens.clone()
20050            }
20051
20052            fn active_screen_id(&self) -> String {
20053                self.active.clone()
20054            }
20055
20056            fn tick_screen(&mut self, screen_id: &str, _tick_count: u64) {
20057                if screen_id == self.active {
20058                    self.subscribed = true;
20059                }
20060            }
20061        }
20062
20063        struct TransitionSubscription;
20064
20065        impl Subscription<TransitionSubMsg> for TransitionSubscription {
20066            fn id(&self) -> SubId {
20067                1
20068            }
20069
20070            fn run(&self, _sender: SubscriptionSender<TransitionSubMsg>, _stop: StopSignal) {}
20071        }
20072
20073        struct TransitionStrategy;
20074
20075        impl crate::tick_strategy::TickStrategy for TransitionStrategy {
20076            fn should_tick(
20077                &mut self,
20078                _screen_id: &str,
20079                _tick_count: u64,
20080                _active_screen: &str,
20081            ) -> crate::tick_strategy::TickDecision {
20082                crate::tick_strategy::TickDecision::Skip
20083            }
20084
20085            fn on_screen_transition(&mut self, _from: &str, _to: &str) {}
20086
20087            fn name(&self) -> &str {
20088                "TransitionStrategy"
20089            }
20090
20091            fn debug_stats(&self) -> Vec<(String, String)> {
20092                vec![]
20093            }
20094        }
20095
20096        let model = TransitionSubModel {
20097            active: "A".to_owned(),
20098            screens: vec!["A".to_owned(), "B".to_owned()],
20099            subscribed: false,
20100        };
20101        let events = HeadlessEventSource::new(80, 24, BackendFeatures::default());
20102        let writer = TerminalWriter::new(
20103            Vec::<u8>::new(),
20104            ScreenMode::AltScreen,
20105            UiAnchor::Bottom,
20106            TerminalCapabilities::dumb(),
20107        );
20108        let config = ProgramConfig::default().with_forced_size(80, 24);
20109
20110        let mut program = Program::with_event_source(
20111            model,
20112            events,
20113            BackendFeatures::default(),
20114            TerminalPresenter::new(writer),
20115            config,
20116        )
20117        .expect("program creation");
20118        program.tick_strategy = Some(Box::new(TransitionStrategy));
20119
20120        program.check_screen_transition();
20121        assert_eq!(program.subscriptions.active_count(), 0);
20122
20123        program.model.active = "B".to_owned();
20124        program.check_screen_transition();
20125
20126        assert!(program.model().subscribed);
20127        assert_eq!(program.subscriptions.active_count(), 1);
20128    }
20129
20130    #[test]
20131    fn tick_strategy_stats_returns_empty_without_strategy() {
20132        let (mut prog, _log) = headless_multi_screen_program("A", &["A", "B"]);
20133        prog.tick_strategy = None;
20134        assert!(prog.tick_strategy_stats().is_empty());
20135    }
20136
20137    #[test]
20138    fn tick_strategy_stats_returns_strategy_fields() {
20139        let (prog, _log) = headless_multi_screen_program("A", &["A", "B"]);
20140        let stats = prog.tick_strategy_stats();
20141        // RecordingStrategy returns [("strategy", "Recording")]
20142        assert!(
20143            !stats.is_empty(),
20144            "stats should not be empty when strategy is configured"
20145        );
20146    }
20147
20148    // =========================================================================
20149    // BackendPresenter decoupling tests (bd-g00-root-epic-ewths.17.7)
20150    // =========================================================================
20151
20152    struct CountingPresenter {
20153        caps: TerminalCapabilities,
20154        pool: ftui_render::grapheme_pool::GraphemePool,
20155        links: ftui_render::link_registry::LinkRegistry,
20156        present_count: usize,
20157        log_lines: Vec<String>,
20158    }
20159
20160    impl CountingPresenter {
20161        fn new() -> Self {
20162            Self {
20163                caps: TerminalCapabilities::basic(),
20164                pool: ftui_render::grapheme_pool::GraphemePool::new(),
20165                links: ftui_render::link_registry::LinkRegistry::new(),
20166                present_count: 0,
20167                log_lines: Vec::new(),
20168            }
20169        }
20170    }
20171
20172    impl BackendPresenter for CountingPresenter {
20173        type Error = io::Error;
20174
20175        fn capabilities(&self) -> &TerminalCapabilities {
20176            &self.caps
20177        }
20178
20179        fn present_ui(
20180            &mut self,
20181            _buf: &Buffer,
20182            _diff: Option<&ftui_render::diff::BufferDiff>,
20183            _full_repaint_hint: bool,
20184        ) -> Result<(), Self::Error> {
20185            self.present_count += 1;
20186            Ok(())
20187        }
20188
20189        fn present_ui_owned(
20190            &mut self,
20191            _buf: Buffer,
20192            _cursor: Option<(u16, u16)>,
20193            _cursor_visible: bool,
20194        ) -> Result<(), Self::Error> {
20195            self.present_count += 1;
20196            Ok(())
20197        }
20198
20199        fn write_log(&mut self, text: &str) -> Result<(), Self::Error> {
20200            self.log_lines.push(text.to_owned());
20201            Ok(())
20202        }
20203
20204        fn write_log_line_with_mode(
20205            &mut self,
20206            text: &str,
20207            _mode: SanitizeMode,
20208        ) -> Result<(), Self::Error> {
20209            self.log_lines.push(text.to_owned());
20210            Ok(())
20211        }
20212
20213        fn pool_and_links_mut(
20214            &mut self,
20215        ) -> (
20216            &mut ftui_render::grapheme_pool::GraphemePool,
20217            &mut ftui_render::link_registry::LinkRegistry,
20218        ) {
20219            (&mut self.pool, &mut self.links)
20220        }
20221
20222        fn pool_mut(&mut self) -> &mut ftui_render::grapheme_pool::GraphemePool {
20223            &mut self.pool
20224        }
20225    }
20226
20227    #[test]
20228    fn program_presents_through_backend_presenter() {
20229        let model = TestModel { value: 42 };
20230        let events = HeadlessEventSource::new(80, 24, BackendFeatures::default());
20231        let presenter = CountingPresenter::new();
20232        let config = ProgramConfig::default().with_forced_size(80, 24);
20233
20234        let mut program = Program::with_event_source(
20235            model,
20236            events,
20237            BackendFeatures::default(),
20238            presenter,
20239            config,
20240        )
20241        .expect("program creation with CountingPresenter");
20242
20243        // Initial render frame calls present_ui / present_ui_owned
20244        program.render_frame().expect("render frame");
20245        assert_eq!(program.presenter.present_count, 1);
20246
20247        // Second render frame increments present count
20248        program.dirty = true;
20249        program.render_frame().expect("second render frame");
20250        assert_eq!(program.presenter.present_count, 2);
20251
20252        // Logging via Cmd::log forwards through write_log / write_log_line_with_mode
20253        program
20254            .execute_cmd(Cmd::log("hello from counting presenter"))
20255            .expect("execute log command");
20256        assert_eq!(program.presenter.log_lines.len(), 1);
20257        assert!(program.presenter.log_lines[0].contains("hello from counting presenter"));
20258    }
20259
20260    #[test]
20261    fn native_and_crossterm_constructors_build_terminal_presenter() {
20262        // Compile-time / type-level verification that DefaultProgram and
20263        // Program::with_config / with_native_backend build Program with TerminalPresenter<Stdout>.
20264
20265        fn assert_uses_terminal_presenter<M: Model, E: BackendEventSource<Error = io::Error>>(
20266            _p: &Program<M, E, TerminalPresenter<Stdout>>,
20267        ) {
20268        }
20269
20270        fn assert_default_program_alias<M: Model>(_p: &DefaultProgram<M>) {
20271            assert_uses_terminal_presenter(_p);
20272        }
20273
20274        let _ = assert_uses_terminal_presenter::<TestModel, CrosstermEventSource>;
20275        let _ = assert_default_program_alias::<TestModel>;
20276
20277        // Also test TerminalPresenter::with_writer type check and basic construction
20278        let sink = Vec::<u8>::new();
20279        let presenter = TerminalPresenter::with_writer(
20280            sink,
20281            ScreenMode::AltScreen,
20282            UiAnchor::Bottom,
20283            TerminalCapabilities::basic(),
20284        );
20285        assert_eq!(presenter.writer.screen_mode(), ScreenMode::AltScreen);
20286    }
20287
20288    // =========================================================================
20289    // Job control: suspend and resume (bd-d4dtr, docs/spec/suspend-resume.md)
20290    // =========================================================================
20291    //
20292    // None of these raise a real stop signal: a stopped test process hangs the
20293    // suite. `stop_process` is replaced with a recorder, and every step of the
20294    // sequence writes to a per-thread log so the ORDER is asserted, which is
20295    // the part that breaks silently (ยง10).
20296
20297    thread_local! {
20298        static JOB_LOG: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };
20299        /// Terminal size the source reports once the process is "continued".
20300        static SIZE_AFTER_STOP: std::cell::Cell<Option<(u16, u16)>> = const { std::cell::Cell::new(None) };
20301    }
20302
20303    fn job_log(entry: impl Into<String>) {
20304        JOB_LOG.with(|log| log.borrow_mut().push(entry.into()));
20305    }
20306
20307    fn take_job_log() -> Vec<String> {
20308        JOB_LOG.with(|log| std::mem::take(&mut *log.borrow_mut()))
20309    }
20310
20311    fn recording_stop(signal: i32) -> io::Result<()> {
20312        job_log(format!("stop({signal})"));
20313        Ok(())
20314    }
20315
20316    fn stop_while_the_terminal_is_resized(signal: i32) -> io::Result<()> {
20317        SIZE_AFTER_STOP.with(|size| size.set(Some((100, 30))));
20318        recording_stop(signal)
20319    }
20320
20321    struct SuspendableSource {
20322        size: (u16, u16),
20323        releases_terminal: bool,
20324    }
20325
20326    impl BackendEventSource for SuspendableSource {
20327        type Error = io::Error;
20328
20329        fn size(&self) -> Result<(u16, u16), io::Error> {
20330            Ok(SIZE_AFTER_STOP
20331                .with(std::cell::Cell::get)
20332                .unwrap_or(self.size))
20333        }
20334
20335        fn set_features(&mut self, _features: BackendFeatures) -> Result<(), io::Error> {
20336            Ok(())
20337        }
20338
20339        fn poll_event(&mut self, _timeout: Duration) -> Result<bool, io::Error> {
20340            Ok(false)
20341        }
20342
20343        fn read_event(&mut self) -> Result<Option<Event>, io::Error> {
20344            Ok(None)
20345        }
20346
20347        fn supports_suspend(&self) -> bool {
20348            true
20349        }
20350
20351        fn suspend(&mut self) -> Result<bool, io::Error> {
20352            job_log("events.suspend");
20353            Ok(self.releases_terminal)
20354        }
20355
20356        fn resume(&mut self) -> Result<(), io::Error> {
20357            job_log("events.resume");
20358            Ok(())
20359        }
20360    }
20361
20362    struct RecordingPresenter(CountingPresenter);
20363
20364    impl BackendPresenter for RecordingPresenter {
20365        type Error = io::Error;
20366
20367        fn capabilities(&self) -> &TerminalCapabilities {
20368            self.0.capabilities()
20369        }
20370
20371        fn write_log(&mut self, text: &str) -> Result<(), Self::Error> {
20372            self.0.write_log(text)
20373        }
20374
20375        fn present_ui(
20376            &mut self,
20377            buf: &Buffer,
20378            diff: Option<&ftui_render::diff::BufferDiff>,
20379            full_repaint_hint: bool,
20380        ) -> Result<(), Self::Error> {
20381            self.0.present_ui(buf, diff, full_repaint_hint)
20382        }
20383
20384        fn resize(&mut self, cols: u16, rows: u16) {
20385            job_log(format!("presenter.resize({cols}x{rows})"));
20386        }
20387
20388        fn suspend(&mut self) -> Result<(), Self::Error> {
20389            job_log("presenter.suspend");
20390            Ok(())
20391        }
20392
20393        fn pool_and_links_mut(
20394            &mut self,
20395        ) -> (
20396            &mut ftui_render::grapheme_pool::GraphemePool,
20397            &mut ftui_render::link_registry::LinkRegistry,
20398        ) {
20399            self.0.pool_and_links_mut()
20400        }
20401
20402        fn pool_mut(&mut self) -> &mut ftui_render::grapheme_pool::GraphemePool {
20403            self.0.pool_mut()
20404        }
20405    }
20406
20407    /// Records every event the model receives, by name.
20408    #[derive(Default)]
20409    struct SeenEvents {
20410        seen: Vec<String>,
20411    }
20412
20413    struct SeenEvent(Event);
20414
20415    impl From<Event> for SeenEvent {
20416        fn from(event: Event) -> Self {
20417            Self(event)
20418        }
20419    }
20420
20421    impl Model for SeenEvents {
20422        type Message = SeenEvent;
20423
20424        fn update(&mut self, msg: SeenEvent) -> Cmd<SeenEvent> {
20425            self.seen.push(match msg.0 {
20426                Event::Resize { width, height } => format!("resize({width}x{height})"),
20427                Event::Key(key) => format!("key({:?},{:?})", key.code, key.modifiers),
20428                other => format!("{other:?}"),
20429            });
20430            Cmd::none()
20431        }
20432
20433        fn view(&self, _frame: &mut Frame) {}
20434    }
20435
20436    fn suspendable_program(
20437        config: ProgramConfig,
20438        releases_terminal: bool,
20439    ) -> Program<SeenEvents, SuspendableSource, RecordingPresenter> {
20440        SIZE_AFTER_STOP.with(|size| size.set(None));
20441        let mut program = Program::with_event_source(
20442            SeenEvents::default(),
20443            SuspendableSource {
20444                size: (80, 24),
20445                releases_terminal,
20446            },
20447            BackendFeatures::default(),
20448            RecordingPresenter(CountingPresenter::new()),
20449            // No OS handlers: stop requests come only from injection.
20450            config.with_signal_interception(false),
20451        )
20452        .expect("program over a suspendable source");
20453        program.stop_process = recording_stop;
20454        take_job_log();
20455        program
20456    }
20457
20458    #[test]
20459    fn stop_request_releases_stops_and_restores_in_order() {
20460        let mut program = suspendable_program(ProgramConfig::default(), true);
20461        program.dirty = false;
20462        program.inject_suspend_signal(20);
20463        program.service_suspend().expect("suspend and resume");
20464
20465        assert_eq!(
20466            take_job_log(),
20467            [
20468                "presenter.suspend",
20469                "events.suspend",
20470                "stop(20)",
20471                "events.resume",
20472                "presenter.resize(80x24)",
20473            ],
20474            "presenter before backend on the way down, backend before repaint on the way up"
20475        );
20476        assert!(program.dirty, "a full repaint follows resume");
20477        assert!(
20478            program.model().seen.is_empty(),
20479            "same size: no Resize for the model"
20480        );
20481
20482        // The request was consumed: a second pass does nothing.
20483        program.service_suspend().expect("idle pass");
20484        assert!(take_job_log().is_empty());
20485    }
20486
20487    #[test]
20488    fn size_change_while_stopped_resizes_the_model_before_the_repaint() {
20489        let mut program = suspendable_program(ProgramConfig::default(), true);
20490        program.stop_process = stop_while_the_terminal_is_resized;
20491        program.inject_suspend_signal(20);
20492        program.service_suspend().expect("suspend and resume");
20493
20494        let log = take_job_log();
20495        assert_eq!(
20496            log.last().map(String::as_str),
20497            Some("presenter.resize(100x30)")
20498        );
20499        assert_eq!(program.model().seen, ["resize(100x30)"]);
20500        assert_eq!((program.width, program.height), (100, 30));
20501    }
20502
20503    #[test]
20504    fn pending_termination_outranks_a_stop_request() {
20505        let mut program = suspendable_program(ProgramConfig::default(), true);
20506        // Observe only this instance's termination slot, never the global one.
20507        program.intercept_signals = true;
20508        program.global_signal_slot = false;
20509        program.inject_termination_signal(15);
20510        program.inject_suspend_signal(20);
20511        program.service_suspend().expect("no suspend");
20512
20513        assert!(
20514            take_job_log().is_empty(),
20515            "exit path wins; nothing is released"
20516        );
20517        assert_eq!(program.pending_termination_signal(), Some(15));
20518    }
20519
20520    #[test]
20521    fn stop_requests_are_ignored_without_job_control() {
20522        let mut program =
20523            suspendable_program(ProgramConfig::default().with_job_control(false), true);
20524        program.inject_suspend_signal(20);
20525        program.service_suspend().expect("ignored");
20526        assert!(take_job_log().is_empty());
20527    }
20528
20529    #[test]
20530    fn a_source_that_releases_nothing_is_never_stopped() {
20531        let mut program = suspendable_program(ProgramConfig::default(), false);
20532        program.dirty = false;
20533        program.inject_suspend_signal(20);
20534        program.service_suspend().expect("no stop");
20535
20536        assert_eq!(
20537            take_job_log(),
20538            [
20539                "presenter.suspend",
20540                "events.suspend",
20541                "presenter.resize(80x24)"
20542            ],
20543            "no stop with the terminal still raw, and a full repaint instead"
20544        );
20545        assert!(program.dirty);
20546    }
20547
20548    #[test]
20549    fn headless_programs_never_suspend() {
20550        let mut program =
20551            headless_program_with_config(TestModel { value: 0 }, ProgramConfig::default());
20552        program.stop_process = recording_stop;
20553        program.inject_suspend_signal(20);
20554        program.service_suspend().expect("ignored");
20555        assert!(take_job_log().is_empty());
20556    }
20557
20558    #[test]
20559    fn ctrl_z_reaches_the_model_unless_suspend_is_opted_into() {
20560        let ctrl_z = || {
20561            Event::Key(
20562                ftui_core::event::KeyEvent::new(KeyCode::Char('z')).with_modifiers(Modifiers::CTRL),
20563            )
20564        };
20565
20566        // Default: Ctrl-Z is an ordinary key (undo in TextArea and the editors).
20567        let mut program = suspendable_program(ProgramConfig::default(), true);
20568        program.handle_event(ctrl_z()).expect("key");
20569        assert_eq!(program.model().seen.len(), 1, "{:?}", program.model().seen);
20570        program.service_suspend().expect("nothing pending");
20571        assert!(take_job_log().is_empty());
20572
20573        // Opted in: the key becomes a SIGTSTP request and the model never sees it.
20574        let mut program =
20575            suspendable_program(ProgramConfig::default().with_ctrl_z_suspend(true), true);
20576        program.handle_event(ctrl_z()).expect("key");
20577        assert!(
20578            program.model().seen.is_empty(),
20579            "{:?}",
20580            program.model().seen
20581        );
20582        program.service_suspend().expect("suspend");
20583        assert!(take_job_log().contains(&format!(
20584            "stop({})",
20585            ftui_core::job_control::KEYBOARD_STOP_SIGNAL
20586        )));
20587
20588        // Other Ctrl chords are untouched.
20589        program
20590            .handle_event(Event::Key(
20591                ftui_core::event::KeyEvent::new(KeyCode::Char('y')).with_modifiers(Modifiers::CTRL),
20592            ))
20593            .expect("key");
20594        assert_eq!(program.model().seen.len(), 1);
20595    }
20596
20597    #[test]
20598    fn suspend_and_resume_write_evidence_rows() {
20599        let path = temp_evidence_path("job_control");
20600        let mut program = suspendable_program(
20601            ProgramConfig::default().with_evidence_sink(EvidenceSinkConfig::enabled_file(&path)),
20602            true,
20603        );
20604        program.stop_process = stop_while_the_terminal_is_resized;
20605        program.inject_suspend_signal(20);
20606        program.service_suspend().expect("suspend and resume");
20607        take_job_log();
20608
20609        let suspend = read_evidence_event(&path, "suspend");
20610        assert_eq!(suspend["signal"], 20);
20611        assert_eq!(
20612            (suspend["cols"].as_u64(), suspend["rows"].as_u64()),
20613            (Some(80), Some(24))
20614        );
20615        assert!(suspend.get("size_changed").is_none());
20616
20617        let resume = read_evidence_event(&path, "resume");
20618        assert_eq!(resume["signal"], 20);
20619        assert_eq!(
20620            (resume["cols"].as_u64(), resume["rows"].as_u64()),
20621            (Some(100), Some(30))
20622        );
20623        assert_eq!(resume["size_changed"], true);
20624    }
20625}