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