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
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
mod async_tests;

use std::time::Duration;

use super::*;
use crate::error;
use ratatui::backend::CrosstermBackend;
use ratatui::widgets::Paragraph;
use std::io::Stdout;

struct CounterApp;

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

#[derive(Clone, Debug)]
enum CounterMsg {
    Increment,
    Decrement,
    IncrementBy(i32),
    Quit,
}

impl App for CounterApp {
    type State = CounterState;
    type Message = CounterMsg;

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

    fn update(state: &mut Self::State, msg: Self::Message) -> super::super::Command<Self::Message> {
        match msg {
            CounterMsg::Increment => state.count += 1,
            CounterMsg::Decrement => state.count -= 1,
            CounterMsg::IncrementBy(n) => state.count += n,
            CounterMsg::Quit => state.quit = true,
        }
        super::super::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
    }
}

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

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

    runtime.dispatch(CounterMsg::Increment);
    assert_eq!(runtime.state().count, 1);

    runtime.dispatch(CounterMsg::Increment);
    runtime.dispatch(CounterMsg::Increment);
    assert_eq!(runtime.state().count, 3);

    runtime.dispatch(CounterMsg::Decrement);
    assert_eq!(runtime.state().count, 2);
}

#[test]
fn test_runtime_render() {
    let mut runtime: Runtime<CounterApp, _> = Runtime::virtual_builder(40, 10).build().unwrap();
    runtime.dispatch(CounterMsg::Increment);
    runtime.dispatch(CounterMsg::Increment);
    runtime.render().unwrap();

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

#[test]
fn test_runtime_quit() {
    let mut runtime: Runtime<CounterApp, _> = Runtime::virtual_builder(80, 24).build().unwrap();
    assert!(!runtime.should_quit());

    runtime.dispatch(CounterMsg::Quit);
    runtime.tick().unwrap();

    assert!(runtime.should_quit());
}

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

    // Queue some events - we'd need to implement handle_event for this
    runtime.dispatch(CounterMsg::Increment);
    runtime.tick().unwrap();

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

#[test]
fn test_runtime_config() {
    let config = RuntimeConfig::new()
        .tick_rate(Duration::from_millis(100))
        .frame_rate(Duration::from_millis(32))
        .with_history(5)
        .max_messages(50)
        .channel_capacity(512);

    assert_eq!(config.tick_rate, Duration::from_millis(100));
    assert_eq!(config.frame_rate, Duration::from_millis(32));
    assert!(config.capture_history);
    assert_eq!(config.history_capacity, 5);
    assert_eq!(config.max_messages_per_tick, 50);
    assert_eq!(config.message_channel_capacity, 512);
}

#[test]
fn test_runtime_config_default() {
    let config = RuntimeConfig::default();
    assert_eq!(config.tick_rate, Duration::from_millis(50));
    assert_eq!(config.frame_rate, Duration::from_millis(16));
    assert_eq!(config.max_messages_per_tick, 100);
    assert!(!config.capture_history);
    assert_eq!(config.history_capacity, 10);
    assert_eq!(config.message_channel_capacity, 256);
}

#[test]
fn test_runtime_headless_with_config() {
    let config = RuntimeConfig::new().with_history(5);
    let runtime: Runtime<CounterApp, _> = Runtime::virtual_builder(80, 24)
        .config(config)
        .build()
        .unwrap();
    assert_eq!(runtime.state().count, 0);
}

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

#[test]
fn test_runtime_state_mut() {
    let mut runtime: Runtime<CounterApp, _> = Runtime::virtual_builder(80, 24).build().unwrap();
    runtime.state_mut().count = 42;
    assert_eq!(runtime.state().count, 42);
}

#[test]
fn test_runtime_terminal_access() {
    let runtime: Runtime<CounterApp, _> = Runtime::virtual_builder(80, 24).build().unwrap();
    let terminal = runtime.terminal();
    assert_eq!(terminal.backend().width(), 80);
    assert_eq!(terminal.backend().height(), 24);
}

#[test]
fn test_runtime_terminal_mut() {
    let mut runtime: Runtime<CounterApp, _> = Runtime::virtual_builder(80, 24).build().unwrap();
    let _terminal = runtime.terminal_mut();
    // Just verify we can get mutable access
}

#[test]
fn test_runtime_backend_access() {
    let runtime: Runtime<CounterApp, _> = Runtime::virtual_builder(80, 24).build().unwrap();
    let backend = runtime.backend();
    assert_eq!(backend.width(), 80);
}

#[test]
fn test_runtime_backend_mut() {
    let mut runtime: Runtime<CounterApp, _> = Runtime::virtual_builder(80, 24).build().unwrap();
    let backend = runtime.backend_mut();
    assert_eq!(backend.width(), 80);
}

#[test]
fn test_runtime_events_access() {
    let mut runtime: Runtime<CounterApp, _> = Runtime::virtual_builder(80, 24).build().unwrap();
    let events = runtime.events();
    assert!(events.is_empty());
}

#[test]
fn test_runtime_cancellation_token() {
    let runtime: Runtime<CounterApp, _> = Runtime::virtual_builder(80, 24).build().unwrap();
    let token = runtime.cancellation_token();
    assert!(!token.is_cancelled());
}

#[test]
fn test_command_request_cancel_token() {
    // Use an app that stores the cancel token via init command
    struct TokenApp;
    #[derive(Default)]
    struct TokenState {
        token: Option<tokio_util::sync::CancellationToken>,
    }
    #[derive(Clone)]
    enum TokenMsg {
        GotToken(tokio_util::sync::CancellationToken),
    }
    impl crate::app::App for TokenApp {
        type State = TokenState;
        type Message = TokenMsg;
        fn init() -> (TokenState, Command<TokenMsg>) {
            (
                TokenState::default(),
                Command::request_cancel_token(TokenMsg::GotToken),
            )
        }
        fn update(state: &mut TokenState, msg: TokenMsg) -> Command<TokenMsg> {
            match msg {
                TokenMsg::GotToken(token) => state.token = Some(token),
            }
            Command::none()
        }
        fn view(_state: &TokenState, _frame: &mut ratatui::Frame) {}
    }

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

    // The cancel token should now be stored in state
    assert!(runtime.state().token.is_some());
    let stored_token = runtime.state().token.as_ref().unwrap().clone();

    // It should not be cancelled yet
    assert!(!stored_token.is_cancelled());

    // After quitting, the stored token should be cancelled
    runtime.quit();
    assert!(stored_token.is_cancelled());
}

#[test]
fn test_runtime_message_sender() {
    let runtime: Runtime<CounterApp, _> = Runtime::virtual_builder(80, 24).build().unwrap();
    let _sender = runtime.message_sender();
}

#[test]
fn test_runtime_error_sender() {
    let runtime: Runtime<CounterApp, _> = Runtime::virtual_builder(80, 24).build().unwrap();
    let _error_tx = runtime.error_sender();
}

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

    runtime.dispatch_all(vec![
        CounterMsg::Increment,
        CounterMsg::Increment,
        CounterMsg::Decrement,
    ]);

    assert_eq!(runtime.state().count, 1);
}

