ftui-runtime 0.4.0

Elm-style runtime loop and subscriptions for FrankenTUI.
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
#![forbid(unsafe_code)]

//! Transaction support for grouping multiple commands atomically.
//!
//! Transactions allow multiple operations to be grouped together and
//! treated as a single undoable unit. If any operation fails, all
//! previous operations in the transaction are rolled back.
//!
//! # Usage
//!
//! ```ignore
//! use ftui_runtime::undo::{HistoryManager, Transaction};
//!
//! let mut history = HistoryManager::default();
//!
//! // Begin a transaction
//! let mut txn = Transaction::begin("Format Document");
//!
//! // Add commands to the transaction
//! txn.push(normalize_whitespace_cmd)?;
//! txn.push(fix_indentation_cmd)?;
//! txn.push(sort_imports_cmd)?;
//!
//! // Commit the transaction to history
//! history.push(txn.commit());
//! ```
//!
//! # Nested Transactions
//!
//! Transactions can be nested using `TransactionScope`:
//!
//! ```ignore
//! let mut scope = TransactionScope::new(&mut history);
//!
//! // Outer transaction
//! scope.begin("Refactor");
//!
//! // Inner transaction
//! scope.begin("Rename Variable");
//! scope.execute(rename_cmd)?;
//! scope.commit()?;
//!
//! // More outer work
//! scope.execute(move_function_cmd)?;
//! scope.commit()?;
//! ```
//!
//! # Invariants
//!
//! 1. A committed transaction acts as a single command in history
//! 2. Rollback undoes all executed commands in reverse order
//! 3. Nested transactions must be committed/rolled back in order
//! 4. Empty transactions produce no history entry

use std::fmt;

use super::command::{CommandBatch, CommandError, CommandResult, UndoableCmd};
use super::history::HistoryManager;

/// Builder for creating a group of commands as a single transaction.
///
/// Commands added to a transaction are executed immediately. If any
/// command fails, all previously executed commands are rolled back.
///
/// When committed, the transaction becomes a single entry in history
/// that can be undone/redone atomically.
pub struct Transaction {
    /// The underlying command batch.
    batch: CommandBatch,
    /// Number of commands that have been successfully executed.
    executed_count: usize,
    /// Whether the transaction has been committed or rolled back.
    finalized: bool,
}

impl fmt::Debug for Transaction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Transaction")
            .field("description", &self.batch.description())
            .field("command_count", &self.batch.len())
            .field("executed_count", &self.executed_count)
            .field("finalized", &self.finalized)
            .finish()
    }
}

impl Transaction {
    /// Begin a new transaction with the given description.
    #[must_use]
    pub fn begin(description: impl Into<String>) -> Self {
        Self {
            batch: CommandBatch::new(description),
            executed_count: 0,
            finalized: false,
        }
    }

    /// Execute a command and add it to the transaction.
    ///
    /// The command is executed immediately. If it fails, all previously
    /// executed commands are rolled back and the error is returned.
    ///
    /// # Errors
    ///
    /// Returns error if the command fails to execute.
    pub fn execute(&mut self, mut cmd: Box<dyn UndoableCmd>) -> CommandResult {
        if self.finalized {
            return Err(CommandError::InvalidState(
                "transaction already finalized".to_string(),
            ));
        }

        // Execute the command
        if let Err(e) = cmd.execute() {
            // Rollback on failure
            self.rollback();
            return Err(e);
        }

        // Add to batch (already executed)
        self.executed_count += 1;
        self.batch.push_executed(cmd);
        Ok(())
    }

    /// Add a pre-executed command to the transaction.
    ///
    /// Use this when the command has already been executed externally.
    /// The command will be undone on rollback and redone on redo.
    ///
    /// # Errors
    ///
    /// Returns error if the transaction is already finalized.
    pub fn add_executed(&mut self, cmd: Box<dyn UndoableCmd>) -> CommandResult {
        if self.finalized {
            return Err(CommandError::InvalidState(
                "transaction already finalized".to_string(),
            ));
        }

        self.executed_count += 1;
        self.batch.push_executed(cmd);
        Ok(())
    }

