logisheets_controller 1.16.1

Core spreadsheet engine for LogiSheets: formula evaluation, dependency tracking, and undo/redo.
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
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
use std::collections::HashSet;
use std::sync::Mutex;

// Last error encountered by handle_action / handle_action_in_temp_status.
// Set whenever the executor returns Err so the caller (wasm bindings,
// integration tests) can surface the message — otherwise the error is
// dropped into a stdout-bound println! that goes nowhere in wasm.
static LAST_ERROR: Mutex<Option<String>> = Mutex::new(None);

/// Take (and clear) the message of the most recent rejected action. Global to
/// the process, not per workbook. Prefer `ActionEffect::error_message`, which
/// carries the same text.
pub fn take_last_error() -> Option<String> {
    LAST_ERROR.lock().ok().and_then(|mut g| g.take())
}

fn record_last_error(e: &dyn std::fmt::Display) {
    if let Ok(mut g) = LAST_ERROR.lock() {
        *g = Some(e.to_string());
    }
}

use logisheets_base::async_func::{AsyncCalcResult, Task};
use logisheets_base::{BlockRange, CellId, NormalRange, Range, SheetId};

use logisheets_workbook::logisheets::AppData;
use logisheets_workbook::prelude::{read, write};
pub mod block_key_guard;
mod defined_names;
pub(crate) use defined_names::is_valid_name as is_valid_defined_name;
pub mod display;
mod executor;
mod pivot_guard;
mod rename_propagation;
pub mod status;
pub mod style;
use crate::checkpoint_manager::CheckpointManager;
use crate::edit_action::{
    ActionEffect, CreateSheet, EditAction, PayloadsAction, RecalcCell, SheetCellId, SheetColId,
    SheetRowId, StatusCode, WorkbookUpdateType,
};
use crate::errors::{Error, Result};
use crate::file_loader::load_file;
use crate::file_saver::save_file;
use crate::formula_manager::Vertex;
use crate::settings::Settings;
use crate::sid_assigner::ShadowIdAssigner;
use crate::version_manager::VersionManager;
use executor::Executor;
use status::Status;

use self::display::SheetInfo;
use crate::async_func_manager::AsyncFuncManager;

/// The single, workbook-wide temp branch (a dry run / what-if sandbox).
pub struct TempStatus {
    /// The committed state at the moment the branch was opened.
    /// `clean_temp_status` restores it; `get_temp_status_changes` diffs
    /// against it.
    pub fork_status: Status,
    /// The branch's own undo history, so undo inside the branch never
    /// reaches the main history.
    pub version_manager: VersionManager,
    pub accumulated_payloads: Vec<crate::edit_action::EditPayload>,
    pub accumulated_updated_cells: HashSet<(SheetId, CellId)>,
}

/// Owns the workbook state and runs transactions against it. Hosts normally go
/// through `api::Workbook`, which wraps this and keeps derived state
/// (validation and conditional-formatting shadows) in step.
pub struct Controller {
    // TODO: clean this field. Use the VersionManager.current
    /// The live state: the temp branch's head while one is open, else the
    /// committed state.
    pub status: Status,
    pub temp_status: Option<TempStatus>,
    pub async_func_manager: AsyncFuncManager,
    pub curr_book_name: String,
    pub settings: Settings,
    pub version_manager: VersionManager,
    /// Session-scoped named checkpoints. Independent of the linear
    /// undo/redo stack (see `checkpoint_manager` module docs).
    /// Populated by AI workflows via `Workbook::save_checkpoint`;
    /// cleared on file save/load.
    pub checkpoint_manager: CheckpointManager,
    pub sid_assigner: ShadowIdAssigner,

    pub app_data: Vec<AppData>,
}

impl Default for Controller {
    fn default() -> Self {
        let mut empty = Controller {
            status: Status::default(),
            curr_book_name: String::from("Book1"),
            settings: Settings::default(),
            version_manager: VersionManager::default(),
            checkpoint_manager: CheckpointManager::default(),
            async_func_manager: AsyncFuncManager::default(),
            sid_assigner: ShadowIdAssigner::new(),
            app_data: vec![],
            temp_status: None,
        };
        let add_sheet = PayloadsAction::new()
            .add_payload(CreateSheet {
                idx: 0,
                new_name: String::from("Sheet1"),
            })
            .set_init(true);
        empty.handle_action(EditAction::Payloads(add_sheet));
        empty
    }
}

/// How block formulas are written when a workbook is saved.
///
/// `BLOCKREF("assumptions","wacc","value")` is the form LogiSheets works in: it
/// names what it reads, so it survives rows moving and blocks being renamed, and
/// it is what a person reading the file can actually follow. But it is a
/// LogiSheets function — no other spreadsheet knows it, so a reader that
/// recalculates the file gets `#NAME?`.
///
/// So the choice is the caller's, and it is a genuine trade, not a default with
/// an exception: keep the names for a file that comes back here, resolve to
/// coordinates for a file going to Excel.
///
/// Resolving is one-way. `BLOCKREFS` over a field becomes a plain range like
/// `L19:L23`, and a range covering part of a block is not a thing LogiSheets can
/// parse back (see `ParseError::PartialBlockRange`), so a resolved file is an
/// export rather than a round trip.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FormulaFormat {
    /// Keep `BLOCKREF` / `BLOCKREFS`. Readable, and reopens here intact.
    #[default]
    Named,
    /// Resolve them to `A1` references, for Excel and everything else.
    Coordinates,
}

impl Controller {
    // TODO: Due to the UUID generating, we can't just `assert_eq!(file1, file2)` where
    // `file1` and `file2` are binary got from saving of the same file. Fix it.
    /// Save with block formulas kept in their readable named form.
    pub fn save(&self) -> Result<Vec<u8>> {
        self.save_with_format(FormulaFormat::default())
    }

    /// Save, choosing how block formulas are written — see [`FormulaFormat`].
    pub fn save_with_format(&self, format: FormulaFormat) -> Result<Vec<u8>> {
        let workbook = save_file(self, format == FormulaFormat::Coordinates)?;
        write(workbook).map_err(|e| Error::Serde(e.into()))
    }

    #[inline]
    pub fn is_editable(&self) -> bool {
        true
    }

    #[inline]
    /// Whether a temp branch is open. There is one per workbook, shared by all
    /// callers.
    pub fn is_in_temp_mode(&self) -> bool {
        self.temp_status.is_some()
    }

    #[deprecated = "no-op in new design; temp mode is always active when temp_status is Some"]
    pub fn toggle_temp_status(&mut self) {}

    /// Discard the temp branch and restore the state it forked from. No-op
    /// without one.
    pub fn clean_temp_status(&mut self) {
        if let Some(temp) = self.temp_status.take() {
            self.status = temp.fork_status;
        }
    }

    /// Keep the temp branch's state and record all its transactions as ONE
    /// undo step on the main history. No-op without one.
    pub fn commit_temp_status(&mut self) {
        if let Some(temp) = self.temp_status.take() {
            let merged_payloads = PayloadsAction {
                payloads: temp.accumulated_payloads,
                undoable: true,
                init: false,
            };
            self.version_manager.record(
                self.status.clone(),
                merged_payloads,
                temp.accumulated_updated_cells,
            );
        }
    }

