rnk 0.15.31

A React-like declarative terminal UI framework for Rust, inspired by Ink
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
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
//! Command System for managing side effects
//!
//! The Command system provides a declarative way to describe side effects
//! (async operations, timers, I/O) without executing them immediately.
//! This enables better control, testability, and predictability.
//!
//! # Command Types
//!
//! - [`Cmd::none()`] - No-op command
//! - [`Cmd::perform()`] - Execute an async task
//! - [`Cmd::batch()`] - Execute multiple commands concurrently (no ordering)
//! - [`Cmd::sequence()`] - Execute multiple commands sequentially (in order)
//! - [`Cmd::sleep()`] - Sleep for a duration
//! - [`Cmd::tick()`] - Execute callback after a duration
//! - [`Cmd::every()`] - Execute callback aligned to system clock
//! - [`Cmd::exec()`] - Execute external interactive process (suspends TUI)
//!
//! # Typed Commands
//!
//! For type-safe message passing, use [`TypedCmd<M>`]:
//!
//! ```rust,ignore
//! use rnk::cmd::TypedCmd;
//!
//! enum Msg {
//!     DataLoaded(String),
//!     Error(String),
//! }
//!
//! let cmd: TypedCmd<Msg> = TypedCmd::perform(|| async {
//!     match fetch_data().await {
//!         Ok(data) => Msg::DataLoaded(data),
//!         Err(e) => Msg::Error(e.to_string()),
//!     }
//! });
//! ```
//!
//! # Example
//!
//! ```rust
//! use rnk::cmd::{Cmd, CmdExecutor};
//! use std::time::Duration;
//! use tokio::sync::mpsc;
//!
//! // Create executor
//! let (tx, mut rx) = mpsc::unbounded_channel();
//! let executor = CmdExecutor::new(tx);
//!
//! // Create and execute commands concurrently
//! let cmd = Cmd::batch(vec![
//!     Cmd::sleep(Duration::from_secs(1)),
//!     Cmd::perform(|| async {
//!         println!("Task completed!");
//!     }),
//! ]);
//!
//! // Or execute commands sequentially
//! let cmd = Cmd::sequence(vec![
//!     Cmd::sleep(Duration::from_secs(1)),
//!     Cmd::perform(|| async {
//!         println!("After 1 second!");
//!     }),
//! ]);
//!
//! executor.execute(cmd);
//! ```

mod exec;
mod executor;
mod msg;
mod tasks;

pub use exec::{ExecConfig, ExecResult};
pub use executor::{CmdExecutor, RenderHandle, run_exec_process};
pub use msg::{AppMsg, BoxedMsg, TypedCmd};
pub use tasks::{HttpRequest, HttpResponse, ProcessOutput};

pub(crate) use exec::ExecRequest;

use std::future::Future;
use std::pin::Pin;
use std::time::{Duration, Instant};

/// A command represents a side effect to be executed.
///
/// Commands are descriptions of side effects, not the execution itself.
/// This allows for better control, composition, and testing.
#[derive(Default)]
pub enum Cmd {
    /// No-op command that does nothing
    #[default]
    None,

    /// Execute multiple commands concurrently (no ordering guarantees)
    Batch(Vec<Cmd>),

    /// Execute multiple commands sequentially (in order)
    Sequence(Vec<Cmd>),

    /// Execute an async task
    Perform {
        /// The future to execute
        future: Pin<Box<dyn Future<Output = ()> + Send + 'static>>,
    },

    /// Sleep for a duration, then execute another command
    Sleep {
        /// Duration to sleep
        duration: Duration,
        /// Command to execute after sleeping
        then: Box<Cmd>,
    },

    /// Timer tick - executes callback after duration with timestamp
    Tick {
        /// Duration to wait
        duration: Duration,
        /// Callback that receives the tick timestamp
        callback: Box<dyn FnOnce(Instant) + Send + 'static>,
    },

    /// System clock aligned tick - executes callback aligned to clock boundaries
    Every {
        /// Duration interval (aligned to system clock)
        duration: Duration,
        /// Callback that receives the tick timestamp
        callback: Box<dyn FnOnce(Instant) + Send + 'static>,
    },

    /// Execute an external interactive process (suspends TUI)
    ///
    /// This command suspends the TUI, executes an external process
    /// (like vim, less, etc.) with full terminal control, and then
    /// resumes the TUI when the process exits.
    Exec {
        /// Configuration for the external process
        config: ExecConfig,
        /// Callback that receives the result when the process exits
        callback: Box<dyn FnOnce(ExecResult) + Send + 'static>,
    },

