envision 0.15.1

A ratatui framework for collaborative TUI development with headless testing support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
//! Builder pattern for constructing [`Runtime`] instances.
//!
//! [`RuntimeBuilder`] provides a fluent API for configuring and creating
//! a runtime. It replaces the combinatorial explosion of 12 constructor
//! methods on [`Runtime`] with a single builder chain.
//!
//! # Entry Points
//!
//! There are three entry points, one for each backend type:
//!
//! - [`Runtime::terminal_builder()`] — real terminal (crossterm)
//! - [`Runtime::virtual_builder()`] — virtual capture backend
//! - [`Runtime::builder()`] — any backend implementing [`Backend`]
//!
//! # Examples
//!
//! ## Virtual terminal (testing / automation)
//!
//! ```rust
//! # use envision::prelude::*;
//! # struct MyApp;
//! # #[derive(Default, Clone)]
//! # struct MyState;
//! # #[derive(Clone)]
//! # enum MyMsg {}
//! # impl App for MyApp {
//! #     type State = MyState;
//! #     type Message = MyMsg;
//! #     fn init() -> (MyState, Command<MyMsg>) { (MyState, Command::none()) }
//! #     fn update(state: &mut MyState, msg: MyMsg) -> Command<MyMsg> { Command::none() }
//! #     fn view(state: &MyState, frame: &mut Frame) {}
//! # }
//! let vt = Runtime::<MyApp, _>::virtual_builder(80, 24).build()?;
//! # Ok::<(), envision::EnvisionError>(())
//! ```
//!
//! ## With custom config
//!
//! ```rust
//! # use envision::prelude::*;
//! # use std::time::Duration;
//! # struct MyApp;
//! # #[derive(Default, Clone)]
//! # struct MyState;
//! # #[derive(Clone)]
//! # enum MyMsg {}
//! # impl App for MyApp {
//! #     type State = MyState;
//! #     type Message = MyMsg;
//! #     fn init() -> (MyState, Command<MyMsg>) { (MyState, Command::none()) }
//! #     fn update(state: &mut MyState, msg: MyMsg) -> Command<MyMsg> { Command::none() }
//! #     fn view(state: &MyState, frame: &mut Frame) {}
//! # }
//! let vt = Runtime::<MyApp, _>::virtual_builder(80, 24)
//!     .tick_rate(Duration::from_millis(100))
//!     .build()?;
//! # Ok::<(), envision::EnvisionError>(())
//! ```
//!
//! ## With pre-built state
//!
//! ```rust
//! # use envision::prelude::*;
//! # struct MyApp;
//! # #[derive(Default, Clone)]
//! # struct MyState { count: i32 }
//! # #[derive(Clone)]
//! # enum MyMsg {}
//! # impl App for MyApp {
//! #     type State = MyState;
//! #     type Message = MyMsg;
//! #     fn init() -> (MyState, Command<MyMsg>) { (MyState::default(), Command::none()) }
//! #     fn update(state: &mut MyState, msg: MyMsg) -> Command<MyMsg> { Command::none() }
//! #     fn view(state: &MyState, frame: &mut Frame) {}
//! # }
//! let state = MyState { count: 42 };
//! let vt = Runtime::<MyApp, _>::virtual_builder(80, 24)
//!     .state(state, Command::none())
//!     .build()?;
//! assert_eq!(vt.state().count, 42);
//! # Ok::<(), envision::EnvisionError>(())
//! ```
//!
//! ## Real terminal (production)
//!
//! ```rust,no_run
//! # use envision::prelude::*;
//! # struct MyApp;
//! # #[derive(Default, Clone)]
//! # struct MyState;
//! # #[derive(Clone)]
//! # enum MyMsg {}
//! # impl App for MyApp {
//! #     type State = MyState;
//! #     type Message = MyMsg;
//! #     fn init() -> (MyState, Command<MyMsg>) { (MyState, Command::none()) }
//! #     fn update(state: &mut MyState, msg: MyMsg) -> Command<MyMsg> { Command::none() }
//! #     fn view(state: &MyState, frame: &mut Frame) {}
//! # }
//! # #[tokio::main]
//! # async fn main() -> envision::Result<()> {
//! let _final_state = Runtime::<MyApp, _>::terminal_builder()?
//!     .build()?
//!     .run_terminal()
//!     .await?;
//! # Ok(())
//! # }
//! ```