    pub fn from(
        status: Status,
        book_name: String,
        settings: Settings,
        app_data: Vec<AppData>,
    ) -> Self {
        Controller {
            curr_book_name: book_name,
            settings,
            status,
            version_manager: VersionManager::default(),
            checkpoint_manager: CheckpointManager::default(),
            async_func_manager: AsyncFuncManager::default(),
            sid_assigner: ShadowIdAssigner::new(),
            app_data,
            temp_status: None,
        }
    }

    /// Count of undoable transactions recorded; see `revision` for change
    /// detection.
    pub fn version(&self) -> u32 {
        self.version_manager.version()
    }

    /// A monotonic counter of committed writes to this workbook (undoable or
    /// not, plus undo/redo). Readers snapshot it to detect whether the state
    /// changed underneath them — the basis for optimistic concurrency in tools.
    pub fn revision(&self) -> u32 {
        self.version_manager.revision()
    }

    /// Load an .xlsx. `name` becomes `curr_book_name`. Formula cells the file carries no cached value for are
    /// calculated before returning.
    pub fn from_file(name: String, f: &[u8]) -> Result<Self> {
        let res = read(f)?;
        let mut controller = load_file(res, name);
        // The loader parks every formula cell the file carries no value for in
        // `dirty_cells_next_round`, but that set is only drained when an action
        // runs — so a workbook straight off disk would keep reporting those
        // cells as blank until something happened to edit it. Run one empty,
        // non-undoable transaction to settle them.
        //
        // This is not exotic: openpyxl, and everything built on it, writes
        // `<f>…</f><v/>` for every formula, and such files ask for exactly this
        // through `calcPr@fullCalcOnLoad`. Files that do carry cached values
        // mark nothing dirty, so they pay nothing here.
        if !controller.status.dirty_cells_next_round.is_empty() {
            controller.handle_action(EditAction::Payloads(PayloadsAction {
                payloads: vec![],
                undoable: false,
                init: true,
            }));
        }
        Ok(controller)
    }

    /// The stable id of the sheet at tab position `idx` (0-based).
    pub fn get_sheet_id_by_idx(&self, idx: usize) -> Option<SheetId> {
        self.status.sheet_info_manager.get_sheet_id(idx)
    }

    /// Exact (case-sensitive) name lookup.
    pub fn get_sheet_id_by_name(&self, name: &str) -> Option<SheetId> {
        self.status.sheet_id_manager.has(name)
    }

    /// Every sheet, hidden ones included, in tab order.
    pub fn get_all_sheet_info(&self) -> Vec<SheetInfo> {
        let id_manager = &self.status.sheet_id_manager;
        let info_manager = &self.status.sheet_info_manager;
        info_manager
            .pos
            .iter()
            .map(|id| SheetInfo {
                name: id_manager.get_string(id).unwrap_or(String::new()),
                id: *id,
                hidden: info_manager.is_hidden(id),
                tab_color: info_manager.get_color(id).unwrap_or(String::new()),
            })
            .collect()
    }

    /// Run a transaction on the temp branch, opening it first if none is open.
    /// Later temp transactions accumulate on the same branch until
    /// `commit_temp_status` or `clean_temp_status`, and any non-temp action
    /// other than undo/redo discards it.
    ///
    /// The branch is workbook-wide: check `is_in_temp_mode` before opening
    /// one, or you may be writing into someone else's. Temp writes do not
    /// bump `revision`.
    pub fn handle_action_in_temp_status(&mut self, action: PayloadsAction) -> ActionEffect {
        // Initialize temp branch on first temp transaction
        if self.temp_status.is_none() {
            // The branch's history must start at the fork point, or its first
            // undo would restore `Status::default()` — a workbook with no sheets.
            let mut version_manager = VersionManager::default();
            version_manager.set_init_status(self.status.clone());
            self.temp_status = Some(TempStatus {
                fork_status: self.status.clone(),
                version_manager,
                accumulated_payloads: vec![],
                accumulated_updated_cells: HashSet::new(),
            });
        }

        // The executor records undoable actions into (and resets on `init`)
        // whichever history it is handed. Hand it the branch's, with both flags
        // cleared: every temp step is recorded below exactly once, and nothing
        // may reach the main history until `commit_temp_status` merges the
        // branch into a single step.
        let exec_action = PayloadsAction {
            payloads: action.payloads.clone(),
            undoable: false,
            init: false,
        };
        let main_version = self.version_manager.version();
        let temp = self.temp_status.as_mut().unwrap();
        let executor = Executor {
            status: self.status.clone(),
            version_manager: &mut temp.version_manager,
            async_func_manager: &mut self.async_func_manager,
            book_name: &self.curr_book_name,
            calc_config: self.settings.calc_config,
            async_funcs: &self.settings.async_funcs,
            updated_cells: HashSet::new(),
            dirty_vertices: HashSet::new(),
            sheet_updated: false,
            cell_updated: false,
            cells_removed: HashSet::new(),
            sid_assigner: &mut self.sid_assigner,
            checkpoint_manager: &self.checkpoint_manager,
            style_updated: HashSet::new(),
            row_inserted: vec![],
            row_removed: vec![],
            col_inserted: vec![],
            col_removed: vec![],
            header_updated: HashSet::new(),
        };
        let result = executor.execute_and_calc(exec_action);
        match result {
            Ok(result) => {
                let cell_updated = result.cell_updated
                    || result.cells_removed.len() > 0
                    || result.updated_cells.len() > 0;
                let c = if cell_updated && result.sheet_updated {
                    WorkbookUpdateType::SheetAndCell
                } else if cell_updated {
                    WorkbookUpdateType::Cell
                } else if result.sheet_updated {
                    WorkbookUpdateType::Sheet
                } else {
                    WorkbookUpdateType::DoNothing
                };

                result.version_manager.record(
                    result.status.clone(),
                    action.clone(),
                    result.updated_cells.clone(),
                );
                let accumulated_cells: Vec<_> = result.updated_cells.iter().copied().collect();
                let header_updated: Vec<u32> = result
                    .header_updated
                    .iter()
                    .filter_map(|id| result.status.sheet_info_manager.get_sheet_idx(id))
                    .map(|i| i as u32)
                    .collect();
                self.status = result.status;

                let effect = ActionEffect {
                    version: main_version,
                    async_tasks: result.async_func_manager.get_calc_tasks(),
                    status: StatusCode::Ok(c),
                    value_changed: result
                        .updated_cells
                        .into_iter()
                        .map(|(sheet_id, cell_id)| SheetCellId { sheet_id, cell_id })
                        .collect(),
                    cell_removed: result
                        .cells_removed
                        .into_iter()
                        .map(|c| SheetCellId {
                            sheet_id: c.0,
                            cell_id: c.1,
                        })
                        .collect(),
                    style_changed: result
                        .style_updated
                        .into_iter()
                        .map(|c| SheetCellId {
                            sheet_id: c.0,
                            cell_id: c.1,
                        })
                        .collect(),
                    row_inserted: result
                        .row_inserted
                        .into_iter()
                        .map(|(sheet_id, row_id)| SheetRowId { sheet_id, row_id })
                        .collect(),
                    row_removed: result
                        .row_removed
                        .into_iter()
                        .map(|(sheet_id, row_id)| SheetRowId { sheet_id, row_id })
                        .collect(),
                    col_inserted: result
                        .col_inserted
                        .into_iter()
                        .map(|(sheet_id, col_id)| SheetColId { sheet_id, col_id })
                        .collect(),
                    col_removed: result
                        .col_removed
                        .into_iter()
                        .map(|(sheet_id, col_id)| SheetColId { sheet_id, col_id })
                        .collect(),
                    header_updated,
                    ..Default::default()
                };
                let temp = self.temp_status.as_mut().unwrap();
                temp.accumulated_payloads.extend(action.payloads);
                temp.accumulated_updated_cells.extend(accumulated_cells);
                effect
            }
            Err(e) => {
                record_last_error(&e);
                ActionEffect::rejected(e.to_string())
            }
        }
    }