    /// Clear the terminal screen
    ///
    /// In fullscreen mode, this clears the entire screen.
    /// In inline mode, this clears the current UI output.
    ClearScreen,

    /// Hide the terminal cursor
    HideCursor,

    /// Show the terminal cursor
    ShowCursor,

    /// Set the terminal window title
    SetWindowTitle(String),

    /// Request the current window size
    ///
    /// This triggers a WindowSizeMsg to be sent to the update function.
    WindowSize,

    /// Enter alternate screen buffer (fullscreen mode)
    EnterAltScreen,

    /// Exit alternate screen buffer (return to inline mode)
    ExitAltScreen,

    /// Enable mouse support
    EnableMouse,

    /// Disable mouse support
    DisableMouse,

    /// Enable bracketed paste mode
    EnableBracketedPaste,

    /// Disable bracketed paste mode
    DisableBracketedPaste,
}

impl Cmd {
    /// Create a no-op command
    ///
    /// # Example
    ///
    /// ```rust
    /// use rnk::cmd::Cmd;
    ///
    /// let cmd = Cmd::none();
    /// ```
    pub fn none() -> Self {
        Cmd::None
    }

    /// Create a batch command that executes multiple commands in parallel
    ///
    /// Empty batches and single-item batches are optimized to avoid nesting.
    ///
    /// # Example
    ///
    /// ```rust
    /// use rnk::cmd::Cmd;
    ///
    /// let cmd = Cmd::batch(vec![
    ///     Cmd::none(),
    ///     Cmd::none(),
    /// ]);
    /// ```
    pub fn batch(cmds: impl IntoIterator<Item = Cmd>) -> Self {
        let mut cmds: Vec<Cmd> = cmds
            .into_iter()
            .filter(|cmd| !matches!(cmd, Cmd::None))
            .collect();

        match cmds.len() {
            0 => Cmd::None,
            1 => cmds.pop().unwrap(),
            _ => Cmd::Batch(cmds),
        }
    }

    /// Create a sequence command that executes multiple commands in order
    ///
    /// Unlike `batch`, which runs commands concurrently, `sequence` runs
    /// commands one at a time, waiting for each to complete before starting
    /// the next.
    ///
    /// Empty sequences and single-item sequences are optimized to avoid nesting.
    ///
    /// # Example
    ///
    /// ```rust
    /// use rnk::cmd::Cmd;
    /// use std::time::Duration;
    ///
    /// let cmd = Cmd::sequence(vec![
    ///     Cmd::sleep(Duration::from_millis(100)),
    ///     Cmd::perform(|| async {
    ///         println!("After 100ms");
    ///     }),
    ///     Cmd::sleep(Duration::from_millis(100)),
    ///     Cmd::perform(|| async {
    ///         println!("After 200ms total");
    ///     }),
    /// ]);
    /// ```
    pub fn sequence(cmds: impl IntoIterator<Item = Cmd>) -> Self {
        let mut cmds: Vec<Cmd> = cmds
            .into_iter()
            .filter(|cmd| !matches!(cmd, Cmd::None))
            .collect();

        match cmds.len() {
            0 => Cmd::None,
            1 => cmds.pop().unwrap(),
            _ => Cmd::Sequence(cmds),
        }
    }