#[test]
fn test_runtime_manual_quit() {
    let mut runtime: Runtime<CounterApp, _> = Runtime::virtual_builder(80, 24).build().unwrap();
    assert!(!runtime.should_quit());
    assert!(!runtime.cancellation_token().is_cancelled());

    runtime.quit();
    assert!(runtime.should_quit());
    assert!(runtime.cancellation_token().is_cancelled());
}

#[test]
fn test_runtime_run_ticks() {
    let mut runtime: Runtime<CounterApp, _> = Runtime::virtual_builder(40, 10).build().unwrap();
    runtime.dispatch(CounterMsg::Increment);

    runtime.run_ticks(3).unwrap();
    assert!(runtime.contains_text("Count: 1"));
}

#[test]
fn test_runtime_run_ticks_with_quit() {
    let mut runtime: Runtime<CounterApp, _> = Runtime::virtual_builder(40, 10).build().unwrap();
    runtime.dispatch(CounterMsg::Quit);
    runtime.tick().unwrap();

    // Should stop early due to quit
    runtime.run_ticks(10).unwrap();
    assert!(runtime.should_quit());
}

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

    let output = runtime.display();
    assert!(output.contains("Count: 0"));
}

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

    let ansi = runtime.display_ansi();
    assert!(ansi.contains("Count: 0"));
}

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

    let positions = runtime.find_text("Count");
    assert!(!positions.is_empty());
}