    /// Run an action and report what it changed. Never panics or returns
    /// `Err`: a rejected transaction leaves the state untouched and comes back
    /// as `StatusCode::Err` with `error_message` set.
    ///
    /// A `Payloads` action discards any open temp branch first; `Undo`/`Redo`
    /// act on the temp branch while one is open. A committed change that is
    /// not `DoNothing` bumps `revision`. `Recalc` does not.
    pub fn handle_action(&mut self, action: EditAction) -> ActionEffect {
        // A non-temp transaction discards any active temp branch
        if self.is_in_temp_mode() && !matches!(action, EditAction::Undo | EditAction::Redo) {
            self.clean_temp_status();
        }
        match action {
            EditAction::Undo => {
                // undo() bumps the revision itself (single funnel).
                let c = if self.undo() {
                    WorkbookUpdateType::Undo
                } else {
                    WorkbookUpdateType::UndoNothing
                };
                ActionEffect::from(0, vec![], c)
            }
            EditAction::Redo => {
                let c = if self.redo() {
                    WorkbookUpdateType::Redo
                } else {
                    WorkbookUpdateType::RedoNothing
                };
                ActionEffect::from(0, vec![], c)
            }
            EditAction::Payloads(payloads_action) => {
                let executor = Executor {
                    status: self.status.clone(),
                    version_manager: &mut self.version_manager,
                    async_func_manager: &mut self.async_func_manager,
                    book_name: &self.curr_book_name,
                    calc_config: self.settings.calc_config,
                    async_funcs: &self.settings.async_funcs,
                    updated_cells: HashSet::new(),
                    dirty_vertices: HashSet::new(),
                    sheet_updated: false,
                    cell_updated: false,
                    cells_removed: HashSet::new(),
                    sid_assigner: &mut self.sid_assigner,
                    checkpoint_manager: &self.checkpoint_manager,
                    style_updated: HashSet::new(),
                    row_inserted: vec![],
                    row_removed: vec![],
                    col_inserted: vec![],
                    col_removed: vec![],
                    header_updated: HashSet::new(),
                };

                let result = executor.execute_and_calc(payloads_action);
                match result {
                    Ok(result) => {
                        let cell_updated = result.cell_updated
                            || result.cells_removed.len() > 0
                            || result.updated_cells.len() > 0;
                        let c = if cell_updated && result.sheet_updated {
                            WorkbookUpdateType::SheetAndCell
                        } else if cell_updated {
                            WorkbookUpdateType::Cell
                        } else if result.sheet_updated {
                            WorkbookUpdateType::Sheet
                        } else {
                            WorkbookUpdateType::DoNothing
                        };
                        let header_updated: Vec<u32> = result
                            .header_updated
                            .iter()
                            .filter_map(|id| result.status.sheet_info_manager.get_sheet_idx(id))
                            .map(|i| i as u32)
                            .collect();
                        self.status = result.status;
                        // Committed write — bump the revision unless nothing
                        // actually changed, so readers can detect concurrent
                        // edits. Go through `result.version_manager` (the same
                        // `&mut self.version_manager` the executor holds).
                        if !matches!(c, WorkbookUpdateType::DoNothing) {
                            result.version_manager.bump_revision();
                        }
                        ActionEffect {
                            version: result.version_manager.version(),
                            async_tasks: result.async_func_manager.get_calc_tasks(),
                            status: StatusCode::Ok(c),
                            value_changed: result
                                .updated_cells
                                .into_iter()
                                .map(|(sheet_id, cell_id)| SheetCellId { sheet_id, cell_id })
                                .collect(),

                            cell_removed: result
                                .cells_removed
                                .into_iter()
                                .map(|c| SheetCellId {
                                    sheet_id: c.0,
                                    cell_id: c.1,
                                })
                                .collect(),
                            style_changed: result
                                .style_updated
                                .into_iter()
                                .map(|c| SheetCellId {
                                    sheet_id: c.0,
                                    cell_id: c.1,
                                })
                                .collect(),
                            row_inserted: result
                                .row_inserted
                                .into_iter()
                                .map(|(sheet_id, row_id)| SheetRowId { sheet_id, row_id })
                                .collect(),
                            row_removed: result
                                .row_removed
                                .into_iter()
                                .map(|(sheet_id, row_id)| SheetRowId { sheet_id, row_id })
                                .collect(),
                            col_inserted: result
                                .col_inserted
                                .into_iter()
                                .map(|(sheet_id, col_id)| SheetColId { sheet_id, col_id })
                                .collect(),
                            col_removed: result
                                .col_removed
                                .into_iter()
                                .map(|(sheet_id, col_id)| SheetColId { sheet_id, col_id })
                                .collect(),
                            header_updated,
                            ..Default::default()
                        }
                    }
                    Err(e) => {
                        record_last_error(&e);
                        ActionEffect::rejected(e.to_string())
                    }
                }
            }
            EditAction::Recalc(cells) => {
                let dirty_vertices = cells
                    .into_iter()
                    .map(|recalc_sheet| {
                        let sheet_id = recalc_sheet.sheet_id;
                        let cell_id = recalc_sheet.cell_id;
                        let range = match cell_id {
                            CellId::NormalCell(c) => Range::Normal(NormalRange::Single(c)),
                            CellId::BlockCell(b) => Range::Block(BlockRange::Single(b)),
                            CellId::EphemeralCell(e) => Range::Ephemeral(e),
                        };
                        let range_id = self.status.range_manager.get_range_id(&sheet_id, &range);
                        Vertex::Range(sheet_id, range_id)
                    })
                    .collect::<HashSet<_>>();
                let executor = Executor {
                    status: self.status.clone(),
                    version_manager: &mut self.version_manager,
                    async_func_manager: &mut self.async_func_manager,
                    book_name: &self.curr_book_name,
                    calc_config: self.settings.calc_config,
                    async_funcs: &self.settings.async_funcs,
                    updated_cells: HashSet::new(),
                    dirty_vertices,
                    sheet_updated: false,
                    cell_updated: false,
                    sid_assigner: &mut self.sid_assigner,
                    checkpoint_manager: &self.checkpoint_manager,
                    cells_removed: HashSet::new(),
                    style_updated: HashSet::new(),
                    row_inserted: vec![],
                    row_removed: vec![],
                    col_inserted: vec![],
                    col_removed: vec![],
                    header_updated: HashSet::new(),
                };
                match executor.calc() {
                    Ok(result) => ActionEffect {
                        version: result.version_manager.version(),
                        async_tasks: vec![],
                        status: StatusCode::Ok(WorkbookUpdateType::Cell),
                        value_changed: result
                            .updated_cells
                            .into_iter()
                            .map(|(sheet_id, cell_id)| SheetCellId { sheet_id, cell_id })
                            .collect(),
                        cell_removed: result
                            .cells_removed
                            .into_iter()
                            .map(|c| SheetCellId {
                                sheet_id: c.0,
                                cell_id: c.1,
                            })
                            .collect(),
                        style_changed: result
                            .style_updated
                            .into_iter()
                            .map(|c| SheetCellId {
                                sheet_id: c.0,
                                cell_id: c.1,
                            })
                            .collect(),
                        ..Default::default()
                    },
                    Err(e) => {
                        record_last_error(&e);
                        ActionEffect::rejected(e.to_string())
                    }
                }
            }
        }
    }