    /// Create a command that executes an async function
    ///
    /// # Example
    ///
    /// ```rust
    /// use rnk::cmd::Cmd;
    ///
    /// let cmd = Cmd::perform(|| async {
    ///     println!("Hello from async!");
    /// });
    /// ```
    pub fn perform<F, Fut>(f: F) -> Self
    where
        F: FnOnce() -> Fut + Send + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        Cmd::Perform {
            future: Box::pin(async move { f().await }),
        }
    }

    /// Create a command that sleeps for a duration
    ///
    /// # Example
    ///
    /// ```rust
    /// use rnk::cmd::Cmd;
    /// use std::time::Duration;
    ///
    /// let cmd = Cmd::sleep(Duration::from_secs(1));
    /// ```
    pub fn sleep(duration: Duration) -> Self {
        Cmd::Sleep {
            duration,
            then: Box::new(Cmd::None),
        }
    }

    /// Create a tick command that executes a callback after a duration
    ///
    /// The callback receives the timestamp when the tick occurred.
    /// Unlike `sleep`, `tick` is designed for timer-based updates where
    /// you need the exact time the tick fired.
    ///
    /// Note: `tick` sends a single message. To create a recurring timer,
    /// return another `tick` command from your callback.
    ///
    /// # Example
    ///
    /// ```rust
    /// use rnk::cmd::Cmd;
    /// use std::time::Duration;
    /// use std::sync::{Arc, atomic::{AtomicU64, Ordering}};
    ///
    /// let counter = Arc::new(AtomicU64::new(0));
    /// let counter_clone = counter.clone();
    ///
    /// let cmd = Cmd::tick(Duration::from_secs(1), move |_timestamp| {
    ///     counter_clone.fetch_add(1, Ordering::SeqCst);
    /// });
    /// ```
    pub fn tick<F>(duration: Duration, callback: F) -> Self
    where
        F: FnOnce(Instant) + Send + 'static,
    {
        Cmd::Tick {
            duration,
            callback: Box::new(callback),
        }
    }

    /// Create a command that ticks in sync with the system clock
    ///
    /// Unlike `tick`, which starts timing from when it's invoked, `every`
    /// aligns to system clock boundaries. For example, if you want to tick
    /// every second and the current time is 12:34:56.789, the first tick
    /// will occur at 12:34:57.000.
    ///
    /// This is useful for:
    /// - Displaying clocks that update on the second
    /// - Synchronizing multiple timers
    /// - Creating animations that align with wall clock time
    ///
    /// Note: `every` sends a single message. To create a recurring timer,
    /// return another `every` command from your callback.
    ///
    /// # Example
    ///
    /// ```rust
    /// use rnk::cmd::Cmd;
    /// use std::time::Duration;
    /// use std::sync::{Arc, atomic::{AtomicU64, Ordering}};
    ///
    /// let counter = Arc::new(AtomicU64::new(0));
    /// let counter_clone = counter.clone();
    ///
    /// // Tick every second, aligned to system clock
    /// let cmd = Cmd::every(Duration::from_secs(1), move |_timestamp| {
    ///     counter_clone.fetch_add(1, Ordering::SeqCst);
    /// });
    /// ```
    pub fn every<F>(duration: Duration, callback: F) -> Self
    where
        F: FnOnce(Instant) + Send + 'static,
    {
        Cmd::Every {
            duration,
            callback: Box::new(callback),
        }
    }

    /// Execute an external interactive process (suspends TUI)
    ///
    /// This command suspends the TUI, executes an external process
    /// (like vim, less, etc.) with full terminal control, and then
    /// resumes the TUI when the process exits.
    ///
    /// # Example
    ///
    /// ```rust
    /// use rnk::cmd::{Cmd, ExecConfig};
    ///
    /// // Open a file in vim
    /// let cmd = Cmd::exec(
    ///     ExecConfig::new("vim").arg("file.txt"),
    ///     |result| {
    ///         if result.success {
    ///             println!("Editor closed successfully");
    ///         }
    ///     }
    /// );
    /// ```
    pub fn exec<F>(config: ExecConfig, callback: F) -> Self
    where
        F: FnOnce(ExecResult) + Send + 'static,
    {
        Cmd::Exec {
            config,
            callback: Box::new(callback),
        }
    }

    /// Execute an external command with simple arguments (convenience method)
    ///
    /// This is a shorthand for `Cmd::exec(ExecConfig::new(program).args(args), callback)`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use rnk::cmd::Cmd;
    ///
    /// // Open a file in vim
    /// let cmd = Cmd::exec_cmd("vim", &["file.txt"], |result| {
    ///     println!("Exit code: {:?}", result.exit_code);
    /// });
    ///
    /// // View a file with less
    /// let cmd = Cmd::exec_cmd("less", &["README.md"], |_| {});
    /// ```
    pub fn exec_cmd<F>(program: &str, args: &[&str], callback: F) -> Self
    where
        F: FnOnce(ExecResult) + Send + 'static,
    {
        let config = ExecConfig::new(program).args(args.iter().map(|s| s.to_string()));
        Cmd::exec(config, callback)
    }

    /// Clear the terminal screen
    ///
    /// In fullscreen mode, this clears the entire screen.
    /// In inline mode, this clears the current UI output.
    ///
    /// # Example
    ///
    /// ```rust
    /// use rnk::cmd::Cmd;
    ///
    /// let cmd = Cmd::clear_screen();
    /// ```
    pub fn clear_screen() -> Self {
        Cmd::ClearScreen
    }

    /// Hide the terminal cursor
    ///
    /// # Example
    ///
    /// ```rust
    /// use rnk::cmd::Cmd;
    ///
    /// let cmd = Cmd::hide_cursor();
    /// ```
    pub fn hide_cursor() -> Self {
        Cmd::HideCursor
    }

    /// Show the terminal cursor
    ///
    /// # Example
    ///
    /// ```rust
    /// use rnk::cmd::Cmd;
    ///
    /// let cmd = Cmd::show_cursor();
    /// ```
    pub fn show_cursor() -> Self {
        Cmd::ShowCursor
    }

    /// Set the terminal window title
    ///
    /// # Example
    ///
    /// ```rust
    /// use rnk::cmd::Cmd;
    ///
    /// let cmd = Cmd::set_window_title("My App");
    /// ```
    pub fn set_window_title(title: impl Into<String>) -> Self {
        Cmd::SetWindowTitle(title.into())
    }

    /// Request the current window size
    ///
    /// This triggers a WindowSizeMsg to be sent to the update function.
    ///
    /// # Example
    ///
    /// ```rust
    /// use rnk::cmd::Cmd;
    ///
    /// let cmd = Cmd::window_size();
    /// ```
    pub fn window_size() -> Self {
        Cmd::WindowSize
    }

    /// Enter alternate screen buffer (fullscreen mode)
    ///
    /// This switches to the alternate screen buffer, which is typically
    /// used for fullscreen applications. The previous screen content is
    /// preserved and restored when exiting.
    ///
    /// # Example
    ///
    /// ```rust
    /// use rnk::cmd::Cmd;
    ///
    /// let cmd = Cmd::enter_alt_screen();
    /// ```
    pub fn enter_alt_screen() -> Self {
        Cmd::EnterAltScreen
    }

    /// Exit alternate screen buffer (return to inline mode)
    ///
    /// This exits the alternate screen buffer and restores the previous
    /// screen content.
    ///
    /// # Example
    ///
    /// ```rust
    /// use rnk::cmd::Cmd;
    ///
    /// let cmd = Cmd::exit_alt_screen();
    /// ```
    pub fn exit_alt_screen() -> Self {
        Cmd::ExitAltScreen
    }

    /// Enable mouse support
    ///
    /// Enables mouse click, release, wheel, and motion events.
    ///
    /// # Example
    ///
    /// ```rust
    /// use rnk::cmd::Cmd;
    ///
    /// let cmd = Cmd::enable_mouse();
    /// ```
    pub fn enable_mouse() -> Self {
        Cmd::EnableMouse
    }

    /// Disable mouse support
    ///
    /// # Example
    ///
    /// ```rust
    /// use rnk::cmd::Cmd;
    ///
    /// let cmd = Cmd::disable_mouse();
    /// ```
    pub fn disable_mouse() -> Self {
        Cmd::DisableMouse
    }

    /// Enable bracketed paste mode
    ///
    /// When enabled, pasted text is wrapped in escape sequences,
    /// allowing the application to distinguish between typed and pasted text.
    ///
    /// # Example
    ///
    /// ```rust
    /// use rnk::cmd::Cmd;
    ///
    /// let cmd = Cmd::enable_bracketed_paste();
    /// ```
    pub fn enable_bracketed_paste() -> Self {
        Cmd::EnableBracketedPaste
    }

    /// Disable bracketed paste mode
    ///
    /// # Example
    ///
    /// ```rust
    /// use rnk::cmd::Cmd;
    ///
    /// let cmd = Cmd::disable_bracketed_paste();
    /// ```
    pub fn disable_bracketed_paste() -> Self {
        Cmd::DisableBracketedPaste
    }

    /// Chain this command with another command
    ///
    /// The next command will execute after this one completes.
    ///
    /// # Example
    ///
    /// ```rust
    /// use rnk::cmd::Cmd;
    /// use std::time::Duration;
    ///
    /// let cmd = Cmd::sleep(Duration::from_secs(1))
    ///     .and_then(Cmd::perform(|| async {
    ///         println!("After 1 second");
    ///     }));
    /// ```
    pub fn and_then(self, next: Cmd) -> Self {
        match self {
            Cmd::None => next,
            Cmd::Sleep { duration, then } => {
                let chained = then.and_then(next);
                Cmd::Sleep {
                    duration,
                    then: Box::new(chained),
                }
            }
            other => Cmd::batch(vec![other, next]),
        }
    }

    /// Check if this command is a no-op
    ///
    /// # Example
    ///
    /// ```rust
    /// use rnk::cmd::Cmd;
    ///
    /// assert!(Cmd::none().is_none());
    /// assert!(!Cmd::perform(|| async {}).is_none());
    /// ```
    pub fn is_none(&self) -> bool {
        matches!(self, Cmd::None)
    }

    /// Map over a command, transforming it
    ///
    /// This is useful for wrapping commands with additional behavior.
    ///
    /// # Example
    ///
    /// ```rust
    /// use rnk::cmd::Cmd;
    ///
    /// let cmd = Cmd::none().map(|c| {
    ///     Cmd::batch(vec![
    ///         Cmd::perform(|| async { println!("Before"); }),
    ///         c,
    ///         Cmd::perform(|| async { println!("After"); }),
    ///     ])
    /// });
    /// ```
    pub fn map<F>(self, f: F) -> Self
    where
        F: FnOnce(Self) -> Self,
    {
        f(self)
    }
}

