Skip to main content

ftui_runtime/
simulator.rs

1#![forbid(unsafe_code)]
2
3//! Deterministic program simulator for testing.
4//!
5//! `ProgramSimulator` runs a [`Model`] without a real terminal, enabling
6//! deterministic snapshot testing, event injection, and frame capture.
7//!
8//! # Example
9//!
10//! ```ignore
11//! use ftui_runtime::simulator::ProgramSimulator;
12//!
13//! let mut sim = ProgramSimulator::new(Counter { value: 0 });
14//! sim.init();
15//! sim.send(Msg::Increment);
16//! assert_eq!(sim.model().value, 1);
17//!
18//! let buf = sim.capture_frame(80, 24);
19//! // Assert on buffer contents...
20//! ```
21
22use crate::program::{ClipboardRequest, Cmd, Model};
23use crate::state_persistence::StateRegistry;
24use crate::subscription::SubId;
25use ftui_core::event::Event;
26use ftui_render::buffer::Buffer;
27use ftui_render::frame::Frame;
28use ftui_render::grapheme_pool::GraphemePool;
29use ftui_render::sanitize::{SanitizeMode, sanitize_with};
30use std::sync::Arc;
31use std::time::Duration;
32
33/// Deterministic simulator operation error.
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub enum SimulatorError {
36    /// The simulator is no longer accepting updates.
37    NotRunning,
38    /// A message targeted a subscription the model does not currently declare.
39    InactiveSubscription(SubId),
40}
41
42impl std::fmt::Display for SimulatorError {
43    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        match self {
45            Self::NotRunning => write!(f, "simulator is not running"),
46            Self::InactiveSubscription(id) => {
47                write!(f, "subscription {id} is not active")
48            }
49        }
50    }
51}
52
53impl std::error::Error for SimulatorError {}
54
55/// Record of a command that was executed during simulation.
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub enum CmdRecord {
58    /// No-op command.
59    None,
60    /// Quit command.
61    Quit,
62    /// Message sent to model (not stored, just noted).
63    Msg,
64    /// Batch of commands.
65    Batch(usize),
66    /// Sequence of commands.
67    Sequence(usize),
68    /// Tick scheduled.
69    Tick(Duration),
70    /// Log message after applying its policy, without terminal line formatting.
71    Log { text: String, mode: SanitizeMode },
72    /// Background task executed synchronously.
73    Task,
74    /// Mouse capture toggle (no-op in simulator).
75    MouseCapture(bool),
76    /// Clipboard effect captured without accessing an external clipboard.
77    Clipboard(ClipboardRequest),
78    /// Widget state save requested (`Cmd::SaveState`).
79    SaveState,
80    /// Widget state restore requested (`Cmd::RestoreState`).
81    RestoreState,
82    /// Runtime tick strategy updated (`Cmd::SetTickStrategy`), carrying the strategy name.
83    SetTickStrategy(String),
84    /// Error delivered to `Model::on_error`.
85    Error(String),
86    /// One-shot model/runtime shutdown.
87    Shutdown,
88}
89
90/// Deterministic simulator for [`Model`] testing.
91///
92/// Runs model logic without any terminal or IO dependencies. Events can be
93/// injected, messages sent directly, and frames captured for snapshot testing.
94pub struct ProgramSimulator<M: Model> {
95    /// The application model.
96    model: M,
97    /// Grapheme pool for frame creation.
98    pool: GraphemePool,
99    /// Captured frame buffers.
100    frames: Vec<Buffer>,
101    /// Record of all executed commands.
102    command_log: Vec<CmdRecord>,
103    /// Whether the simulated program is still running.
104    running: bool,
105    /// Whether `Model::init` has already run.
106    initialized: bool,
107    /// Whether `Model::on_shutdown` has already run.
108    shutdown_complete: bool,
109    /// Whether an error hook is currently executing.
110    handling_error: bool,
111    /// Current tick rate (if any).
112    tick_rate: Option<Duration>,
113    /// Deterministic monotonic simulator time.
114    now: Duration,
115    /// Next scheduled tick at the injected simulator clock.
116    next_tick_at: Option<Duration>,
117    /// Monotonic tick counter for tick-strategy dispatch.
118    tick_count: u64,
119    /// Optional tick strategy for selective background screen ticking.
120    tick_strategy: Option<Box<dyn crate::tick_strategy::TickStrategy>>,
121    /// Last active screen observed by the tick strategy dispatch path.
122    last_active_screen_for_strategy: Option<String>,
123    /// Declarative subscription IDs from the last reconciliation.
124    active_subscriptions: Vec<SubId>,
125    /// Log messages emitted via Cmd::Log.
126    logs: Vec<String>,
127    clipboard_requests: Vec<ClipboardRequest>,
128    /// Errors delivered through `Model::on_error`.
129    errors: Vec<String>,
130    /// Optional state registry for persistence integration.
131    state_registry: Option<Arc<StateRegistry>>,
132}
133
134impl<M: Model> ProgramSimulator<M> {
135    /// Create a new simulator with the given model.
136    ///
137    /// The model is not initialized until [`init`](Self::init) is called.
138    pub fn new(model: M) -> Self {
139        Self {
140            model,
141            pool: GraphemePool::new(),
142            frames: Vec::new(),
143            command_log: Vec::new(),
144            running: true,
145            initialized: false,
146            shutdown_complete: false,
147            handling_error: false,
148            tick_rate: None,
149            now: Duration::ZERO,
150            next_tick_at: None,
151            tick_count: 0,
152            tick_strategy: None,
153            last_active_screen_for_strategy: None,
154            active_subscriptions: Vec::new(),
155            logs: Vec::new(),
156            clipboard_requests: Vec::new(),
157            errors: Vec::new(),
158            state_registry: None,
159        }
160    }
161
162    /// Create a new simulator with the given model and persistence registry.
163    ///
164    /// When provided, `Cmd::SaveState`/`Cmd::RestoreState` will flush/load
165    /// through the registry, mirroring runtime behavior.
166    pub fn with_registry(model: M, registry: Arc<StateRegistry>) -> Self {
167        let mut sim = Self::new(model);
168        sim.state_registry = Some(registry);
169        sim
170    }
171
172    /// Attach a [`TickStrategy`](crate::tick_strategy::TickStrategy) for selective per-screen tick dispatch.
173    #[must_use]
174    pub fn with_tick_strategy(
175        mut self,
176        strategy: impl crate::tick_strategy::TickStrategy + 'static,
177    ) -> Self {
178        self.tick_strategy = Some(Box::new(strategy));
179        self.last_active_screen_for_strategy = None;
180        self
181    }
182
183    /// Name of the active tick strategy, if one is configured.
184    #[must_use]
185    pub fn tick_strategy_name(&self) -> Option<&str> {
186        self.tick_strategy
187            .as_deref()
188            .map(crate::tick_strategy::TickStrategy::name)
189    }
190
191    /// Initialize the model once and execute its startup commands.
192    ///
193    /// Should be called once before injecting events or capturing frames.
194    pub fn init(&mut self) {
195        if self.initialized || self.shutdown_complete {
196            return;
197        }
198        self.initialized = true;
199        let cmd = self.model.init();
200        self.execute_cmd(cmd);
201        self.poll_subscriptions();
202        self.check_screen_transition();
203    }
204
205    /// Inject terminal events into the model.
206    ///
207    /// Each event is converted to a message via `From<Event>` and dispatched
208    /// through `Model::update()`. Commands returned from update are executed.
209    pub fn inject_events(&mut self, events: &[Event]) {
210        for event in events {
211            if !self.running {
212                break;
213            }
214            let msg = M::Message::from(event.clone());
215            let cmd = self.model.update(msg);
216            self.execute_cmd(cmd);
217            self.poll_subscriptions();
218            self.check_screen_transition();
219        }
220    }
221
222    /// Inject a single terminal event into the model.
223    ///
224    /// The event is converted to a message via `From<Event>` and dispatched
225    /// through `Model::update()`. Commands returned from update are executed.
226    pub fn inject_event(&mut self, event: Event) {
227        self.inject_events(&[event]);
228    }
229
230    /// Send a specific message to the model.
231    ///
232    /// The message is dispatched through `Model::update()` and returned
233    /// commands are executed.
234    pub fn send(&mut self, msg: M::Message) {
235        if !self.running {
236            return;
237        }
238        let cmd = self.model.update(msg);
239        self.execute_cmd(cmd);
240        self.poll_subscriptions();
241        self.check_screen_transition();
242    }
243
244    /// Current deterministic monotonic simulator time.
245    #[inline]
246    pub fn now(&self) -> Duration {
247        self.now
248    }
249
250    /// Advance deterministic time and deliver every scheduled tick now due.
251    ///
252    /// Positive tick intervals are delivered at their exact deadlines. A zero
253    /// interval remains manually driven to avoid an unbounded loop.
254    pub fn advance_time(&mut self, delta: Duration) -> usize {
255        let target = self.now.saturating_add(delta);
256        let mut delivered = 0_usize;
257
258        while self.running {
259            let Some(due) = self.next_tick_at else {
260                break;
261            };
262            if due > target {
263                break;
264            }
265
266            self.now = due;
267            self.next_tick_at = self
268                .tick_rate
269                .filter(|rate| !rate.is_zero())
270                .and_then(|rate| due.checked_add(rate));
271            self.tick();
272            delivered = delivered.saturating_add(1);
273        }
274
275        self.now = target;
276        delivered
277    }
278
279    /// Deliver one tick immediately without advancing deterministic time.
280    pub fn tick(&mut self) {
281        if !self.running {
282            return;
283        }
284        self.tick_count = self.tick_count.wrapping_add(1);
285        let tick_count = self.tick_count;
286        let mut used_screen_dispatch = false;
287
288        if let Some(strategy) = self.tick_strategy.as_mut() {
289            let dispatch_snapshot = self.model.as_screen_tick_dispatch().map(|dispatch| {
290                let active = dispatch.active_screen_id();
291                let all_screens = dispatch.screen_ids();
292                (active, all_screens)
293            });
294
295            if let Some((active, all_screens)) = dispatch_snapshot {
296                used_screen_dispatch = true;
297                if let Some(previous_active) = self.last_active_screen_for_strategy.as_deref()
298                    && previous_active != active
299                {
300                    strategy.on_screen_transition(previous_active, &active);
301                }
302                self.last_active_screen_for_strategy = Some(active.clone());
303
304                let mut tick_targets = Vec::with_capacity(all_screens.len().max(1));
305                tick_targets.push(active.clone());
306                for screen_id in all_screens {
307                    if screen_id != active
308                        && strategy.should_tick(&screen_id, tick_count, &active)
309                            == crate::tick_strategy::TickDecision::Tick
310                    {
311                        tick_targets.push(screen_id);
312                    }
313                }
314                if let Some(dispatch) = self.model.as_screen_tick_dispatch() {
315                    for screen_id in &tick_targets {
316                        dispatch.tick_screen(screen_id, tick_count);
317                    }
318                }
319                strategy.maintenance_tick(tick_count);
320            }
321        }
322
323        if used_screen_dispatch {
324            if self.running {
325                self.poll_subscriptions();
326            }
327        } else {
328            self.last_active_screen_for_strategy = None;
329            self.send(M::Message::from(Event::Tick));
330        }
331    }
332
333    fn check_screen_transition(&mut self) {
334        if self.tick_strategy.is_none() || !self.running {
335            return;
336        }
337        let current_active = match self.model.as_screen_tick_dispatch() {
338            Some(dispatch) => dispatch.active_screen_id(),
339            None => return,
340        };
341        let previous = match self.last_active_screen_for_strategy.take() {
342            Some(prev) => prev,
343            None => {
344                self.last_active_screen_for_strategy = Some(current_active);
345                return;
346            }
347        };
348        if previous == current_active {
349            self.last_active_screen_for_strategy = Some(current_active);
350            return;
351        }
352        if let Some(strategy) = self.tick_strategy.as_mut() {
353            strategy.on_screen_transition(&previous, &current_active);
354        }
355        if let Some(dispatch) = self.model.as_screen_tick_dispatch() {
356            dispatch.tick_screen(&current_active, self.tick_count);
357            if self.running {
358                self.poll_subscriptions();
359            }
360        }
361        self.last_active_screen_for_strategy = Some(current_active);
362    }
363
364    /// Reconcile the model's declarative subscriptions without starting
365    /// background threads.
366    ///
367    /// Tests explicitly deliver subscription messages with
368    /// [`deliver_subscription`](Self::deliver_subscription), keeping ordering
369    /// and time fully deterministic.
370    pub fn poll_subscriptions(&mut self) -> &[SubId] {
371        if self.shutdown_complete {
372            self.active_subscriptions.clear();
373            return &self.active_subscriptions;
374        }
375
376        let mut ids: Vec<_> = self
377            .model
378            .subscriptions()
379            .into_iter()
380            .map(|subscription| subscription.id())
381            .collect();
382        ids.sort_unstable();
383        ids.dedup();
384        self.active_subscriptions = ids;
385        &self.active_subscriptions
386    }
387
388    /// IDs of subscriptions active at the last deterministic reconciliation.
389    #[inline]
390    pub fn active_subscription_ids(&self) -> &[SubId] {
391        &self.active_subscriptions
392    }
393
394    /// Deliver one message from an active declarative subscription.
395    pub fn deliver_subscription(
396        &mut self,
397        id: SubId,
398        msg: M::Message,
399    ) -> Result<(), SimulatorError> {
400        if !self.running {
401            return Err(SimulatorError::NotRunning);
402        }
403        if !self.active_subscriptions.contains(&id) {
404            let error = SimulatorError::InactiveSubscription(id);
405            self.report_error(error.to_string());
406            return Err(error);
407        }
408
409        let cmd = self.model.update(msg);
410        self.execute_cmd(cmd);
411        self.check_screen_transition();
412        self.poll_subscriptions();
413        Ok(())
414    }
415
416    /// Inject a runtime error through `Model::on_error`.
417    pub fn report_error(&mut self, error: impl Into<String>) {
418        let error = error.into();
419        self.errors.push(error.clone());
420        self.command_log.push(CmdRecord::Error(error.clone()));
421
422        if self.handling_error || self.shutdown_complete {
423            return;
424        }
425
426        self.handling_error = true;
427        let cmd = self.model.on_error(&error);
428        self.execute_lifecycle_cmd(cmd);
429        self.handling_error = false;
430        self.poll_subscriptions();
431    }
432
433    /// Cancel the simulated runtime and complete shutdown exactly once.
434    pub fn cancel(&mut self) {
435        self.running = false;
436        self.shutdown();
437    }
438
439    /// Run `Model::on_shutdown` and clear simulated subscriptions exactly once.
440    pub fn shutdown(&mut self) {
441        if self.shutdown_complete {
442            return;
443        }
444        self.shutdown_complete = true;
445        self.running = false;
446        self.command_log.push(CmdRecord::Shutdown);
447        if let Some(ref mut strategy) = self.tick_strategy {
448            strategy.shutdown();
449        }
450        let cmd = self.model.on_shutdown();
451        self.execute_lifecycle_cmd(cmd);
452        self.active_subscriptions.clear();
453    }
454
455    /// Whether the one-shot shutdown contract has completed.
456    #[inline]
457    pub fn is_shutdown(&self) -> bool {
458        self.shutdown_complete
459    }
460
461    /// Errors delivered through `Model::on_error`.
462    #[inline]
463    pub fn errors(&self) -> &[String] {
464        &self.errors
465    }
466
467    /// Capture the current frame at the given dimensions.
468    ///
469    /// Calls `Model::view()` to render into a fresh buffer and stores the
470    /// result. Returns a reference to the captured buffer.
471    pub fn capture_frame(&mut self, width: u16, height: u16) -> &Buffer {
472        let mut frame = Frame::new(width, height, &mut self.pool);
473        self.model.view(&mut frame);
474        self.frames.push(frame.buffer);
475        self.frames.last().expect("frame just pushed")
476    }
477
478    /// Get all captured frame buffers.
479    pub fn frames(&self) -> &[Buffer] {
480        &self.frames
481    }
482
483    /// Get the most recently captured frame buffer, if any.
484    pub fn last_frame(&self) -> Option<&Buffer> {
485        self.frames.last()
486    }
487
488    /// Get the number of captured frames.
489    pub fn frame_count(&self) -> usize {
490        self.frames.len()
491    }
492
493    /// Get a reference to the model.
494    #[inline]
495    pub fn model(&self) -> &M {
496        &self.model
497    }
498
499    /// Get a mutable reference to the model.
500    #[inline]
501    pub fn model_mut(&mut self) -> &mut M {
502        &mut self.model
503    }
504
505    /// Access the simulator grapheme pool used to render captured frames.
506    #[inline]
507    pub fn pool(&self) -> &GraphemePool {
508        &self.pool
509    }
510
511    /// Check if the simulated program is still running.
512    ///
513    /// Returns `false` after a `Cmd::Quit` has been executed.
514    #[inline]
515    pub fn is_running(&self) -> bool {
516        self.running
517    }
518
519    /// Get the current tick rate (if any).
520    #[inline]
521    pub fn tick_rate(&self) -> Option<Duration> {
522        self.tick_rate
523    }
524
525    /// Get all log messages emitted via `Cmd::Log`.
526    #[inline]
527    pub fn logs(&self) -> &[String] {
528        &self.logs
529    }
530
531    /// Clipboard commands in execution order. Replies must be injected explicitly.
532    pub fn clipboard_requests(&self) -> &[ClipboardRequest] {
533        &self.clipboard_requests
534    }
535
536    /// Get the command execution log.
537    #[inline]
538    pub fn command_log(&self) -> &[CmdRecord] {
539        &self.command_log
540    }
541
542    /// Clear all captured frames.
543    pub fn clear_frames(&mut self) {
544        self.frames.clear();
545    }
546
547    /// Clear all logs.
548    pub fn clear_logs(&mut self) {
549        self.logs.clear();
550    }
551
552    /// Execute a lifecycle command after normal message dispatch has stopped.
553    fn execute_lifecycle_cmd(&mut self, cmd: Cmd<M::Message>) {
554        let was_running = std::mem::replace(&mut self.running, true);
555        self.execute_cmd(cmd);
556        self.running = was_running && self.running;
557    }
558
559    /// Execute a command without IO.
560    ///
561    /// Cmd::Msg runs update and then its result; Cmd::Log records the text;
562    /// IO-dependent operations are simulated (no real terminal writes).
563    /// Save/Restore use the configured registry when present.
564    ///
565    /// Like `Program`, commands run depth-first from an explicit stack of
566    /// batch iterators. Running each `update` result recursively overflowed
567    /// the stack for a model that takes one step per `Cmd::Msg`.
568    fn execute_cmd(&mut self, cmd: Cmd<M::Message>) {
569        let mut batches: Vec<std::vec::IntoIter<Cmd<M::Message>>> = Vec::new();
570        let mut next = Some(cmd);
571        loop {
572            let cmd = match next.take() {
573                Some(cmd) => cmd,
574                None => {
575                    // Resume the innermost batch. A batch stops after any
576                    // command that ends the program.
577                    let Some(rest) = batches.last_mut() else {
578                        return;
579                    };
580                    if !self.running {
581                        return;
582                    }
583                    match rest.next() {
584                        Some(cmd) => cmd,
585                        None => {
586                            batches.pop();
587                            continue;
588                        }
589                    }
590                }
591            };
592            next = self.execute_one_cmd(cmd, &mut batches);
593        }
594    }
595
596    /// Execute `cmd` for [`Self::execute_cmd`], returning the command to run
597    /// next and pushing the rest of a batch onto `batches`.
598    fn execute_one_cmd(
599        &mut self,
600        cmd: Cmd<M::Message>,
601        batches: &mut Vec<std::vec::IntoIter<Cmd<M::Message>>>,
602    ) -> Option<Cmd<M::Message>> {
603        match cmd {
604            Cmd::None => {
605                self.command_log.push(CmdRecord::None);
606            }
607            Cmd::Quit => {
608                self.running = false;
609                self.command_log.push(CmdRecord::Quit);
610            }
611            Cmd::Msg(m) => {
612                self.command_log.push(CmdRecord::Msg);
613                return Some(self.model.update(m));
614            }
615            Cmd::Batch(cmds) => {
616                self.command_log.push(CmdRecord::Batch(cmds.len()));
617                let mut rest = cmds.into_iter();
618                let first = rest.next();
619                batches.push(rest);
620                return first;
621            }
622            Cmd::Sequence(cmds) => {
623                self.command_log.push(CmdRecord::Sequence(cmds.len()));
624                let mut rest = cmds.into_iter();
625                let first = rest.next();
626                batches.push(rest);
627                return first;
628            }
629            Cmd::Tick(duration) => {
630                self.tick_rate = Some(duration);
631                self.next_tick_at = if duration.is_zero() {
632                    None
633                } else {
634                    self.now.checked_add(duration)
635                };
636                self.command_log.push(CmdRecord::Tick(duration));
637            }
638            Cmd::Log { text, mode } => {
639                let text = sanitize_with(&text, mode).into_owned();
640                self.command_log.push(CmdRecord::Log {
641                    text: text.clone(),
642                    mode,
643                });
644                self.logs.push(text);
645            }
646            Cmd::SetMouseCapture(enabled) => {
647                self.command_log.push(CmdRecord::MouseCapture(enabled));
648            }
649            Cmd::SetClipboard(text) => {
650                let request = ClipboardRequest::Set(text);
651                self.command_log.push(CmdRecord::Clipboard(request.clone()));
652                self.clipboard_requests.push(request);
653            }
654            Cmd::GetClipboard => {
655                self.command_log
656                    .push(CmdRecord::Clipboard(ClipboardRequest::Get));
657                self.clipboard_requests.push(ClipboardRequest::Get);
658            }
659            Cmd::Task(_, f) => {
660                self.command_log.push(CmdRecord::Task);
661                match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
662                    Ok(msg) => {
663                        return Some(self.model.update(msg));
664                    }
665                    Err(payload) => {
666                        let error = if let Some(message) = payload.downcast_ref::<&str>() {
667                            (*message).to_owned()
668                        } else if let Some(message) = payload.downcast_ref::<String>() {
669                            message.clone()
670                        } else {
671                            "background task panicked with a non-string payload".to_owned()
672                        };
673                        self.report_error(format!("background task failed: {error}"));
674                    }
675                }
676            }
677            Cmd::SaveState => {
678                self.command_log.push(CmdRecord::SaveState);
679                let error = self
680                    .state_registry
681                    .as_ref()
682                    .and_then(|registry| registry.flush().err())
683                    .map(|error| format!("state save failed: {error}"));
684                if let Some(error) = error {
685                    self.report_error(error);
686                }
687            }
688            Cmd::RestoreState => {
689                self.command_log.push(CmdRecord::RestoreState);
690                let error = self
691                    .state_registry
692                    .as_ref()
693                    .and_then(|registry| registry.load().err())
694                    .map(|error| format!("state restore failed: {error}"));
695                if let Some(error) = error {
696                    self.report_error(error);
697                }
698            }
699            Cmd::SetTickStrategy(strategy) => {
700                let name = strategy.name().to_owned();
701                self.command_log.push(CmdRecord::SetTickStrategy(name));
702                if let Some(ref mut prev) = self.tick_strategy {
703                    prev.shutdown();
704                }
705                self.tick_strategy = Some(strategy);
706                self.last_active_screen_for_strategy = None;
707            }
708        }
709        None
710    }
711}
712
713#[cfg(test)]
714mod tests {
715    use super::*;
716    use ftui_core::event::{KeyCode, KeyEvent, KeyEventKind, Modifiers};
717    use std::cell::RefCell;
718    use std::sync::Arc;
719
720    // ---------- Test model ----------
721
722    struct Counter {
723        value: i32,
724        initialized: bool,
725    }
726
727    #[derive(Debug)]
728    enum CounterMsg {
729        Increment,
730        Decrement,
731        Reset,
732        Quit,
733        LogValue,
734        BatchIncrement(usize),
735    }
736
737    impl From<Event> for CounterMsg {
738        fn from(event: Event) -> Self {
739            match event {
740                Event::Key(k) if k.code == KeyCode::Char('+') => CounterMsg::Increment,
741                Event::Key(k) if k.code == KeyCode::Char('-') => CounterMsg::Decrement,
742                Event::Key(k) if k.code == KeyCode::Char('r') => CounterMsg::Reset,
743                Event::Key(k) if k.code == KeyCode::Char('q') => CounterMsg::Quit,
744                _ => CounterMsg::Increment,
745            }
746        }
747    }
748
749    impl Model for Counter {
750        type Message = CounterMsg;
751
752        fn init(&mut self) -> Cmd<Self::Message> {
753            self.initialized = true;
754            Cmd::none()
755        }
756
757        fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
758            match msg {
759                CounterMsg::Increment => {
760                    self.value += 1;
761                    Cmd::none()
762                }
763                CounterMsg::Decrement => {
764                    self.value -= 1;
765                    Cmd::none()
766                }
767                CounterMsg::Reset => {
768                    self.value = 0;
769                    Cmd::none()
770                }
771                CounterMsg::Quit => Cmd::quit(),
772                CounterMsg::LogValue => Cmd::log(format!("value={}", self.value)),
773                CounterMsg::BatchIncrement(n) => {
774                    let cmds: Vec<_> = (0..n).map(|_| Cmd::msg(CounterMsg::Increment)).collect();
775                    Cmd::batch(cmds)
776                }
777            }
778        }
779
780        fn view(&self, frame: &mut Frame) {
781            // Render counter value as text in the first row
782            let text = format!("Count: {}", self.value);
783            for (i, c) in text.chars().enumerate() {
784                if (i as u16) < frame.width() {
785                    use ftui_render::cell::Cell;
786                    frame.buffer.set_raw(i as u16, 0, Cell::from_char(c));
787                }
788            }
789        }
790    }
791
792    fn key_event(c: char) -> Event {
793        Event::Key(KeyEvent {
794            code: KeyCode::Char(c),
795            modifiers: Modifiers::empty(),
796            kind: KeyEventKind::Press,
797        })
798    }
799
800    fn resize_event(width: u16, height: u16) -> Event {
801        Event::Resize { width, height }
802    }
803
804    #[derive(Default)]
805    struct ResizeTracker {
806        last: Option<(u16, u16)>,
807        history: Vec<(u16, u16)>,
808    }
809
810    #[derive(Debug, Clone, Copy)]
811    enum ResizeMsg {
812        Resize(u16, u16),
813        Quit,
814        Noop,
815    }
816
817    impl From<Event> for ResizeMsg {
818        fn from(event: Event) -> Self {
819            match event {
820                Event::Resize { width, height } => Self::Resize(width, height),
821                Event::Key(k) if k.code == KeyCode::Char('q') => Self::Quit,
822                _ => Self::Noop,
823            }
824        }
825    }
826
827    impl Model for ResizeTracker {
828        type Message = ResizeMsg;
829
830        fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
831            match msg {
832                ResizeMsg::Resize(width, height) => {
833                    self.last = Some((width, height));
834                    self.history.push((width, height));
835                    Cmd::none()
836                }
837                ResizeMsg::Quit => Cmd::quit(),
838                ResizeMsg::Noop => Cmd::none(),
839            }
840        }
841
842        fn view(&self, _frame: &mut Frame) {}
843    }
844
845    #[derive(Default)]
846    struct PersistModel;
847
848    #[derive(Debug, Clone, Copy)]
849    enum PersistMsg {
850        Save,
851        Restore,
852        Noop,
853    }
854
855    impl From<Event> for PersistMsg {
856        fn from(event: Event) -> Self {
857            match event {
858                Event::Key(k) if k.code == KeyCode::Char('s') => Self::Save,
859                Event::Key(k) if k.code == KeyCode::Char('r') => Self::Restore,
860                _ => Self::Noop,
861            }
862        }
863    }
864
865    impl Model for PersistModel {
866        type Message = PersistMsg;
867
868        fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
869            match msg {
870                PersistMsg::Save => Cmd::save_state(),
871                PersistMsg::Restore => Cmd::restore_state(),
872                PersistMsg::Noop => Cmd::none(),
873            }
874        }
875
876        fn view(&self, _frame: &mut Frame) {}
877    }
878
879    // ---------- Tests ----------
880
881    #[test]
882    fn new_simulator() {
883        let sim = ProgramSimulator::new(Counter {
884            value: 0,
885            initialized: false,
886        });
887        assert!(sim.is_running());
888        assert_eq!(sim.model().value, 0);
889        assert!(!sim.model().initialized);
890        assert_eq!(sim.frame_count(), 0);
891        assert!(sim.logs().is_empty());
892    }
893
894    #[test]
895    fn clipboard_requests_preserve_order_without_fabricated_replies() {
896        let mut sim = ProgramSimulator::new(Counter {
897            value: 0,
898            initialized: false,
899        });
900        sim.init();
901        sim.execute_cmd(Cmd::sequence(vec![
902            Cmd::set_clipboard("界"),
903            Cmd::get_clipboard(),
904        ]));
905        assert_eq!(
906            sim.clipboard_requests(),
907            &[ClipboardRequest::Set("界".into()), ClipboardRequest::Get]
908        );
909        assert_eq!(sim.model().value, 0);
910        assert!(matches!(
911            sim.command_log().last(),
912            Some(CmdRecord::Clipboard(ClipboardRequest::Get))
913        ));
914    }
915
916    #[test]
917    fn init_calls_model_init() {
918        let mut sim = ProgramSimulator::new(Counter {
919            value: 0,
920            initialized: false,
921        });
922        sim.init();
923        assert!(sim.model().initialized);
924    }
925
926    #[test]
927    fn inject_events_processes_all() {
928        let mut sim = ProgramSimulator::new(Counter {
929            value: 0,
930            initialized: false,
931        });
932        sim.init();
933
934        let events = vec![key_event('+'), key_event('+'), key_event('+')];
935        sim.inject_events(&events);
936
937        assert_eq!(sim.model().value, 3);
938    }
939
940    #[test]
941    fn inject_events_stops_on_quit() {
942        let mut sim = ProgramSimulator::new(Counter {
943            value: 0,
944            initialized: false,
945        });
946        sim.init();
947
948        // Quit in the middle - subsequent events should be ignored
949        let events = vec![key_event('+'), key_event('q'), key_event('+')];
950        sim.inject_events(&events);
951
952        assert_eq!(sim.model().value, 1);
953        assert!(!sim.is_running());
954    }
955
956    #[test]
957    fn save_state_flushes_registry() {
958        use crate::state_persistence::StateRegistry;
959
960        let registry = Arc::new(StateRegistry::in_memory());
961        registry.set("viewer", 1, vec![1, 2, 3]);
962        assert!(registry.is_dirty());
963
964        let mut sim = ProgramSimulator::with_registry(PersistModel, Arc::clone(&registry));
965        sim.send(PersistMsg::Save);
966
967        assert!(!registry.is_dirty());
968        let stored = registry.get("viewer").expect("entry present");
969        assert_eq!(stored.version, 1);
970        assert_eq!(stored.data, vec![1, 2, 3]);
971    }
972
973    #[test]
974    fn restore_state_round_trips_cache() {
975        use crate::state_persistence::StateRegistry;
976
977        let registry = Arc::new(StateRegistry::in_memory());
978        registry.set("viewer", 7, vec![9, 8, 7]);
979
980        let mut sim = ProgramSimulator::with_registry(PersistModel, Arc::clone(&registry));
981        sim.send(PersistMsg::Save);
982
983        let removed = registry.remove("viewer");
984        assert!(removed.is_some());
985        assert!(registry.get("viewer").is_none());
986
987        sim.send(PersistMsg::Restore);
988        let restored = registry.get("viewer").expect("restored entry");
989        assert_eq!(restored.version, 7);
990        assert_eq!(restored.data, vec![9, 8, 7]);
991    }
992
993    #[test]
994    fn resize_events_apply_in_order() {
995        let mut sim = ProgramSimulator::new(ResizeTracker::default());
996        sim.init();
997
998        let events = vec![
999            resize_event(80, 24),
1000            resize_event(100, 40),
1001            resize_event(120, 50),
1002        ];
1003        sim.inject_events(&events);
1004
1005        assert_eq!(sim.model().history, vec![(80, 24), (100, 40), (120, 50)]);
1006        assert_eq!(sim.model().last, Some((120, 50)));
1007    }
1008
1009    #[test]
1010    fn resize_events_after_quit_are_ignored() {
1011        let mut sim = ProgramSimulator::new(ResizeTracker::default());
1012        sim.init();
1013
1014        let events = vec![resize_event(80, 24), key_event('q'), resize_event(120, 50)];
1015        sim.inject_events(&events);
1016
1017        assert!(!sim.is_running());
1018        assert_eq!(sim.model().history, vec![(80, 24)]);
1019        assert_eq!(sim.model().last, Some((80, 24)));
1020    }
1021
1022    #[test]
1023    fn send_message_directly() {
1024        let mut sim = ProgramSimulator::new(Counter {
1025            value: 0,
1026            initialized: false,
1027        });
1028        sim.init();
1029
1030        sim.send(CounterMsg::Increment);
1031        sim.send(CounterMsg::Increment);
1032        sim.send(CounterMsg::Decrement);
1033
1034        assert_eq!(sim.model().value, 1);
1035    }
1036
1037    #[test]
1038    fn capture_frame_renders_correctly() {
1039        let mut sim = ProgramSimulator::new(Counter {
1040            value: 42,
1041            initialized: false,
1042        });
1043        sim.init();
1044
1045        let buf = sim.capture_frame(80, 24);
1046
1047        // "Count: 42" should be rendered
1048        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('C'));
1049        assert_eq!(buf.get(1, 0).unwrap().content.as_char(), Some('o'));
1050        assert_eq!(buf.get(7, 0).unwrap().content.as_char(), Some('4'));
1051        assert_eq!(buf.get(8, 0).unwrap().content.as_char(), Some('2'));
1052    }
1053
1054    #[test]
1055    fn multiple_frame_captures() {
1056        let mut sim = ProgramSimulator::new(Counter {
1057            value: 0,
1058            initialized: false,
1059        });
1060        sim.init();
1061
1062        sim.capture_frame(80, 24);
1063        sim.send(CounterMsg::Increment);
1064        sim.capture_frame(80, 24);
1065
1066        assert_eq!(sim.frame_count(), 2);
1067
1068        // First frame: "Count: 0"
1069        assert_eq!(
1070            sim.frames()[0].get(7, 0).unwrap().content.as_char(),
1071            Some('0')
1072        );
1073        // Second frame: "Count: 1"
1074        assert_eq!(
1075            sim.frames()[1].get(7, 0).unwrap().content.as_char(),
1076            Some('1')
1077        );
1078    }
1079
1080    #[test]
1081    fn quit_command_stops_running() {
1082        let mut sim = ProgramSimulator::new(Counter {
1083            value: 0,
1084            initialized: false,
1085        });
1086        sim.init();
1087
1088        assert!(sim.is_running());
1089        sim.send(CounterMsg::Quit);
1090        assert!(!sim.is_running());
1091    }
1092
1093    #[test]
1094    fn log_command_records_text() {
1095        let mut sim = ProgramSimulator::new(Counter {
1096            value: 5,
1097            initialized: false,
1098        });
1099        sim.init();
1100
1101        sim.send(CounterMsg::LogValue);
1102
1103        assert_eq!(sim.logs(), &["value=5"]);
1104    }
1105
1106    #[test]
1107    fn batch_command_executes_all() {
1108        let mut sim = ProgramSimulator::new(Counter {
1109            value: 0,
1110            initialized: false,
1111        });
1112        sim.init();
1113
1114        sim.send(CounterMsg::BatchIncrement(5));
1115
1116        assert_eq!(sim.model().value, 5);
1117    }
1118
1119    #[test]
1120    fn tick_command_sets_rate() {
1121        let mut sim = ProgramSimulator::new(Counter {
1122            value: 0,
1123            initialized: false,
1124        });
1125
1126        assert!(sim.tick_rate().is_none());
1127
1128        // Manually execute a tick command through the model
1129        // We'll test by checking the internal tick_rate after setting it
1130        // via the execute_cmd path. Since Counter doesn't emit ticks,
1131        // we'll test via the command log.
1132        sim.execute_cmd(Cmd::tick(Duration::from_millis(100)));
1133
1134        assert_eq!(sim.tick_rate(), Some(Duration::from_millis(100)));
1135    }
1136
1137    #[test]
1138    fn deterministic_clock_stops_when_next_deadline_would_overflow() {
1139        let mut sim = ProgramSimulator::new(Counter {
1140            value: 0,
1141            initialized: false,
1142        });
1143        sim.execute_cmd(Cmd::tick(Duration::MAX));
1144
1145        assert_eq!(sim.advance_time(Duration::MAX), 1);
1146        assert_eq!(sim.now(), Duration::MAX);
1147        assert_eq!(sim.advance_time(Duration::ZERO), 0);
1148    }
1149
1150    #[test]
1151    fn command_log_records_all() {
1152        let mut sim = ProgramSimulator::new(Counter {
1153            value: 0,
1154            initialized: false,
1155        });
1156        sim.init();
1157
1158        sim.send(CounterMsg::Increment);
1159        sim.send(CounterMsg::Quit);
1160
1161        // init returns Cmd::None, then Increment returns Cmd::None, then Quit returns Cmd::Quit
1162        assert!(sim.command_log().len() >= 3);
1163        assert!(matches!(sim.command_log().last(), Some(CmdRecord::Quit)));
1164    }
1165
1166    #[test]
1167    fn clear_frames() {
1168        let mut sim = ProgramSimulator::new(Counter {
1169            value: 0,
1170            initialized: false,
1171        });
1172        sim.capture_frame(10, 10);
1173        sim.capture_frame(10, 10);
1174        assert_eq!(sim.frame_count(), 2);
1175
1176        sim.clear_frames();
1177        assert_eq!(sim.frame_count(), 0);
1178    }
1179
1180    #[test]
1181    fn clear_logs() {
1182        let mut sim = ProgramSimulator::new(Counter {
1183            value: 0,
1184            initialized: false,
1185        });
1186        sim.init();
1187        sim.send(CounterMsg::LogValue);
1188        assert_eq!(sim.logs().len(), 1);
1189
1190        sim.clear_logs();
1191        assert!(sim.logs().is_empty());
1192    }
1193
1194    #[test]
1195    fn model_mut_access() {
1196        let mut sim = ProgramSimulator::new(Counter {
1197            value: 0,
1198            initialized: false,
1199        });
1200
1201        sim.model_mut().value = 100;
1202        assert_eq!(sim.model().value, 100);
1203    }
1204
1205    #[test]
1206    fn last_frame() {
1207        let mut sim = ProgramSimulator::new(Counter {
1208            value: 0,
1209            initialized: false,
1210        });
1211
1212        assert!(sim.last_frame().is_none());
1213
1214        sim.capture_frame(10, 10);
1215        assert!(sim.last_frame().is_some());
1216    }
1217
1218    #[test]
1219    fn send_after_quit_is_ignored() {
1220        let mut sim = ProgramSimulator::new(Counter {
1221            value: 0,
1222            initialized: false,
1223        });
1224        sim.init();
1225
1226        sim.send(CounterMsg::Quit);
1227        assert!(!sim.is_running());
1228
1229        sim.send(CounterMsg::Increment);
1230        // Value should not change since we quit
1231        assert_eq!(sim.model().value, 0);
1232    }
1233
1234    // =========================================================================
1235    // DETERMINISM TESTS - ProgramSimulator determinism (bd-2nu8.10.3)
1236    // =========================================================================
1237
1238    #[test]
1239    fn identical_inputs_yield_identical_outputs() {
1240        fn run_scenario() -> (i32, Vec<u8>) {
1241            let mut sim = ProgramSimulator::new(Counter {
1242                value: 0,
1243                initialized: false,
1244            });
1245            sim.init();
1246
1247            sim.send(CounterMsg::Increment);
1248            sim.send(CounterMsg::Increment);
1249            sim.send(CounterMsg::Decrement);
1250            sim.send(CounterMsg::BatchIncrement(3));
1251
1252            let buf = sim.capture_frame(20, 10);
1253            let mut frame_bytes = Vec::new();
1254            for y in 0..10 {
1255                for x in 0..20 {
1256                    if let Some(cell) = buf.get(x, y)
1257                        && let Some(c) = cell.content.as_char()
1258                    {
1259                        frame_bytes.push(c as u8);
1260                    }
1261                }
1262            }
1263            (sim.model().value, frame_bytes)
1264        }
1265
1266        let (value1, frame1) = run_scenario();
1267        let (value2, frame2) = run_scenario();
1268        let (value3, frame3) = run_scenario();
1269
1270        assert_eq!(value1, value2);
1271        assert_eq!(value2, value3);
1272        assert_eq!(value1, 4); // 0 + 1 + 1 - 1 + 3 = 4
1273
1274        assert_eq!(frame1, frame2);
1275        assert_eq!(frame2, frame3);
1276    }
1277
1278    #[test]
1279    fn command_log_records_in_order() {
1280        let mut sim = ProgramSimulator::new(Counter {
1281            value: 0,
1282            initialized: false,
1283        });
1284        sim.init();
1285
1286        sim.send(CounterMsg::Increment);
1287        sim.send(CounterMsg::LogValue);
1288        sim.send(CounterMsg::Increment);
1289        sim.send(CounterMsg::LogValue);
1290
1291        let log = sim.command_log();
1292
1293        // Find Log entries and verify they're in order
1294        let log_entries: Vec<_> = log
1295            .iter()
1296            .filter_map(|r| {
1297                if let CmdRecord::Log { text: s, .. } = r {
1298                    Some(s.as_str())
1299                } else {
1300                    None
1301                }
1302            })
1303            .collect();
1304
1305        assert_eq!(log_entries, vec!["value=1", "value=2"]);
1306    }
1307
1308    #[test]
1309    fn log_modes_capture_policy_and_preserve_command_mode() {
1310        let mut sim = ProgramSimulator::new(Counter {
1311            value: 0,
1312            initialized: false,
1313        });
1314        sim.init();
1315        let payload = "a\x1b[31mb\x1b[2Jc\x1b]0;secret\x07d\n";
1316        sim.execute_cmd(Cmd::sequence(vec![
1317            Cmd::log(payload),
1318            Cmd::log_sgr_only(payload),
1319            Cmd::log_raw(payload),
1320            Cmd::quit(),
1321            Cmd::log("unreachable"),
1322        ]));
1323        assert_eq!(sim.logs(), &["abcd\n", "a\x1b[31mbcd\n", payload]);
1324        let records: Vec<_> = sim
1325            .command_log()
1326            .iter()
1327            .filter_map(|record| match record {
1328                CmdRecord::Log { text, mode } => Some((text.as_str(), *mode)),
1329                _ => None,
1330            })
1331            .collect();
1332        assert_eq!(
1333            records,
1334            [
1335                ("abcd\n", SanitizeMode::Strip),
1336                ("a\x1b[31mbcd\n", SanitizeMode::SgrOnly),
1337                (payload, SanitizeMode::Raw),
1338            ]
1339        );
1340    }
1341
1342    #[test]
1343    fn sequence_command_records_correctly() {
1344        // Model that emits a sequence command
1345        struct SeqModel {
1346            steps: Vec<i32>,
1347        }
1348
1349        #[derive(Debug)]
1350        enum SeqMsg {
1351            Step(i32),
1352            TriggerSeq,
1353        }
1354
1355        impl From<Event> for SeqMsg {
1356            fn from(_: Event) -> Self {
1357                SeqMsg::Step(0)
1358            }
1359        }
1360
1361        impl Model for SeqModel {
1362            type Message = SeqMsg;
1363
1364            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
1365                match msg {
1366                    SeqMsg::Step(n) => {
1367                        self.steps.push(n);
1368                        Cmd::none()
1369                    }
1370                    SeqMsg::TriggerSeq => Cmd::sequence(vec![
1371                        Cmd::msg(SeqMsg::Step(1)),
1372                        Cmd::msg(SeqMsg::Step(2)),
1373                        Cmd::msg(SeqMsg::Step(3)),
1374                    ]),
1375                }
1376            }
1377
1378            fn view(&self, _frame: &mut Frame) {}
1379        }
1380
1381        let mut sim = ProgramSimulator::new(SeqModel { steps: vec![] });
1382        sim.init();
1383        sim.send(SeqMsg::TriggerSeq);
1384
1385        // Verify sequence is recorded
1386        let has_sequence = sim
1387            .command_log()
1388            .iter()
1389            .any(|r| matches!(r, CmdRecord::Sequence(3)));
1390        assert!(has_sequence, "Should record Sequence(3)");
1391
1392        // Verify steps executed in order
1393        assert_eq!(sim.model().steps, vec![1, 2, 3]);
1394    }
1395
1396    #[test]
1397    fn batch_command_records_correctly() {
1398        let mut sim = ProgramSimulator::new(Counter {
1399            value: 0,
1400            initialized: false,
1401        });
1402        sim.init();
1403
1404        sim.send(CounterMsg::BatchIncrement(5));
1405
1406        // Should have Batch(5) in the log
1407        let has_batch = sim
1408            .command_log()
1409            .iter()
1410            .any(|r| matches!(r, CmdRecord::Batch(5)));
1411        assert!(has_batch, "Should record Batch(5)");
1412
1413        assert_eq!(sim.model().value, 5);
1414    }
1415
1416    struct OrderingModel {
1417        trace: RefCell<Vec<&'static str>>,
1418    }
1419
1420    impl OrderingModel {
1421        fn new() -> Self {
1422            Self {
1423                trace: RefCell::new(Vec::new()),
1424            }
1425        }
1426
1427        fn trace(&self) -> Vec<&'static str> {
1428            self.trace.borrow().clone()
1429        }
1430    }
1431
1432    #[derive(Debug)]
1433    enum OrderingMsg {
1434        Step(&'static str),
1435        StartSequence,
1436        StartBatch,
1437    }
1438
1439    impl From<Event> for OrderingMsg {
1440        fn from(_: Event) -> Self {
1441            OrderingMsg::StartSequence
1442        }
1443    }
1444
1445    impl Model for OrderingModel {
1446        type Message = OrderingMsg;
1447
1448        fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
1449            match msg {
1450                OrderingMsg::Step(tag) => {
1451                    self.trace.borrow_mut().push(tag);
1452                    Cmd::none()
1453                }
1454                OrderingMsg::StartSequence => Cmd::sequence(vec![
1455                    Cmd::msg(OrderingMsg::Step("seq-1")),
1456                    Cmd::msg(OrderingMsg::Step("seq-2")),
1457                    Cmd::msg(OrderingMsg::Step("seq-3")),
1458                ]),
1459                OrderingMsg::StartBatch => Cmd::batch(vec![
1460                    Cmd::msg(OrderingMsg::Step("batch-1")),
1461                    Cmd::msg(OrderingMsg::Step("batch-2")),
1462                    Cmd::msg(OrderingMsg::Step("batch-3")),
1463                ]),
1464            }
1465        }
1466
1467        fn view(&self, _frame: &mut Frame) {
1468            self.trace.borrow_mut().push("view");
1469        }
1470    }
1471
1472    #[test]
1473    fn long_msg_and_task_chains_run_without_recursion() {
1474        // One step per `Cmd::Msg` or inline task. Running each `update`
1475        // result recursively overflowed the stack at about 10k steps.
1476        struct Walker {
1477            steps: u32,
1478        }
1479
1480        enum WalkMsg {
1481            Step(u32),
1482            Event,
1483        }
1484
1485        impl From<Event> for WalkMsg {
1486            fn from(_: Event) -> Self {
1487                WalkMsg::Event
1488            }
1489        }
1490
1491        impl Model for Walker {
1492            type Message = WalkMsg;
1493
1494            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
1495                match msg {
1496                    WalkMsg::Step(0) | WalkMsg::Event => Cmd::none(),
1497                    WalkMsg::Step(n) if n % 2 == 0 => {
1498                        self.steps += 1;
1499                        Cmd::msg(WalkMsg::Step(n - 1))
1500                    }
1501                    WalkMsg::Step(n) => {
1502                        self.steps += 1;
1503                        Cmd::task(move || WalkMsg::Step(n - 1))
1504                    }
1505                }
1506            }
1507
1508            fn view(&self, _frame: &mut Frame) {}
1509        }
1510
1511        let mut sim = ProgramSimulator::new(Walker { steps: 0 });
1512        sim.send(WalkMsg::Step(200_000));
1513        assert_eq!(sim.model().steps, 200_000);
1514    }
1515
1516    #[test]
1517    fn sequence_preserves_update_order_before_view() {
1518        let mut sim = ProgramSimulator::new(OrderingModel::new());
1519        sim.init();
1520
1521        sim.send(OrderingMsg::StartSequence);
1522        sim.capture_frame(1, 1);
1523
1524        assert_eq!(sim.model().trace(), vec!["seq-1", "seq-2", "seq-3", "view"]);
1525    }
1526
1527    #[test]
1528    fn batch_preserves_update_order_before_view() {
1529        let mut sim = ProgramSimulator::new(OrderingModel::new());
1530        sim.init();
1531
1532        sim.send(OrderingMsg::StartBatch);
1533        sim.capture_frame(1, 1);
1534
1535        assert_eq!(
1536            sim.model().trace(),
1537            vec!["batch-1", "batch-2", "batch-3", "view"]
1538        );
1539    }
1540
1541    #[test]
1542    fn frame_dimensions_match_request() {
1543        let mut sim = ProgramSimulator::new(Counter {
1544            value: 42,
1545            initialized: false,
1546        });
1547        sim.init();
1548
1549        let buf = sim.capture_frame(100, 50);
1550        assert_eq!(buf.width(), 100);
1551        assert_eq!(buf.height(), 50);
1552    }
1553
1554    #[test]
1555    fn multiple_frame_captures_are_independent() {
1556        let mut sim = ProgramSimulator::new(Counter {
1557            value: 0,
1558            initialized: false,
1559        });
1560        sim.init();
1561
1562        // Capture at value 0
1563        sim.capture_frame(20, 10);
1564
1565        // Change value
1566        sim.send(CounterMsg::Increment);
1567        sim.send(CounterMsg::Increment);
1568
1569        // Capture at value 2
1570        sim.capture_frame(20, 10);
1571
1572        let frames = sim.frames();
1573        assert_eq!(frames.len(), 2);
1574
1575        // First frame should show "Count: 0"
1576        assert_eq!(frames[0].get(7, 0).unwrap().content.as_char(), Some('0'));
1577
1578        // Second frame should show "Count: 2"
1579        assert_eq!(frames[1].get(7, 0).unwrap().content.as_char(), Some('2'));
1580    }
1581
1582    #[test]
1583    fn inject_events_processes_in_order() {
1584        let mut sim = ProgramSimulator::new(Counter {
1585            value: 0,
1586            initialized: false,
1587        });
1588        sim.init();
1589
1590        // '+' increments, '-' decrements
1591        let events = vec![
1592            key_event('+'),
1593            key_event('+'),
1594            key_event('+'),
1595            key_event('-'),
1596            key_event('+'),
1597        ];
1598
1599        sim.inject_events(&events);
1600
1601        // 0 + 1 + 1 + 1 - 1 + 1 = 3
1602        assert_eq!(sim.model().value, 3);
1603    }
1604
1605    #[test]
1606    fn task_command_records_task() {
1607        struct TaskModel {
1608            result: Option<i32>,
1609        }
1610
1611        #[derive(Debug)]
1612        enum TaskMsg {
1613            SetResult(i32),
1614            SpawnTask,
1615        }
1616
1617        impl From<Event> for TaskMsg {
1618            fn from(_: Event) -> Self {
1619                TaskMsg::SetResult(0)
1620            }
1621        }
1622
1623        impl Model for TaskModel {
1624            type Message = TaskMsg;
1625
1626            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
1627                match msg {
1628                    TaskMsg::SetResult(v) => {
1629                        self.result = Some(v);
1630                        Cmd::none()
1631                    }
1632                    TaskMsg::SpawnTask => Cmd::task(|| {
1633                        // Simulate computation
1634                        TaskMsg::SetResult(42)
1635                    }),
1636                }
1637            }
1638
1639            fn view(&self, _frame: &mut Frame) {}
1640        }
1641
1642        let mut sim = ProgramSimulator::new(TaskModel { result: None });
1643        sim.init();
1644        sim.send(TaskMsg::SpawnTask);
1645
1646        // Task should execute synchronously in simulator
1647        assert_eq!(sim.model().result, Some(42));
1648
1649        // Should have Task record in command log
1650        let has_task = sim
1651            .command_log()
1652            .iter()
1653            .any(|r| matches!(r, CmdRecord::Task));
1654        assert!(has_task);
1655    }
1656
1657    #[test]
1658    fn tick_rate_is_set() {
1659        let mut sim = ProgramSimulator::new(Counter {
1660            value: 0,
1661            initialized: false,
1662        });
1663
1664        assert!(sim.tick_rate().is_none());
1665
1666        sim.execute_cmd(Cmd::tick(std::time::Duration::from_millis(100)));
1667
1668        assert_eq!(sim.tick_rate(), Some(std::time::Duration::from_millis(100)));
1669    }
1670
1671    #[test]
1672    fn logs_accumulate_across_messages() {
1673        let mut sim = ProgramSimulator::new(Counter {
1674            value: 0,
1675            initialized: false,
1676        });
1677        sim.init();
1678
1679        sim.send(CounterMsg::LogValue);
1680        sim.send(CounterMsg::Increment);
1681        sim.send(CounterMsg::LogValue);
1682        sim.send(CounterMsg::Increment);
1683        sim.send(CounterMsg::LogValue);
1684
1685        assert_eq!(sim.logs().len(), 3);
1686        assert_eq!(sim.logs()[0], "value=0");
1687        assert_eq!(sim.logs()[1], "value=1");
1688        assert_eq!(sim.logs()[2], "value=2");
1689    }
1690
1691    #[test]
1692    fn deterministic_frame_content_across_runs() {
1693        fn capture_frame_content(value: i32) -> Vec<Option<char>> {
1694            let mut sim = ProgramSimulator::new(Counter {
1695                value,
1696                initialized: false,
1697            });
1698            sim.init();
1699
1700            let buf = sim.capture_frame(15, 1);
1701            (0..15)
1702                .map(|x| buf.get(x, 0).and_then(|c| c.content.as_char()))
1703                .collect()
1704        }
1705
1706        let content1 = capture_frame_content(123);
1707        let content2 = capture_frame_content(123);
1708        let content3 = capture_frame_content(123);
1709
1710        assert_eq!(content1, content2);
1711        assert_eq!(content2, content3);
1712
1713        // Should be "Count: 123" followed by None (unwritten cells)
1714        let expected: Vec<Option<char>> = "Count: 123"
1715            .chars()
1716            .map(Some)
1717            .chain(std::iter::repeat_n(None, 5))
1718            .collect();
1719        assert_eq!(content1, expected);
1720    }
1721
1722    #[test]
1723    fn complex_scenario_is_deterministic() {
1724        fn run_complex_scenario() -> (i32, usize, Vec<String>) {
1725            let mut sim = ProgramSimulator::new(Counter {
1726                value: 0,
1727                initialized: false,
1728            });
1729            sim.init();
1730
1731            // Complex sequence of operations
1732            for _ in 0..10 {
1733                sim.send(CounterMsg::Increment);
1734            }
1735            sim.send(CounterMsg::LogValue);
1736
1737            sim.send(CounterMsg::BatchIncrement(5));
1738            sim.send(CounterMsg::LogValue);
1739
1740            for _ in 0..3 {
1741                sim.send(CounterMsg::Decrement);
1742            }
1743            sim.send(CounterMsg::LogValue);
1744
1745            sim.send(CounterMsg::Reset);
1746            sim.send(CounterMsg::LogValue);
1747
1748            sim.capture_frame(20, 10);
1749
1750            (
1751                sim.model().value,
1752                sim.command_log().len(),
1753                sim.logs().to_vec(),
1754            )
1755        }
1756
1757        let result1 = run_complex_scenario();
1758        let result2 = run_complex_scenario();
1759
1760        assert_eq!(result1.0, result2.0);
1761        assert_eq!(result1.1, result2.1);
1762        assert_eq!(result1.2, result2.2);
1763    }
1764
1765    #[test]
1766    fn model_unchanged_when_not_running() {
1767        let mut sim = ProgramSimulator::new(Counter {
1768            value: 5,
1769            initialized: false,
1770        });
1771        sim.init();
1772
1773        sim.send(CounterMsg::Quit);
1774
1775        let value_before = sim.model().value;
1776        sim.send(CounterMsg::Increment);
1777        sim.send(CounterMsg::BatchIncrement(10));
1778        let value_after = sim.model().value;
1779
1780        assert_eq!(value_before, value_after);
1781    }
1782
1783    #[test]
1784    fn init_produces_consistent_command_log() {
1785        // Model with init that returns a command
1786        struct InitModel {
1787            init_ran: bool,
1788        }
1789
1790        #[derive(Debug)]
1791        enum InitMsg {
1792            MarkInit,
1793        }
1794
1795        impl From<Event> for InitMsg {
1796            fn from(_: Event) -> Self {
1797                InitMsg::MarkInit
1798            }
1799        }
1800
1801        impl Model for InitModel {
1802            type Message = InitMsg;
1803
1804            fn init(&mut self) -> Cmd<Self::Message> {
1805                Cmd::msg(InitMsg::MarkInit)
1806            }
1807
1808            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
1809                match msg {
1810                    InitMsg::MarkInit => {
1811                        self.init_ran = true;
1812                        Cmd::none()
1813                    }
1814                }
1815            }
1816
1817            fn view(&self, _frame: &mut Frame) {}
1818        }
1819
1820        let mut sim1 = ProgramSimulator::new(InitModel { init_ran: false });
1821        let mut sim2 = ProgramSimulator::new(InitModel { init_ran: false });
1822
1823        sim1.init();
1824        sim2.init();
1825
1826        assert_eq!(sim1.model().init_ran, sim2.model().init_ran);
1827        assert_eq!(sim1.command_log().len(), sim2.command_log().len());
1828    }
1829
1830    #[test]
1831    fn execute_cmd_directly() {
1832        let mut sim = ProgramSimulator::new(Counter {
1833            value: 0,
1834            initialized: false,
1835        });
1836
1837        // Execute commands directly without going through update
1838        sim.execute_cmd(Cmd::log("direct log"));
1839        sim.execute_cmd(Cmd::tick(std::time::Duration::from_secs(1)));
1840
1841        assert_eq!(sim.logs(), &["direct log"]);
1842        assert_eq!(sim.tick_rate(), Some(std::time::Duration::from_secs(1)));
1843    }
1844
1845    #[test]
1846    fn save_restore_are_noops_in_simulator() {
1847        let mut sim = ProgramSimulator::new(Counter {
1848            value: 7,
1849            initialized: false,
1850        });
1851        sim.init();
1852
1853        let log_len = sim.command_log().len();
1854        let tick_rate = sim.tick_rate();
1855        let value_before = sim.model().value;
1856
1857        sim.execute_cmd(Cmd::save_state());
1858        sim.execute_cmd(Cmd::restore_state());
1859
1860        assert_eq!(
1861            &sim.command_log()[log_len..],
1862            &[CmdRecord::SaveState, CmdRecord::RestoreState]
1863        );
1864        assert_eq!(sim.tick_rate(), tick_rate);
1865        assert_eq!(sim.model().value, value_before);
1866        assert!(sim.is_running());
1867    }
1868
1869    #[test]
1870    fn set_tick_strategy_drives_selective_screen_ticks_in_simulator() {
1871        use crate::tick_strategy::{ActiveOnly, ScreenTickDispatch, TickDecision, Uniform};
1872
1873        struct MultiScreenModel {
1874            active: &'static str,
1875            active_ticks: Vec<u64>,
1876            bg_ticks: Vec<u64>,
1877        }
1878
1879        enum MultiMsg {
1880            Switch(&'static str),
1881            UseUniform(u64),
1882            Tick,
1883        }
1884
1885        impl From<Event> for MultiMsg {
1886            fn from(_: Event) -> Self {
1887                Self::Tick
1888            }
1889        }
1890
1891        impl Model for MultiScreenModel {
1892            type Message = MultiMsg;
1893
1894            fn init(&mut self) -> Cmd<Self::Message> {
1895                Cmd::set_tick_strategy(ActiveOnly)
1896            }
1897
1898            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
1899                match msg {
1900                    MultiMsg::Switch(screen) => {
1901                        self.active = screen;
1902                        Cmd::none()
1903                    }
1904                    MultiMsg::UseUniform(divisor) => Cmd::set_tick_strategy(Uniform::new(divisor)),
1905                    MultiMsg::Tick => {
1906                        self.active_ticks.push(0);
1907                        Cmd::none()
1908                    }
1909                }
1910            }
1911
1912            fn view(&self, _frame: &mut Frame) {}
1913
1914            fn as_screen_tick_dispatch(&mut self) -> Option<&mut dyn ScreenTickDispatch> {
1915                Some(self)
1916            }
1917        }
1918
1919        impl ScreenTickDispatch for MultiScreenModel {
1920            fn active_screen_id(&self) -> String {
1921                self.active.to_owned()
1922            }
1923
1924            fn screen_ids(&self) -> Vec<String> {
1925                vec!["alpha".to_owned(), "beta".to_owned()]
1926            }
1927
1928            fn tick_screen(&mut self, screen_id: &str, tick_count: u64) {
1929                if screen_id == self.active {
1930                    self.active_ticks.push(tick_count);
1931                } else {
1932                    self.bg_ticks.push(tick_count);
1933                }
1934            }
1935        }
1936
1937        let mut sim = ProgramSimulator::new(MultiScreenModel {
1938            active: "alpha",
1939            active_ticks: Vec::new(),
1940            bg_ticks: Vec::new(),
1941        });
1942        sim.init();
1943        assert_eq!(sim.tick_strategy_name(), Some("ActiveOnly"));
1944        assert!(
1945            sim.command_log()
1946                .contains(&CmdRecord::SetTickStrategy("ActiveOnly".to_owned()))
1947        );
1948
1949        // Under ActiveOnly, background screen "beta" is skipped.
1950        sim.tick();
1951        sim.tick();
1952        assert_eq!(sim.model().active_ticks, vec![1, 2]);
1953        assert!(sim.model().bg_ticks.is_empty());
1954
1955        // Switch to Uniform(2): background screen "beta" ticks on even tick counts.
1956        sim.send(MultiMsg::UseUniform(2));
1957        assert_eq!(sim.tick_strategy_name(), Some("Uniform"));
1958        sim.tick(); // tick_count = 3 (odd -> Skip)
1959        sim.tick(); // tick_count = 4 (even -> Tick)
1960        assert_eq!(sim.model().bg_ticks, vec![4]);
1961
1962        // Switching active screen notifies strategy and force-ticks newly active screen.
1963        sim.send(MultiMsg::Switch("beta"));
1964        assert_eq!(sim.model().active_ticks, vec![1, 2, 3, 4, 4]);
1965        let _ = TickDecision::Tick;
1966    }
1967
1968    #[test]
1969    fn grapheme_pool_is_reused() {
1970        let mut sim = ProgramSimulator::new(Counter {
1971            value: 0,
1972            initialized: false,
1973        });
1974        sim.init();
1975
1976        // Capture multiple frames - pool should be reused
1977        for i in 0..10 {
1978            sim.model_mut().value = i;
1979            sim.capture_frame(80, 24);
1980        }
1981
1982        assert_eq!(sim.frame_count(), 10);
1983    }
1984
1985    // =========================================================================
1986    // LIFECYCLE CONTRACT TESTS (bd-1dg21)
1987    //
1988    // These tests capture the observable lifecycle contract for subscriptions,
1989    // commands, processes, and teardown ordering. The Asupersync migration
1990    // MUST preserve all behaviors documented here.
1991    // =========================================================================
1992
1993    /// CONTRACT: Model::init() is called exactly once, before any update() calls.
1994    /// init() return value is executed as a command.
1995    #[test]
1996    fn contract_init_called_once_before_updates() {
1997        use std::sync::atomic::{AtomicUsize, Ordering as AO};
1998
1999        struct InitTracker {
2000            init_count: Arc<AtomicUsize>,
2001            update_count: Arc<AtomicUsize>,
2002            init_saw_zero_updates: bool,
2003        }
2004
2005        #[derive(Debug)]
2006        enum TrackerMsg {
2007            FromInit,
2008            Manual,
2009        }
2010
2011        impl From<Event> for TrackerMsg {
2012            fn from(_: Event) -> Self {
2013                TrackerMsg::Manual
2014            }
2015        }
2016
2017        impl Model for InitTracker {
2018            type Message = TrackerMsg;
2019
2020            fn init(&mut self) -> Cmd<Self::Message> {
2021                self.init_count.fetch_add(1, AO::SeqCst);
2022                self.init_saw_zero_updates = self.update_count.load(AO::SeqCst) == 0;
2023                Cmd::msg(TrackerMsg::FromInit)
2024            }
2025
2026            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
2027                self.update_count.fetch_add(1, AO::SeqCst);
2028                Cmd::none()
2029            }
2030
2031            fn view(&self, _frame: &mut Frame) {}
2032        }
2033
2034        let init_count = Arc::new(AtomicUsize::new(0));
2035        let update_count = Arc::new(AtomicUsize::new(0));
2036
2037        let mut sim = ProgramSimulator::new(InitTracker {
2038            init_count: init_count.clone(),
2039            update_count: update_count.clone(),
2040            init_saw_zero_updates: false,
2041        });
2042
2043        sim.init();
2044        assert_eq!(init_count.load(AO::SeqCst), 1, "init called exactly once");
2045        assert!(
2046            sim.model().init_saw_zero_updates,
2047            "init must run before any update"
2048        );
2049        // init returned Cmd::msg(FromInit) which triggered one update
2050        assert_eq!(
2051            update_count.load(AO::SeqCst),
2052            1,
2053            "init's command should trigger update"
2054        );
2055    }
2056
2057    /// CONTRACT: on_shutdown() is called during program shutdown, providing
2058    /// the model a chance to emit final commands.
2059    #[test]
2060    fn contract_on_shutdown_called_with_final_commands() {
2061        struct ShutdownTracker {
2062            shutdown_called: bool,
2063            final_log: Option<String>,
2064        }
2065
2066        #[derive(Debug)]
2067        enum ShutMsg {
2068            Quit,
2069            LogFinal(String),
2070        }
2071
2072        impl From<Event> for ShutMsg {
2073            fn from(_: Event) -> Self {
2074                ShutMsg::Quit
2075            }
2076        }
2077
2078        impl Model for ShutdownTracker {
2079            type Message = ShutMsg;
2080
2081            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
2082                match msg {
2083                    ShutMsg::Quit => Cmd::quit(),
2084                    ShutMsg::LogFinal(s) => {
2085                        self.final_log = Some(s);
2086                        Cmd::none()
2087                    }
2088                }
2089            }
2090
2091            fn view(&self, _frame: &mut Frame) {}
2092
2093            fn on_shutdown(&mut self) -> Cmd<Self::Message> {
2094                self.shutdown_called = true;
2095                Cmd::msg(ShutMsg::LogFinal("shutdown-complete".into()))
2096            }
2097        }
2098
2099        let mut sim = ProgramSimulator::new(ShutdownTracker {
2100            shutdown_called: false,
2101            final_log: None,
2102        });
2103        sim.init();
2104        sim.send(ShutMsg::Quit);
2105        sim.shutdown();
2106        sim.shutdown();
2107
2108        assert!(sim.model().shutdown_called, "on_shutdown must be called");
2109        assert!(sim.is_shutdown(), "shutdown state must be observable");
2110        assert_eq!(
2111            sim.model().final_log.as_deref(),
2112            Some("shutdown-complete"),
2113            "on_shutdown commands must be executed"
2114        );
2115    }
2116
2117    /// CONTRACT: Cmd::Batch stops executing remaining commands after Cmd::Quit.
2118    #[test]
2119    fn contract_batch_stops_on_quit() {
2120        struct BatchQuitModel {
2121            steps: Vec<&'static str>,
2122        }
2123
2124        #[derive(Debug)]
2125        enum BQMsg {
2126            Step(&'static str),
2127            TriggerBatchWithQuit,
2128        }
2129
2130        impl From<Event> for BQMsg {
2131            fn from(_: Event) -> Self {
2132                BQMsg::Step("event")
2133            }
2134        }
2135
2136        impl Model for BatchQuitModel {
2137            type Message = BQMsg;
2138
2139            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
2140                match msg {
2141                    BQMsg::Step(s) => {
2142                        self.steps.push(s);
2143                        Cmd::none()
2144                    }
2145                    BQMsg::TriggerBatchWithQuit => Cmd::batch(vec![
2146                        Cmd::msg(BQMsg::Step("before-quit")),
2147                        Cmd::quit(),
2148                        Cmd::msg(BQMsg::Step("after-quit")),
2149                    ]),
2150                }
2151            }
2152
2153            fn view(&self, _frame: &mut Frame) {}
2154        }
2155
2156        let mut sim = ProgramSimulator::new(BatchQuitModel { steps: vec![] });
2157        sim.init();
2158        sim.send(BQMsg::TriggerBatchWithQuit);
2159
2160        assert!(!sim.is_running(), "should be stopped");
2161        assert_eq!(
2162            sim.model().steps,
2163            vec!["before-quit"],
2164            "commands after Quit in a Batch must not execute"
2165        );
2166    }
2167
2168    /// CONTRACT: Cmd::Sequence stops executing remaining commands after Cmd::Quit.
2169    #[test]
2170    fn contract_sequence_stops_on_quit() {
2171        struct SeqQuitModel {
2172            steps: Vec<&'static str>,
2173        }
2174
2175        #[derive(Debug)]
2176        enum SQMsg {
2177            Step(&'static str),
2178            TriggerSeqWithQuit,
2179        }
2180
2181        impl From<Event> for SQMsg {
2182            fn from(_: Event) -> Self {
2183                SQMsg::Step("event")
2184            }
2185        }
2186
2187        impl Model for SeqQuitModel {
2188            type Message = SQMsg;
2189
2190            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
2191                match msg {
2192                    SQMsg::Step(s) => {
2193                        self.steps.push(s);
2194                        Cmd::none()
2195                    }
2196                    SQMsg::TriggerSeqWithQuit => Cmd::sequence(vec![
2197                        Cmd::msg(SQMsg::Step("before-quit")),
2198                        Cmd::quit(),
2199                        Cmd::msg(SQMsg::Step("after-quit")),
2200                    ]),
2201                }
2202            }
2203
2204            fn view(&self, _frame: &mut Frame) {}
2205        }
2206
2207        let mut sim = ProgramSimulator::new(SeqQuitModel { steps: vec![] });
2208        sim.init();
2209        sim.send(SQMsg::TriggerSeqWithQuit);
2210
2211        assert!(!sim.is_running(), "should be stopped");
2212        assert_eq!(
2213            sim.model().steps,
2214            vec!["before-quit"],
2215            "commands after Quit in a Sequence must not execute"
2216        );
2217    }
2218
2219    /// CONTRACT: Cmd::Task results are routed back through Model::update().
2220    /// In simulator mode, tasks execute synchronously.
2221    #[test]
2222    fn contract_task_result_routes_through_update() {
2223        struct TaskModel {
2224            trace: Vec<String>,
2225        }
2226
2227        #[derive(Debug)]
2228        enum TMsg {
2229            Spawn,
2230            TaskDone(i32),
2231        }
2232
2233        impl From<Event> for TMsg {
2234            fn from(_: Event) -> Self {
2235                TMsg::Spawn
2236            }
2237        }
2238
2239        impl Model for TaskModel {
2240            type Message = TMsg;
2241
2242            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
2243                match msg {
2244                    TMsg::Spawn => {
2245                        self.trace.push("spawn".into());
2246                        Cmd::task(|| TMsg::TaskDone(42))
2247                    }
2248                    TMsg::TaskDone(v) => {
2249                        self.trace.push(format!("done:{v}"));
2250                        Cmd::none()
2251                    }
2252                }
2253            }
2254
2255            fn view(&self, _frame: &mut Frame) {}
2256        }
2257
2258        let mut sim = ProgramSimulator::new(TaskModel { trace: vec![] });
2259        sim.init();
2260        sim.send(TMsg::Spawn);
2261
2262        assert_eq!(
2263            sim.model().trace,
2264            vec!["spawn", "done:42"],
2265            "task result must route through update()"
2266        );
2267    }
2268
2269    /// CONTRACT: Cmd::Msg causes recursive dispatch through update().
2270    /// The message is processed immediately, not deferred.
2271    #[test]
2272    fn contract_cmd_msg_dispatches_recursively() {
2273        struct RecursiveModel {
2274            trace: Vec<i32>,
2275        }
2276
2277        #[derive(Debug)]
2278        enum RMsg {
2279            Chain(i32),
2280        }
2281
2282        impl From<Event> for RMsg {
2283            fn from(_: Event) -> Self {
2284                RMsg::Chain(0)
2285            }
2286        }
2287
2288        impl Model for RecursiveModel {
2289            type Message = RMsg;
2290
2291            fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
2292                match msg {
2293                    RMsg::Chain(n) => {
2294                        self.trace.push(n);
2295                        if n < 3 {
2296                            Cmd::msg(RMsg::Chain(n + 1))
2297                        } else {
2298                            Cmd::none()
2299                        }
2300                    }
2301                }
2302            }
2303
2304            fn view(&self, _frame: &mut Frame) {}
2305        }
2306
2307        let mut sim = ProgramSimulator::new(RecursiveModel { trace: vec![] });
2308        sim.init();
2309        sim.send(RMsg::Chain(0));
2310
2311        assert_eq!(
2312            sim.model().trace,
2313            vec![0, 1, 2, 3],
2314            "Cmd::Msg must dispatch recursively through update()"
2315        );
2316    }
2317
2318    /// CONTRACT: Cmd::batch with empty vec produces Cmd::None.
2319    /// Cmd::batch with single element unwraps to that element.
2320    #[test]
2321    fn contract_batch_normalization() {
2322        let empty: Cmd<CounterMsg> = Cmd::batch(vec![]);
2323        assert!(matches!(empty, Cmd::None), "empty batch must be Cmd::None");
2324
2325        let single: Cmd<CounterMsg> = Cmd::batch(vec![Cmd::quit()]);
2326        assert!(
2327            matches!(single, Cmd::Quit),
2328            "single-element batch must unwrap"
2329        );
2330
2331        let multi: Cmd<CounterMsg> = Cmd::batch(vec![Cmd::none(), Cmd::quit()]);
2332        assert!(
2333            matches!(multi, Cmd::Batch(_)),
2334            "multi-element batch stays Batch"
2335        );
2336    }
2337
2338    /// CONTRACT: Cmd::sequence with empty vec produces Cmd::None.
2339    #[test]
2340    fn contract_sequence_normalization() {
2341        let empty: Cmd<CounterMsg> = Cmd::sequence(vec![]);
2342        assert!(
2343            matches!(empty, Cmd::None),
2344            "empty sequence must be Cmd::None"
2345        );
2346    }
2347
2348    /// CONTRACT: After Cmd::Quit, no further messages are processed.
2349    /// This applies to both inject_events and send.
2350    #[test]
2351    fn contract_no_processing_after_quit() {
2352        let mut sim = ProgramSimulator::new(Counter {
2353            value: 0,
2354            initialized: false,
2355        });
2356        sim.init();
2357
2358        sim.send(CounterMsg::Increment); // value = 1
2359        sim.send(CounterMsg::Quit);
2360        sim.send(CounterMsg::Increment); // should be ignored
2361        sim.send(CounterMsg::Increment); // should be ignored
2362
2363        assert_eq!(sim.model().value, 1, "messages after Quit must be ignored");
2364        assert!(!sim.is_running());
2365
2366        // Also via inject_events
2367        sim.inject_events(&[key_event('+'), key_event('+')]);
2368        assert_eq!(
2369            sim.model().value,
2370            1,
2371            "events after Quit must also be ignored"
2372        );
2373    }
2374
2375    #[test]
2376    fn simulator_resize_reflows_view() {
2377        use ftui_render::cell::Cell;
2378
2379        struct WidthEchoModel;
2380        impl Model for WidthEchoModel {
2381            type Message = Event;
2382            fn update(&mut self, _msg: Self::Message) -> Cmd<Self::Message> {
2383                Cmd::none()
2384            }
2385            fn view(&self, frame: &mut Frame) {
2386                let label = format!("W={}xH={}", frame.width(), frame.height());
2387                for (i, ch) in label.chars().enumerate() {
2388                    if (i as u16) < frame.width() {
2389                        frame.buffer.set_raw(i as u16, 0, Cell::from_char(ch));
2390                    }
2391                }
2392            }
2393        }
2394
2395        let mut sim = ProgramSimulator::new(WidthEchoModel);
2396        sim.init();
2397        let buf_before = sim.capture_frame(40, 10);
2398        let row_before: String = (0..9)
2399            .filter_map(|x| buf_before.get(x, 0)?.content.as_char())
2400            .collect();
2401        assert_eq!(row_before, "W=40xH=10");
2402
2403        let buf_after = sim.capture_frame(120, 32);
2404        let row_after: String = (0..10)
2405            .filter_map(|x| buf_after.get(x, 0)?.content.as_char())
2406            .collect();
2407        assert_eq!(row_after, "W=120xH=32");
2408    }
2409}