    /// Feed back results for `ActionEffect::async_tasks`, pairwise by
    /// position, and recalculate the cells waiting on them.
    pub fn handle_async_calc_results(
        &mut self,
        tasks: Vec<Task>,
        res: Vec<AsyncCalcResult>,
    ) -> ActionEffect {
        let mut pending_cells = vec![];
        tasks.into_iter().zip(res.into_iter()).for_each(|(t, r)| {
            let cells = self
                .async_func_manager
                .commit_value(t, r)
                .into_iter()
                .map(|(s, c)| RecalcCell {
                    sheet_id: s,
                    cell_id: c,
                });
            pending_cells.extend(cells);
        });
        self.handle_action(EditAction::Recalc(pending_cells))
    }

    /// Undo one step (of the temp branch's history while one is open).
    /// Returns whether anything changed.
    pub fn undo(&mut self) -> bool {
        let changed = if let Some(temp) = &mut self.temp_status {
            // Undo within temp branch; stop at fork point (never crosses into main history)
            match temp.version_manager.undo() {
                Some(status) => {
                    self.status = status;
                    true
                }
                None => false,
            }
        } else {
            match self.version_manager.undo() {
                Some(status) => {
                    self.status = status;
                    true
                }
                None => false,
            }
        };
        // Undo changes the visible state — bump the revision so readers notice.
        // (This is the single funnel for undo: the RPC path and handle_action
        // both call it.)
        if changed {
            self.version_manager.bump_revision();
        }
        changed
    }

    pub fn redo(&mut self) -> bool {
        let changed = if let Some(temp) = &mut self.temp_status {
            match temp.version_manager.redo() {
                Some(status) => {
                    self.status = status;
                    true
                }
                None => false,
            }
        } else {
            match self.version_manager.redo() {
                Some(status) => {
                    self.status = status;
                    true
                }
                None => false,
            }
        };
        if changed {
            self.version_manager.bump_revision();
        }
        changed
    }

    /// Drop the undo/redo history, keeping the current workbook state as the
    /// new baseline. Nothing is reverted — only the history is cleared. Used
    /// by headless/server callers that treat each operation as atomic and
    /// don't want history to accumulate across requests.
    pub fn clear_history(&mut self) {
        if let Some(temp) = &mut self.temp_status {
            temp.version_manager.set_init_status(self.status.clone());
        } else {
            self.version_manager.set_init_status(self.status.clone());
        }
    }
}

#[cfg(test)]
mod tests {
    use logisheets_base::{CellId, CellValue};

    use crate::edit_action::{
        Alignment, BindFormSchema, BlockLineNameFieldUpdate, BlockLineStyleUpdate, CellInput,
        CellStyleUpdate, CreateBlock, CreateSheet, DeleteCols, DeleteRows, DeleteSheet, EditAction,
        EditPayload, EphemeralCellInput, HorizontalAlignment, InsertCols, InsertRows,
        LineStyleUpdate, PayloadsAction, SchemaFieldSpec, StatusCode, StyleUpdateType,
        VerticalAlignment,
    };

    use super::Controller;

    #[test]
    fn controller_default_test() {
        let wb = Controller::default();
        println!("{:?}", wb.status);
    }

    #[test]
    fn controller_input_formula() {
        let mut wb = Controller::default();
        let payloads_action = PayloadsAction {
            payloads: vec![EditPayload::CellInput(CellInput {
                sheet_idx: 0,
                row: 0,
                col: 0,
                content: String::from("=ABS(1)"),
            })],
            undoable: true,
            init: false,
        };
        wb.handle_action(EditAction::Payloads(payloads_action));
        let len = wb.status.formula_manager.formulas.len();
        assert_eq!(len, 1);
    }

    #[test]
    fn controller_input_value() {
        let mut wb = Controller::default();
        let payloads_action = PayloadsAction {
            payloads: vec![EditPayload::CellInput(CellInput {
                sheet_idx: 0,
                row: 0,
                col: 0,
                content: String::from("abcdefghijklmnopqrstuvwx"),
            })],
            undoable: true,
            init: false,
        };
        let result = wb.handle_action(EditAction::Payloads(payloads_action));
        assert_eq!(result.value_changed.len(), 1);
    }

    #[test]
    fn from_file_test() {
        use std::fs;
        let buf = fs::read("../../tests/6.xlsx").unwrap();
        let controller = Controller::from_file(String::from("6"), &buf);
        match controller {
            Ok(_) => {}
            Err(_) => {
                panic!()
            }
        }
    }

    #[test]
    fn load_charts_into_manager() {
        use logisheets_workbook::prelude::{ChartType, LegendPos};
        use std::fs;
        let buf = fs::read("../../tests/graph.xlsx").unwrap();
        let controller =
            Controller::from_file(String::from("graph"), &buf).expect("load graph.xlsx");

        // Find the sheet that carries the chart and assert it parsed through.
        let chart = controller
            .status
            .chart_manager
            .charts
            .values()
            .flat_map(|v| v.iter())
            .next()
            .expect("a chart should be loaded into the ChartManager");

        assert_eq!(chart.data.chart_type, ChartType::Col);
        assert!(!chart.data.stacked);
        assert_eq!(chart.data.legend_pos, Some(LegendPos::Bottom));
        assert_eq!(chart.data.series.len(), 3);
        assert_eq!(
            chart.data.series[0].val_ref.as_deref(),
            Some("Sheet1!$B$2:$E$2")
        );
        // The raw OOXML is retained for lossless save.
        assert!(chart.raw.iter().any(|p| p.path.ends_with("chart1.xml")));
    }

    #[test]
    fn controller_ephemeral_input_and_intput() {
        let mut wb = Controller::default();
        let sheet_idx = 0;
        let sheet_id = wb.get_sheet_id_by_idx(sheet_idx).unwrap();

        let cell_id = wb.status.navigator.fetch_cell_id(&sheet_id, 0, 0).unwrap();
        let shadow_id = wb.sid_assigner.get_shawdow_id(
            sheet_id,
            cell_id,
            crate::sid_assigner::ShadowKind::Validation,
        );

        let ephemeral_input = PayloadsAction {
            payloads: vec![EditPayload::EphemeralCellInput(EphemeralCellInput {
                sheet_idx,
                id: shadow_id,
                content: String::from("=#PLACEHOLDER < ABS(100)"),
            })],
            undoable: true,
            init: false,
        };
        wb.handle_action(EditAction::Payloads(ephemeral_input));

        let input = PayloadsAction {
            payloads: vec![EditPayload::CellInput(CellInput {
                sheet_idx,
                row: 0,
                col: 0,
                content: String::from("=ABS(100)"),
            })],
            undoable: true,
            init: false,
        };
        let result = wb.handle_action(EditAction::Payloads(input));
        assert!(result.value_changed.len() == 2);

        let cell = wb.status.container.get_cell(sheet_id, &cell_id).unwrap();
        assert!(matches!(cell.value, CellValue::Number(100.0)));
        let ephemeral_cell = wb
            .status
            .container
            .get_cell(sheet_id, &CellId::EphemeralCell(shadow_id))
            .unwrap();
        assert!(matches!(ephemeral_cell.value, CellValue::Boolean(false)));
    }