impl std::fmt::Debug for Cmd {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Cmd::None => write!(f, "Cmd::None"),
            Cmd::Batch(cmds) => f.debug_tuple("Cmd::Batch").field(cmds).finish(),
            Cmd::Sequence(cmds) => f.debug_tuple("Cmd::Sequence").field(cmds).finish(),
            Cmd::Perform { .. } => write!(f, "Cmd::Perform {{ ... }}"),
            Cmd::Sleep { duration, then } => f
                .debug_struct("Cmd::Sleep")
                .field("duration", duration)
                .field("then", then)
                .finish(),
            Cmd::Tick { duration, .. } => f
                .debug_struct("Cmd::Tick")
                .field("duration", duration)
                .finish(),
            Cmd::Every { duration, .. } => f
                .debug_struct("Cmd::Every")
                .field("duration", duration)
                .finish(),
            Cmd::Exec { config, .. } => {
                f.debug_struct("Cmd::Exec").field("config", config).finish()
            }
            Cmd::ClearScreen => write!(f, "Cmd::ClearScreen"),
            Cmd::HideCursor => write!(f, "Cmd::HideCursor"),
            Cmd::ShowCursor => write!(f, "Cmd::ShowCursor"),
            Cmd::SetWindowTitle(title) => {
                f.debug_tuple("Cmd::SetWindowTitle").field(title).finish()
            }
            Cmd::WindowSize => write!(f, "Cmd::WindowSize"),
            Cmd::EnterAltScreen => write!(f, "Cmd::EnterAltScreen"),
            Cmd::ExitAltScreen => write!(f, "Cmd::ExitAltScreen"),
            Cmd::EnableMouse => write!(f, "Cmd::EnableMouse"),
            Cmd::DisableMouse => write!(f, "Cmd::DisableMouse"),
            Cmd::EnableBracketedPaste => write!(f, "Cmd::EnableBracketedPaste"),
            Cmd::DisableBracketedPaste => write!(f, "Cmd::DisableBracketedPaste"),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_cmd_none() {
        let cmd = Cmd::none();
        assert!(cmd.is_none());
        assert!(matches!(cmd, Cmd::None));
    }