use std::io::Stdout;
use std::time::Duration;

use ratatui::backend::{Backend, CrosstermBackend};

use super::Runtime;
use super::config::RuntimeConfig;
use crate::app::command::Command;
use crate::app::model::App;
use crate::backend::CaptureBackend;
use crate::error;

/// A builder for constructing [`Runtime`] instances.
///
/// Created via [`Runtime::builder()`], [`Runtime::terminal_builder()`],
/// or [`Runtime::virtual_builder()`].
///
/// The builder provides fluent methods to configure:
/// - **State**: `.state(state, init_cmd)` to bypass `App::init()`
/// - **Config**: `.config(config)` to supply a full [`RuntimeConfig`]
/// - **Individual settings**: `.tick_rate()`, `.frame_rate()`, etc.
///
/// Call `.build()` to create the [`Runtime`].
///
/// # Example
///
/// ```rust
/// # use envision::prelude::*;
/// # use std::time::Duration;
/// # struct MyApp;
/// # #[derive(Default, Clone)]
/// # struct MyState;
/// # #[derive(Clone)]
/// # enum MyMsg {}
/// # impl App for MyApp {
/// #     type State = MyState;
/// #     type Message = MyMsg;
/// #     fn init() -> (MyState, Command<MyMsg>) { (MyState, Command::none()) }
/// #     fn update(state: &mut MyState, msg: MyMsg) -> Command<MyMsg> { Command::none() }
/// #     fn view(state: &MyState, frame: &mut Frame) {}
/// # }
/// let vt = Runtime::<MyApp, _>::virtual_builder(80, 24)
///     .tick_rate(Duration::from_millis(100))
///     .frame_rate(Duration::from_millis(32))
///     .build()?;
/// # Ok::<(), envision::EnvisionError>(())
/// ```
pub struct RuntimeBuilder<A: App, B: Backend> {
    backend: B,
    state: Option<(A::State, Command<A::Message>)>,
    config: Option<RuntimeConfig>,
}

impl<A: App, B: Backend> RuntimeBuilder<A, B> {
    /// Creates a new builder with the given backend.
    ///
    /// Prefer the convenience entry points [`Runtime::terminal_builder()`]
    /// and [`Runtime::virtual_builder()`] for common backends. Use this
    /// method when providing a custom [`Backend`] implementation.
    pub(crate) fn new(backend: B) -> Self {
        Self {
            backend,
            state: None,
            config: None,
        }
    }

    /// Provides a pre-built initial state, bypassing [`App::init()`].
    ///
    /// When this is set, `App::init()` is **not called** — the provided
    /// `state` and `init_cmd` are used instead. This is useful for
    /// constructing the initial state from external sources (CLI arguments,
    /// config files, databases, etc.).
    ///
    /// Pass [`Command::none()`] for `init_cmd` if no startup command is needed.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use envision::prelude::*;
    /// # struct MyApp;
    /// # #[derive(Default, Clone)]
    /// # struct MyState { count: i32 }
    /// # #[derive(Clone)]
    /// # enum MyMsg {}
    /// # impl App for MyApp {
    /// #     type State = MyState;
    /// #     type Message = MyMsg;
    /// #     fn init() -> (MyState, Command<MyMsg>) { (MyState::default(), Command::none()) }
    /// #     fn update(state: &mut MyState, msg: MyMsg) -> Command<MyMsg> { Command::none() }
    /// #     fn view(state: &MyState, frame: &mut Frame) {}
    /// # }
    /// let state = MyState { count: 42 };
    /// let vt = Runtime::<MyApp, _>::virtual_builder(80, 24)
    ///     .state(state, Command::none())
    ///     .build()?;
    /// assert_eq!(vt.state().count, 42);
    /// # Ok::<(), envision::EnvisionError>(())
    /// ```
    pub fn state(mut self, state: A::State, init_cmd: Command<A::Message>) -> Self {
        self.state = Some((state, init_cmd));
        self
    }