    #[test]
    fn formula_input() {
        let mut wb = Controller::default();
        let sheet_idx = 0;
        let action = PayloadsAction {
            payloads: vec![EditPayload::CellInput(CellInput {
                sheet_idx,
                row: 0,
                col: 0,
                content: String::from("=B2"),
            })],
            undoable: true,
            init: false,
        };
        let result = wb.handle_action(EditAction::Payloads(action));
        assert!(result.value_changed.len() == 1);
        let action = PayloadsAction {
            payloads: vec![EditPayload::CellInput(CellInput {
                sheet_idx,
                row: 0,
                col: 0,
                content: String::from("=B2+1"),
            })],
            undoable: true,
            init: false,
        };
        let result = wb.handle_action(EditAction::Payloads(action));
        assert!(result.value_changed.len() == 1);

        let sheet_id = wb.get_sheet_id_by_idx(sheet_idx).unwrap();
        let cell_id = wb.status.navigator.fetch_cell_id(&sheet_id, 0, 0).unwrap();
        let cell = wb.status.container.get_cell(sheet_id, &cell_id).unwrap();
        assert!(matches!(cell.value, CellValue::Number(1.0)));
    }

    #[test]
    fn controller_ephemeral_cell_input() {
        let mut wb = Controller::default();
        let sheet_idx = 0;
        let ephemeral_id = 1;
        let sheet_id = wb.get_sheet_id_by_idx(sheet_idx).unwrap();
        let payloads_action = PayloadsAction {
            payloads: vec![EditPayload::EphemeralCellInput(EphemeralCellInput {
                sheet_idx,
                id: ephemeral_id,
                content: String::from("1"),
            })],
            undoable: true,
            init: false,
        };
        let affect = wb.handle_action(EditAction::Payloads(payloads_action));
        assert!(matches!(affect.status, StatusCode::Ok(_)));
        let cell = wb
            .status
            .container
            .get_cell(sheet_id, &CellId::EphemeralCell(ephemeral_id))
            .unwrap();
        assert!(matches!(cell.value, CellValue::Number(_)));

        let payloads_action = PayloadsAction {
            payloads: vec![EditPayload::EphemeralCellInput(EphemeralCellInput {
                sheet_idx,
                id: ephemeral_id,
                content: String::from("=1+1"),
            })],
            undoable: true,
            init: false,
        };
        wb.handle_action(EditAction::Payloads(payloads_action));
        let cell = wb
            .status
            .container
            .get_cell(sheet_id, &CellId::EphemeralCell(ephemeral_id))
            .unwrap();
        assert!(matches!(cell.value, CellValue::Number(_)));
    }

    #[test]
    fn controller_set_cell_num_fmt() {
        let mut wb = Controller::default();
        let sheet_idx = 0;
        let action = PayloadsAction {
            payloads: vec![EditPayload::CellStyleUpdate(CellStyleUpdate {
                sheet_idx,
                row: 0,
                col: 0,
                ty: StyleUpdateType {
                    set_num_fmt: Some("0.00".to_string()),
                    ..Default::default()
                },
            })],
            undoable: true,
            init: false,
        };
        let _ = wb.handle_action(EditAction::Payloads(action));

        let cell_id = wb
            .status
            .navigator
            .fetch_cell_id(&wb.get_sheet_id_by_idx(sheet_idx).unwrap(), 0, 0)
            .unwrap();
        let cell = wb
            .status
            .container
            .get_cell(wb.get_sheet_id_by_idx(sheet_idx).unwrap(), &cell_id)
            .unwrap();
        let style_id = cell.style;
        let style = wb.status.style_manager.get_style(style_id);
        assert_eq!(style.formatter, "0.00");
    }

    #[test]
    fn controller_set_line_num_fmt() {
        let mut wb = Controller::default();
        let sheet_idx = 0;
        let action = PayloadsAction {
            payloads: vec![EditPayload::LineStyleUpdate(LineStyleUpdate {
                sheet_idx,
                from: 0,
                to: 1,
                row: true,
                ty: StyleUpdateType {
                    set_num_fmt: Some("0.00".to_string()),
                    ..Default::default()
                },
            })],
            undoable: true,
            init: false,
        };
        let _ = wb.handle_action(EditAction::Payloads(action));

        let sheet_id = wb.get_sheet_id_by_idx(sheet_idx).unwrap();
        let row_id = wb.status.navigator.fetch_row_id(&sheet_id, 0).unwrap();
        let row_info = wb.status.container.get_row_info(sheet_id, row_id).unwrap();
        let style_id = row_info.style;
        let style = wb.status.style_manager.get_style(style_id);
        assert_eq!(style.formatter, "0.00");
    }

    #[test]
    fn delete_sheet1() {
        let mut wb = Controller::default();
        let sheet_idx = 0;
        let action = PayloadsAction {
            payloads: vec![EditPayload::CreateSheet(CreateSheet {
                new_name: "11".to_string(),
                idx: sheet_idx,
            })],
            undoable: true,
            init: false,
        };
        let result = wb.handle_action(EditAction::Payloads(action));
        assert!(result.version > 0);
        let action = PayloadsAction {
            payloads: vec![EditPayload::DeleteSheet(DeleteSheet { idx: sheet_idx + 1 })],
            undoable: true,
            init: false,
        };
        let result = wb.handle_action(EditAction::Payloads(action));
        assert!(result.version > 0);
    }

    #[test]
    fn delete_sheet2() {
        let mut wb = Controller::default();
        let sheet_idx = 0;
        let action = PayloadsAction {
            payloads: vec![EditPayload::CreateSheet(CreateSheet {
                new_name: "11".to_string(),
                idx: sheet_idx,
            })],
            undoable: true,
            init: false,
        };
        let result = wb.handle_action(EditAction::Payloads(action));
        assert!(result.version > 0);
        let action = PayloadsAction {
            payloads: vec![EditPayload::DeleteSheet(DeleteSheet { idx: sheet_idx })],
            undoable: true,
            init: false,
        };
        let result = wb.handle_action(EditAction::Payloads(action));
        assert!(result.version > 0);
    }

    #[test]
    fn recreate_deleted_sheet_name() {
        // Regression: deleting a sheet must release its name so the same name
        // can be used again by a later CreateSheet. Previously the name stayed
        // reserved in sheet_id_manager (delete never cleaned it up), so the
        // re-create failed with SheetNameAlreadyExists (ActionEffect version 0).
        let mut wb = Controller::default();
        let name = "Beads board".to_string();
        let create = || {
            EditAction::Payloads(PayloadsAction {
                payloads: vec![EditPayload::CreateSheet(CreateSheet {
                    new_name: name.clone(),
                    idx: 1,
                })],
                undoable: true,
                init: false,
            })
        };

        let result = wb.handle_action(create());
        assert!(result.version > 0, "first create should succeed");

        let result = wb.handle_action(EditAction::Payloads(PayloadsAction {
            payloads: vec![EditPayload::DeleteSheet(DeleteSheet { idx: 1 })],
            undoable: true,
            init: false,
        }));
        assert!(result.version > 0, "delete should succeed");

        let result = wb.handle_action(create());
        assert!(
            result.version > 0,
            "recreating a sheet with a previously-deleted name should succeed"
        );
    }