    /// Commit the transaction, returning it as a single undoable command.
    ///
    /// Returns `None` if the transaction is empty.
    #[must_use]
    pub fn commit(mut self) -> Option<Box<dyn UndoableCmd>> {
        // Rollback/drop already finalized this transaction; never emit history.
        if self.finalized {
            return None;
        }
        self.finalized = true;

        if self.batch.is_empty() {
            None
        } else {
            // Take ownership of the batch, replacing with an empty one.
            // This works because Drop only rolls back if not finalized,
            // and we just set finalized = true.
            let batch = std::mem::replace(&mut self.batch, CommandBatch::new(""));
            Some(Box::new(batch))
        }
    }

    /// Roll back all executed commands in the transaction.
    ///
    /// This undoes all commands in reverse order. After rollback,
    /// the transaction is finalized and cannot be used further.
    pub fn rollback(&mut self) {
        if self.finalized {
            return;
        }

        // Rollback already happens in batch.undo(), but we need to
        // manually track that we're rolling back here
        // Since commands are in the batch but haven't been "undone" via
        // the batch's undo mechanism, we need to undo them directly.

        // The batch stores commands but doesn't track execution state
        // the same way we do. We need to undo the executed commands.
        // Since we can't easily access individual commands in the batch,
        // we rely on the batch's undo mechanism.

        // Mark as finalized before undo to prevent re-entry
        self.finalized = true;

        // If we have executed commands, undo them via the batch
        if self.executed_count > 0 {
            // The batch's undo will undo all commands
            let _ = self.batch.undo();
            self.executed_count = 0;
        }
    }

    /// Check if the transaction is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.batch.is_empty()
    }

    /// Get the number of commands in the transaction.
    #[must_use]
    pub fn len(&self) -> usize {
        self.batch.len()
    }

    /// Get the transaction description.
    #[must_use]
    pub fn description(&self) -> &str {
        self.batch.description()
    }
}

impl Drop for Transaction {
    fn drop(&mut self) {
        // If transaction wasn't finalized, auto-rollback
        if !self.finalized {
            self.rollback();
        }
    }
}

/// Scope-based transaction manager for nested transactions.
///
/// Provides a stack-based interface for managing nested transactions.
/// Each `begin()` pushes a new transaction, and `commit()` or `rollback()`
/// pops and finalizes it.
pub struct TransactionScope<'a> {
    /// Reference to the history manager.
    history: &'a mut HistoryManager,
    /// Stack of active transactions.
    stack: Vec<Transaction>,
}

impl<'a> TransactionScope<'a> {
    /// Create a new transaction scope.
    #[must_use]
    pub fn new(history: &'a mut HistoryManager) -> Self {
        Self {
            history,
            stack: Vec::new(),
        }
    }

    /// Begin a new nested transaction.
    pub fn begin(&mut self, description: impl Into<String>) {
        self.stack.push(Transaction::begin(description));
    }

    /// Execute a command in the current transaction.
    ///
    /// If no transaction is active, the command is executed and added
    /// directly to history.
    ///
    /// # Errors
    ///
    /// Returns error if the command fails.
    pub fn execute(&mut self, cmd: Box<dyn UndoableCmd>) -> CommandResult {
        if let Some(txn) = self.stack.last_mut() {
            txn.execute(cmd)
        } else {
            // No active transaction, execute directly
            let mut cmd = cmd;
            cmd.execute()?;
            self.history.push(cmd);
            Ok(())
        }
    }

    /// Commit the current transaction.
    ///
    /// If nested, the committed transaction is added to the parent.
    /// If at top level, it's added to history.
    ///
    /// # Errors
    ///
    /// Returns error if no transaction is active.
    pub fn commit(&mut self) -> CommandResult {
        let txn = self
            .stack
            .pop()
            .ok_or_else(|| CommandError::InvalidState("no active transaction".to_string()))?;

        if let Some(cmd) = txn.commit() {
            if let Some(parent) = self.stack.last_mut() {
                // Add to parent transaction as pre-executed
                parent.add_executed(cmd)?;
            } else {
                // Add to history
                self.history.push(cmd);
            }
        }

        Ok(())
    }

    /// Roll back the current transaction.
    ///
    /// # Errors
    ///
    /// Returns error if no transaction is active.
    pub fn rollback(&mut self) -> CommandResult {
        let mut txn = self
            .stack
            .pop()
            .ok_or_else(|| CommandError::InvalidState("no active transaction".to_string()))?;

        txn.rollback();
        Ok(())
    }

    /// Check if there are active transactions.
    #[must_use]
    pub fn is_active(&self) -> bool {
        !self.stack.is_empty()
    }

    /// Get the current nesting depth.
    #[must_use]
    pub fn depth(&self) -> usize {
        self.stack.len()
    }
}