    /// Sets the full runtime configuration.
    ///
    /// This replaces any previously set configuration (including individual
    /// settings like [`tick_rate`](Self::tick_rate) or
    /// [`frame_rate`](Self::frame_rate)). If you want to set only specific
    /// fields, use the individual builder methods instead.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use envision::prelude::*;
    /// # struct MyApp;
    /// # #[derive(Default, Clone)]
    /// # struct MyState;
    /// # #[derive(Clone)]
    /// # enum MyMsg {}
    /// # impl App for MyApp {
    /// #     type State = MyState;
    /// #     type Message = MyMsg;
    /// #     fn init() -> (MyState, Command<MyMsg>) { (MyState, Command::none()) }
    /// #     fn update(state: &mut MyState, msg: MyMsg) -> Command<MyMsg> { Command::none() }
    /// #     fn view(state: &MyState, frame: &mut Frame) {}
    /// # }
    /// let config = RuntimeConfig::new()
    ///     .tick_rate(std::time::Duration::from_millis(100))
    ///     .max_messages(50);
    /// let vt = Runtime::<MyApp, _>::virtual_builder(80, 24)
    ///     .config(config)
    ///     .build()?;
    /// # Ok::<(), envision::EnvisionError>(())
    /// ```
    pub fn config(mut self, config: RuntimeConfig) -> Self {
        self.config = Some(config);
        self
    }

    /// Sets the tick rate (how often to poll for events).
    ///
    /// Default: 50ms.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use envision::prelude::*;
    /// # use std::time::Duration;
    /// # struct MyApp;
    /// # #[derive(Default, Clone)]
    /// # struct MyState;
    /// # #[derive(Clone)]
    /// # enum MyMsg {}
    /// # impl App for MyApp {
    /// #     type State = MyState;
    /// #     type Message = MyMsg;
    /// #     fn init() -> (MyState, Command<MyMsg>) { (MyState, Command::none()) }
    /// #     fn update(state: &mut MyState, msg: MyMsg) -> Command<MyMsg> { Command::none() }
    /// #     fn view(state: &MyState, frame: &mut Frame) {}
    /// # }
    /// let vt = Runtime::<MyApp, _>::virtual_builder(80, 24)
    ///     .tick_rate(Duration::from_millis(100))
    ///     .build()?;
    /// # Ok::<(), envision::EnvisionError>(())
    /// ```
    pub fn tick_rate(mut self, rate: Duration) -> Self {
        self.config_mut().tick_rate = rate;
        self
    }

    /// Sets the frame rate (how often to render).
    ///
    /// Default: 16ms (~60fps).
    ///
    /// # Example
    ///
    /// ```rust
    /// # use envision::prelude::*;
    /// # use std::time::Duration;
    /// # struct MyApp;
    /// # #[derive(Default, Clone)]
    /// # struct MyState;
    /// # #[derive(Clone)]
    /// # enum MyMsg {}
    /// # impl App for MyApp {
    /// #     type State = MyState;
    /// #     type Message = MyMsg;
    /// #     fn init() -> (MyState, Command<MyMsg>) { (MyState, Command::none()) }
    /// #     fn update(state: &mut MyState, msg: MyMsg) -> Command<MyMsg> { Command::none() }
    /// #     fn view(state: &MyState, frame: &mut Frame) {}
    /// # }
    /// let vt = Runtime::<MyApp, _>::virtual_builder(80, 24)
    ///     .frame_rate(Duration::from_millis(32))
    ///     .build()?;
    /// # Ok::<(), envision::EnvisionError>(())
    /// ```
    pub fn frame_rate(mut self, rate: Duration) -> Self {
        self.config_mut().frame_rate = rate;
        self
    }

    /// Sets the maximum number of messages to process per tick.
    ///
    /// This prevents infinite loops when messages trigger other messages.
    /// Default: 100.
    pub fn max_messages(mut self, max: usize) -> Self {
        self.config_mut().max_messages_per_tick = max;
        self
    }

    /// Sets the capacity of the async message channel.
    ///
    /// Default: 256.
    pub fn channel_capacity(mut self, capacity: usize) -> Self {
        self.config_mut().message_channel_capacity = capacity;
        self
    }