    #[test]
    fn set_block_line_name_field() {
        let mut wb = Controller::default();
        let sheet_idx = 0;
        let action = PayloadsAction {
            payloads: vec![
                EditPayload::CreateBlock(CreateBlock {
                    sheet_idx,
                    id: 0,
                    master_row: 10,
                    master_col: 4,
                    row_cnt: 1,
                    col_cnt: 1,
                    owner: None,
                    modify_policy: None,
                    permissions: None,
                    description: None,
                    analyzes: None,
                    pivot: None,
                }),
                EditPayload::BlockLineNameFieldUpdate(BlockLineNameFieldUpdate {
                    sheet_idx,
                    block_id: 0,
                    line: 0,
                    row: true,
                    field_id: "field_id".to_string(),
                    name: Some("11".to_string()),
                    diy_render: None,
                }),
            ],
            undoable: true,
            init: false,
        };
        let result = wb.handle_action(EditAction::Payloads(action));
        assert!(result.version > 0);
    }

    #[test]
    fn create_block_with_num_fmt_and_field() {
        let mut wb = Controller::default();
        let sheet_idx = 0;
        let action = PayloadsAction {
            payloads: vec![
                EditPayload::CreateBlock(CreateBlock {
                    sheet_idx,
                    id: 1,
                    master_row: 6,
                    master_col: 3,
                    row_cnt: 1,
                    col_cnt: 1,
                    owner: None,
                    modify_policy: None,
                    permissions: None,
                    description: None,
                    analyzes: None,
                    pivot: None,
                }),
                EditPayload::BlockLineStyleUpdate(BlockLineStyleUpdate {
                    sheet_idx,
                    block_id: 1,
                    from: 0,
                    to: 0,
                    row: false,
                    ty: StyleUpdateType {
                        set_num_fmt: Some("0.00".to_string()),
                        ..Default::default()
                    },
                }),
                EditPayload::BlockLineNameFieldUpdate(BlockLineNameFieldUpdate {
                    sheet_idx,
                    block_id: 1,
                    line: 0,
                    row: false,
                    field_id: "field_1_1762435654448".to_string(),
                    name: Some("Customer Status".to_string()),
                    diy_render: Some(false),
                }),
            ],
            undoable: true,
            init: false,
        };
        let result = wb.handle_action(EditAction::Payloads(action));
        assert!(result.version > 0);
    }

    #[test]
    fn set_wrap_test() {
        let mut wb = Controller::default();
        let sheet_idx = 0;
        let action = PayloadsAction {
            payloads: vec![EditPayload::CellStyleUpdate(CellStyleUpdate {
                sheet_idx,
                row: 0,
                col: 0,
                ty: StyleUpdateType {
                    set_alignment: Some(Alignment {
                        horizontal: Some(HorizontalAlignment::General),
                        vertical: Some(VerticalAlignment::Top),
                        wrap_text: Some(true),
                    }),
                    ..Default::default()
                },
            })],
            undoable: true,
            init: false,
        };
        let result = wb.handle_action(EditAction::Payloads(action));
        assert!(result.version > 0);
        let cell_id = wb
            .status
            .navigator
            .fetch_cell_id(&wb.get_sheet_id_by_idx(sheet_idx).unwrap(), 0, 0)
            .unwrap();
        let cell = wb
            .status
            .container
            .get_cell(wb.get_sheet_id_by_idx(sheet_idx).unwrap(), &cell_id)
            .unwrap();
        let style_id = cell.style;
        let style = wb.status.style_manager.get_style(style_id);
        assert!(style.alignment.unwrap().wrap_text.unwrap());
    }

    #[test]
    fn test_temp_status() {
        let mut wb = Controller::default();
        let sheet_idx = 0;
        let action = PayloadsAction {
            payloads: vec![EditPayload::CellInput(CellInput {
                sheet_idx,
                row: 0,
                col: 0,
                content: String::from("1"),
            })],
            undoable: true,
            init: false,
        };

        // Before temp action: cell should be empty
        let sheet_id = wb.get_sheet_id_by_idx(sheet_idx).unwrap();
        let cell_id = wb.status.navigator.fetch_cell_id(&sheet_id, 0, 0).unwrap();
        let cell_before = wb.status.container.get_cell(sheet_id, &cell_id);
        assert!(cell_before.is_none());

        let result = wb.handle_action_in_temp_status(action);
        assert!(result.value_changed.len() == 1);
        assert!(wb.is_in_temp_mode());

        // After temp action: self.status reflects temp state
        let cell_id = wb.status.navigator.fetch_cell_id(&sheet_id, 0, 0).unwrap();
        let cell = wb.status.container.get_cell(sheet_id, &cell_id).unwrap();
        assert!(matches!(cell.value, CellValue::Number(1.0)));

        // Undo within temp branch: back to fork state (cell gone)
        let did_undo = wb.undo();
        assert!(did_undo);
        let cell_after_undo = wb.status.container.get_cell(sheet_id, &cell_id);
        assert!(cell_after_undo.is_none());

        // Undo again: at fork point, should stop
        let did_undo_again = wb.undo();
        assert!(!did_undo_again);

        // Redo: cell back
        let did_redo = wb.redo();
        assert!(did_redo);
        let cell_after_redo = wb.status.container.get_cell(sheet_id, &cell_id).unwrap();
        assert!(matches!(cell_after_redo.value, CellValue::Number(1.0)));

        // Commit: temp branch merged into main history
        wb.commit_temp_status();
        assert!(!wb.is_in_temp_mode());

        let cell_id = wb.status.navigator.fetch_cell_id(&sheet_id, 0, 0).unwrap();
        let cell = wb.status.container.get_cell(sheet_id, &cell_id).unwrap();
        assert!(matches!(cell.value, CellValue::Number(1.0)));
    }

    fn input_a1(content: &str, undoable: bool) -> PayloadsAction {
        PayloadsAction {
            payloads: vec![EditPayload::CellInput(CellInput {
                sheet_idx: 0,
                row: 0,
                col: 0,
                content: String::from(content),
            })],
            undoable,
            init: false,
        }
    }

    fn a1_value(wb: &Controller) -> Option<CellValue> {
        let sheet_id = wb.get_sheet_id_by_idx(0)?;
        let cell_id = wb.status.navigator.fetch_cell_id(&sheet_id, 0, 0).ok()?;
        wb.status
            .container
            .get_cell(sheet_id, &cell_id)
            .map(|c| c.value.clone())
    }

    #[test]
    fn test_temp_undo_returns_to_fork_not_empty_workbook() {
        let mut wb = Controller::default();
        wb.handle_action(EditAction::Payloads(input_a1("5", true)));

        wb.handle_action_in_temp_status(input_a1("1", true));
        assert!(matches!(a1_value(&wb), Some(CellValue::Number(1.0))));

        assert!(wb.undo());
        assert_eq!(wb.get_all_sheet_info().len(), 1);
        assert!(matches!(a1_value(&wb), Some(CellValue::Number(5.0))));
        assert!(!wb.undo(), "undo must stop at the fork point");
    }