impl Drop for TransactionScope<'_> {
    fn drop(&mut self) {
        // Auto-rollback any uncommitted transactions
        while let Some(mut txn) = self.stack.pop() {
            txn.rollback();
        }
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::undo::command::{TextInsertCmd, WidgetId};
    use crate::undo::history::HistoryConfig;
    use std::sync::Arc;
    use std::sync::Mutex;

    /// Helper to create a test command that is **pre-executed**.
    ///
    /// Use this with APIs that expect an executed command (e.g. `add_executed`).
    fn make_cmd(buffer: Arc<Mutex<String>>, text: &str) -> Box<dyn UndoableCmd> {
        let b1 = buffer.clone();
        let b2 = buffer.clone();
        let text = text.to_string();
        let text_clone = text.clone();

        let mut cmd = TextInsertCmd::new(WidgetId::new(1), 0, text)
            .with_apply(move |_, _, txt| {
                let mut buf = b1.lock().unwrap();
                buf.push_str(txt);
                Ok(())
            })
            .with_remove(move |_, _, _| {
                let mut buf = b2.lock().unwrap();
                let new_len = buf.len().saturating_sub(text_clone.len());
                buf.truncate(new_len);
                Ok(())
            });

        cmd.execute().unwrap();
        Box::new(cmd)
    }

    #[test]
    fn test_empty_transaction() {
        let txn = Transaction::begin("Empty");
        assert!(txn.is_empty());
        assert_eq!(txn.len(), 0);
        assert!(txn.commit().is_none());
    }

    #[test]
    fn test_single_command_transaction() {
        let buffer = Arc::new(Mutex::new(String::new()));

        let mut txn = Transaction::begin("Single");
        txn.add_executed(make_cmd(buffer.clone(), "hello")).unwrap();

        assert_eq!(txn.len(), 1);

        let cmd = txn.commit();
        assert!(cmd.is_some());
    }

    #[test]
    fn test_transaction_rollback() {
        let buffer = Arc::new(Mutex::new(String::new()));

        let mut txn = Transaction::begin("Rollback Test");
        txn.add_executed(make_cmd(buffer.clone(), "hello")).unwrap();
        txn.add_executed(make_cmd(buffer.clone(), " world"))
            .unwrap();

        assert_eq!(*buffer.lock().unwrap(), "hello world");

        txn.rollback();

        // Buffer should be back to empty after rollback
        assert_eq!(*buffer.lock().unwrap(), "");
    }

    #[test]
    fn test_transaction_commit_to_history() {
        let buffer = Arc::new(Mutex::new(String::new()));
        let mut history = HistoryManager::new(HistoryConfig::unlimited());

        let mut txn = Transaction::begin("Commit Test");
        txn.add_executed(make_cmd(buffer.clone(), "a")).unwrap();
        txn.add_executed(make_cmd(buffer.clone(), "b")).unwrap();

        if let Some(cmd) = txn.commit() {
            history.push(cmd);
        }

        assert_eq!(history.undo_depth(), 1);
        assert!(history.can_undo());
    }

    #[test]
    fn test_transaction_undo_redo() {
        let buffer = Arc::new(Mutex::new(String::new()));
        let mut history = HistoryManager::new(HistoryConfig::unlimited());

        let mut txn = Transaction::begin("Undo/Redo Test");
        txn.add_executed(make_cmd(buffer.clone(), "hello")).unwrap();
        txn.add_executed(make_cmd(buffer.clone(), " world"))
            .unwrap();

        if let Some(cmd) = txn.commit() {
            history.push(cmd);
        }

        assert_eq!(*buffer.lock().unwrap(), "hello world");

        // Undo the entire transaction
        history.undo();
        assert_eq!(*buffer.lock().unwrap(), "");

        // Redo the entire transaction
        history.redo();
        assert_eq!(*buffer.lock().unwrap(), "hello world");
    }

    #[test]
    fn test_scope_basic() {
        let buffer = Arc::new(Mutex::new(String::new()));
        let mut history = HistoryManager::new(HistoryConfig::unlimited());

        {
            let mut scope = TransactionScope::new(&mut history);
            scope.begin("Scope Test");

            scope.execute(make_scope_cmd(buffer.clone(), "a")).unwrap();
            scope.execute(make_scope_cmd(buffer.clone(), "b")).unwrap();

            scope.commit().unwrap();
        }

        assert_eq!(history.undo_depth(), 1);
        assert_eq!(*buffer.lock().unwrap(), "ab");
    }

    #[test]
    fn test_scope_nested() {
        let buffer = Arc::new(Mutex::new(String::new()));
        let mut history = HistoryManager::new(HistoryConfig::unlimited());

        {
            let mut scope = TransactionScope::new(&mut history);

            // Outer transaction
            scope.begin("Outer");
            scope
                .execute(make_scope_cmd(buffer.clone(), "outer1"))
                .unwrap();

            // Inner transaction
            scope.begin("Inner");
            scope
                .execute(make_scope_cmd(buffer.clone(), "inner"))
                .unwrap();
            scope.commit().unwrap();

            scope
                .execute(make_scope_cmd(buffer.clone(), "outer2"))
                .unwrap();
            scope.commit().unwrap();
        }

        // Both transactions committed as one (nested was added to parent)
        assert_eq!(history.undo_depth(), 1);
        assert_eq!(*buffer.lock().unwrap(), "outer1innerouter2");
    }

    #[test]
    fn test_scope_rollback() {
        let buffer = Arc::new(Mutex::new(String::new()));
        let mut history = HistoryManager::new(HistoryConfig::unlimited());

        {
            let mut scope = TransactionScope::new(&mut history);
            scope.begin("Rollback");

            scope.execute(make_scope_cmd(buffer.clone(), "a")).unwrap();
            scope.execute(make_scope_cmd(buffer.clone(), "b")).unwrap();

            scope.rollback().unwrap();
        }

        // Nothing should be in history
        assert_eq!(history.undo_depth(), 0);
        assert_eq!(*buffer.lock().unwrap(), "");
    }

    #[test]
    fn test_scope_auto_rollback_on_drop() {
        let buffer = Arc::new(Mutex::new(String::new()));
        let mut history = HistoryManager::new(HistoryConfig::unlimited());

        {
            let mut scope = TransactionScope::new(&mut history);
            scope.begin("Will be dropped");
            scope
                .execute(make_scope_cmd(buffer.clone(), "test"))
                .unwrap();
            // scope drops without commit
        }

        // Should have auto-rolled back
        assert_eq!(history.undo_depth(), 0);
        assert_eq!(*buffer.lock().unwrap(), "");
    }

    #[test]
    fn test_scope_depth() {
        let mut history = HistoryManager::new(HistoryConfig::unlimited());

        let mut scope = TransactionScope::new(&mut history);
        assert_eq!(scope.depth(), 0);
        assert!(!scope.is_active());

        scope.begin("Level 1");
        assert_eq!(scope.depth(), 1);
        assert!(scope.is_active());

        scope.begin("Level 2");
        assert_eq!(scope.depth(), 2);

        scope.commit().unwrap();
        assert_eq!(scope.depth(), 1);

        scope.commit().unwrap();
        assert_eq!(scope.depth(), 0);
        assert!(!scope.is_active());
    }

    #[test]
    fn test_transaction_description() {
        let txn = Transaction::begin("My Transaction");
        assert_eq!(txn.description(), "My Transaction");
    }

    #[test]
    fn test_finalized_transaction_rejects_commands() {
        let buffer = Arc::new(Mutex::new(String::new()));

        let mut txn = Transaction::begin("Finalized");
        txn.rollback();

        let result = txn.add_executed(make_cmd(buffer, "test"));
        assert!(result.is_err());
    }

    #[test]
    fn test_transaction_execute_method() {
        let buffer = Arc::new(Mutex::new(String::new()));
        let b1 = buffer.clone();
        let b2 = buffer.clone();

        let cmd = TextInsertCmd::new(WidgetId::new(1), 0, "exec")
            .with_apply(move |_, _, txt| {
                let mut buf = b1.lock().unwrap();
                buf.push_str(txt);
                Ok(())
            })
            .with_remove(move |_, _, _| {
                let mut buf = b2.lock().unwrap();
                buf.drain(..4);
                Ok(())
            });

        let mut txn = Transaction::begin("Execute Test");
        txn.execute(Box::new(cmd)).unwrap();
        assert_eq!(txn.len(), 1);
        assert_eq!(*buffer.lock().unwrap(), "exec");
    }

    #[test]
    fn test_transaction_finalized_rejects_execute() {
        let buffer = Arc::new(Mutex::new(String::new()));

        let mut txn = Transaction::begin("Finalized");
        txn.rollback();

        let result = txn.execute(make_scope_cmd(buffer, "test"));
        assert!(result.is_err());
    }

    #[test]
    fn test_commit_after_rollback_returns_none() {
        let buffer = Arc::new(Mutex::new(String::new()));

        let mut txn = Transaction::begin("Rollback then commit");
        txn.add_executed(make_cmd(buffer.clone(), "a")).unwrap();
        txn.rollback();

        assert!(txn.commit().is_none());
        assert_eq!(*buffer.lock().unwrap(), "");
    }

    #[test]
    fn test_scope_commit_after_execute_failure_does_not_push_rolled_back_batch() {
        let buffer = Arc::new(Mutex::new(String::new()));
        let mut history = HistoryManager::new(HistoryConfig::unlimited());

        let failing_cmd = TextInsertCmd::new(WidgetId::new(1), 0, "boom")
            .with_apply(move |_, _, _| Err(CommandError::Other("boom".to_string())))
            .with_remove(move |_, _, _| Ok(()));

        {
            let mut scope = TransactionScope::new(&mut history);
            scope.begin("Failure path");
            let b_ok_apply = buffer.clone();
            let b_ok_remove = buffer.clone();
            let ok_cmd = TextInsertCmd::new(WidgetId::new(1), 0, "ok")
                .with_apply(move |_, _, txt| {
                    let mut buf = b_ok_apply.lock().unwrap();
                    buf.push_str(txt);
                    Ok(())
                })
                .with_remove(move |_, _, _| {
                    let mut buf = b_ok_remove.lock().unwrap();
                    buf.drain(..2);
                    Ok(())
                });
            scope.execute(Box::new(ok_cmd)).unwrap();
            assert!(scope.execute(Box::new(failing_cmd)).is_err());
            // This used to leak the rolled-back batch into history.
            scope.commit().unwrap();
        }

        assert_eq!(history.undo_depth(), 0);
        assert_eq!(*buffer.lock().unwrap(), "");
    }

    #[test]
    fn test_scope_execute_without_transaction() {
        let buffer = Arc::new(Mutex::new(String::new()));
        let mut history = HistoryManager::new(HistoryConfig::unlimited());

        {
            let mut scope = TransactionScope::new(&mut history);
            // Execute without begin() - should go directly to history
            scope
                .execute(make_scope_cmd(buffer.clone(), "direct"))
                .unwrap();
        }

        assert_eq!(history.undo_depth(), 1);
        assert_eq!(*buffer.lock().unwrap(), "direct");
    }

    #[test]
    fn test_scope_commit_without_begin_errors() {
        let mut history = HistoryManager::new(HistoryConfig::unlimited());

        let mut scope = TransactionScope::new(&mut history);
        let result = scope.commit();
        assert!(result.is_err());
    }

    #[test]
    fn test_scope_rollback_without_begin_errors() {
        let mut history = HistoryManager::new(HistoryConfig::unlimited());

        let mut scope = TransactionScope::new(&mut history);
        let result = scope.rollback();
        assert!(result.is_err());
    }

    #[test]
    fn test_transaction_multi_command_rollback_order() {
        let buffer = Arc::new(Mutex::new(String::new()));

        let mut txn = Transaction::begin("Multi Rollback");
        txn.add_executed(make_cmd(buffer.clone(), "a")).unwrap();
        txn.add_executed(make_cmd(buffer.clone(), "b")).unwrap();
        txn.add_executed(make_cmd(buffer.clone(), "c")).unwrap();

        assert_eq!(*buffer.lock().unwrap(), "abc");
        txn.rollback();
        assert_eq!(*buffer.lock().unwrap(), "");
    }

    #[test]
    fn test_transaction_debug_impl() {
        let txn = Transaction::begin("Debug Test");
        let s = format!("{txn:?}");
        assert!(s.contains("Transaction"));
        assert!(s.contains("Debug Test"));
    }

    // ====================================================================
    // Additional coverage: double rollback, scope edge cases
    // ====================================================================

    #[test]
    fn test_rollback_is_idempotent() {
        let buffer = Arc::new(Mutex::new(String::new()));
        let mut txn = Transaction::begin("Double Rollback");
        txn.add_executed(make_cmd(buffer.clone(), "x")).unwrap();

        txn.rollback();
        assert_eq!(*buffer.lock().unwrap(), "");

        // Second rollback is a no-op (finalized)
        txn.rollback();
        assert_eq!(*buffer.lock().unwrap(), "");
    }

    #[test]
    fn test_rollback_empty_transaction() {
        let mut txn = Transaction::begin("Empty Rollback");
        txn.rollback();
        // Should not panic, nothing to undo
        assert!(txn.commit().is_none());
    }

    #[test]
    fn test_scope_drop_with_multiple_uncommitted() {
        let mut history = HistoryManager::new(HistoryConfig::unlimited());
        let buf_a = Arc::new(Mutex::new(String::new()));
        let buf_b = Arc::new(Mutex::new(String::new()));

        {
            let mut scope = TransactionScope::new(&mut history);
            scope.begin("Outer");
            // Use separate buffers to avoid cross-transaction interference
            scope.execute(make_scope_cmd(buf_a.clone(), "a")).unwrap();

            scope.begin("Inner");
            scope.execute(make_scope_cmd(buf_b.clone(), "b")).unwrap();

            // Drop without committing either transaction
        }

        // Both should have been rolled back — nothing in history
        assert_eq!(history.undo_depth(), 0);
        assert_eq!(*buf_a.lock().unwrap(), "");
        assert_eq!(*buf_b.lock().unwrap(), "");
    }

    #[test]
    fn test_scope_inner_rollback_outer_continues() {
        let buffer = Arc::new(Mutex::new(String::new()));
        let mut history = HistoryManager::new(HistoryConfig::unlimited());

        {
            let mut scope = TransactionScope::new(&mut history);

            // Outer transaction
            scope.begin("Outer");
            scope
                .execute(make_scope_cmd(buffer.clone(), "outer"))
                .unwrap();

            // Inner transaction
            scope.begin("Inner");
            scope
                .execute(make_scope_cmd(buffer.clone(), "inner"))
                .unwrap();
            scope.rollback().unwrap(); // Roll back inner only

            assert_eq!(scope.depth(), 1); // Outer still active
            assert_eq!(*buffer.lock().unwrap(), "outer");

            // Commit outer
            scope.commit().unwrap();
        }

        assert_eq!(history.undo_depth(), 1);
    }

    #[test]
    fn test_scope_commit_empty_inner_txn() {
        let mut history = HistoryManager::new(HistoryConfig::unlimited());

        {
            let mut scope = TransactionScope::new(&mut history);
            scope.begin("Outer");
            scope.begin("Empty Inner");
            scope.commit().unwrap(); // Empty inner commits as None
            scope.commit().unwrap(); // Outer commits as empty too
        }

        // Empty transactions produce no history entry
        assert_eq!(history.undo_depth(), 0);
    }

    #[test]
    fn test_transaction_execute_failure_rolls_back_prior() {
        let buffer = Arc::new(Mutex::new(String::new()));
        let b1 = buffer.clone();
        let b2 = buffer.clone();

        let ok_cmd = TextInsertCmd::new(WidgetId::new(1), 0, "ok")
            .with_apply(move |_, _, txt| {
                let mut buf = b1.lock().unwrap();
                buf.push_str(txt);
                Ok(())
            })
            .with_remove(move |_, _, _| {
                let mut buf = b2.lock().unwrap();
                buf.drain(..2);
                Ok(())
            });

        // A command that fails on execute (no apply callback)
        let fail_cmd = TextInsertCmd::new(WidgetId::new(1), 2, "fail");

        let mut txn = Transaction::begin("Execute Failure");
        txn.execute(Box::new(ok_cmd)).unwrap();
        assert_eq!(*buffer.lock().unwrap(), "ok");

        // This should fail and rollback the "ok" command
        let result = txn.execute(Box::new(fail_cmd));
        assert!(result.is_err());
        assert_eq!(*buffer.lock().unwrap(), "");
    }

    #[test]
    fn test_transaction_is_empty_after_add() {
        let buffer = Arc::new(Mutex::new(String::new()));
        let mut txn = Transaction::begin("Not Empty");
        assert!(txn.is_empty());

        txn.add_executed(make_cmd(buffer, "x")).unwrap();
        assert!(!txn.is_empty());
    }

    #[test]
    fn test_scope_execute_failure_without_txn() {
        let mut history = HistoryManager::new(HistoryConfig::unlimited());

        // Execute without begin() with a failing command
        let fail_cmd = TextInsertCmd::new(WidgetId::new(1), 0, "fail");
        // No callbacks, so execute will fail

        {
            let mut scope = TransactionScope::new(&mut history);
            let result = scope.execute(Box::new(fail_cmd));
            assert!(result.is_err());
        }
        assert_eq!(history.undo_depth(), 0);
    }

    // ====================================================================
    // Additional coverage: sequential scopes, deep nesting, edge cases
    // (bd-1o6q1)
    // ====================================================================

    #[test]
    fn test_scope_sequential_transactions() {
        let buffer = Arc::new(Mutex::new(String::new()));
        let mut history = HistoryManager::new(HistoryConfig::unlimited());

        {
            let mut scope = TransactionScope::new(&mut history);

            // First transaction
            scope.begin("First");
            scope.execute(make_scope_cmd(buffer.clone(), "a")).unwrap();
            scope.commit().unwrap();

            // Second transaction in same scope
            scope.begin("Second");
            scope.execute(make_scope_cmd(buffer.clone(), "b")).unwrap();
            scope.commit().unwrap();
        }

        // Both should be separate history entries
        assert_eq!(history.undo_depth(), 2);
    }

    #[test]
    fn test_scope_three_level_nesting() {
        let buffer = Arc::new(Mutex::new(String::new()));
        let mut history = HistoryManager::new(HistoryConfig::unlimited());

        {
            let mut scope = TransactionScope::new(&mut history);

            scope.begin("Level 1");
            scope.execute(make_scope_cmd(buffer.clone(), "a")).unwrap();

            scope.begin("Level 2");
            scope.execute(make_scope_cmd(buffer.clone(), "b")).unwrap();

            scope.begin("Level 3");
            scope.execute(make_scope_cmd(buffer.clone(), "c")).unwrap();
            assert_eq!(scope.depth(), 3);

            scope.commit().unwrap();
            scope.commit().unwrap();
            scope.commit().unwrap();
        }

        assert_eq!(history.undo_depth(), 1);
        assert_eq!(*buffer.lock().unwrap(), "abc");

        history.undo();
        assert_eq!(*buffer.lock().unwrap(), "");
    }

    #[test]
    fn test_scope_alternating_commit_rollback() {
        let mut history = HistoryManager::new(HistoryConfig::unlimited());

        {
            let mut scope = TransactionScope::new(&mut history);

            // First: commit
            scope.begin("Committed");
            let buf1 = Arc::new(Mutex::new(String::new()));
            scope.execute(make_scope_cmd(buf1, "ok")).unwrap();
            scope.commit().unwrap();

            // Second: rollback
            scope.begin("Rolled back");
            let buf2 = Arc::new(Mutex::new(String::new()));
            scope.execute(make_scope_cmd(buf2, "no")).unwrap();
            scope.rollback().unwrap();

            // Third: commit
            scope.begin("Also committed");
            let buf3 = Arc::new(Mutex::new(String::new()));
            scope.execute(make_scope_cmd(buf3, "yes")).unwrap();
            scope.commit().unwrap();
        }

        // Two committed, one rolled back
        assert_eq!(history.undo_depth(), 2);
    }

    #[test]
    fn test_scope_rollback_then_new_transaction() {
        let buf_bad = Arc::new(Mutex::new(String::new()));
        let buf_good = Arc::new(Mutex::new(String::new()));
        let mut history = HistoryManager::new(HistoryConfig::unlimited());

        {
            let mut scope = TransactionScope::new(&mut history);

            scope.begin("Failed attempt");
            scope
                .execute(make_scope_cmd(buf_bad.clone(), "bad"))
                .unwrap();
            scope.rollback().unwrap();

            scope.begin("Retry");
            scope
                .execute(make_scope_cmd(buf_good.clone(), "good"))
                .unwrap();
            scope.commit().unwrap();
        }

        assert_eq!(history.undo_depth(), 1);
        assert_eq!(*buf_bad.lock().unwrap(), "");
        assert_eq!(*buf_good.lock().unwrap(), "good");
    }

    #[test]
    fn test_transaction_len_after_execute() {
        let buffer = Arc::new(Mutex::new(String::new()));
        let b1 = buffer.clone();
        let b2 = buffer.clone();

        let cmd = TextInsertCmd::new(WidgetId::new(1), 0, "x")
            .with_apply(move |_, _, txt| {
                b1.lock().unwrap().push_str(txt);
                Ok(())
            })
            .with_remove(move |_, _, _| {
                b2.lock().unwrap().drain(..1);
                Ok(())
            });

        let mut txn = Transaction::begin("Len Test");
        assert_eq!(txn.len(), 0);

        txn.execute(Box::new(cmd)).unwrap();
        assert_eq!(txn.len(), 1);
    }

    #[test]
    fn test_transaction_many_commands() {
        let buffer = Arc::new(Mutex::new(String::new()));
        let mut txn = Transaction::begin("Many Commands");

        for _ in 0..20 {
            txn.add_executed(make_cmd(buffer.clone(), ".")).unwrap();
        }

        assert_eq!(txn.len(), 20);
        assert_eq!(buffer.lock().unwrap().len(), 20);

        txn.rollback();
        assert_eq!(*buffer.lock().unwrap(), "");
    }

    #[test]
    fn test_scope_execute_after_all_committed() {
        let buffer = Arc::new(Mutex::new(String::new()));
        let mut history = HistoryManager::new(HistoryConfig::unlimited());

        {
            let mut scope = TransactionScope::new(&mut history);

            // Transaction
            scope.begin("Txn");
            scope.execute(make_scope_cmd(buffer.clone(), "a")).unwrap();
            scope.commit().unwrap();

            // Direct execute (no active transaction) goes to history
            scope.execute(make_scope_cmd(buffer.clone(), "b")).unwrap();
        }

        // One from transaction, one from direct execute
        assert_eq!(history.undo_depth(), 2);
        assert_eq!(*buffer.lock().unwrap(), "ab");
    }

    #[test]
    fn test_scope_inner_commit_empty_outer_has_content() {
        let buffer = Arc::new(Mutex::new(String::new()));
        let mut history = HistoryManager::new(HistoryConfig::unlimited());

        {
            let mut scope = TransactionScope::new(&mut history);

            scope.begin("Outer with content");
            scope
                .execute(make_scope_cmd(buffer.clone(), "outer"))
                .unwrap();

            scope.begin("Empty inner");
            scope.commit().unwrap();

            scope.commit().unwrap();
        }

        assert_eq!(history.undo_depth(), 1);
        assert_eq!(*buffer.lock().unwrap(), "outer");
    }

    #[test]
    fn test_drop_transaction_without_finalize_rolls_back() {
        let buffer = Arc::new(Mutex::new(String::new()));

        {
            let mut txn = Transaction::begin("Will be dropped");
            txn.add_executed(make_cmd(buffer.clone(), "dropped"))
                .unwrap();
            assert_eq!(*buffer.lock().unwrap(), "dropped");
            // txn dropped here without commit or rollback
        }

        // Drop should auto-rollback
        assert_eq!(*buffer.lock().unwrap(), "");
    }

    /// Helper creating a command that is NOT pre-executed (for scope.execute).
    fn make_scope_cmd(buffer: Arc<Mutex<String>>, text: &str) -> Box<dyn UndoableCmd> {
        let b1 = buffer.clone();
        let b2 = buffer.clone();
        let text = text.to_string();
        let text_clone = text.clone();

        Box::new(
            TextInsertCmd::new(WidgetId::new(1), 0, text)
                .with_apply(move |_, _, txt| {
                    let mut buf = b1.lock().unwrap();
                    buf.push_str(txt);
                    Ok(())
                })
                .with_remove(move |_, _, _| {
                    let mut buf = b2.lock().unwrap();
                    let new_len = buf.len().saturating_sub(text_clone.len());
                    buf.truncate(new_len);
                    Ok(())
                }),
        )
    }

    #[test]
    fn test_scope_nested_rollback_preserves_outer() {
        let buf_outer = Arc::new(Mutex::new(String::new()));
        let buf_inner = Arc::new(Mutex::new(String::new()));
        let mut history = HistoryManager::new(HistoryConfig::unlimited());

        {
            let mut scope = TransactionScope::new(&mut history);

            scope.begin("Outer");
            scope
                .execute(make_scope_cmd(buf_outer.clone(), "A"))
                .unwrap();
            assert_eq!(*buf_outer.lock().unwrap(), "A");

            scope.begin("Inner (will rollback)");
            scope
                .execute(make_scope_cmd(buf_inner.clone(), "B"))
                .unwrap();
            assert_eq!(*buf_inner.lock().unwrap(), "B");

            scope.rollback().unwrap();
            assert_eq!(*buf_inner.lock().unwrap(), "");
            assert_eq!(*buf_outer.lock().unwrap(), "A");

            scope.commit().unwrap();
        }

        assert_eq!(history.undo_depth(), 1);
        assert_eq!(*buf_outer.lock().unwrap(), "A");
    }
}