// Test app that handles events and uses on_tick
struct EventApp;

#[derive(Clone, Default)]
struct EventState {
    events_received: u32,
    last_key: Option<char>,
    ticks: u32,
    quit: bool,
}

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

impl App for EventApp {
    type State = EventState;
    type Message = EventMsg;

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

    fn update(state: &mut Self::State, msg: Self::Message) -> super::super::Command<Self::Message> {
        match msg {
            EventMsg::KeyPressed(c) => {
                state.events_received += 1;
                state.last_key = Some(c);
            }
            EventMsg::Tick => state.ticks += 1,
            EventMsg::Quit => state.quit = true,
        }
        super::super::Command::none()
    }

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

    fn handle_event(event: &crate::input::Event) -> Option<Self::Message> {
        use crate::input::Key;
        if let Some(key) = event.as_key() {
            if let Key::Char(c) = key.code {
                if c == 'q' {
                    return Some(EventMsg::Quit);
                }
                return Some(EventMsg::KeyPressed(c));
            }
        }
        None
    }

    fn on_tick(_state: &Self::State) -> Option<Self::Message> {
        Some(EventMsg::Tick)
    }

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

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

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

    runtime.events().push(Event::char('a'));
    assert!(runtime.process_event());
    assert_eq!(runtime.state().events_received, 1);

    // No more events
    assert!(!runtime.process_event());
}

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

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

    runtime.events().push(Event::char('a'));
    runtime.events().push(Event::char('b'));
    runtime.events().push(Event::char('c'));

    runtime.process_all_events();
    assert_eq!(runtime.state().events_received, 3);
}

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

    runtime.tick().unwrap();
    assert_eq!(runtime.state().ticks, 1);

    runtime.tick().unwrap();
    assert_eq!(runtime.state().ticks, 2);
}

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

    let mut runtime: Runtime<EventApp, _> = Runtime::virtual_builder(80, 24).build().unwrap();
    runtime.events().push(Event::char('q'));

    runtime.tick().unwrap();
    assert!(runtime.should_quit());
}

#[test]
fn test_runtime_process_commands() {
    // Test with an app that issues commands
    struct CmdApp;

    #[derive(Clone, Default)]
    struct CmdState {
        value: i32,
    }

    #[derive(Clone)]
    enum CmdMsg {
        Set(i32),
        Double,
    }

    impl App for CmdApp {
        type State = CmdState;
        type Message = CmdMsg;

        fn init() -> (Self::State, super::super::Command<Self::Message>) {
            // Issue a command on init
            (
                CmdState::default(),
                super::super::Command::message(CmdMsg::Set(10)),
            )
        }

        fn update(
            state: &mut Self::State,
            msg: Self::Message,
        ) -> super::super::Command<Self::Message> {
            match msg {
                CmdMsg::Set(v) => {
                    state.value = v;
                    super::super::Command::none()
                }
                CmdMsg::Double => {
                    state.value *= 2;
                    super::super::Command::none()
                }
            }
        }

        fn view(_state: &Self::State, _frame: &mut ratatui::Frame) {}
    }

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

    // Process init command (Set(10))
    runtime.process_commands();
    assert_eq!(runtime.state().value, 10);

    // Manually dispatch Double message to test that variant
    runtime.dispatch(CmdMsg::Double);
    runtime.process_commands();
    assert_eq!(runtime.state().value, 20);
}

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

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

    // Queue more events than max_messages_per_tick
    for _ in 0..5 {
        runtime.events().push(Event::char('x'));
    }

    runtime.tick().unwrap();
    // Should only process up to max_messages (2)
    // But since on_tick also increments ticks, let's check events
    assert!(runtime.state().events_received <= 3);
}