    /// Builds the [`Runtime`].
    ///
    /// If no state was provided via [`state()`](Self::state), this calls
    /// `App::init()` to obtain the initial state and startup command.
    /// If no config was provided, uses [`RuntimeConfig::default()`].
    ///
    /// # Errors
    ///
    /// Returns an error if creating the ratatui `Terminal` with the
    /// provided backend fails.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use envision::prelude::*;
    /// # struct MyApp;
    /// # #[derive(Default, Clone)]
    /// # struct MyState;
    /// # #[derive(Clone)]
    /// # enum MyMsg {}
    /// # impl App for MyApp {
    /// #     type State = MyState;
    /// #     type Message = MyMsg;
    /// #     fn init() -> (MyState, Command<MyMsg>) { (MyState, Command::none()) }
    /// #     fn update(state: &mut MyState, msg: MyMsg) -> Command<MyMsg> { Command::none() }
    /// #     fn view(state: &MyState, frame: &mut Frame) {}
    /// # }
    /// let runtime = Runtime::<MyApp, _>::virtual_builder(80, 24).build()?;
    /// # Ok::<(), envision::EnvisionError>(())
    /// ```
    pub fn build(self) -> error::Result<Runtime<A, B>> {
        let config = self.config.unwrap_or_default();
        let (state, init_cmd) = self.state.unwrap_or_else(A::init);
        Runtime::with_backend_state_and_config(self.backend, state, init_cmd, config)
    }

    /// Returns a mutable reference to the config, creating a default if needed.
    fn config_mut(&mut self) -> &mut RuntimeConfig {
        self.config.get_or_insert_with(RuntimeConfig::default)
    }
}

// =============================================================================
// Entry points on Runtime
// =============================================================================

impl<A: App, B: Backend> Runtime<A, B> {
    /// Creates a [`RuntimeBuilder`] with the given backend.
    ///
    /// This is the most flexible entry point — it accepts any backend
    /// implementing [`Backend`]. For common backends, prefer the
    /// convenience methods:
    /// - [`terminal_builder()`](Runtime::terminal_builder) for real terminals
    /// - [`virtual_builder()`](Runtime::virtual_builder) for virtual terminals
    ///
    /// # Example
    ///
    /// ```rust
    /// # use envision::prelude::*;
    /// # struct MyApp;
    /// # #[derive(Default, Clone)]
    /// # struct MyState;
    /// # #[derive(Clone)]
    /// # enum MyMsg {}
    /// # impl App for MyApp {
    /// #     type State = MyState;
    /// #     type Message = MyMsg;
    /// #     fn init() -> (MyState, Command<MyMsg>) { (MyState, Command::none()) }
    /// #     fn update(state: &mut MyState, msg: MyMsg) -> Command<MyMsg> { Command::none() }
    /// #     fn view(state: &MyState, frame: &mut Frame) {}
    /// # }
    /// let backend = CaptureBackend::new(80, 24);
    /// let runtime = Runtime::<MyApp, _>::builder(backend).build()?;
    /// # Ok::<(), envision::EnvisionError>(())
    /// ```
    pub fn builder(backend: B) -> RuntimeBuilder<A, B> {
        RuntimeBuilder::new(backend)
    }
}

// =============================================================================
// Terminal builder entry point
// =============================================================================