    #[test]
    fn test_cmd_default() {
        let cmd = Cmd::default();
        assert!(cmd.is_none());
    }

    #[test]
    fn test_cmd_batch_empty() {
        let cmd = Cmd::batch(vec![]);
        assert!(cmd.is_none());
    }

    #[test]
    fn test_cmd_batch_single() {
        let cmd = Cmd::batch(vec![Cmd::none()]);
        assert!(cmd.is_none());
    }

    #[test]
    fn test_cmd_batch_filters_none() {
        let cmd = Cmd::batch(vec![Cmd::none(), Cmd::none(), Cmd::none()]);
        assert!(cmd.is_none());
    }

    #[test]
    fn test_cmd_batch_single_non_none() {
        let cmd = Cmd::batch(vec![
            Cmd::none(),
            Cmd::sleep(Duration::from_secs(1)),
            Cmd::none(),
        ]);
        assert!(matches!(cmd, Cmd::Sleep { .. }));
    }

    #[test]
    fn test_cmd_batch_multiple() {
        let cmd = Cmd::batch(vec![
            Cmd::sleep(Duration::from_secs(1)),
            Cmd::sleep(Duration::from_secs(2)),
        ]);
        assert!(matches!(cmd, Cmd::Batch(_)));

        if let Cmd::Batch(cmds) = cmd {
            assert_eq!(cmds.len(), 2);
        }
    }

    #[test]
    fn test_cmd_perform() {
        let cmd = Cmd::perform(|| async {
            println!("test");
        });
        assert!(matches!(cmd, Cmd::Perform { .. }));
        assert!(!cmd.is_none());
    }

    #[test]
    fn test_cmd_sleep() {
        let duration = Duration::from_secs(1);
        let cmd = Cmd::sleep(duration);

        assert!(matches!(cmd, Cmd::Sleep { .. }));

        if let Cmd::Sleep {
            duration: d,
            then: t,
        } = cmd
        {
            assert_eq!(d, duration);
            assert!(t.is_none());
        }
    }