    #[test]
    fn test_temp_steps_stay_out_of_main_history() {
        let mut wb = Controller::default();
        wb.handle_action(EditAction::Payloads(input_a1("5", true)));
        let main_version = wb.version();

        wb.handle_action_in_temp_status(input_a1("1", true));
        wb.handle_action_in_temp_status(input_a1("2", true));
        assert_eq!(wb.version(), main_version);

        // Discarded: the main history is exactly as it was.
        wb.clean_temp_status();
        assert_eq!(wb.version(), main_version);
        assert!(matches!(a1_value(&wb), Some(CellValue::Number(5.0))));
        assert!(wb.undo());
        assert!(a1_value(&wb).is_none());

        // Committed: the whole branch is ONE main step.
        let mut wb = Controller::default();
        wb.handle_action(EditAction::Payloads(input_a1("5", true)));
        wb.handle_action_in_temp_status(input_a1("1", true));
        wb.handle_action_in_temp_status(input_a1("2", true));
        wb.commit_temp_status();
        assert_eq!(wb.version(), main_version + 1);
        assert!(wb.undo());
        assert!(matches!(a1_value(&wb), Some(CellValue::Number(5.0))));
    }

    #[test]
    fn test_temp_init_action_keeps_main_history() {
        let mut wb = Controller::default();
        wb.handle_action(EditAction::Payloads(input_a1("5", true)));
        let mut init = input_a1("1", false);
        init.init = true;
        wb.handle_action_in_temp_status(init);
        wb.clean_temp_status();
        assert!(wb.undo(), "a temp `init` must not reset the main history");
    }

    #[test]
    fn test_temp_status_accumulate() {
        let mut wb = Controller::default();
        let sheet_idx = 0;
        let sheet_id = wb.get_sheet_id_by_idx(sheet_idx).unwrap();

        // First temp action
        let action1 = PayloadsAction {
            payloads: vec![EditPayload::CellInput(CellInput {
                sheet_idx,
                row: 0,
                col: 0,
                content: String::from("1"),
            })],
            undoable: true,
            init: false,
        };
        wb.handle_action_in_temp_status(action1);
        assert!(wb.is_in_temp_mode());

        // Second temp action on same branch
        let action2 = PayloadsAction {
            payloads: vec![EditPayload::CellInput(CellInput {
                sheet_idx,
                row: 1,
                col: 0,
                content: String::from("2"),
            })],
            undoable: true,
            init: false,
        };
        wb.handle_action_in_temp_status(action2);
        assert!(wb.is_in_temp_mode());

        // Both cells should be set
        let cell_id0 = wb.status.navigator.fetch_cell_id(&sheet_id, 0, 0).unwrap();
        let cell_id1 = wb.status.navigator.fetch_cell_id(&sheet_id, 1, 0).unwrap();
        let cell0 = wb.status.container.get_cell(sheet_id, &cell_id0).unwrap();
        let cell1 = wb.status.container.get_cell(sheet_id, &cell_id1).unwrap();
        assert!(matches!(cell0.value, CellValue::Number(1.0)));
        assert!(matches!(cell1.value, CellValue::Number(2.0)));

        // Undo second action
        wb.undo();
        let cell1_gone = wb.status.container.get_cell(sheet_id, &cell_id1);
        assert!(cell1_gone.is_none());
        let cell0_still = wb.status.container.get_cell(sheet_id, &cell_id0).unwrap();
        assert!(matches!(cell0_still.value, CellValue::Number(1.0)));

        // Undo first action
        wb.undo();
        let cell0_gone = wb.status.container.get_cell(sheet_id, &cell_id0);
        assert!(cell0_gone.is_none());

        // At fork point, undo should stop
        assert!(!wb.undo());

        // Clean: restore fork state
        wb.redo(); // restore action1 to test clean
        wb.redo(); // restore action2
        wb.clean_temp_status();
        assert!(!wb.is_in_temp_mode());
        let cell0_cleaned = wb.status.container.get_cell(sheet_id, &cell_id0);
        assert!(cell0_cleaned.is_none());
    }

    #[test]
    fn test_temp_status_non_temp_cleans() {
        let mut wb = Controller::default();
        let sheet_idx = 0;
        let sheet_id = wb.get_sheet_id_by_idx(sheet_idx).unwrap();

        let temp_action = PayloadsAction {
            payloads: vec![EditPayload::CellInput(CellInput {
                sheet_idx,
                row: 0,
                col: 0,
                content: String::from("temp"),
            })],
            undoable: true,
            init: false,
        };
        wb.handle_action_in_temp_status(temp_action);
        assert!(wb.is_in_temp_mode());

        // Non-temp action discards temp and applies normally
        let normal_action = PayloadsAction {
            payloads: vec![EditPayload::CellInput(CellInput {
                sheet_idx,
                row: 0,
                col: 0,
                content: String::from("real"),
            })],
            undoable: true,
            init: false,
        };
        wb.handle_action(EditAction::Payloads(normal_action));
        assert!(!wb.is_in_temp_mode());

        let cell_id = wb.status.navigator.fetch_cell_id(&sheet_id, 0, 0).unwrap();
        let cell = wb.status.container.get_cell(sheet_id, &cell_id).unwrap();
        // Value should be "real", not "temp"
        assert!(!matches!(cell.value, CellValue::Blank));
    }

    #[test]
    fn insert_rows_action_effect() {
        let mut wb = Controller::default();
        let sheet_idx = 0;
        let sheet_id = wb.get_sheet_id_by_idx(sheet_idx).unwrap();

        let action = PayloadsAction {
            payloads: vec![EditPayload::InsertRows(InsertRows {
                sheet_idx,
                start: 2,
                count: 3,
            })],
            undoable: true,
            init: false,
        };
        let result = wb.handle_action(EditAction::Payloads(action));

        assert_eq!(result.row_inserted.len(), 3);
        assert!(result.row_inserted.iter().all(|r| r.sheet_id == sheet_id));
        assert!(result.row_removed.is_empty());
        assert!(result.col_inserted.is_empty());
        assert!(result.col_removed.is_empty());
    }

    #[test]
    fn delete_rows_action_effect() {
        let mut wb = Controller::default();
        let sheet_idx = 0;
        let sheet_id = wb.get_sheet_id_by_idx(sheet_idx).unwrap();

        let action = PayloadsAction {
            payloads: vec![EditPayload::DeleteRows(DeleteRows {
                sheet_idx,
                start: 1,
                count: 2,
            })],
            undoable: true,
            init: false,
        };
        let result = wb.handle_action(EditAction::Payloads(action));

        assert_eq!(result.row_removed.len(), 2);
        assert!(result.row_removed.iter().all(|r| r.sheet_id == sheet_id));
        assert!(result.row_inserted.is_empty());
        assert!(result.col_inserted.is_empty());
        assert!(result.col_removed.is_empty());
    }

    #[test]
    fn insert_cols_action_effect() {
        let mut wb = Controller::default();
        let sheet_idx = 0;
        let sheet_id = wb.get_sheet_id_by_idx(sheet_idx).unwrap();

        let action = PayloadsAction {
            payloads: vec![EditPayload::InsertCols(InsertCols {
                sheet_idx,
                start: 0,
                count: 2,
            })],
            undoable: true,
            init: false,
        };
        let result = wb.handle_action(EditAction::Payloads(action));

        assert_eq!(result.col_inserted.len(), 2);
        assert!(result.col_inserted.iter().all(|c| c.sheet_id == sheet_id));
        assert!(result.col_removed.is_empty());
        assert!(result.row_inserted.is_empty());
        assert!(result.row_removed.is_empty());
    }