impl<A: App> Runtime<A, CrosstermBackend<Stdout>> {
    /// Creates a [`RuntimeBuilder`] for a real terminal.
    ///
    /// This performs terminal setup (raw mode, alternate screen, mouse
    /// capture) immediately and returns a builder for further configuration.
    /// The terminal remains in raw mode even if `build()` is never called,
    /// so callers should build promptly or handle cleanup.
    ///
    /// # Errors
    ///
    /// Returns an error if enabling raw mode, entering alternate screen,
    /// enabling mouse capture, or running the `on_setup` hook fails.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use envision::prelude::*;
    /// # struct MyApp;
    /// # #[derive(Default, Clone)]
    /// # struct MyState;
    /// # #[derive(Clone)]
    /// # enum MyMsg {}
    /// # impl App for MyApp {
    /// #     type State = MyState;
    /// #     type Message = MyMsg;
    /// #     fn init() -> (MyState, Command<MyMsg>) { (MyState, Command::none()) }
    /// #     fn update(state: &mut MyState, msg: MyMsg) -> Command<MyMsg> { Command::none() }
    /// #     fn view(state: &MyState, frame: &mut Frame) {}
    /// # }
    /// # #[tokio::main]
    /// # async fn main() -> envision::Result<()> {
    /// let _final_state = Runtime::<MyApp, _>::terminal_builder()?
    ///     .build()?
    ///     .run_terminal()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn terminal_builder() -> error::Result<RuntimeBuilder<A, CrosstermBackend<Stdout>>> {
        let config = RuntimeConfig::default();
        let backend = Self::setup_terminal(&config)?;
        Ok(RuntimeBuilder::new(backend))
    }
}

// =============================================================================
// Virtual terminal builder entry point
// =============================================================================