    #[test]
    fn test_cmd_and_then_none() {
        let cmd = Cmd::none().and_then(Cmd::sleep(Duration::from_secs(1)));
        assert!(matches!(cmd, Cmd::Sleep { .. }));
    }

    #[test]
    fn test_cmd_and_then_sleep() {
        let cmd = Cmd::sleep(Duration::from_secs(1)).and_then(Cmd::sleep(Duration::from_secs(2)));

        assert!(matches!(cmd, Cmd::Sleep { .. }));

        if let Cmd::Sleep { duration, then } = cmd {
            assert_eq!(duration, Duration::from_secs(1));
            assert!(matches!(*then, Cmd::Sleep { .. }));

            if let Cmd::Sleep { duration, .. } = *then {
                assert_eq!(duration, Duration::from_secs(2));
            }
        }
    }

    #[test]
    fn test_cmd_and_then_perform() {
        let cmd = Cmd::perform(|| async {}).and_then(Cmd::perform(|| async {}));

        assert!(matches!(cmd, Cmd::Batch(_)));

        if let Cmd::Batch(cmds) = cmd {
            assert_eq!(cmds.len(), 2);
        }
    }

    #[test]
    fn test_cmd_and_then_chain() {
        let cmd = Cmd::sleep(Duration::from_secs(1))
            .and_then(Cmd::sleep(Duration::from_secs(2)))
            .and_then(Cmd::sleep(Duration::from_secs(3)));

        // Should create nested Sleep commands
        assert!(matches!(cmd, Cmd::Sleep { .. }));
    }

    #[test]
    fn test_cmd_map() {
        let cmd = Cmd::none().map(|_| Cmd::sleep(Duration::from_secs(1)));
        assert!(matches!(cmd, Cmd::Sleep { .. }));
    }

    #[test]
    fn test_cmd_map_wrap() {
        let cmd = Cmd::perform(|| async {}).map(|c| {
            Cmd::batch(vec![
                Cmd::perform(|| async {
                    println!("before");
                }),
                c,
                Cmd::perform(|| async {
                    println!("after");
                }),
            ])
        });

        assert!(matches!(cmd, Cmd::Batch(_)));

        if let Cmd::Batch(cmds) = cmd {
            assert_eq!(cmds.len(), 3);
        }
    }

    #[test]
    fn test_cmd_debug() {
        let cmd = Cmd::none();
        let debug_str = format!("{:?}", cmd);
        assert_eq!(debug_str, "Cmd::None");

        let cmd = Cmd::batch(vec![Cmd::none(), Cmd::none()]);
        let debug_str = format!("{:?}", cmd);
        assert_eq!(debug_str, "Cmd::None");

        let cmd = Cmd::sleep(Duration::from_secs(1));
        let debug_str = format!("{:?}", cmd);
        assert!(debug_str.contains("Cmd::Sleep"));

        let cmd = Cmd::perform(|| async {});
        let debug_str = format!("{:?}", cmd);
        assert!(debug_str.contains("Cmd::Perform"));
    }

    #[test]
    fn test_cmd_nested_batch() {
        let cmd = Cmd::batch(vec![
            Cmd::batch(vec![Cmd::sleep(Duration::from_secs(1))]),
            Cmd::batch(vec![Cmd::sleep(Duration::from_secs(2))]),
        ]);

        // Nested batches should be flattened by smart construction
        assert!(matches!(cmd, Cmd::Batch(_)));
    }

    #[test]
    fn test_cmd_complex_composition() {
        let cmd = Cmd::batch(vec![
            Cmd::sleep(Duration::from_secs(1)).and_then(Cmd::perform(|| async {})),
            Cmd::perform(|| async {}).and_then(Cmd::sleep(Duration::from_secs(2))),
            Cmd::none(),
        ]);

        assert!(matches!(cmd, Cmd::Batch(_)));

        if let Cmd::Batch(cmds) = cmd {
            // Should filter out Cmd::None
            assert_eq!(cmds.len(), 2);
        }
    }

    // ==================== Sequence Tests ====================

    #[test]
    fn test_cmd_sequence_empty() {
        let cmd = Cmd::sequence(vec![]);
        assert!(cmd.is_none());
    }

    #[test]
    fn test_cmd_sequence_single() {
        let cmd = Cmd::sequence(vec![Cmd::none()]);
        assert!(cmd.is_none());
    }