// =========================================================================
// Virtual Terminal API Tests
// =========================================================================

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

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

    // Send events
    vt.send(Event::char('a'));
    vt.send(Event::char('b'));

    // Step processes the events
    vt.tick().unwrap();

    assert_eq!(vt.state().events_received, 2);
}

#[test]
fn test_virtual_terminal_display() {
    let mut vt: Runtime<CounterApp, _> = Runtime::virtual_builder(40, 10).build().unwrap();
    vt.dispatch(CounterMsg::Increment);
    vt.tick().unwrap();

    let display = vt.display();
    assert!(display.contains("Count: 1"));
}

#[test]
fn test_virtual_terminal_display_ansi() {
    let mut vt: Runtime<CounterApp, _> = Runtime::virtual_builder(40, 10).build().unwrap();
    vt.dispatch(CounterMsg::Increment);
    vt.tick().unwrap();

    let display = vt.display_ansi();
    assert!(display.contains("Count: 1"));
}

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

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

    vt.send(Event::char('q'));
    vt.tick().unwrap();

    assert!(vt.should_quit());
}

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

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

    // First tick with one event
    vt.send(Event::char('a'));
    vt.tick().unwrap();
    assert_eq!(vt.state().events_received, 1);

    // Second tick with two events
    vt.send(Event::char('b'));
    vt.send(Event::char('c'));
    vt.tick().unwrap();
    assert_eq!(vt.state().events_received, 3);
}

#[test]
fn test_virtual_terminal_cell_at() {
    let mut vt: Runtime<CounterApp, _> = Runtime::virtual_builder(40, 10).build().unwrap();
    vt.tick().unwrap();

    // Cell at (0,0) should have the 'C' from "Count: 0"
    let cell = vt.cell_at(0, 0).unwrap();
    assert_eq!(cell.symbol(), "C");

    // Out of bounds should return None
    assert!(vt.cell_at(100, 100).is_none());
}

#[test]
fn test_virtual_terminal_contains_text() {
    let mut vt: Runtime<CounterApp, _> = Runtime::virtual_builder(40, 10).build().unwrap();
    vt.tick().unwrap();

    assert!(vt.contains_text("Count: 0"));
    assert!(!vt.contains_text("Not Here"));
}

#[test]
fn test_virtual_terminal_find_text() {
    let mut vt: Runtime<CounterApp, _> = Runtime::virtual_builder(40, 10).build().unwrap();
    vt.tick().unwrap();

    let positions = vt.find_text("Count");
    assert!(!positions.is_empty());

    let positions = vt.find_text("Not Here");
    assert!(positions.is_empty());
}

#[test]
fn test_run_terminal_blocking_exists() {
    // Verify that run_terminal_blocking is available on the terminal runtime type.
    // We can't actually call it (requires a real terminal), but we can verify
    // the method exists by taking a function pointer to it.
    let _: fn(Runtime<CounterApp, CrosstermBackend<Stdout>>) -> error::Result<CounterState> =
        Runtime::<CounterApp, CrosstermBackend<Stdout>>::run_terminal_blocking;
}

// =========================================================================
// Overlay Tests
// =========================================================================

mod overlay_tests {
    use super::*;
    use crate::app::Command;
    use crate::component::RenderContext;
    use crate::input::Event;
    use crate::input::Key;
    use crate::overlay::{Overlay, OverlayAction};

    /// An overlay that consumes all events.
    struct ConsumeOverlay;

    impl Overlay<CounterMsg> for ConsumeOverlay {
        fn handle_event(&mut self, _event: &Event) -> OverlayAction<CounterMsg> {
            OverlayAction::Consumed
        }
        fn view(&self, _ctx: &mut RenderContext<'_, '_>) {}
    }

    /// An overlay that propagates all events.
    struct PropagateOverlay;