impl<A: App> Runtime<A, CaptureBackend> {
    /// Creates a [`RuntimeBuilder`] for a virtual terminal.
    ///
    /// A virtual terminal is not connected to a physical terminal. Events
    /// are injected via `send()`, the application is advanced via `tick()`,
    /// and the display can be inspected via `display()`.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use envision::prelude::*;
    /// # struct MyApp;
    /// # #[derive(Default, Clone)]
    /// # struct MyState;
    /// # #[derive(Clone)]
    /// # enum MyMsg {}
    /// # impl App for MyApp {
    /// #     type State = MyState;
    /// #     type Message = MyMsg;
    /// #     fn init() -> (MyState, Command<MyMsg>) { (MyState, Command::none()) }
    /// #     fn update(state: &mut MyState, msg: MyMsg) -> Command<MyMsg> { Command::none() }
    /// #     fn view(state: &MyState, frame: &mut Frame) {}
    /// # }
    /// let vt = Runtime::<MyApp, _>::virtual_builder(80, 24).build()?;
    /// # Ok::<(), envision::EnvisionError>(())
    /// ```
    pub fn virtual_builder(width: u16, height: u16) -> RuntimeBuilder<A, CaptureBackend> {
        let backend = CaptureBackend::new(width, height);
        RuntimeBuilder::new(backend)
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use super::*;
    use crate::app::command::Command;
    use crate::app::model::App;
    use ratatui::widgets::Paragraph;

    // =========================================================================
    // Test App
    // =========================================================================

    struct TestApp;

    #[derive(Clone, Default)]
    struct TestState {
        count: i32,
        quit: bool,
    }

    #[derive(Clone, Debug)]
    enum TestMsg {
        Increment,
        Quit,
    }

    impl App for TestApp {
        type State = TestState;
        type Message = TestMsg;

        fn init() -> (Self::State, Command<Self::Message>) {
            (TestState::default(), Command::none())
        }

        fn update(state: &mut Self::State, msg: Self::Message) -> Command<Self::Message> {
            match msg {
                TestMsg::Increment => state.count += 1,
                TestMsg::Quit => state.quit = true,
            }
            Command::none()
        }

        fn view(state: &Self::State, frame: &mut ratatui::Frame) {
            let text = format!("Count: {}", state.count);
            frame.render_widget(Paragraph::new(text), frame.area());
        }

        fn should_quit(state: &Self::State) -> bool {
            state.quit
        }
    }

    // =========================================================================
    // builder() — generic backend entry point
    // =========================================================================

    #[test]
    fn test_builder_with_capture_backend() {
        let backend = CaptureBackend::new(80, 24);
        let runtime = Runtime::<TestApp, _>::builder(backend).build().unwrap();
        assert_eq!(runtime.state().count, 0);
    }

    #[test]
    fn test_builder_with_state() {
        let backend = CaptureBackend::new(80, 24);
        let state = TestState {
            count: 42,
            quit: false,
        };
        let runtime = Runtime::<TestApp, _>::builder(backend)
            .state(state, Command::none())
            .build()
            .unwrap();
        assert_eq!(runtime.state().count, 42);
    }

    #[test]
    fn test_builder_with_config() {
        let backend = CaptureBackend::new(80, 24);
        let config = RuntimeConfig::new()
            .tick_rate(Duration::from_millis(100))
            .max_messages(50);
        let runtime = Runtime::<TestApp, _>::builder(backend)
            .config(config)
            .build()
            .unwrap();
        assert_eq!(runtime.state().count, 0);
    }

    #[test]
    fn test_builder_with_state_and_config() {
        let backend = CaptureBackend::new(80, 24);
        let state = TestState {
            count: 7,
            quit: false,
        };
        let config = RuntimeConfig::new().tick_rate(Duration::from_millis(200));
        let runtime = Runtime::<TestApp, _>::builder(backend)
            .state(state, Command::none())
            .config(config)
            .build()
            .unwrap();
        assert_eq!(runtime.state().count, 7);
    }

    // =========================================================================
    // virtual_builder() — CaptureBackend entry point
    // =========================================================================

    #[test]
    fn test_virtual_builder_default() {
        let runtime = Runtime::<TestApp, _>::virtual_builder(80, 24)
            .build()
            .unwrap();
        assert_eq!(runtime.state().count, 0);
    }

    #[test]
    fn test_virtual_builder_with_state() {
        let state = TestState {
            count: 99,
            quit: false,
        };
        let runtime = Runtime::<TestApp, _>::virtual_builder(80, 24)
            .state(state, Command::none())
            .build()
            .unwrap();
        assert_eq!(runtime.state().count, 99);
    }

    #[test]
    fn test_virtual_builder_with_tick_rate() {
        let mut runtime = Runtime::<TestApp, _>::virtual_builder(80, 24)
            .tick_rate(Duration::from_millis(200))
            .build()
            .unwrap();
        // Verify the runtime works (tick_rate is internal, but the runtime
        // should function correctly)
        runtime.dispatch(TestMsg::Increment);
        assert_eq!(runtime.state().count, 1);
    }

    #[test]
    fn test_virtual_builder_with_frame_rate() {
        let mut runtime = Runtime::<TestApp, _>::virtual_builder(80, 24)
            .frame_rate(Duration::from_millis(32))
            .build()
            .unwrap();
        runtime.tick().unwrap();
        assert!(runtime.contains_text("Count: 0"));
    }

    #[test]
    fn test_virtual_builder_with_max_messages() {
        let runtime = Runtime::<TestApp, _>::virtual_builder(80, 24)
            .max_messages(50)
            .build()
            .unwrap();
        assert_eq!(runtime.state().count, 0);
    }

    #[test]
    fn test_virtual_builder_with_channel_capacity() {
        let runtime = Runtime::<TestApp, _>::virtual_builder(80, 24)
            .channel_capacity(512)
            .build()
            .unwrap();
        assert_eq!(runtime.state().count, 0);
    }

    #[test]
    fn test_virtual_builder_chained_config() {
        let mut runtime = Runtime::<TestApp, _>::virtual_builder(80, 24)
            .tick_rate(Duration::from_millis(100))
            .frame_rate(Duration::from_millis(32))
            .max_messages(50)
            .channel_capacity(512)
            .build()
            .unwrap();

        runtime.dispatch(TestMsg::Increment);
        runtime.dispatch(TestMsg::Increment);
        runtime.tick().unwrap();
        assert_eq!(runtime.state().count, 2);
        assert!(runtime.contains_text("Count: 2"));
    }

    #[test]
    fn test_virtual_builder_state_and_config() {
        let state = TestState {
            count: 10,
            quit: false,
        };
        let mut runtime = Runtime::<TestApp, _>::virtual_builder(80, 24)
            .state(state, Command::none())
            .tick_rate(Duration::from_millis(100))
            .build()
            .unwrap();

        assert_eq!(runtime.state().count, 10);
        runtime.dispatch(TestMsg::Increment);
        assert_eq!(runtime.state().count, 11);
    }

    #[test]
    fn test_virtual_builder_config_overrides_individual_settings() {
        // When .config() is called after individual settings, it replaces them
        let config = RuntimeConfig::new().tick_rate(Duration::from_millis(200));
        let runtime = Runtime::<TestApp, _>::virtual_builder(80, 24)
            .tick_rate(Duration::from_millis(50)) // this gets overridden
            .config(config)
            .build()
            .unwrap();
        assert_eq!(runtime.state().count, 0);
    }

    #[test]
    fn test_virtual_builder_individual_settings_override_config() {
        // When individual settings are called after .config(), they modify it
        let config = RuntimeConfig::new().tick_rate(Duration::from_millis(200));
        let runtime = Runtime::<TestApp, _>::virtual_builder(80, 24)
            .config(config)
            .tick_rate(Duration::from_millis(50)) // this overrides the config's value
            .build()
            .unwrap();
        assert_eq!(runtime.state().count, 0);
    }

    // =========================================================================
    // Functional tests — verify built runtime works correctly
    // =========================================================================

    #[test]
    fn test_built_runtime_dispatch_and_render() {
        let mut runtime = Runtime::<TestApp, _>::virtual_builder(40, 10)
            .build()
            .unwrap();

        runtime.dispatch(TestMsg::Increment);
        runtime.dispatch(TestMsg::Increment);
        runtime.render().unwrap();

        assert!(runtime.contains_text("Count: 2"));
    }

    #[test]
    fn test_built_runtime_quit() {
        let mut runtime = Runtime::<TestApp, _>::virtual_builder(80, 24)
            .build()
            .unwrap();

        assert!(!runtime.should_quit());
        runtime.dispatch(TestMsg::Quit);
        runtime.tick().unwrap();
        assert!(runtime.should_quit());
    }

    #[test]
    fn test_built_runtime_send_and_tick() {
        use crate::input::Event;

        struct EventApp;

        #[derive(Clone, Default)]
        struct EventState {
            events: u32,
        }

        #[derive(Clone)]
        enum EventMsg {
            KeyPressed,
        }

        impl App for EventApp {
            type State = EventState;
            type Message = EventMsg;
            fn init() -> (Self::State, Command<Self::Message>) {
                (EventState::default(), Command::none())
            }
            fn update(state: &mut Self::State, msg: Self::Message) -> Command<Self::Message> {
                match msg {
                    EventMsg::KeyPressed => state.events += 1,
                }
                Command::none()
            }
            fn view(state: &Self::State, frame: &mut ratatui::Frame) {
                let text = format!("Events: {}", state.events);
                frame.render_widget(Paragraph::new(text), frame.area());
            }
            fn handle_event(event: &crate::input::Event) -> Option<Self::Message> {
                if event.as_key().is_some() {
                    Some(EventMsg::KeyPressed)
                } else {
                    None
                }
            }
        }

        let mut runtime = Runtime::<EventApp, _>::virtual_builder(80, 24)
            .build()
            .unwrap();

        runtime.send(Event::char('a'));
        runtime.send(Event::char('b'));
        runtime.tick().unwrap();

        assert_eq!(runtime.state().events, 2);
    }

    #[test]
    fn test_built_runtime_with_init_state_skips_app_init() {
        struct InitApp;

        #[derive(Clone, Default)]
        struct InitState {
            source: String,
        }

        #[derive(Clone)]
        enum InitMsg {}

        impl App for InitApp {
            type State = InitState;
            type Message = InitMsg;
            fn init() -> (Self::State, Command<Self::Message>) {
                (
                    InitState {
                        source: "App::init".into(),
                    },
                    Command::none(),
                )
            }
            fn update(_state: &mut Self::State, _msg: Self::Message) -> Command<Self::Message> {
                Command::none()
            }
            fn view(_state: &Self::State, _frame: &mut ratatui::Frame) {}
        }

        // Without state — should use App::init()
        let runtime = Runtime::<InitApp, _>::virtual_builder(80, 24)
            .build()
            .unwrap();
        assert_eq!(runtime.state().source, "App::init");

        // With state — should bypass App::init()
        let state = InitState {
            source: "external".into(),
        };
        let runtime = Runtime::<InitApp, _>::virtual_builder(80, 24)
            .state(state, Command::none())
            .build()
            .unwrap();
        assert_eq!(runtime.state().source, "external");
    }
}