    #[test]
    fn test_cmd_sequence_filters_none() {
        let cmd = Cmd::sequence(vec![Cmd::none(), Cmd::none(), Cmd::none()]);
        assert!(cmd.is_none());
    }

    #[test]
    fn test_cmd_sequence_single_non_none() {
        let cmd = Cmd::sequence(vec![
            Cmd::none(),
            Cmd::sleep(Duration::from_secs(1)),
            Cmd::none(),
        ]);
        assert!(matches!(cmd, Cmd::Sleep { .. }));
    }

    #[test]
    fn test_cmd_sequence_multiple() {
        let cmd = Cmd::sequence(vec![
            Cmd::sleep(Duration::from_secs(1)),
            Cmd::sleep(Duration::from_secs(2)),
        ]);
        assert!(matches!(cmd, Cmd::Sequence(_)));

        if let Cmd::Sequence(cmds) = cmd {
            assert_eq!(cmds.len(), 2);
        }
    }

    #[test]
    fn test_cmd_sequence_preserves_order() {
        let cmd = Cmd::sequence(vec![
            Cmd::sleep(Duration::from_secs(1)),
            Cmd::sleep(Duration::from_secs(2)),
            Cmd::sleep(Duration::from_secs(3)),
        ]);

        if let Cmd::Sequence(cmds) = cmd {
            assert_eq!(cmds.len(), 3);
            // Verify order is preserved
            if let Cmd::Sleep { duration, .. } = &cmds[0] {
                assert_eq!(*duration, Duration::from_secs(1));
            }
            if let Cmd::Sleep { duration, .. } = &cmds[1] {
                assert_eq!(*duration, Duration::from_secs(2));
            }
            if let Cmd::Sleep { duration, .. } = &cmds[2] {
                assert_eq!(*duration, Duration::from_secs(3));
            }
        }
    }

    #[test]
    fn test_cmd_sequence_debug() {
        let cmd = Cmd::sequence(vec![
            Cmd::sleep(Duration::from_secs(1)),
            Cmd::sleep(Duration::from_secs(2)),
        ]);
        let debug_str = format!("{:?}", cmd);
        assert!(debug_str.contains("Cmd::Sequence"));
    }

    #[test]
    fn test_cmd_nested_sequence() {
        let cmd = Cmd::sequence(vec![
            Cmd::sequence(vec![Cmd::sleep(Duration::from_secs(1))]),
            Cmd::sequence(vec![Cmd::sleep(Duration::from_secs(2))]),
        ]);

        // Nested sequences should remain as Sequence
        assert!(matches!(cmd, Cmd::Sequence(_)));
    }

    #[test]
    fn test_cmd_sequence_with_batch() {
        let cmd = Cmd::sequence(vec![
            Cmd::batch(vec![
                Cmd::sleep(Duration::from_millis(100)),
                Cmd::sleep(Duration::from_millis(100)),
            ]),
            Cmd::perform(|| async {}),
        ]);

        assert!(matches!(cmd, Cmd::Sequence(_)));

        if let Cmd::Sequence(cmds) = cmd {
            assert_eq!(cmds.len(), 2);
            assert!(matches!(cmds[0], Cmd::Batch(_)));
            assert!(matches!(cmds[1], Cmd::Perform { .. }));
        }
    }

    // ==================== Tick Tests ====================

    #[test]
    fn test_cmd_tick() {
        let duration = Duration::from_secs(1);
        let cmd = Cmd::tick(duration, |_| {});

        assert!(matches!(cmd, Cmd::Tick { .. }));

        if let Cmd::Tick {
            duration: d,
            callback: _,
        } = cmd
        {
            assert_eq!(d, duration);
        }
    }

    #[test]
    fn test_cmd_tick_debug() {
        let cmd = Cmd::tick(Duration::from_secs(1), |_| {});
        let debug_str = format!("{:?}", cmd);
        assert!(debug_str.contains("Cmd::Tick"));
        assert!(debug_str.contains("duration"));
    }

    #[test]
    fn test_cmd_tick_is_not_none() {
        let cmd = Cmd::tick(Duration::from_millis(100), |_| {});
        assert!(!cmd.is_none());
    }

    // ==================== Every Tests ====================

    #[test]
    fn test_cmd_every() {
        let duration = Duration::from_secs(1);
        let cmd = Cmd::every(duration, |_| {});

        assert!(matches!(cmd, Cmd::Every { .. }));

        if let Cmd::Every {
            duration: d,
            callback: _,
        } = cmd
        {
            assert_eq!(d, duration);
        }
    }