    impl Overlay<EventMsg> for PropagateOverlay {
        fn handle_event(&mut self, _event: &Event) -> OverlayAction<EventMsg> {
            OverlayAction::Propagate
        }
        fn view(&self, _ctx: &mut RenderContext<'_, '_>) {}
    }

    /// An overlay that dismisses on Esc and sends a message on Enter.
    struct DialogOverlay;

    impl Overlay<EventMsg> for DialogOverlay {
        fn handle_event(&mut self, event: &Event) -> OverlayAction<EventMsg> {
            if let Some(key) = event.as_key() {
                match key.code {
                    Key::Esc => OverlayAction::Dismiss,
                    Key::Enter => OverlayAction::DismissWithMessage(EventMsg::KeyPressed('!')),
                    _ => OverlayAction::Consumed,
                }
            } else {
                OverlayAction::Propagate
            }
        }
        fn view(&self, _ctx: &mut RenderContext<'_, '_>) {}
    }

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

        assert!(!vt.has_overlays());
        assert_eq!(vt.overlay_count(), 0);

        vt.push_overlay(Box::new(ConsumeOverlay));
        assert!(vt.has_overlays());
        assert_eq!(vt.overlay_count(), 1);

        vt.push_overlay(Box::new(ConsumeOverlay));
        assert_eq!(vt.overlay_count(), 2);

        let popped = vt.pop_overlay();
        assert!(popped.is_some());
        assert_eq!(vt.overlay_count(), 1);