    #[test]
    fn delete_cols_action_effect() {
        let mut wb = Controller::default();
        let sheet_idx = 0;
        let sheet_id = wb.get_sheet_id_by_idx(sheet_idx).unwrap();

        let action = PayloadsAction {
            payloads: vec![EditPayload::DeleteCols(DeleteCols {
                sheet_idx,
                start: 0,
                count: 1,
            })],
            undoable: true,
            init: false,
        };
        let result = wb.handle_action(EditAction::Payloads(action));

        assert_eq!(result.col_removed.len(), 1);
        assert!(result.col_removed.iter().all(|c| c.sheet_id == sheet_id));
        assert!(result.col_inserted.is_empty());
        assert!(result.row_inserted.is_empty());
        assert!(result.row_removed.is_empty());
    }

    #[test]
    fn mixed_insert_delete_action_effect() {
        let mut wb = Controller::default();
        let sheet_idx = 0;
        let sheet_id = wb.get_sheet_id_by_idx(sheet_idx).unwrap();

        // Insert 2 rows then delete 1 col in a single action
        let action = PayloadsAction {
            payloads: vec![
                EditPayload::InsertRows(InsertRows {
                    sheet_idx,
                    start: 0,
                    count: 2,
                }),
                EditPayload::DeleteCols(DeleteCols {
                    sheet_idx,
                    start: 0,
                    count: 1,
                }),
            ],
            undoable: true,
            init: false,
        };
        let result = wb.handle_action(EditAction::Payloads(action));

        assert_eq!(result.row_inserted.len(), 2);
        assert_eq!(result.col_removed.len(), 1);
        assert!(result.row_inserted.iter().all(|r| r.sheet_id == sheet_id));
        assert!(result.col_removed.iter().all(|c| c.sheet_id == sheet_id));
        assert!(result.row_removed.is_empty());
        assert!(result.col_inserted.is_empty());
    }

    /// Reproduces the user-reported flow: create a block + bind a schema,
    /// save to .xlsx bytes, load back, verify both block geometry and
    /// schema survive the round-trip.
    #[test]
    fn save_load_block_and_schema_round_trip() {
        let mut wb = Controller::default();

        // Create a 3x3 block on sheet 0.
        let action = PayloadsAction {
            payloads: vec![EditPayload::CreateBlock(CreateBlock {
                sheet_idx: 0,
                id: 1,
                master_row: 0,
                master_col: 0,
                row_cnt: 3,
                col_cnt: 3,
                owner: None,
                modify_policy: None,
                permissions: None,
                description: None,
                analyzes: None,
                pivot: None,
            })],
            undoable: true,
            init: false,
        };
        wb.handle_action(EditAction::Payloads(action));

        // Bind a row schema to the block.
        let action = PayloadsAction {
            payloads: vec![EditPayload::BindFormSchema(BindFormSchema {
                ref_name: "materials".to_string(),
                sheet_idx: 0,
                block_id: 1,
                field_from: 1,
                key_idx: 0,
                fields: vec![
                    SchemaFieldSpec::new("qty", "r1"),
                    SchemaFieldSpec::new("name", "r2"),
                ],
                row: true,
                header_idx: None,
                unique_together: None,
            })],
            undoable: true,
            init: false,
        };
        wb.handle_action(EditAction::Payloads(action));

        // Pre-save snapshot.
        let sheet_id_before = wb.status.sheet_id_manager.get_id("Sheet1").unwrap();
        let blocks_before = wb
            .status
            .navigator
            .sheet_navs
            .get(sheet_id_before)
            .expect("sheet nav present before save")
            .data
            .blocks
            .len();
        let schemas_before = wb.status.block_schema_manager.schemas.len();
        assert!(blocks_before > 0, "block should be present before save");
        assert!(schemas_before > 0, "schema should be present before save");

        // Save → bytes.
        let bytes = wb.save().expect("save should succeed");
        assert!(!bytes.is_empty(), "saved bytes should be non-empty");

        // Load → new controller.
        let restored =
            Controller::from_file("rt".to_string(), &bytes).expect("load should succeed");

        // Post-load: sheet name preserved? Look up by name.
        let sheet_id_after = restored
            .status
            .sheet_id_manager
            .get_id("Sheet1")
            .expect("Sheet1 should be present after load");
        let blocks_after = restored
            .status
            .navigator
            .sheet_navs
            .get(sheet_id_after)
            .expect("sheet nav present after load")
            .data
            .blocks
            .len();
        let schemas_after = restored.status.block_schema_manager.schemas.len();

        assert_eq!(
            blocks_after, blocks_before,
            "block count should match across save/load"
        );
        assert_eq!(
            schemas_after, schemas_before,
            "schema count should match across save/load"
        );
        assert_eq!(
            restored
                .status
                .block_schema_manager
                .refs
                .get("materials")
                .map(|(_, b)| *b),
            Some(1),
            "ref-name index should be rebuilt and point to block 1"
        );
    }

    /// Mirrors the frontend's render path AND verifies the block's
    /// `info.schema` survives — without that field, the host's
    /// BlockInterfaceComponent silently soft-skips every block (treats
    /// the missing schema as the transient craft-rebind race) and the
    /// user sees no block UI even though the geometry persisted.
    #[test]
    fn save_load_display_window_includes_block() {
        let mut wb = Controller::default();
        wb.handle_action(EditAction::Payloads(PayloadsAction {
            payloads: vec![EditPayload::CreateBlock(CreateBlock {
                sheet_idx: 0,
                id: 7,
                master_row: 1,
                master_col: 1,
                row_cnt: 4,
                col_cnt: 3,
                owner: None,
                modify_policy: None,
                permissions: None,
                description: None,
                analyzes: None,
                pivot: None,
            })],
            undoable: true,
            init: false,
        }));
        // Bind a schema so the frontend's BlockInterface would actually render.
        wb.handle_action(EditAction::Payloads(PayloadsAction {
            payloads: vec![EditPayload::BindFormSchema(BindFormSchema {
                ref_name: "scenarios".to_string(),
                sheet_idx: 0,
                block_id: 7,
                field_from: 1,
                key_idx: 0,
                fields: vec![SchemaFieldSpec::new("amount", "render-amount")],
                row: true,
                header_idx: None,
                unique_together: None,
            })],
            undoable: true,
            init: false,
        }));

        let bytes = wb.save().expect("save");

        // The host renders via `Workbook::get_sheet_by_idx(...)` →
        // `get_display_window` (the same path WASM exposes to the worker
        // RPC). Round-trip through the public Workbook API to mirror that.
        let workbook = crate::Workbook::from_file(&bytes, "rt".to_string()).expect("load");
        let ws = workbook.get_sheet_by_idx(0).expect("sheet 0 worksheet");
        let window = ws.get_display_window(0, 0, 20, 20).expect("display window");
        let block_ids: Vec<_> = window.blocks.iter().map(|b| b.info.block_id).collect();
        assert!(
            block_ids.contains(&7),
            "loaded block id=7 should appear in display window, got {:?}",
            block_ids
        );

        // The host's BlockInterfaceComponent reads `info.schema`. If this
        // is None after load, the soft-skip drops the block from the UI
        // and the user sees nothing where the block should be.
        let block_with_schema = window
            .blocks
            .iter()
            .find(|b| b.info.block_id == 7)
            .expect("block 7 should be in display window");
        assert!(
            block_with_schema.info.schema.is_some(),
            "loaded block's info.schema should be populated after load — got None, which would \
             cause the host's soft-skip to hide the block in the UI"
        );
    }
}