    #[test]
    fn test_cmd_every_debug() {
        let cmd = Cmd::every(Duration::from_secs(1), |_| {});
        let debug_str = format!("{:?}", cmd);
        assert!(debug_str.contains("Cmd::Every"));
        assert!(debug_str.contains("duration"));
    }

    #[test]
    fn test_cmd_every_is_not_none() {
        let cmd = Cmd::every(Duration::from_millis(100), |_| {});
        assert!(!cmd.is_none());
    }

    // ==================== Mixed Composition Tests ====================

    #[test]
    fn test_cmd_batch_with_tick() {
        let cmd = Cmd::batch(vec![
            Cmd::tick(Duration::from_millis(100), |_| {}),
            Cmd::tick(Duration::from_millis(200), |_| {}),
        ]);

        assert!(matches!(cmd, Cmd::Batch(_)));

        if let Cmd::Batch(cmds) = cmd {
            assert_eq!(cmds.len(), 2);
        }
    }

    #[test]
    fn test_cmd_sequence_with_tick() {
        let cmd = Cmd::sequence(vec![
            Cmd::tick(Duration::from_millis(100), |_| {}),
            Cmd::perform(|| async {}),
        ]);

        assert!(matches!(cmd, Cmd::Sequence(_)));

        if let Cmd::Sequence(cmds) = cmd {
            assert_eq!(cmds.len(), 2);
        }
    }

    #[test]
    fn test_cmd_batch_with_every() {
        let cmd = Cmd::batch(vec![
            Cmd::every(Duration::from_secs(1), |_| {}),
            Cmd::every(Duration::from_secs(2), |_| {}),
        ]);

        assert!(matches!(cmd, Cmd::Batch(_)));

        if let Cmd::Batch(cmds) = cmd {
            assert_eq!(cmds.len(), 2);
        }
    }

    #[test]
    fn test_cmd_complex_mixed_composition() {
        let cmd = Cmd::sequence(vec![
            Cmd::batch(vec![
                Cmd::tick(Duration::from_millis(50), |_| {}),
                Cmd::perform(|| async {}),
            ]),
            Cmd::sleep(Duration::from_millis(100)),
            Cmd::every(Duration::from_secs(1), |_| {}),
        ]);

        assert!(matches!(cmd, Cmd::Sequence(_)));

        if let Cmd::Sequence(cmds) = cmd {
            assert_eq!(cmds.len(), 3);
            assert!(matches!(cmds[0], Cmd::Batch(_)));
            assert!(matches!(cmds[1], Cmd::Sleep { .. }));
            assert!(matches!(cmds[2], Cmd::Every { .. }));
        }
    }

    // ==================== Exec Tests ====================

    #[test]
    fn test_cmd_exec() {
        let cmd = Cmd::exec(ExecConfig::new("vim").arg("file.txt"), |_| {});

        assert!(matches!(cmd, Cmd::Exec { .. }));

        if let Cmd::Exec { config, .. } = cmd {
            assert_eq!(config.command, "vim");
            assert_eq!(config.args, vec!["file.txt"]);
        }
    }

    #[test]
    fn test_cmd_exec_cmd() {
        let cmd = Cmd::exec_cmd("less", &["README.md", "-N"], |_| {});

        assert!(matches!(cmd, Cmd::Exec { .. }));

        if let Cmd::Exec { config, .. } = cmd {
            assert_eq!(config.command, "less");
            assert_eq!(config.args, vec!["README.md", "-N"]);
        }
    }

    #[test]
    fn test_cmd_exec_debug() {
        let cmd = Cmd::exec(ExecConfig::new("vim"), |_| {});
        let debug_str = format!("{:?}", cmd);
        assert!(debug_str.contains("Cmd::Exec"));
        assert!(debug_str.contains("vim"));
    }

    #[test]
    fn test_cmd_exec_is_not_none() {
        let cmd = Cmd::exec(ExecConfig::new("echo"), |_| {});
        assert!(!cmd.is_none());
    }

    #[test]
    fn test_cmd_exec_in_sequence() {
        let cmd = Cmd::sequence(vec![
            Cmd::exec(ExecConfig::new("vim"), |_| {}),
            Cmd::perform(|| async {}),
        ]);

        assert!(matches!(cmd, Cmd::Sequence(_)));

        if let Cmd::Sequence(cmds) = cmd {
            assert_eq!(cmds.len(), 2);
            assert!(matches!(cmds[0], Cmd::Exec { .. }));
            assert!(matches!(cmds[1], Cmd::Perform { .. }));
        }
    }
}