        vt.clear_overlays();
        assert!(!vt.has_overlays());
    }

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

        // Push an overlay that consumes all events
        struct ConsumeAll;
        impl Overlay<EventMsg> for ConsumeAll {
            fn handle_event(&mut self, _event: &Event) -> OverlayAction<EventMsg> {
                OverlayAction::Consumed
            }
            fn view(&self, _ctx: &mut RenderContext<'_, '_>) {}
        }

        vt.push_overlay(Box::new(ConsumeAll));

        // Send events — they should be consumed by the overlay, not reaching the app
        vt.send(Event::char('a'));
        vt.send(Event::char('b'));
        vt.tick().unwrap();

        assert_eq!(vt.state().events_received, 0);
    }

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

        // Push an overlay that propagates all events
        vt.push_overlay(Box::new(PropagateOverlay));

        // Send events — they should reach the app
        vt.send(Event::char('a'));
        vt.tick().unwrap();

        assert_eq!(vt.state().events_received, 1);
    }

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

        vt.push_overlay(Box::new(DialogOverlay));
        assert_eq!(vt.overlay_count(), 1);

        // Esc dismisses the overlay
        vt.send(Event::key(Key::Esc));
        vt.tick().unwrap();

        assert_eq!(vt.overlay_count(), 0);
    }

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

        vt.push_overlay(Box::new(DialogOverlay));

        // Enter dismisses with a message
        vt.send(Event::key(Key::Enter));
        vt.tick().unwrap();

        assert_eq!(vt.overlay_count(), 0);
        // The message should have been dispatched
        assert_eq!(vt.state().events_received, 1);
        assert_eq!(vt.state().last_key, Some('!'));
    }

    #[test]
    fn test_runtime_overlay_via_command() {
        // Test that Command::push_overlay and Command::pop_overlay work through the runtime
        struct CmdOverlayApp;

        #[derive(Clone, Default)]
        struct CmdOverlayState {
            overlay_pushed: bool,
        }

        #[derive(Clone)]
        enum CmdOverlayMsg {
            PushOverlay,
            PopOverlay,
        }

        struct NoopOverlay;
        impl Overlay<CmdOverlayMsg> for NoopOverlay {
            fn handle_event(&mut self, _event: &Event) -> OverlayAction<CmdOverlayMsg> {
                OverlayAction::Consumed
            }
            fn view(&self, _ctx: &mut RenderContext<'_, '_>) {}
        }

        impl App for CmdOverlayApp {
            type State = CmdOverlayState;
            type Message = CmdOverlayMsg;

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

            fn update(state: &mut Self::State, msg: Self::Message) -> Command<Self::Message> {
                match msg {
                    CmdOverlayMsg::PushOverlay => {
                        state.overlay_pushed = true;
                        Command::push_overlay(NoopOverlay)
                    }
                    CmdOverlayMsg::PopOverlay => Command::pop_overlay(),
                }
            }

            fn view(_state: &Self::State, _frame: &mut ratatui::Frame) {}
        }

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

        // Dispatch push overlay message
        vt.dispatch(CmdOverlayMsg::PushOverlay);
        vt.process_commands();
        assert!(vt.has_overlays());
        assert_eq!(vt.overlay_count(), 1);

        // Dispatch pop overlay message
        vt.dispatch(CmdOverlayMsg::PopOverlay);
        vt.process_commands();
        assert!(!vt.has_overlays());
    }

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

        // Default theme should be set
        let _theme = vt.theme();

        // Set a custom theme
        let nord = Theme::nord();
        let expected_bg = nord.background;
        vt.set_theme(nord);
        assert_eq!(vt.theme().background, expected_bg);
    }

    #[test]
    fn test_runtime_render_with_overlay() {
        // Verifies the overlay rendering path in render()
        let mut vt: Runtime<CounterApp, _> = Runtime::virtual_builder(40, 10).build().unwrap();

        vt.push_overlay(Box::new(ConsumeOverlay));
        vt.render().unwrap();

        // App content should still be rendered underneath
        assert!(vt.contains_text("Count: 0"));
    }

    #[test]
    fn test_runtime_overlay_message_from_event() {
        // Test the OverlayAction::KeepAndMessage path in process_event
        struct MsgOverlay;
        impl Overlay<EventMsg> for MsgOverlay {
            fn handle_event(&mut self, _event: &Event) -> OverlayAction<EventMsg> {
                OverlayAction::KeepAndMessage(EventMsg::KeyPressed('z'))
            }
            fn view(&self, _ctx: &mut RenderContext<'_, '_>) {}
        }

        let mut vt: Runtime<EventApp, _> = Runtime::virtual_builder(80, 24).build().unwrap();
        vt.push_overlay(Box::new(MsgOverlay));

        vt.send(Event::char('x'));
        vt.tick().unwrap();

        // The overlay should have produced a message, not the app's handle_event
        assert_eq!(vt.state().events_received, 1);
        assert_eq!(vt.state().last_key, Some('z'));
    }

    #[test]
    fn test_runtime_process_commands_overlay_push_pop() {
        // Directly test the overlay processing in process_commands()
        struct CmdApp;

        #[derive(Clone, Default)]
        struct CmdState;

        #[derive(Clone)]
        enum CmdMsg {
            Push,
            Pop,
        }

        struct NoopOverlay;
        impl Overlay<CmdMsg> for NoopOverlay {
            fn handle_event(&mut self, _event: &Event) -> OverlayAction<CmdMsg> {
                OverlayAction::Consumed
            }
            fn view(&self, _ctx: &mut RenderContext<'_, '_>) {}
        }

        impl App for CmdApp {
            type State = CmdState;
            type Message = CmdMsg;

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

            fn update(_state: &mut Self::State, msg: Self::Message) -> Command<Self::Message> {
                match msg {
                    CmdMsg::Push => Command::push_overlay(NoopOverlay),
                    CmdMsg::Pop => Command::pop_overlay(),
                }
            }

            fn view(_state: &Self::State, _frame: &mut ratatui::Frame) {}
        }

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

        // Push two overlays via commands
        vt.dispatch(CmdMsg::Push);
        vt.process_commands();
        assert_eq!(vt.overlay_count(), 1);

        vt.dispatch(CmdMsg::Push);
        vt.process_commands();
        assert_eq!(vt.overlay_count(), 2);

        // Pop one via command
        vt.dispatch(CmdMsg::Pop);
        vt.process_commands();
        assert_eq!(vt.overlay_count(), 1);
    }
}