Skip to main content

ftui_web/
step_program.rs

1#![forbid(unsafe_code)]
2
3//! Step-based WASM program runner for FrankenTUI.
4//!
5//! [`StepProgram`] drives an [`ftui_runtime::program::Model`] through
6//! init / event / update / view / present cycles without threads or blocking.
7//! The host (JavaScript) controls the event loop:
8//!
9//! 1. Push events via [`StepProgram::push_event`].
10//! 2. Advance time via [`StepProgram::advance_time`].
11//! 3. Call [`StepProgram::step`] to process one batch of events and render.
12//! 4. Read the rendered buffer via [`StepProgram::take_outputs`].
13//!
14//! # Accessibility
15//!
16//! Opt in with [`StepProgram::with_accessibility`]. Each rendered frame then
17//! collects the widgets' accessibility nodes, finalizes hierarchy and focus,
18//! and uses the same diff/announcement policy as the native runtime. A changed
19//! tree invokes [`Model::on_accessibility`] after presentation. Mutations and
20//! commands from that hook are rendered on a subsequent host step, never by
21//! recursively rendering inside the callback.
22//!
23//! Hosts can read the current tree or bounded text mirror and drain the latest
24//! frame's announcements. This local channel is separate from renderer logs:
25//! labels, descriptions and input values are never implicitly logged. A host
26//! must forward announcements to its accessibility bridge; this runner does
27//! not itself create DOM nodes or deliver operating-system accessibility events.
28//!
29//! # Example
30//!
31//! ```ignore
32//! use ftui_web::step_program::StepProgram;
33//! use ftui_core::event::Event;
34//! use core::time::Duration;
35//!
36//! let mut prog = StepProgram::new(MyModel::default(), 80, 24);
37//! prog.init().unwrap();
38//!
39//! // Host-driven frame loop
40//! prog.push_event(Event::Tick).expect("tick admission");
41//! prog.advance_time(Duration::from_millis(16));
42//! let result = prog.step().unwrap();
43//!
44//! if result.rendered {
45//!     let outputs = prog.take_outputs();
46//!     // Send outputs.last_buffer to the renderer...
47//! }
48//! ```
49
50use core::time::Duration;
51
52use ftui_a11y::tree::{
53    A11yTree, A11yTreeBuilder, ScreenReaderAnnouncement, ScreenReaderAnnouncements,
54    ScreenReaderMirror, ScreenReaderPolicy,
55};
56use ftui_backend::{BackendClock, BackendEventSource, BackendPresenter};
57use ftui_core::event::Event;
58use ftui_render::buffer::{Buffer, DoubleBuffer};
59use ftui_render::diff::BufferDiff;
60use ftui_render::frame::Frame;
61use ftui_render::grapheme_pool::GraphemePool;
62use ftui_runtime::program::{AccessibilityFrame, Cmd, Model};
63
64use crate::{WebBackend, WebBackendError, WebOutputs};
65
66/// Run grapheme-pool GC every N rendered frames in host-driven WASM mode.
67const POOL_GC_INTERVAL_FRAMES: u64 = 256;
68/// Minimum supported terminal dimension.
69const MIN_TERMINAL_DIMENSION: u16 = 1;
70
71#[inline]
72fn clamp_terminal_dimension(value: u16) -> u16 {
73    if value < MIN_TERMINAL_DIMENSION {
74        MIN_TERMINAL_DIMENSION
75    } else {
76        value
77    }
78}
79
80#[inline]
81fn clamp_terminal_size(width: u16, height: u16) -> (u16, u16) {
82    (
83        clamp_terminal_dimension(width),
84        clamp_terminal_dimension(height),
85    )
86}
87
88/// Result of a single [`StepProgram::step`] call.
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
90pub struct StepResult {
91    /// Whether the program is still running (false after `Cmd::Quit`).
92    pub running: bool,
93    /// Whether a frame was rendered during this step.
94    pub rendered: bool,
95    /// Number of events processed during this step.
96    pub events_processed: u32,
97    /// Accepted events still queued, including the unprocessed tail after quit.
98    pub events_pending: u32,
99    /// Current frame index (monotonically increasing).
100    pub frame_idx: u64,
101}
102
103#[derive(Debug, Clone, Copy, PartialEq, Eq)]
104struct GeometryTransition {
105    from_cols: u16,
106    from_rows: u16,
107    to_cols: u16,
108    to_rows: u16,
109}
110
111/// Host-driven, non-blocking program runner for WASM.
112///
113/// Wraps a [`Model`] and a [`WebBackend`], providing a step-based execution
114/// model suitable for `wasm32-unknown-unknown`. No threads, no blocking, no
115/// `std::time::Instant` — all I/O and time are host-driven.
116///
117/// # Lifecycle
118///
119/// 1. [`StepProgram::new`] — create with model and initial terminal size.
120/// 2. [`StepProgram::init`] — call once to initialize the model and render the first frame.
121/// 3. [`StepProgram::step`] — call repeatedly from the host event loop (e.g., `requestAnimationFrame`).
122/// 4. Read outputs after each step via [`StepProgram::take_outputs`].
123pub struct StepProgram<M: Model> {
124    model: M,
125    backend: WebBackend,
126    pool: GraphemePool,
127    running: bool,
128    initialized: bool,
129    dirty: bool,
130    frame_idx: u64,
131    tick_rate: Option<Duration>,
132    last_tick: Duration,
133    width: u16,
134    height: u16,
135    /// Double-buffered render target: O(1) swap instead of O(w*h) clone.
136    dbl_buf: Option<DoubleBuffer>,
137    /// Pending geometry transition that must force a baseline reset + full repaint marker.
138    pending_geometry_transition: Option<GeometryTransition>,
139    clipboard_requests: Vec<ftui_runtime::program::ClipboardRequest>,
140    /// Opt-in, local accessibility channel. No builder is allocated when off.
141    accessibility: Option<ScreenReaderPolicy>,
142    a11y_tree: A11yTree,
143    a11y_order: Vec<u64>,
144    a11y_announcements: Vec<ScreenReaderAnnouncement>,
145    a11y_dropped: usize,
146}
147
148impl<M: Model> StepProgram<M> {
149    /// Create a new step program with the given model and initial terminal size.
150    #[must_use]
151    pub fn new(model: M, width: u16, height: u16) -> Self {
152        let (width, height) = clamp_terminal_size(width, height);
153        Self {
154            model,
155            backend: WebBackend::new(width, height),
156            pool: GraphemePool::new(),
157            running: true,
158            initialized: false,
159            dirty: true,
160            frame_idx: 0,
161            tick_rate: None,
162            last_tick: Duration::ZERO,
163            width,
164            height,
165            dbl_buf: None,
166            pending_geometry_transition: None,
167            clipboard_requests: Vec::new(),
168            accessibility: None,
169            a11y_tree: A11yTree::empty(),
170            a11y_order: Vec::new(),
171            a11y_announcements: Vec::new(),
172            a11y_dropped: 0,
173        }
174    }
175
176    /// Create a step program with an existing [`WebBackend`].
177    #[must_use]
178    pub fn with_backend(model: M, mut backend: WebBackend) -> Self {
179        let (raw_width, raw_height) = backend.events_mut().size().unwrap_or((80, 24));
180        let (width, height) = clamp_terminal_size(raw_width, raw_height);
181        backend.events_mut().set_size(width, height);
182        Self {
183            model,
184            backend,
185            pool: GraphemePool::new(),
186            running: true,
187            initialized: false,
188            dirty: true,
189            frame_idx: 0,
190            tick_rate: None,
191            last_tick: Duration::ZERO,
192            width,
193            height,
194            dbl_buf: None,
195            pending_geometry_transition: None,
196            clipboard_requests: Vec::new(),
197            accessibility: None,
198            a11y_tree: A11yTree::empty(),
199            a11y_order: Vec::new(),
200            a11y_announcements: Vec::new(),
201            a11y_dropped: 0,
202        }
203    }
204
205    /// Enable the local accessibility channel, normally before [`init`](Self::init).
206    ///
207    /// A host should choose either its model callback or the drain accessor
208    /// for speech delivery, not forward both copies of the same transition.
209    #[must_use]
210    pub fn with_accessibility(mut self, policy: ScreenReaderPolicy) -> Self {
211        self.set_accessibility_policy(Some(policy));
212        self
213    }
214
215    /// Enable, update, or disable accessibility collection at runtime.
216    ///
217    /// Disabling immediately releases the previous tree, reading order and
218    /// undrained announcements. Re-enabling builds a fresh baseline on the
219    /// next rendered step. Changing limits while enabled preserves the tree
220    /// baseline so it does not fabricate another focus arrival. Passing the
221    /// unchanged policy is a no-op, including for undrained announcements.
222    pub fn set_accessibility_policy(&mut self, policy: Option<ScreenReaderPolicy>) {
223        if self.accessibility == policy {
224            return;
225        }
226        self.accessibility = policy;
227        self.a11y_announcements.clear();
228        self.a11y_dropped = 0;
229        if policy.is_none() {
230            self.a11y_tree = A11yTree::empty();
231            self.a11y_order = Vec::new();
232            self.a11y_announcements = Vec::new();
233        }
234        self.dirty = true;
235    }
236
237    /// Schedule a repaint for the next [`step`](Self::step).
238    ///
239    /// Only an event, a tick or an accessibility-policy change marks the frame
240    /// stale. A host that reaches the model another way — [`model_mut`] to
241    /// select a screen, say — leaves nothing to render, and `step` reports
242    /// `rendered: false` until something else happens to arrive.
243    ///
244    /// [`model_mut`]: Self::model_mut
245    pub fn request_redraw(&mut self) {
246        self.dirty = true;
247    }
248
249    /// The active accessibility policy, or `None` when collection is disabled.
250    #[must_use]
251    pub fn accessibility_policy(&self) -> Option<ScreenReaderPolicy> {
252        self.accessibility
253    }
254
255    /// Latest finalized tree (empty until rendering), absent when disabled.
256    #[must_use]
257    pub fn accessibility_tree(&self) -> Option<&A11yTree> {
258        self.accessibility.map(|_| &self.a11y_tree)
259    }
260
261    /// Reading order from the latest render, independent of hash-map order.
262    #[must_use]
263    pub fn accessibility_order(&self) -> &[u64] {
264        &self.a11y_order
265    }
266
267    /// Announcements from the latest rendered frame, unless already drained.
268    ///
269    /// Rendering an unchanged tree clears this batch. An idle step that does
270    /// not render leaves it alone. Use the drain accessor for at-most-once
271    /// forwarding rather than replaying this slice on every animation tick.
272    #[must_use]
273    pub fn accessibility_announcements(&self) -> &[ScreenReaderAnnouncement] {
274        &self.a11y_announcements
275    }
276
277    /// Drain the latest frame's bounded batch without consuming visual output.
278    ///
279    /// Call after `init` and after each rendered `step`. This is a per-frame
280    /// channel, not an unbounded queue of old speech: a subsequent render
281    /// replaces any undrained batch. `dropped_count` reports the current
282    /// frame's policy-cap drops, not missed host reads. A second drain returns
283    /// an empty batch with zero drops. The model callback sees the batch before
284    /// the host can drain it; hosts must avoid forwarding both channels.
285    pub fn take_accessibility_announcements(&mut self) -> ScreenReaderAnnouncements {
286        ScreenReaderAnnouncements {
287            announcements: std::mem::take(&mut self.a11y_announcements),
288            dropped_count: std::mem::take(&mut self.a11y_dropped),
289        }
290    }
291
292    /// A bounded, deterministic mirror of the latest tree for a host bridge.
293    ///
294    /// Mirror text is not a live-region announcement. Hosts should expose it
295    /// for navigation without automatically speaking the entire tree on every
296    /// update. Native semantic bridges should not replay equivalent text too.
297    #[must_use]
298    pub fn accessibility_mirror(&self) -> Option<ScreenReaderMirror> {
299        self.accessibility
300            .map(|policy| self.a11y_tree.screen_reader_mirror(policy))
301    }
302
303    /// Initialize the model and render the first frame.
304    ///
305    /// Must be called exactly once before [`step`](Self::step).
306    /// Calls `Model::init()`, executes returned commands, and presents
307    /// the initial frame.
308    pub fn init(&mut self) -> Result<(), WebBackendError> {
309        assert!(!self.initialized, "StepProgram::init() called twice");
310        self.initialized = true;
311        let cmd = self.model.init();
312        self.execute_cmd(cmd);
313        if self.running {
314            self.render_frame()?;
315        } else {
316            self.backend.events.set_size(self.width, self.height);
317        }
318        Ok(())
319    }
320
321    /// Process one batch of pending events, handle ticks, and render if dirty.
322    ///
323    /// This is the main entry point for the host event loop. Call this after
324    /// pushing events and advancing time.
325    ///
326    /// Returns [`StepResult`] describing what happened during the step.
327    pub fn step(&mut self) -> Result<StepResult, WebBackendError> {
328        assert!(self.initialized, "StepProgram::step() called before init()");
329
330        if !self.running {
331            return Ok(StepResult {
332                running: false,
333                rendered: false,
334                events_processed: 0,
335                events_pending: self.pending_events(),
336                frame_idx: self.frame_idx,
337            });
338        }
339
340        // 1. Process all pending events.
341        let mut events_processed: u32 = 0;
342        while let Some(event) = self.backend.events.read_event()? {
343            events_processed += 1;
344            self.handle_event(event);
345            if !self.running {
346                break;
347            }
348        }
349
350        // 2. Handle tick if tick_rate is set and enough time has elapsed.
351        if self.running
352            && let Some(rate) = self.tick_rate
353        {
354            let now = self.backend.clock.now_mono();
355            let delta = now.saturating_sub(self.last_tick);
356            let should_tick = if rate.is_zero() { true } else { delta >= rate };
357            if should_tick {
358                // Preserve remainder when running on high-refresh displays:
359                // snapping `last_tick` to the nearest boundary avoids drift and under-ticking.
360                if rate.is_zero() {
361                    self.last_tick = now;
362                } else {
363                    let rem_ns = delta.as_nanos() % rate.as_nanos();
364                    let rem = Duration::from_nanos(rem_ns as u64);
365                    self.last_tick = now.saturating_sub(rem);
366                }
367                let msg = M::Message::from(Event::Tick);
368                let cmd = self.model.update(msg);
369                self.dirty = true;
370                self.execute_cmd(cmd);
371            }
372        }
373
374        // 3. Render if dirty.
375        let rendered = if self.running && self.dirty {
376            self.render_frame()?;
377            true
378        } else {
379            false
380        };
381
382        if !self.running {
383            // Queued resizes after quit were accepted but never processed.
384            self.backend.events.set_size(self.width, self.height);
385        }
386
387        Ok(StepResult {
388            running: self.running,
389            rendered,
390            events_processed,
391            events_pending: self.pending_events(),
392            frame_idx: self.frame_idx,
393        })
394    }
395
396    /// Push a terminal event into the event queue.
397    ///
398    /// Accepted events are processed on the next [`step`](Self::step) call.
399    /// Rejection leaves the queue and backend size unchanged. Capacity errors
400    /// return the event; a stopped program rejects further input as unsupported.
401    pub fn push_event(&mut self, event: Event) -> Result<(), WebBackendError> {
402        if !self.running {
403            return Err(WebBackendError::Unsupported("program has stopped"));
404        }
405        let event = match event {
406            Event::Resize { width, height } => {
407                let (width, height) = clamp_terminal_size(width, height);
408                Event::Resize { width, height }
409            }
410            other => other,
411        };
412        let resize = match &event {
413            Event::Resize { width, height } => Some((*width, *height)),
414            _ => None,
415        };
416        self.backend.events_mut().push_event(event)?;
417        // Publish the requested size only after its event is admitted. The
418        // model and render baseline update when `step()` processes it.
419        if let Some((width, height)) = resize {
420            self.backend.events_mut().set_size(width, height);
421        }
422        Ok(())
423    }
424
425    /// Advance the deterministic clock by `dt`.
426    pub fn advance_time(&mut self, dt: Duration) {
427        self.backend.clock_mut().advance(dt);
428    }
429
430    /// Set the deterministic clock to an absolute time.
431    pub fn set_time(&mut self, now: Duration) {
432        self.backend.clock_mut().set(now);
433    }
434
435    /// Resize the terminal.
436    ///
437    /// Pushes a `Resize` event and updates the backend size. The resize
438    /// is processed on the next [`step`](Self::step) call.
439    pub fn resize(&mut self, width: u16, height: u16) -> Result<(), WebBackendError> {
440        self.push_event(Event::Resize { width, height })
441    }
442
443    /// Number of accepted events awaiting processing or explicit recovery.
444    #[must_use]
445    pub fn pending_events(&self) -> u32 {
446        self.backend.events.queued_events() as u32
447    }
448
449    /// Recover queued events in FIFO order without executing their effects.
450    ///
451    /// After quit, the host can retain this tail for inspection or another
452    /// session. Taking pending input cancels any queued resize request and
453    /// restores the backend's requested size to the last processed geometry.
454    pub fn take_pending_events(&mut self) -> Vec<Event> {
455        let events = self.backend.events.drain_events().collect();
456        self.backend.events.set_size(self.width, self.height);
457        events
458    }
459
460    /// Current deterministic clock value, independently of recording timestamps.
461    #[must_use]
462    pub fn time(&self) -> Duration {
463        self.backend.clock.now_mono()
464    }
465
466    /// Take the captured outputs (rendered buffer, logs), leaving empty defaults.
467    pub fn take_outputs(&mut self) -> WebOutputs {
468        self.backend.presenter_mut().take_outputs()
469    }
470
471    /// Drain clipboard effects for the host's clipboard API.
472    /// Successful reads should be returned through `push_event(Event::Clipboard(...))`.
473    pub fn take_clipboard_requests(&mut self) -> Vec<ftui_runtime::program::ClipboardRequest> {
474        std::mem::take(&mut self.clipboard_requests)
475    }
476
477    /// Read the captured outputs without consuming them.
478    pub fn outputs(&self) -> &WebOutputs {
479        self.backend.presenter.outputs()
480    }
481
482    /// Access the model.
483    pub fn model(&self) -> &M {
484        &self.model
485    }
486
487    /// Mutably access the model.
488    pub fn model_mut(&mut self) -> &mut M {
489        &mut self.model
490    }
491
492    /// Access the backend.
493    pub fn backend(&self) -> &WebBackend {
494        &self.backend
495    }
496
497    /// Mutably access the backend.
498    pub fn backend_mut(&mut self) -> &mut WebBackend {
499        &mut self.backend
500    }
501
502    /// Whether the program is still running.
503    pub fn is_running(&self) -> bool {
504        self.running
505    }
506
507    /// Whether the program has been initialized.
508    pub fn is_initialized(&self) -> bool {
509        self.initialized
510    }
511
512    /// Current frame index.
513    pub fn frame_idx(&self) -> u64 {
514        self.frame_idx
515    }
516
517    /// Current terminal dimensions.
518    pub fn size(&self) -> (u16, u16) {
519        (self.width, self.height)
520    }
521
522    /// Current tick rate, if any.
523    pub fn tick_rate(&self) -> Option<Duration> {
524        self.tick_rate
525    }
526
527    /// Access the grapheme pool (needed for deterministic checksumming).
528    pub fn pool(&self) -> &GraphemePool {
529        &self.pool
530    }
531
532    // --- Private helpers ---
533
534    fn handle_event(&mut self, event: Event) {
535        if let Event::Resize { width, height } = &event {
536            let (prev_width, prev_height) = (self.width, self.height);
537            self.width = *width;
538            self.height = *height;
539            // Invalidate diff baseline for every resize signal.
540            // Host-side fit/DPR/zoom transitions can require a repaint boundary
541            // even when cols/rows remain numerically unchanged.
542            self.dbl_buf = None;
543            self.pending_geometry_transition = Some(GeometryTransition {
544                from_cols: prev_width,
545                from_rows: prev_height,
546                to_cols: *width,
547                to_rows: *height,
548            });
549        }
550        let msg = M::Message::from(event);
551        let cmd = self.model.update(msg);
552        self.dirty = true;
553        self.execute_cmd(cmd);
554    }
555
556    fn render_frame(&mut self) -> Result<(), WebBackendError> {
557        // Ensure double buffer exists; first frame triggers allocation.
558        let full_repaint = self.dbl_buf.is_none();
559        let geometry_transition = if full_repaint {
560            self.pending_geometry_transition.take()
561        } else {
562            None
563        };
564        if self.dbl_buf.is_none() {
565            self.dbl_buf = Some(DoubleBuffer::new(self.width, self.height));
566        }
567
568        // Swap: previous current becomes the diff baseline, current is cleared.
569        {
570            let dbl = self.dbl_buf.as_mut().unwrap();
571            dbl.swap();
572            dbl.current_mut().clear();
573        }
574
575        // Take the cleared buffer out for Frame construction (avoids per-frame
576        // allocation). The 1×1 placeholder is trivially cheap.
577        let render_buf = std::mem::replace(
578            self.dbl_buf.as_mut().unwrap().current_mut(),
579            Buffer::new(1, 1),
580        );
581        let mut a11y_builder = self.accessibility.map(|_| A11yTreeBuilder::new());
582        let (rendered_buffer, a11y_order) = {
583            let mut frame = Frame::from_buffer(render_buf, &mut self.pool);
584            if let Some(builder) = a11y_builder.as_mut() {
585                frame.set_a11y(builder);
586            }
587            self.model.view(&mut frame);
588            frame.finish_a11y();
589            let order = frame.take_a11y_order();
590            (frame.buffer, order)
591        };
592        let a11y_tree = a11y_builder.map(A11yTreeBuilder::build);
593
594        // Move rendered buffer back into the double buffer's current slot.
595        *self.dbl_buf.as_mut().unwrap().current_mut() = rendered_buffer;
596
597        // Compute diff and present.
598        let dbl = self.dbl_buf.as_ref().unwrap();
599        let diff = if full_repaint {
600            None
601        } else {
602            Some(BufferDiff::compute(dbl.previous(), dbl.current()))
603        };
604        let buf = dbl.current().clone();
605
606        self.backend
607            .presenter_mut()
608            .present_ui_owned(buf, diff.as_ref(), full_repaint);
609
610        if let Some(transition) = geometry_transition {
611            self.emit_geometry_transition_markers(transition);
612        }
613
614        self.dirty = false;
615        let rendered_frame_idx = self.frame_idx;
616        self.frame_idx += 1;
617
618        // Periodic grapheme-pool GC. Destructure to satisfy the borrow
619        // checker: pool and dbl_buf are disjoint fields.
620        if self.frame_idx.is_multiple_of(POOL_GC_INTERVAL_FRAMES) {
621            let Self { dbl_buf, pool, .. } = self;
622            let dbl = dbl_buf.as_ref().unwrap();
623            pool.gc(&[dbl.current(), dbl.previous()]);
624        }
625
626        if let (Some(tree), Some(policy)) = (a11y_tree, self.accessibility) {
627            let diff = tree.diff(&self.a11y_tree);
628            let changed = !diff.is_empty();
629            let batch = diff.screen_reader_announcements(&tree, policy);
630            self.a11y_tree = tree;
631            self.a11y_order = a11y_order;
632            self.a11y_announcements = batch.announcements;
633            self.a11y_dropped = batch.dropped_count;
634            if changed {
635                // The hook may mutate model state even when it returns None.
636                // Match native Program's one-follow-up-frame contract. An
637                // identical subsequent tree does not invoke the hook again.
638                self.dirty = true;
639                let cmd = self.model.on_accessibility(AccessibilityFrame {
640                    frame_idx: rendered_frame_idx,
641                    tree: &self.a11y_tree,
642                    order: &self.a11y_order,
643                    announcements: &self.a11y_announcements,
644                    dropped: self.a11y_dropped,
645                });
646                self.execute_cmd(cmd);
647            }
648        }
649        Ok(())
650    }
651
652    fn emit_geometry_transition_markers(&mut self, transition: GeometryTransition) {
653        let reset_marker = format!(
654            r#"{{"event":"diff_baseline_reset","reason":"geometry_transition","from_cols":{},"from_rows":{},"to_cols":{},"to_rows":{},"frame_idx":{}}}"#,
655            transition.from_cols,
656            transition.from_rows,
657            transition.to_cols,
658            transition.to_rows,
659            self.frame_idx
660        );
661        let repaint_marker = format!(
662            r#"{{"event":"full_repaint_boundary","reason":"geometry_transition","from_cols":{},"from_rows":{},"to_cols":{},"to_rows":{},"frame_idx":{},"full_repaint":true}}"#,
663            transition.from_cols,
664            transition.from_rows,
665            transition.to_cols,
666            transition.to_rows,
667            self.frame_idx
668        );
669        let presenter = self.backend.presenter_mut();
670        let _ = presenter.write_log(&reset_marker);
671        let _ = presenter.write_log(&repaint_marker);
672    }
673
674    /// Commands run depth-first from an explicit stack of batch iterators, in
675    /// the order recursion gave. Running each `update` result recursively
676    /// overflowed the stack for a model that takes one step per `Cmd::Msg`,
677    /// which on wasm traps and kills the instance.
678    fn execute_cmd(&mut self, cmd: Cmd<M::Message>) {
679        let mut batches: Vec<std::vec::IntoIter<Cmd<M::Message>>> = Vec::new();
680        let mut next = Some(cmd);
681        loop {
682            let cmd = match next.take() {
683                Some(cmd) => cmd,
684                None => {
685                    // Resume the innermost batch. A batch stops after any
686                    // command that ends the program.
687                    let Some(rest) = batches.last_mut() else {
688                        return;
689                    };
690                    if !self.running {
691                        return;
692                    }
693                    match rest.next() {
694                        Some(cmd) => cmd,
695                        None => {
696                            batches.pop();
697                            continue;
698                        }
699                    }
700                }
701            };
702            next = self.execute_one_cmd(cmd, &mut batches);
703        }
704    }
705
706    /// Execute `cmd` for [`Self::execute_cmd`], returning the command to run
707    /// next and pushing the rest of a batch onto `batches`.
708    fn execute_one_cmd(
709        &mut self,
710        cmd: Cmd<M::Message>,
711        batches: &mut Vec<std::vec::IntoIter<Cmd<M::Message>>>,
712    ) -> Option<Cmd<M::Message>> {
713        match cmd {
714            Cmd::None => {}
715            Cmd::Quit => {
716                self.running = false;
717            }
718            Cmd::Msg(m) => {
719                return Some(self.model.update(m));
720            }
721            Cmd::Batch(cmds) | Cmd::Sequence(cmds) => {
722                let mut rest = cmds.into_iter();
723                let first = rest.next();
724                batches.push(rest);
725                return first;
726            }
727            Cmd::Tick(duration) => {
728                self.tick_rate = Some(duration);
729            }
730            Cmd::Log { text, mode } => {
731                let text = ftui_render::sanitize::sanitize_with(&text, mode);
732                let _ = self.backend.presenter_mut().write_log(&text);
733            }
734            Cmd::Task(_spec, f) => {
735                // WASM has no threads — execute tasks synchronously.
736                let msg = f();
737                return Some(self.model.update(msg));
738            }
739            Cmd::SetMouseCapture(enabled) => {
740                let mut features = self.backend.events_mut().features();
741                features.mouse_capture = enabled;
742                let _ = self.backend.events_mut().set_features(features);
743            }
744            Cmd::SetClipboard(text) => self
745                .clipboard_requests
746                .push(ftui_runtime::program::ClipboardRequest::Set(text)),
747            Cmd::GetClipboard => self
748                .clipboard_requests
749                .push(ftui_runtime::program::ClipboardRequest::Get),
750            Cmd::SaveState | Cmd::RestoreState => {
751                // No persistence in WASM (yet).
752            }
753            Cmd::SetTickStrategy(_) => {
754                // Runtime tick strategy selection is handled by host configuration.
755            }
756        }
757        None
758    }
759}
760
761#[cfg(test)]
762mod tests {
763    use super::*;
764    use ftui_core::event::{KeyCode, KeyEvent, KeyEventKind, Modifiers};
765    use ftui_render::cell::Cell;
766    use ftui_render::drawing::Draw;
767    use pretty_assertions::assert_eq;
768
769    // ---- Test model ----
770
771    #[test]
772    fn clipboard_requests_are_drained_for_host_delivery() {
773        use ftui_runtime::program::ClipboardRequest;
774        let mut program = StepProgram::new(new_counter(0), 10, 5);
775        program.init().unwrap();
776        program.execute_cmd(Cmd::sequence(vec![
777            Cmd::set_clipboard("界"),
778            Cmd::get_clipboard(),
779        ]));
780        assert_eq!(
781            program.take_clipboard_requests(),
782            [ClipboardRequest::Set("界".into()), ClipboardRequest::Get]
783        );
784        assert!(program.take_clipboard_requests().is_empty());
785        assert_eq!(program.model.value, 0);
786    }
787
788    #[test]
789    fn long_msg_and_task_chains_run_without_recursion() {
790        // One step per `Cmd::Msg` or inline task. Running each `update`
791        // result recursively overflowed the stack at a few thousand steps.
792        struct Walker {
793            steps: u32,
794        }
795
796        enum WalkMsg {
797            Step(u32),
798            Event,
799        }
800
801        impl From<Event> for WalkMsg {
802            fn from(_: Event) -> Self {
803                WalkMsg::Event
804            }
805        }
806
807        impl Model for Walker {
808            type Message = WalkMsg;
809
810            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
811                match msg {
812                    WalkMsg::Step(0) | WalkMsg::Event => Cmd::none(),
813                    WalkMsg::Step(n) if n % 2 == 0 => {
814                        self.steps += 1;
815                        Cmd::msg(WalkMsg::Step(n - 1))
816                    }
817                    WalkMsg::Step(n) => {
818                        self.steps += 1;
819                        Cmd::task(move || WalkMsg::Step(n - 1))
820                    }
821                }
822            }
823
824            fn view(&self, _frame: &mut Frame) {}
825        }
826
827        let mut program = StepProgram::new(Walker { steps: 0 }, 10, 5);
828        program.init().unwrap();
829        program.execute_cmd(Cmd::msg(WalkMsg::Step(200_000)));
830        assert_eq!(program.model.steps, 200_000);
831    }
832
833    /// The runtime keeps several command executors — `ProgramSimulator`,
834    /// this `StepProgram`, `Program` and the experimental `WasmRunner` — and a
835    /// fix to one has repeatedly had to be made in all of them. Nothing held
836    /// them to the same answer, so this walks random command trees through two
837    /// of them and compares what the model saw.
838    #[test]
839    fn the_simulator_and_the_step_program_run_a_command_tree_the_same_way() {
840        use ftui_runtime::ProgramSimulator;
841        use std::cell::RefCell;
842        use std::rc::Rc;
843
844        /// A command tree in a form that can be replayed into both runtimes:
845        /// `Cmd` holds closures and cannot be cloned.
846        #[derive(Clone, Debug)]
847        enum Plan {
848            None,
849            Msg(u32),
850            Quit,
851            Log(String),
852            Batch(Vec<Plan>),
853            Sequence(Vec<Plan>),
854        }
855
856        fn build(plan: &Plan) -> Cmd<Step> {
857            match plan {
858                Plan::None => Cmd::none(),
859                Plan::Msg(n) => Cmd::msg(Step::Seen(*n)),
860                Plan::Quit => Cmd::quit(),
861                Plan::Log(text) => Cmd::log(text.clone()),
862                Plan::Batch(children) => Cmd::batch(children.iter().map(build).collect::<Vec<_>>()),
863                Plan::Sequence(children) => {
864                    Cmd::sequence(children.iter().map(build).collect::<Vec<_>>())
865                }
866            }
867        }
868
869        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
870        enum Step {
871            Seen(u32),
872            Ignored,
873        }
874        impl From<Event> for Step {
875            fn from(_: Event) -> Self {
876                Step::Ignored
877            }
878        }
879
880        struct Recorder {
881            plan: Plan,
882            seen: Rc<RefCell<Vec<u32>>>,
883        }
884        impl Model for Recorder {
885            type Message = Step;
886            fn init(&mut self) -> Cmd<Step> {
887                build(&self.plan)
888            }
889            fn update(&mut self, msg: Step) -> Cmd<Step> {
890                if let Step::Seen(n) = msg {
891                    self.seen.borrow_mut().push(n);
892                }
893                Cmd::none()
894            }
895            fn view(&self, _frame: &mut Frame) {}
896        }
897
898        // Deterministic: the same trees on every machine and every run.
899        let mut state = 0x2545_F491_4F6C_DD1Du64;
900        let mut next = move || {
901            state ^= state << 13;
902            state ^= state >> 7;
903            state ^= state << 17;
904            state
905        };
906        let plan = |depth: u32, id: &mut u32, rng: &mut dyn FnMut() -> u64| -> Plan {
907            fn go(depth: u32, id: &mut u32, rng: &mut dyn FnMut() -> u64) -> Plan {
908                match rng() % if depth == 0 { 4 } else { 6 } {
909                    0 => Plan::None,
910                    1 | 2 => {
911                        *id += 1;
912                        Plan::Msg(*id)
913                    }
914                    3 => {
915                        if rng().is_multiple_of(6) {
916                            Plan::Quit
917                        } else {
918                            Plan::Log(format!("log{}", rng() % 100))
919                        }
920                    }
921                    4 => Plan::Batch((0..rng() % 4).map(|_| go(depth - 1, id, rng)).collect()),
922                    _ => Plan::Sequence((0..rng() % 4).map(|_| go(depth - 1, id, rng)).collect()),
923                }
924            }
925            go(depth, id, rng)
926        };
927
928        let (mut with_messages, mut that_quit) = (0u32, 0u32);
929        for trial in 0..2_000 {
930            let mut id = 0;
931            let tree = plan(3, &mut id, &mut next);
932
933            let simulator_seen = Rc::new(RefCell::new(Vec::new()));
934            let mut simulator = ProgramSimulator::new(Recorder {
935                plan: tree.clone(),
936                seen: Rc::clone(&simulator_seen),
937            });
938            simulator.init();
939
940            let step_seen = Rc::new(RefCell::new(Vec::new()));
941            let mut program = StepProgram::new(
942                Recorder {
943                    plan: tree.clone(),
944                    seen: Rc::clone(&step_seen),
945                },
946                80,
947                24,
948            );
949            program.init().expect("init the step program");
950
951            let (from_simulator, from_step) =
952                (simulator_seen.borrow().clone(), step_seen.borrow().clone());
953            if !from_simulator.is_empty() {
954                with_messages += 1;
955            }
956            if !simulator.is_running() {
957                that_quit += 1;
958            }
959            assert_eq!(
960                from_simulator, from_step,
961                "trial {trial}: the two runtimes delivered different messages for {tree:?}"
962            );
963            assert_eq!(
964                simulator.is_running(),
965                program.is_running(),
966                "trial {trial}: the two runtimes disagreed about quitting for {tree:?}"
967            );
968        }
969
970        // An equal pair of empty vectors would prove nothing.
971        assert!(
972            with_messages > 500 && that_quit > 50,
973            "the trees were too dull to compare: {with_messages} delivered a message \
974             and {that_quit} quit"
975        );
976    }
977
978    struct Counter {
979        value: i32,
980        initialized: bool,
981    }
982
983    #[derive(Debug)]
984    enum CounterMsg {
985        Increment,
986        Decrement,
987        Reset,
988        Quit,
989        LogValue,
990        BatchIncrement(usize),
991        SpawnTask,
992    }
993
994    impl From<Event> for CounterMsg {
995        fn from(event: Event) -> Self {
996            match event {
997                Event::Key(k) if k.code == KeyCode::Char('+') => CounterMsg::Increment,
998                Event::Key(k) if k.code == KeyCode::Char('-') => CounterMsg::Decrement,
999                Event::Key(k) if k.code == KeyCode::Char('r') => CounterMsg::Reset,
1000                Event::Key(k) if k.code == KeyCode::Char('q') => CounterMsg::Quit,
1001                Event::Tick => CounterMsg::Increment,
1002                _ => CounterMsg::Increment,
1003            }
1004        }
1005    }
1006
1007    impl Model for Counter {
1008        type Message = CounterMsg;
1009
1010        fn init(&mut self) -> Cmd<Self::Message> {
1011            self.initialized = true;
1012            Cmd::none()
1013        }
1014
1015        fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
1016            match msg {
1017                CounterMsg::Increment => {
1018                    self.value += 1;
1019                    Cmd::none()
1020                }
1021                CounterMsg::Decrement => {
1022                    self.value -= 1;
1023                    Cmd::none()
1024                }
1025                CounterMsg::Reset => {
1026                    self.value = 0;
1027                    Cmd::none()
1028                }
1029                CounterMsg::Quit => Cmd::quit(),
1030                CounterMsg::LogValue => Cmd::log(format!("value={}", self.value)),
1031                CounterMsg::BatchIncrement(n) => {
1032                    let cmds: Vec<_> = (0..n).map(|_| Cmd::msg(CounterMsg::Increment)).collect();
1033                    Cmd::batch(cmds)
1034                }
1035                CounterMsg::SpawnTask => Cmd::task(|| CounterMsg::Increment),
1036            }
1037        }
1038
1039        fn view(&self, frame: &mut Frame) {
1040            let text = format!("Count: {}", self.value);
1041            for (i, c) in text.chars().enumerate() {
1042                if (i as u16) < frame.width() {
1043                    frame.buffer.set_raw(i as u16, 0, Cell::from_char(c));
1044                }
1045            }
1046        }
1047    }
1048
1049    /// Test model that emits a new combining-mark grapheme each frame.
1050    ///
1051    /// Used to verify periodic grapheme-pool GC in `StepProgram`.
1052    struct GraphemeChurn {
1053        value: u32,
1054    }
1055
1056    impl Model for GraphemeChurn {
1057        type Message = CounterMsg;
1058
1059        fn init(&mut self) -> Cmd<Self::Message> {
1060            Cmd::none()
1061        }
1062
1063        fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
1064            if let CounterMsg::Increment = msg {
1065                self.value = self.value.wrapping_add(1);
1066            }
1067            Cmd::none()
1068        }
1069
1070        fn view(&self, frame: &mut Frame) {
1071            let base = char::from_u32(0x4e00 + (self.value % 2048)).unwrap_or('字');
1072            let text = format!("{base}\u{0301}");
1073            frame.print_text(0, 0, &text, Cell::default());
1074        }
1075    }
1076
1077    fn key_event(c: char) -> Event {
1078        Event::Key(KeyEvent {
1079            code: KeyCode::Char(c),
1080            modifiers: Modifiers::empty(),
1081            kind: KeyEventKind::Press,
1082        })
1083    }
1084
1085    fn new_counter(value: i32) -> Counter {
1086        Counter {
1087            value,
1088            initialized: false,
1089        }
1090    }
1091
1092    fn new_grapheme_churn() -> GraphemeChurn {
1093        GraphemeChurn { value: 0 }
1094    }
1095
1096    // ---- Construction and lifecycle ----
1097
1098    #[test]
1099    fn new_creates_uninitialized_program() {
1100        let prog = StepProgram::new(new_counter(0), 80, 24);
1101        assert!(!prog.is_initialized());
1102        assert!(prog.is_running());
1103        assert_eq!(prog.size(), (80, 24));
1104        assert_eq!(prog.frame_idx(), 0);
1105        assert!(prog.tick_rate().is_none());
1106    }
1107
1108    #[test]
1109    fn new_clamps_zero_dimensions_to_minimum() {
1110        let prog = StepProgram::new(new_counter(0), 0, 0);
1111        assert_eq!(prog.size(), (1, 1));
1112    }
1113
1114    #[test]
1115    fn with_backend_clamps_zero_dimensions_to_minimum() {
1116        let backend = WebBackend::new(0, 0);
1117        let prog = StepProgram::with_backend(new_counter(0), backend);
1118        assert_eq!(prog.size(), (1, 1));
1119    }
1120
1121    #[test]
1122    fn init_initializes_model_and_renders_first_frame() {
1123        let mut prog = StepProgram::new(new_counter(0), 80, 24);
1124        prog.init().unwrap();
1125
1126        assert!(prog.is_initialized());
1127        assert!(prog.model().initialized);
1128        assert_eq!(prog.frame_idx(), 1); // First frame rendered.
1129
1130        let outputs = prog.outputs();
1131        assert!(outputs.last_buffer.is_some());
1132        assert!(outputs.last_full_repaint_hint); // First frame is full repaint.
1133        assert_eq!(outputs.last_patches.len(), 1);
1134        let stats = outputs
1135            .last_patch_stats
1136            .expect("patch stats should be captured");
1137        assert_eq!(stats.patch_count, 1);
1138        assert_eq!(stats.dirty_cells, 80 * 24);
1139    }
1140
1141    #[test]
1142    #[should_panic(expected = "init() called twice")]
1143    fn double_init_panics() {
1144        let mut prog = StepProgram::new(new_counter(0), 80, 24);
1145        prog.init().unwrap();
1146        prog.init().unwrap();
1147    }
1148
1149    #[test]
1150    #[should_panic(expected = "step() called before init()")]
1151    fn step_before_init_panics() {
1152        let mut prog = StepProgram::new(new_counter(0), 80, 24);
1153        let _ = prog.step();
1154    }
1155
1156    // ---- Event processing ----
1157
1158    #[test]
1159    fn step_processes_pushed_events() {
1160        let mut prog = StepProgram::new(new_counter(0), 80, 24);
1161        prog.init().unwrap();
1162
1163        prog.push_event(key_event('+')).expect("key admission");
1164        prog.push_event(key_event('+')).expect("key admission");
1165        prog.push_event(key_event('+')).expect("key admission");
1166        let result = prog.step().unwrap();
1167
1168        assert!(result.running);
1169        assert!(result.rendered);
1170        assert_eq!(result.events_processed, 3);
1171        assert_eq!(prog.model().value, 3);
1172    }
1173
1174    #[test]
1175    fn step_with_no_events_does_not_render() {
1176        let mut prog = StepProgram::new(new_counter(0), 80, 24);
1177        prog.init().unwrap();
1178
1179        // Take initial outputs.
1180        prog.take_outputs();
1181
1182        let result = prog.step().unwrap();
1183        assert!(result.running);
1184        assert!(!result.rendered);
1185        assert_eq!(result.events_processed, 0);
1186    }
1187
1188    #[test]
1189    fn quit_event_stops_program() {
1190        let mut prog = StepProgram::new(new_counter(0), 80, 24);
1191        prog.init().unwrap();
1192
1193        prog.push_event(key_event('+')).expect("key admission");
1194        prog.push_event(key_event('q')).expect("quit admission");
1195        prog.push_event(key_event('+')).expect("key admission"); // Should not be processed.
1196        let paste = Event::Paste(ftui_core::event::PasteEvent::bracketed("尾巴 🦀"));
1197        prog.push_event(paste.clone()).unwrap();
1198        prog.resize(120, 40).unwrap();
1199        let result = prog.step().unwrap();
1200
1201        assert!(!result.running);
1202        assert!(!result.rendered);
1203        assert_eq!(result.events_processed, 2);
1204        assert_eq!(result.events_pending, 3);
1205        assert!(!prog.is_running());
1206        assert_eq!(prog.model().value, 1); // Only first '+' processed.
1207        assert_eq!(prog.size(), (80, 24));
1208        assert_eq!(prog.backend.events_mut().size().unwrap(), (80, 24));
1209        assert_eq!(prog.step().unwrap().events_pending, 3);
1210        assert_eq!(
1211            prog.take_pending_events(),
1212            vec![
1213                key_event('+'),
1214                paste,
1215                Event::Resize {
1216                    width: 120,
1217                    height: 40
1218                }
1219            ]
1220        );
1221        assert_eq!(prog.pending_events(), 0);
1222        assert_eq!(prog.backend.events.queued_payload_bytes(), 0);
1223        assert!(prog.take_pending_events().is_empty());
1224        assert_eq!(prog.model().value, 1);
1225    }
1226
1227    #[test]
1228    fn step_after_quit_returns_immediately() {
1229        let mut prog = StepProgram::new(new_counter(0), 80, 24);
1230        prog.init().unwrap();
1231
1232        prog.push_event(key_event('q')).expect("quit admission");
1233        prog.step().unwrap();
1234
1235        // Stopped programs reject new input and geometry changes.
1236        assert_eq!(
1237            prog.push_event(key_event('+')),
1238            Err(WebBackendError::Unsupported("program has stopped"))
1239        );
1240        assert_eq!(
1241            prog.resize(120, 40),
1242            Err(WebBackendError::Unsupported("program has stopped"))
1243        );
1244        assert_eq!(prog.size(), (80, 24));
1245        let result = prog.step().unwrap();
1246        assert!(!result.running);
1247        assert!(!result.rendered);
1248        assert_eq!(result.events_processed, 0);
1249        assert_eq!(prog.model().value, 0);
1250    }
1251
1252    // ---- Resize ----
1253
1254    #[test]
1255    fn rejected_resize_preserves_geometry_and_accepted_input_until_recovery() {
1256        let mut prog = StepProgram::new(new_counter(0), 80, 24);
1257        prog.init().unwrap();
1258        for _ in 0..crate::WebEventSource::MAX_EVENTS {
1259            prog.push_event(key_event('+')).unwrap();
1260        }
1261        assert!(matches!(
1262            prog.resize(120, 40),
1263            Err(WebBackendError::InputQueueFull {
1264                limit: crate::WebInputLimit::Events,
1265                event: Event::Resize {
1266                    width: 120,
1267                    height: 40
1268                },
1269            })
1270        ));
1271        assert_eq!(prog.backend.events_mut().size().unwrap(), (80, 24));
1272        assert_eq!(prog.size(), (80, 24));
1273        let result = prog.step().unwrap();
1274        assert_eq!(
1275            result.events_processed as usize,
1276            crate::WebEventSource::MAX_EVENTS
1277        );
1278        assert_eq!(
1279            prog.model().value as usize,
1280            crate::WebEventSource::MAX_EVENTS
1281        );
1282        assert_eq!(prog.size(), (80, 24));
1283        prog.resize(120, 40).unwrap();
1284        assert_eq!(prog.step().unwrap().events_processed, 1);
1285        assert_eq!(prog.size(), (120, 40));
1286        assert_eq!(prog.backend.events_mut().size().unwrap(), (120, 40));
1287    }
1288
1289    #[test]
1290    fn resize_updates_dimensions() {
1291        let mut prog = StepProgram::new(new_counter(0), 80, 24);
1292        prog.init().unwrap();
1293
1294        prog.resize(120, 40).expect("resize admission");
1295        prog.step().unwrap();
1296
1297        assert_eq!(prog.size(), (120, 40));
1298    }
1299
1300    #[test]
1301    fn resize_clamps_zero_dimensions_to_minimum() {
1302        let mut prog = StepProgram::new(new_counter(0), 80, 24);
1303        prog.init().unwrap();
1304
1305        prog.resize(0, 0).expect("resize admission");
1306        prog.step().unwrap();
1307
1308        assert_eq!(prog.size(), (1, 1));
1309        let outputs = prog.outputs();
1310        let buf = outputs.last_buffer.as_ref().expect("resize should render");
1311        assert_eq!(buf.width(), 1);
1312        assert_eq!(buf.height(), 1);
1313    }
1314
1315    #[test]
1316    fn resize_produces_correctly_sized_buffer() {
1317        let mut prog = StepProgram::new(new_counter(42), 80, 24);
1318        prog.init().unwrap();
1319
1320        prog.resize(40, 10).expect("resize admission");
1321        prog.step().unwrap();
1322
1323        let outputs = prog.outputs();
1324        let buf = outputs.last_buffer.as_ref().unwrap();
1325        assert_eq!(buf.width(), 40);
1326        assert_eq!(buf.height(), 10);
1327    }
1328
1329    #[test]
1330    fn resize_emits_baseline_reset_and_full_repaint_markers() {
1331        let mut prog = StepProgram::new(new_counter(0), 80, 24);
1332        prog.init().unwrap();
1333        let _ = prog.take_outputs(); // discard init frame
1334
1335        prog.resize(120, 40).expect("resize admission");
1336        prog.step().unwrap();
1337
1338        let outputs = prog.outputs();
1339        assert!(
1340            outputs
1341                .logs
1342                .iter()
1343                .any(|line| line.contains(r#""event":"diff_baseline_reset""#))
1344        );
1345        assert!(
1346            outputs
1347                .logs
1348                .iter()
1349                .any(|line| line.contains(r#""event":"full_repaint_boundary""#))
1350        );
1351        assert!(
1352            outputs
1353                .logs
1354                .iter()
1355                .any(|line| line.contains(r#""from_cols":80"#) && line.contains(r#""to_cols":120"#))
1356        );
1357    }
1358
1359    #[test]
1360    fn same_size_resize_still_forces_repaint_boundary() {
1361        let mut prog = StepProgram::new(new_counter(0), 80, 24);
1362        prog.init().unwrap();
1363        let _ = prog.take_outputs(); // discard init frame
1364
1365        prog.resize(80, 24).expect("resize admission");
1366        prog.step().unwrap();
1367
1368        let outputs = prog.take_outputs();
1369        assert!(outputs.last_full_repaint_hint);
1370        assert_eq!(outputs.last_patches.len(), 1);
1371        assert_eq!(outputs.last_patches[0].offset, 0);
1372        assert_eq!(outputs.last_patches[0].cells.len(), 80usize * 24usize);
1373        assert!(outputs.logs.iter().any(|line| {
1374            line.contains(r#""event":"diff_baseline_reset""#)
1375                && line.contains(r#""from_cols":80"#)
1376                && line.contains(r#""to_cols":80"#)
1377        }));
1378        assert!(outputs.logs.iter().any(|line| {
1379            line.contains(r#""event":"full_repaint_boundary""#)
1380                && line.contains(r#""from_rows":24"#)
1381                && line.contains(r#""to_rows":24"#)
1382        }));
1383    }
1384
1385    #[test]
1386    fn resize_oscillation_forces_full_repaint_without_stale_patch_offsets() {
1387        let mut prog = StepProgram::new(new_counter(0), 80, 24);
1388        prog.init().unwrap();
1389        let _ = prog.take_outputs();
1390
1391        for (w, h) in [(120, 40), (80, 24), (120, 40), (80, 24)] {
1392            prog.resize(w, h).expect("resize admission");
1393            prog.step().unwrap();
1394
1395            let outputs = prog.take_outputs();
1396            assert!(outputs.last_full_repaint_hint);
1397
1398            let buf = outputs
1399                .last_buffer
1400                .expect("resize render should produce a buffer");
1401            assert_eq!(buf.width(), w);
1402            assert_eq!(buf.height(), h);
1403
1404            let max_cells = usize::from(w) * usize::from(h);
1405            assert_eq!(outputs.last_patches.len(), 1);
1406            let run = &outputs.last_patches[0];
1407            assert_eq!(run.offset, 0);
1408            assert_eq!(run.cells.len(), max_cells);
1409            assert!(run.offset as usize + run.cells.len() <= max_cells);
1410        }
1411    }
1412
1413    #[test]
1414    fn resize_boundary_full_repaint_then_incremental_diff_resume() {
1415        let mut prog = StepProgram::new(new_counter(0), 80, 24);
1416        prog.init().unwrap();
1417        let _ = prog.take_outputs();
1418
1419        prog.resize(100, 30).expect("resize admission");
1420        prog.step().unwrap();
1421        let after_resize = prog.take_outputs();
1422        assert!(after_resize.last_full_repaint_hint);
1423
1424        prog.push_event(key_event('+')).expect("key admission");
1425        prog.step().unwrap();
1426        let after_increment = prog.take_outputs();
1427        assert!(!after_increment.last_full_repaint_hint);
1428        assert!(!after_increment.last_patches.is_empty());
1429    }
1430
1431    // ---- Tick handling ----
1432
1433    #[test]
1434    fn tick_fires_when_rate_elapsed() {
1435        let mut prog = StepProgram::new(new_counter(0), 80, 24);
1436        prog.init().unwrap();
1437
1438        // Schedule tick at 100ms intervals.
1439        // Will map to Increment, but we use send for ScheduleTick.
1440        prog.push_event(key_event('+')).expect("key admission");
1441        prog.step().unwrap();
1442
1443        // Manually set tick rate (since our test model doesn't emit ScheduleTick from events).
1444        prog.model_mut().value = 0;
1445        // Directly use the Cmd to schedule ticks through a dedicated message.
1446        prog.execute_cmd(Cmd::tick(Duration::from_millis(100)));
1447        prog.dirty = false; // Reset dirty so we can detect tick-triggered renders.
1448
1449        // Advance less than tick rate — no tick.
1450        prog.advance_time(Duration::from_millis(50));
1451        let result = prog.step().unwrap();
1452        assert_eq!(prog.model().value, 0);
1453        assert!(!result.rendered);
1454
1455        // Advance past tick rate — tick fires.
1456        prog.advance_time(Duration::from_millis(60));
1457        let result = prog.step().unwrap();
1458        assert_eq!(prog.model().value, 1); // Tick -> Increment.
1459        assert!(result.rendered);
1460    }
1461
1462    #[test]
1463    fn tick_uses_deterministic_clock() {
1464        let mut prog = StepProgram::new(new_counter(0), 80, 24);
1465        prog.init().unwrap();
1466        prog.execute_cmd(Cmd::tick(Duration::from_millis(100)));
1467
1468        // Set absolute time to trigger tick.
1469        prog.set_time(Duration::from_millis(200));
1470        prog.step().unwrap();
1471        assert_eq!(prog.model().value, 1);
1472
1473        // Advance to next tick boundary.
1474        prog.set_time(Duration::from_millis(350));
1475        prog.step().unwrap();
1476        assert_eq!(prog.model().value, 2);
1477    }
1478
1479    // ---- Command execution ----
1480
1481    #[test]
1482    fn log_command_captures_to_presenter() {
1483        let mut prog = StepProgram::new(new_counter(5), 80, 24);
1484        prog.init().unwrap();
1485
1486        // LogValue emits Cmd::log("value=5").
1487        prog.execute_cmd(Cmd::msg(CounterMsg::LogValue));
1488
1489        let outputs = prog.outputs();
1490        assert_eq!(outputs.logs, vec!["value=5"]);
1491    }
1492
1493    #[test]
1494    fn log_modes_capture_policy_text_without_terminal_formatting() {
1495        let mut prog = StepProgram::new(new_counter(0), 80, 24);
1496        prog.init().unwrap();
1497        let payload = "a\x1b[31mb\x1b[2Jc\x1b]0;secret\x07d\n";
1498        prog.execute_cmd(Cmd::sequence(vec![
1499            Cmd::log(payload),
1500            Cmd::log_sgr_only(payload),
1501            Cmd::log_raw(payload),
1502            Cmd::quit(),
1503            Cmd::log("unreachable"),
1504        ]));
1505        assert!(!prog.is_running());
1506        assert_eq!(prog.outputs().logs, ["abcd\n", "a\x1b[31mbcd\n", payload]);
1507    }
1508
1509    #[test]
1510    fn batch_command_executes_all() {
1511        let mut prog = StepProgram::new(new_counter(0), 80, 24);
1512        prog.init().unwrap();
1513
1514        prog.execute_cmd(Cmd::msg(CounterMsg::BatchIncrement(5)));
1515        assert_eq!(prog.model().value, 5);
1516    }
1517
1518    #[test]
1519    fn task_executes_synchronously() {
1520        let mut prog = StepProgram::new(new_counter(0), 80, 24);
1521        prog.init().unwrap();
1522
1523        prog.execute_cmd(Cmd::msg(CounterMsg::SpawnTask));
1524        assert_eq!(prog.model().value, 1); // Task returns Increment.
1525    }
1526
1527    #[test]
1528    fn set_mouse_capture_updates_features() {
1529        let mut prog = StepProgram::new(new_counter(0), 80, 24);
1530        prog.init().unwrap();
1531
1532        prog.execute_cmd(Cmd::set_mouse_capture(true));
1533        assert!(prog.backend().events.features().mouse_capture);
1534
1535        prog.execute_cmd(Cmd::set_mouse_capture(false));
1536        assert!(!prog.backend().events.features().mouse_capture);
1537    }
1538
1539    // ---- Rendering ----
1540
1541    #[test]
1542    fn rendered_buffer_reflects_model_state() {
1543        let mut prog = StepProgram::new(new_counter(42), 80, 24);
1544        prog.init().unwrap();
1545
1546        let outputs = prog.outputs();
1547        let buf = outputs.last_buffer.as_ref().unwrap();
1548
1549        // "Count: 42"
1550        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('C'));
1551        assert_eq!(buf.get(7, 0).unwrap().content.as_char(), Some('4'));
1552        assert_eq!(buf.get(8, 0).unwrap().content.as_char(), Some('2'));
1553    }
1554
1555    #[test]
1556    fn subsequent_renders_produce_diffs() {
1557        let mut prog = StepProgram::new(new_counter(0), 80, 24);
1558        prog.init().unwrap();
1559
1560        // First frame is full repaint.
1561        let outputs = prog.take_outputs();
1562        assert!(outputs.last_full_repaint_hint);
1563
1564        // Second frame after an event should not be full repaint.
1565        prog.push_event(key_event('+')).expect("key admission");
1566        prog.step().unwrap();
1567
1568        let outputs = prog.outputs();
1569        assert!(!outputs.last_full_repaint_hint);
1570        assert!(!outputs.last_patches.is_empty());
1571        let stats = outputs
1572            .last_patch_stats
1573            .expect("patch stats should be captured");
1574        assert!(stats.patch_count >= 1);
1575        assert!(stats.dirty_cells >= 1);
1576    }
1577
1578    #[test]
1579    fn take_outputs_clears_state() {
1580        let mut prog = StepProgram::new(new_counter(0), 80, 24);
1581        prog.init().unwrap();
1582
1583        let outputs = prog.take_outputs();
1584        assert!(outputs.last_buffer.is_some());
1585
1586        // After take, outputs should be empty.
1587        let outputs = prog.outputs();
1588        assert!(outputs.last_buffer.is_none());
1589        assert!(outputs.logs.is_empty());
1590    }
1591
1592    // ---- Determinism ----
1593
1594    #[test]
1595    fn identical_inputs_produce_identical_outputs() {
1596        fn run_scenario() -> (i32, u64, Vec<Option<char>>) {
1597            let mut prog = StepProgram::new(new_counter(0), 20, 1);
1598            prog.init().unwrap();
1599
1600            prog.push_event(key_event('+')).expect("key admission");
1601            prog.push_event(key_event('+')).expect("key admission");
1602            prog.push_event(key_event('-')).expect("key admission");
1603            prog.push_event(key_event('+')).expect("key admission");
1604            prog.step().unwrap();
1605
1606            let outputs = prog.outputs();
1607            let buf = outputs.last_buffer.as_ref().unwrap();
1608            let chars: Vec<Option<char>> = (0..20)
1609                .map(|x| buf.get(x, 0).and_then(|c| c.content.as_char()))
1610                .collect();
1611
1612            (prog.model().value, prog.frame_idx(), chars)
1613        }
1614
1615        let (v1, f1, c1) = run_scenario();
1616        let (v2, f2, c2) = run_scenario();
1617        let (v3, f3, c3) = run_scenario();
1618
1619        assert_eq!(v1, v2);
1620        assert_eq!(v2, v3);
1621        assert_eq!(v1, 2); // +1+1-1+1 = 2
1622        assert_eq!(f1, f2);
1623        assert_eq!(f2, f3);
1624        assert_eq!(c1, c2);
1625        assert_eq!(c2, c3);
1626    }
1627
1628    // ---- with_backend constructor ----
1629
1630    #[test]
1631    fn with_backend_uses_provided_backend() {
1632        let mut backend = WebBackend::new(100, 50);
1633        backend.clock_mut().set(Duration::from_secs(10));
1634
1635        let prog = StepProgram::with_backend(new_counter(0), backend);
1636        assert_eq!(prog.size(), (100, 50));
1637    }
1638
1639    // ---- Multi-step scenario ----
1640
1641    #[test]
1642    fn multi_step_interaction() {
1643        let mut prog = StepProgram::new(new_counter(0), 80, 24);
1644        prog.init().unwrap();
1645
1646        // Frame 1: increment twice.
1647        prog.push_event(key_event('+')).expect("key admission");
1648        prog.push_event(key_event('+')).expect("key admission");
1649        let r1 = prog.step().unwrap();
1650        assert_eq!(r1.events_processed, 2);
1651        assert!(r1.rendered);
1652        assert_eq!(prog.model().value, 2);
1653
1654        // Frame 2: decrement once.
1655        prog.push_event(key_event('-')).expect("key admission");
1656        let r2 = prog.step().unwrap();
1657        assert_eq!(r2.events_processed, 1);
1658        assert_eq!(prog.model().value, 1);
1659
1660        // Frame 3: no events.
1661        let r3 = prog.step().unwrap();
1662        assert_eq!(r3.events_processed, 0);
1663        assert!(!r3.rendered);
1664
1665        // Frame indices are monotonic.
1666        assert!(r2.frame_idx > r1.frame_idx);
1667        assert_eq!(r3.frame_idx, r2.frame_idx); // No render, same index.
1668    }
1669
1670    #[test]
1671    fn periodic_pool_gc_bounds_grapheme_growth() {
1672        let mut prog = StepProgram::new(new_grapheme_churn(), 8, 1);
1673        prog.init().unwrap();
1674        prog.execute_cmd(Cmd::tick(Duration::from_millis(1)));
1675
1676        let mut peak_pool_len = prog.pool().len();
1677        for _ in 0..2000 {
1678            prog.advance_time(Duration::from_millis(1));
1679            let _ = prog.step().unwrap();
1680            peak_pool_len = peak_pool_len.max(prog.pool().len());
1681        }
1682
1683        let final_pool_len = prog.pool().len();
1684        assert!(
1685            peak_pool_len <= (POOL_GC_INTERVAL_FRAMES as usize).saturating_add(2),
1686            "peak grapheme pool length should stay bounded by GC interval (peak={peak_pool_len})"
1687        );
1688        assert!(
1689            final_pool_len <= (POOL_GC_INTERVAL_FRAMES as usize).saturating_add(2),
1690            "final grapheme pool length should stay bounded by GC interval (final={final_pool_len})"
1691        );
1692    }
1693}