tij 0.4.16

Text-mode interface for Jujutsu - a TUI for jj version control
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
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
//! jj operations (actions that modify repository state)

mod bookmark;
mod dialog;
mod push;
mod tag;

use std::io;
use std::process::ExitStatus;
use std::time::{Instant, SystemTime};

use crate::jj::{JjError, RunResult};
use crate::model::{
    CommandRecord, CommandStatus, CompareInfo, DiffContent, DiffDisplayFormat, Notification,
    RebaseMode,
};
use crate::ui::components::{Dialog, DialogCallback, SelectItem};

use crate::app::helpers::revision::{SelectedRevision, is_root_by_commit_id, short_id};

use super::state::{App, DirtyFlags, View};

/// Suspend TUI mode (raw mode off, leave alternate screen).
///
/// Returns a scope guard that restores TUI mode on drop.
/// Use this before running interactive jj commands (describe --edit, split, diffedit, resolve).
fn suspend_tui() -> impl Drop {
    use crossterm::execute;
    use crossterm::terminal::{
        Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode,
        enable_raw_mode,
    };
    use std::io::stdout;

    let _ = disable_raw_mode();
    let _ = execute!(stdout(), LeaveAlternateScreen, Clear(ClearType::All));

    scopeguard::guard((), |_| {
        let _ = enable_raw_mode();
        let _ = execute!(stdout(), EnterAlternateScreen);
    })
}

impl App {
    // ── Notification / error helpers ──────────────────────────────────

    /// Set a success notification (green)
    pub(crate) fn notify_success(&mut self, msg: impl Into<String>) {
        self.notification = Some(Notification::success(msg));
    }

    /// Set an info notification (blue)
    pub(crate) fn notify_info(&mut self, msg: impl Into<String>) {
        self.notification = Some(Notification::info(msg));
    }

    /// Set a warning notification (yellow)
    pub(crate) fn notify_warning(&mut self, msg: impl Into<String>) {
        self.notification = Some(Notification::warning(msg));
    }

    /// Set an error message (displayed in error area)
    pub(crate) fn set_error(&mut self, msg: impl Into<String>) {
        self.error_message = Some(msg.into());
    }

    // ── Command history recording helpers ─────────────────────────────

    /// Record a command execution into the command history.
    ///
    /// Called after a jj command completes. `args` are provided separately
    /// so that the command is recorded even on failure (when `RunResult` is not available).
    fn record_command(
        &mut self,
        operation: &str,
        args: &[&str],
        start: Instant,
        result: &Result<RunResult, JjError>,
    ) {
        let (status, error) = match result {
            Ok(_) => (CommandStatus::Success, None),
            Err(e) => (CommandStatus::Failed, Some(e.to_string())),
        };
        self.command_history.push(CommandRecord {
            operation: operation.to_string(),
            args: args.iter().map(|s| s.to_string()).collect(),
            timestamp: SystemTime::now(),
            duration_ms: start.elapsed().as_millis(),
            status,
            error,
        });
    }

    /// Run a jj command via the executor's `run()` and record it in command history.
    ///
    /// Returns the output string (same API as executor individual methods).
    /// Use this for write operations that should appear in Command History View.
    fn run_and_record(&mut self, operation: &str, args: &[&str]) -> Result<String, JjError> {
        let start = Instant::now();
        let result = self.jj.run(args);
        self.record_command(operation, args, start, &result);
        result.map(|r| r.output)
    }

    /// Record an interactive command execution (ExitStatus-based).
    ///
    /// Used for commands that go through `Stdio::inherit()` (split, diffedit, etc.)
    /// where we don't get RunResult but only ExitStatus.
    fn record_interactive_command(
        &mut self,
        operation: &str,
        args: &[&str],
        start: Instant,
        result: &io::Result<ExitStatus>,
    ) {
        let (status, error) = match result {
            Ok(s) if s.success() => (CommandStatus::Success, None),
            Ok(s) => (
                CommandStatus::Failed,
                Some(format!("exit code: {}", s.code().unwrap_or(-1))),
            ),
            Err(e) => (CommandStatus::Failed, Some(e.to_string())),
        };
        self.command_history.push(CommandRecord {
            operation: operation.to_string(),
            args: args.iter().map(|s| s.to_string()).collect(),
            timestamp: SystemTime::now(),
            duration_ms: start.elapsed().as_millis(),
            status,
            error,
        });
    }

    /// Record a command from a `Result<String, JjError>` (for methods that don't use RunResult).
    ///
    /// Used by push operations where executor methods return String directly.
    fn record_str_command(
        &mut self,
        operation: &str,
        args: &[&str],
        start: Instant,
        result: &Result<String, JjError>,
    ) {
        let (status, error) = match result {
            Ok(_) => (CommandStatus::Success, None),
            Err(e) => (CommandStatus::Failed, Some(e.to_string())),
        };
        self.command_history.push(CommandRecord {
            operation: operation.to_string(),
            args: args.iter().map(|s| s.to_string()).collect(),
            timestamp: SystemTime::now(),
            duration_ms: start.elapsed().as_millis(),
            status,
            error,
        });
    }

    /// Handle a simple jj action result: notify on success, set error on failure
    ///
    /// For the common pattern: Ok → notify_success + mark_dirty, Err → set_error.
    /// `err_prefix` is prepended to the error: `"{err_prefix}: {e}"`.
    /// Not suitable for actions that parse output, branch on result, or have side-effects.
    fn run_jj_action(
        &mut self,
        result: Result<String, crate::jj::JjError>,
        err_prefix: &str,
        success_msg: &str,
        dirty: DirtyFlags,
    ) {
        match result {
            Ok(_) => {
                self.notify_success(success_msg);
                self.mark_dirty_and_refresh_current(dirty);
            }
            Err(e) => {
                self.set_error(format!("{}: {}", err_prefix, e));
            }
        }
    }

    /// Execute undo operation
    ///
    /// jj 0.39+ outputs "Undid operation: ..." to stderr.
    /// We extract the description part for a more informative notification.
    pub(crate) fn execute_undo(&mut self) {
        let args: &[&str] = &["undo"];
        let start = Instant::now();
        let result = self.jj.run(args);
        self.record_command("Undo", args, start, &result);
        match result {
            Ok(r) => {
                let msg = Self::parse_undo_message(&r.stderr);
                self.notify_success(msg);
                self.mark_dirty_and_refresh_current(DirtyFlags::all());
            }
            Err(e) => {
                self.set_error(format!("Undo failed: {}", e));
            }
        }
    }

    /// Parse jj undo output to extract a concise notification message.
    ///
    /// Input format (jj 0.39+):
    ///   "Undid operation: <id> (<timestamp>) <description>\nRestored to ..."
    /// Returns: "Undo: <description>" or "Undo complete" as fallback.
    fn parse_undo_message(output: &str) -> String {
        // Find first line starting with "Undid operation:"
        for line in output.lines() {
            if let Some(rest) = line.strip_prefix("Undid operation:") {
                // Format: " <id> (<timestamp>) <description>"
                // Find closing ')' of timestamp, take everything after it
                if let Some(paren_end) = rest.find(')') {
                    let description = rest[paren_end + 1..].trim();
                    if !description.is_empty() {
                        return format!("Undo: {}", description);
                    }
                }
            }
        }
        "Undo complete".to_string()
    }

    /// Start describe input mode by fetching the full description
    ///
    /// If the description is multi-line, automatically opens the external
    /// editor instead of the 1-line input bar to prevent data loss.
    pub(crate) fn start_describe_input(&mut self, revision: &str) {
        // Fetch the full (multi-line) description from jj
        match self.jj.get_description(revision) {
            Ok(full_description) => {
                let description = full_description.trim_end_matches('\n').to_string();

                // Multi-line: fall through to external editor directly
                if description.lines().nth(1).is_some() {
                    self.execute_describe_external(revision);
                    return;
                }

                self.log_view
                    .set_describe_input(revision.to_string(), description);
            }
            Err(e) => {
                self.set_error(format!("Failed to get description: {}", e));
            }
        }
    }

    /// Execute describe via external editor (jj describe --edit)
    ///
    /// Temporarily exits TUI mode to allow the editor to run.
    /// Uses before/after description comparison to detect changes,
    /// since jj describe --edit exits 0 regardless of whether the user saved.
    pub(crate) fn execute_describe_external(&mut self, revision: &str) {
        // Pre-check: immutable commits cannot be described
        if self.jj.is_immutable(revision) {
            self.set_error("Cannot describe: commit is immutable");
            return;
        }

        // Capture description before editing for change detection
        let before = match self.jj.get_description(revision) {
            Ok(desc) => Some(desc.trim_end().to_string()),
            Err(_) => None,
        };

        let _guard = suspend_tui();

        // Run jj describe --editor (blocking, interactive)
        let start = Instant::now();
        let result = self.jj.describe_edit_interactive(revision);
        self.record_interactive_command(
            "Describe (editor)",
            &["describe", revision],
            start,
            &result,
        );

        match result {
            Ok(status) if status.success() => {
                // Compare before/after to detect actual changes
                let after = match self.jj.get_description(revision) {
                    Ok(desc) => Some(desc.trim_end().to_string()),
                    Err(_) => None,
                };

                match (before, after) {
                    (Some(b), Some(a)) if b == a => {
                        self.notify_info("Description unchanged");
                    }
                    (Some(_), Some(_)) => {
                        self.notify_success("Description updated");
                    }
                    _ => {
                        // Could not compare (get_description failed before or after)
                        self.notify_success("Describe editor closed");
                    }
                }
            }
            Ok(status) => {
                self.set_error(format!(
                    "Describe editor exited with error (code: {})",
                    status.code().unwrap_or(-1)
                ));
                return;
            }
            Err(e) => {
                self.set_error(format!("Describe failed: {}", e));
                return;
            }
        }

        // Refresh views (only on success — refresh_log clears error_message)
        self.mark_dirty_and_refresh_current(DirtyFlags::log());
    }

    /// Execute describe operation
    pub(crate) fn execute_describe(&mut self, revision: &str, message: &str) {
        let result = self.run_and_record("Describe", &["describe", revision, "-m", message]);
        self.run_jj_action(
            result,
            "Failed to update description",
            "Description updated",
            DirtyFlags::log(),
        );
    }

    /// Execute edit operation (set working-copy to specified change)
    pub(crate) fn execute_edit(&mut self, revision: &str) {
        let short_id = short_id(revision);
        let msg = format!("Now editing: {}", short_id);
        let result = self.run_and_record("Edit", &["edit", revision]);
        self.run_jj_action(result, "Failed to edit", &msg, DirtyFlags::log_and_status());
    }

    /// Execute new change operation
    pub(crate) fn execute_new_change(&mut self) {
        let result = self.run_and_record("New", &["new"]);
        self.run_jj_action(
            result,
            "Failed to create change",
            "Created new change",
            DirtyFlags::log_and_status(),
        );
    }

    /// Execute new change from specified parent
    pub(crate) fn execute_new_change_from(&mut self, parent_id: &str, display_name: &str) {
        let msg = format!("Created new change from {}", display_name);
        let result = self.run_and_record("New from", &["new", parent_id]);
        self.run_jj_action(
            result,
            "Failed to create change",
            &msg,
            DirtyFlags::log_and_status(),
        );
    }

    /// Execute commit operation (describe current change + create new change)
    pub(crate) fn execute_commit(&mut self, message: &str) {
        let result = self.run_and_record("Commit", &["commit", "-m", message]);
        self.run_jj_action(
            result,
            "Commit failed",
            "Changes committed",
            DirtyFlags::log_and_status(),
        );
    }

    /// Execute squash into target (requires terminal control transfer)
    ///
    /// jj squash --from/--into may open an editor when both source and destination
    /// have non-empty descriptions. Temporarily exits TUI mode to allow editor interaction.
    pub(crate) fn execute_squash_into(&mut self, source: &str, destination: &str) {
        if is_root_by_commit_id(&self.log_view.changes, source) {
            self.notify_info("Cannot squash: root commit has no parent");
            return;
        }

        let _guard = suspend_tui();

        // Run jj squash --from --into (blocking, interactive)
        let start = Instant::now();
        let result = self.jj.squash_into_interactive(source, destination);
        self.record_interactive_command(
            "Squash into",
            &["squash", "--from", source, "--into", destination],
            start,
            &result,
        );

        // 4. Handle result (io::Result<ExitStatus>)
        match result {
            Ok(status) if status.success() => {
                let src_short = short_id(source);
                let dst_short = short_id(destination);
                self.notify_success(format!(
                    "Squashed {} into {} (undo: u)",
                    src_short, dst_short
                ));
            }
            Ok(_) => {
                // Non-zero exit (user cancelled editor, or jj error)
                self.notify_info("Squash cancelled or failed");
            }
            Err(e) => {
                // IO error (command not found, etc.)
                self.set_error(format!("Squash failed: {}", e));
            }
        }

        // 5. Refresh views
        self.mark_dirty_and_refresh_current(DirtyFlags::log_and_status());
    }

    /// Execute abandon operation (abandon a change)
    pub(crate) fn execute_abandon(&mut self, revision: &str) {
        if is_root_by_commit_id(&self.log_view.changes, revision) {
            self.notify_info("Cannot abandon: root commit");
            return;
        }
        let short_id = short_id(revision);
        let msg = format!("Abandoned {} (undo: u)", short_id);
        let result = self.run_and_record("Abandon", &["abandon", revision]);
        self.run_jj_action(result, "Abandon failed", &msg, DirtyFlags::log_and_status());
    }

    /// Execute revert operation (creates reverse-diff commit)
    pub(crate) fn execute_revert(&mut self, revision: &str) {
        let short_id = short_id(revision);
        let msg = format!("Reverted {} (undo: u)", short_id);
        let result = self.run_and_record("Revert", &["revert", "-r", revision, "--onto", "@"]);
        self.run_jj_action(result, "Revert failed", &msg, DirtyFlags::log());
    }

    /// Execute redo operation
    ///
    /// Only works if the last operation was an undo.
    pub(crate) fn execute_redo(&mut self) {
        // First, check if last operation was an undo and get the target
        match self.jj.get_redo_target() {
            Ok(Some(op_id)) => {
                let result = self.run_and_record("Redo", &["op", "restore", &op_id]);
                match result {
                    Ok(_) => {
                        self.notify_success("Redo complete");
                        self.mark_dirty_and_refresh_current(DirtyFlags::all());
                    }
                    Err(e) => {
                        self.set_error(format!("Redo failed: {}", e));
                    }
                }
            }
            Ok(None) => {
                // Not in an undo/redo chain, or multiple consecutive undos
                // Note: After multiple undos, use 'o' (Operation History) to restore
                self.notify_info(
                    "Nothing to redo (use 'o' for operation history after multiple undos)",
                );
            }
            Err(e) => {
                self.set_error(format!("Failed to check redo target: {}", e));
            }
        }
    }

    /// Execute operation restore
    ///
    /// **Warning**: This is a destructive operation that modifies repository history.
    /// TODO: Add confirmation dialog (Phase 5.2) before executing.
    /// Currently, users can undo with `u` key if needed.
    pub(crate) fn execute_op_restore(&mut self, operation_id: &str) {
        match self.run_and_record("Op restore", &["op", "restore", operation_id]) {
            Ok(_) => {
                let short_id = &operation_id[..12.min(operation_id.len())];
                self.notify_success(format!("Restored to {} (undo: u)", short_id));
                self.mark_dirty_and_refresh_current(DirtyFlags::all());
                // Go back to log view
                self.go_to_view(View::Log);
            }
            Err(e) => {
                self.set_error(format!("Restore failed: {}", e));
            }
        }
    }

    /// Execute split operation (requires terminal control transfer)
    ///
    /// This method temporarily exits raw mode to allow jj split
    /// to use its external diff editor.
    ///
    /// Uses scope guard to ensure terminal state is always restored,
    /// even if jj split panics or returns early.
    pub(crate) fn execute_split(&mut self, revision: &str) {
        // Guard: cannot split an empty commit (nothing to split)
        let is_empty = self.log_view.selected_change().is_some_and(|c| c.is_empty);
        if is_empty {
            self.notify_info("Cannot split: no changes in this revision");
            return;
        }

        let _guard = suspend_tui();

        // Run jj split (blocking)
        let start = Instant::now();
        let result = self.jj.split_interactive(revision);
        self.record_interactive_command("Split", &["split", "-r", revision], start, &result);

        // 4. Handle result and refresh
        // Note: _guard will restore terminal when this function returns
        match result {
            Ok(status) if status.success() => {
                let short_id = short_id(revision);
                self.notify_success(format!("Split {} complete (undo: u)", short_id));
            }
            Ok(_) => {
                self.notify_info("Split cancelled or failed");
            }
            Err(e) => {
                self.set_error(format!("Split failed: {}", e));
            }
        }

        // 5. Refresh views
        self.mark_dirty_and_refresh_current(DirtyFlags::log_and_status());
    }

    /// Execute diffedit (interactive diff editor)
    ///
    /// When `file` is None, opens the full diffedit for the revision.
    /// When `file` is Some, opens diffedit scoped to that file.
    pub(crate) fn execute_diffedit(&mut self, revision: &str, file: Option<&str>) {
        let _guard = suspend_tui();

        // Run jj diffedit (blocking)
        let start = Instant::now();
        let result = if let Some(f) = file {
            self.jj.diffedit_file_interactive(revision, f)
        } else {
            self.jj.diffedit_interactive(revision)
        };
        let args: Vec<&str> = if let Some(f) = file {
            vec!["diffedit", "-r", revision, f]
        } else {
            vec!["diffedit", "-r", revision]
        };
        self.record_interactive_command("Diffedit", &args, start, &result);

        // 4. Handle result
        match result {
            Ok(status) if status.success() => {
                let short_id = short_id(revision);
                self.notify_success(format!("Diffedit {} complete (undo: u)", short_id));
            }
            Ok(_) => {
                self.notify_info("Diffedit cancelled or failed");
            }
            Err(e) => {
                self.set_error(format!("Diffedit failed: {}", e));
            }
        }

        // 5. Refresh views
        self.mark_dirty_and_refresh_current(DirtyFlags::log_and_status());
    }

    /// Execute restore for a single file
    pub(crate) fn execute_restore_file(&mut self, file_path: &str) {
        let msg = format!("Restored: {}", file_path);
        let result = self.run_and_record("Restore", &["restore", file_path]);
        self.run_jj_action(result, "Restore failed", &msg, DirtyFlags::log_and_status());
    }

    /// Execute restore for all files
    pub(crate) fn execute_restore_all(&mut self) {
        let result = self.run_and_record("Restore all", &["restore"]);
        self.run_jj_action(
            result,
            "Restore failed",
            "All files restored",
            DirtyFlags::log_and_status(),
        );
    }

    /// Execute `jj next --edit` and refresh
    pub(crate) fn execute_next(&mut self) {
        match self.run_and_record("Next", &["next", "--edit"]) {
            Ok(output) => {
                self.mark_dirty_and_refresh_current(DirtyFlags::log_and_status());

                // Move cursor to @ position
                self.log_view.select_working_copy();

                let msg = Self::parse_next_prev_message(&output, "next");
                self.notify_success(msg);
            }
            Err(e) => {
                let msg = Self::format_next_prev_error(&e, "next");
                self.notify_warning(msg);
            }
        }
    }

    /// Execute `jj prev --edit` and refresh
    pub(crate) fn execute_prev(&mut self) {
        match self.run_and_record("Prev", &["prev", "--edit"]) {
            Ok(output) => {
                self.mark_dirty_and_refresh_current(DirtyFlags::log_and_status());

                // Move cursor to @ position
                self.log_view.select_working_copy();

                let msg = Self::parse_next_prev_message(&output, "prev");
                self.notify_success(msg);
            }
            Err(e) => {
                let msg = Self::format_next_prev_error(&e, "prev");
                self.notify_warning(msg);
            }
        }
    }

    /// Parse jj next/prev success output to notification message
    fn parse_next_prev_message(output: &str, direction: &str) -> String {
        let trimmed = output.trim();
        if trimmed.is_empty() {
            format!("Moved {} successfully", direction)
        } else {
            let first_line = trimmed.lines().next().unwrap_or(trimmed);
            format!("Moved {}: {}", direction, first_line)
        }
    }

    /// Format next/prev error message for user
    fn format_next_prev_error(error: &crate::jj::JjError, direction: &str) -> String {
        let err_str = error.to_string();
        if err_str.contains("more than one child") || err_str.contains("more than one parent") {
            format!(
                "Cannot move {}: multiple {}. Use 'e' to edit a specific revision.",
                direction,
                if direction == "next" {
                    "children"
                } else {
                    "parents"
                }
            )
        } else if err_str.contains("No descendant") || err_str.contains("no child") {
            "Already at the newest change".to_string()
        } else if err_str.contains("No ancestor") || err_str.contains("no parent") {
            "Already at the root".to_string()
        } else {
            format!("Move {} failed: {}", direction, err_str)
        }
    }

    /// Execute `jj duplicate <change_id>` and refresh log
    ///
    /// Parses the output to extract the new change ID, refreshes the log,
    /// and moves focus to the duplicated change.
    pub(crate) fn duplicate(&mut self, revision: &str) {
        match self.jj.duplicate(revision) {
            Ok(output) => {
                // Parse new change_id from output
                let new_change_id = Self::parse_duplicate_output(&output);

                // Refresh log first (before notification)
                self.mark_dirty_and_refresh_current(DirtyFlags::log());

                // If refresh_log failed, don't show success notification
                if self.error_message.is_some() {
                    return;
                }

                // Move focus to duplicated change + build notification
                match new_change_id {
                    Some(ref new_id) => {
                        let short = &new_id[..new_id.len().min(8)];
                        if self.log_view.select_change_by_prefix(new_id) {
                            self.notification =
                                Some(Notification::success(format!("Duplicated as {}", short)));
                        } else {
                            self.notify_success(format!(
                                "Duplicated as {} (not in current revset)",
                                short
                            ));
                        }
                    }
                    None => {
                        self.notification =
                            Some(Notification::success("Duplicated successfully".to_string()));
                    }
                }
            }
            Err(e) => {
                self.set_error(format!("Duplicate failed: {}", e));
            }
        }
    }

    /// Parse the new change ID from `jj duplicate` output
    ///
    /// Output format: "Duplicated <commit_id> as <new_change_id> <new_commit_id> <description>"
    fn parse_duplicate_output(output: &str) -> Option<String> {
        for line in output.lines() {
            if let Some(rest) = line.strip_prefix("Duplicated ") {
                let parts: Vec<&str> = rest.splitn(4, ' ').collect();
                // parts[0] = commit_id, parts[1] = "as", parts[2] = new_change_id
                if parts.len() >= 3 && parts[1] == "as" {
                    return Some(parts[2].to_string());
                }
            }
        }
        None
    }

    /// Execute absorb: move working copy changes into ancestor commits
    ///
    /// Each hunk is moved to the closest mutable ancestor where the
    /// corresponding lines were modified last.
    pub(crate) fn execute_absorb(&mut self) {
        match self.run_and_record("Absorb", &["absorb"]) {
            Ok(output) => {
                self.mark_dirty_and_refresh_current(DirtyFlags::log_and_status());

                // Simple notification: check if output is empty or contains "nothing"
                // Avoid detailed parsing due to jj version differences
                let notification =
                    if output.trim().is_empty() || output.to_lowercase().contains("nothing") {
                        Notification::info("Nothing to absorb")
                    } else {
                        Notification::success("Absorb finished")
                    };
                self.notification = Some(notification);
            }
            Err(e) => {
                self.set_error(format!("Absorb failed: {}", e));
            }
        }
    }

    /// Execute simplify-parents: remove redundant parent edges
    pub(crate) fn execute_simplify_parents(&mut self, revision: &str) {
        match self.run_and_record("Simplify parents", &["simplify-parents", "-r", revision]) {
            Ok(output) => {
                self.mark_dirty_and_refresh_current(DirtyFlags::log_and_status());

                let notification = if output.trim().is_empty()
                    || output.to_lowercase().contains("nothing")
                {
                    Notification::info("No redundant parents found")
                } else {
                    let short_id = short_id(revision);
                    Notification::success(format!("Simplified parents for {} (undo: u)", short_id))
                };
                self.notification = Some(notification);
            }
            Err(e) => {
                self.set_error(format!("Simplify parents failed: {}", e));
            }
        }
    }

    /// Execute fix: apply configured code formatters to revision and descendants
    pub(crate) fn execute_fix(&mut self, revision: &str, change_id: &str) {
        // Capture commit_id before fix to detect if changes were made
        let commit_id_before = self
            .log_view
            .changes
            .iter()
            .find(|c| c.change_id == change_id)
            .map(|c| c.commit_id.to_string());

        match self.run_and_record("Fix", &["fix", "-s", revision]) {
            Ok(_) => {
                self.mark_dirty_and_refresh_current(DirtyFlags::log_and_status());

                let short_id = short_id(change_id);

                // Compare commit_id after refresh to detect actual changes
                let commit_id_after = self
                    .log_view
                    .changes
                    .iter()
                    .find(|c| c.change_id == change_id)
                    .map(|c| c.commit_id.to_string());

                let notification = if commit_id_before == commit_id_after {
                    Notification::info("No fixes needed")
                } else {
                    Notification::success(format!(
                        "Applied fix to {} and descendants (undo: u)",
                        short_id
                    ))
                };
                self.notification = Some(notification);
            }
            Err(e) => {
                let err_msg = e.to_string();
                // jj actual error: "Config error: No `fix.tools` are configured"
                // Match on "fix.tools" only — specific to this error, avoids false positives
                if err_msg.contains("fix.tools") {
                    self.set_error("Fix failed: no fix.tools configured in jj config");
                } else {
                    self.set_error(format!("Fix failed: {}", e));
                }
            }
        }
    }

    /// Execute parallelize: convert linear chain to parallel (sibling) commits
    pub(crate) fn execute_parallelize(&mut self, from: &str, to: &str) {
        let revset = format!("{}::{} | {}::{}", from, to, to, from);
        match self.run_and_record("Parallelize", &["parallelize", &revset]) {
            Ok(output) => {
                self.mark_dirty_and_refresh_current(DirtyFlags::log_and_status());
                self.notification = Some(Self::parallelize_notification(&output));
            }
            Err(e) => {
                self.set_error(format!("Parallelize failed: {}", e));
            }
        }
    }

    /// Determine the notification for parallelize output
    ///
    /// Unlike simplify-parents, `jj parallelize` outputs nothing to stdout on success
    /// (changes are reported on stderr). So empty output means success, not "nothing happened".
    /// Only explicit "nothing" in output indicates no change.
    fn parallelize_notification(output: &str) -> Notification {
        if output.to_lowercase().contains("nothing") {
            Notification::info("Nothing to parallelize (revisions may not be connected)")
        } else {
            Notification::success("Parallelized (undo: u)")
        }
    }

    /// Execute git fetch (default behavior)
    pub(crate) fn execute_fetch(&mut self) {
        match self.run_and_record("Fetch", &["git", "fetch"]) {
            Ok(output) => {
                self.mark_dirty_and_refresh_current(DirtyFlags::all());

                let notification = if output.trim().is_empty() {
                    Notification::info("Already up to date")
                } else {
                    Notification::success("Fetched from remote")
                };
                self.notification = Some(notification);
            }
            Err(e) => {
                self.set_error(format!("Fetch failed: {}", e));
            }
        }
    }

    /// Start fetch flow: check remotes and show dialog if multiple
    ///
    /// When multiple remotes exist, shows a selection dialog including
    /// a "Specific branch..." option that opens a second dialog for
    /// branch selection.
    pub(crate) fn start_fetch(&mut self) {
        match self.jj.git_remote_list() {
            Ok(remotes) => {
                if remotes.len() <= 1 {
                    // Single remote (or none): execute immediately
                    self.execute_fetch();
                } else {
                    // Multiple remotes: show selection dialog
                    let mut items = vec![
                        SelectItem {
                            label: "Default fetch (jj config)".to_string(),
                            value: "__default__".to_string(),
                            selected: false,
                        },
                        SelectItem {
                            label: "All remotes (including untracked)".to_string(),
                            value: "__all_remotes__".to_string(),
                            selected: false,
                        },
                        SelectItem {
                            label: "Tracked bookmarks only".to_string(),
                            value: "__tracked__".to_string(),
                            selected: false,
                        },
                    ];
                    for remote in &remotes {
                        items.push(SelectItem {
                            label: remote.clone(),
                            value: remote.clone(),
                            selected: false,
                        });
                    }
                    items.push(SelectItem {
                        label: "Specific branch...".to_string(),
                        value: "__branch__".to_string(),
                        selected: false,
                    });
                    self.active_dialog = Some(Dialog::select_single(
                        "Git Fetch",
                        "Select remote to fetch from:",
                        items,
                        None,
                        DialogCallback::GitFetch,
                    ));
                }
            }
            Err(_) => {
                // Fallback to default fetch on remote list failure
                self.execute_fetch();
            }
        }
    }

    /// Execute fetch with specific remote option
    pub(crate) fn execute_fetch_with_option(&mut self, option: &str) {
        let (label, result) = match option {
            "__default__" => ("Fetch", self.run_and_record("Fetch", &["git", "fetch"])),
            "__all_remotes__" => (
                "Fetch all",
                self.run_and_record("Fetch all", &["git", "fetch", "--all-remotes"]),
            ),
            "__tracked__" => (
                "Fetch tracked",
                self.run_and_record("Fetch tracked", &["git", "fetch", "--tracked"]),
            ),
            remote => (
                "Fetch remote",
                self.run_and_record("Fetch remote", &["git", "fetch", "--remote", remote]),
            ),
        };
        let _ = label;
        match result {
            Ok(output) => {
                self.mark_dirty_and_refresh_current(DirtyFlags::all());

                let notification = if output.trim().is_empty() {
                    let msg = match option {
                        "__tracked__" => "Tracked bookmarks: already up to date",
                        _ => "Already up to date",
                    };
                    Notification::info(msg)
                } else {
                    let source = match option {
                        "__default__" => "default remotes",
                        "__all_remotes__" => "all remotes",
                        "__tracked__" => "tracked bookmarks",
                        remote => remote,
                    };
                    Notification::success(format!("Fetched {}", source))
                };
                self.notification = Some(notification);
            }
            Err(e) => {
                self.set_error(format!("Fetch failed: {}", e));
            }
        }
    }

    /// Show 2nd-step Select dialog for branch selection
    ///
    /// Gets local bookmark names via `jj bookmark list` and shows a Select dialog.
    /// If no bookmarks found, falls back to default fetch with notification.
    fn start_fetch_branch_select(&mut self) {
        match self.jj.bookmark_list_all() {
            Ok(bookmarks) => {
                // Filter to local-only bookmarks (no remote)
                let local_names: Vec<String> = bookmarks
                    .iter()
                    .filter(|b| b.remote.is_none())
                    .map(|b| b.name.clone())
                    .collect();

                if local_names.is_empty() {
                    self.notify_info("No bookmarks found");
                    self.execute_fetch();
                    return;
                }

                let items: Vec<SelectItem> = local_names
                    .iter()
                    .map(|name| SelectItem {
                        label: name.clone(),
                        value: name.clone(),
                        selected: false,
                    })
                    .collect();

                self.active_dialog = Some(Dialog::select_single(
                    "Fetch Branch",
                    "Select branch to fetch:",
                    items,
                    None,
                    DialogCallback::GitFetchBranch,
                ));
            }
            Err(_) => {
                // Fallback to default fetch on bookmark list failure
                self.notification =
                    Some(Notification::info("Failed to list bookmarks, fetching all"));
                self.execute_fetch();
            }
        }
    }

    /// Execute `jj git fetch --branch <name>` for a specific branch
    fn execute_fetch_branch(&mut self, branch: &str) {
        match self.run_and_record("Fetch branch", &["git", "fetch", "--branch", branch]) {
            Ok(output) => {
                self.mark_dirty_and_refresh_current(DirtyFlags::all());

                let notification = if output.trim().is_empty() {
                    Notification::info(format!("Branch '{}': already up to date", branch))
                } else {
                    Notification::success(format!("Fetched branch '{}'", branch))
                };
                self.notification = Some(notification);
            }
            Err(e) => {
                self.set_error(format!("Fetch failed: {}", e));
            }
        }
    }

    /// Resolve a conflict using :ours tool
    pub(crate) fn execute_resolve_ours(&mut self, file_path: &str) {
        let (change_id, is_wc) = match self.resolve_view {
            Some(ref v) => (v.revision.clone(), v.is_working_copy),
            None => return,
        };

        match self.run_and_record(
            "Resolve :ours",
            &["resolve", "--tool", ":ours", "-r", &change_id, file_path],
        ) {
            Ok(_) => {
                self.notify_success(format!("Resolved {} with :ours", file_path));
                self.refresh_resolve_list(&change_id, is_wc);
            }
            Err(e) => {
                self.set_error(format!("Resolve failed: {}", e));
            }
        }
    }

    /// Resolve a conflict using :theirs tool
    pub(crate) fn execute_resolve_theirs(&mut self, file_path: &str) {
        let (change_id, is_wc) = match self.resolve_view {
            Some(ref v) => (v.revision.clone(), v.is_working_copy),
            None => return,
        };

        match self.run_and_record(
            "Resolve :theirs",
            &["resolve", "--tool", ":theirs", "-r", &change_id, file_path],
        ) {
            Ok(_) => {
                self.notify_success(format!("Resolved {} with :theirs", file_path));
                self.refresh_resolve_list(&change_id, is_wc);
            }
            Err(e) => {
                self.set_error(format!("Resolve failed: {}", e));
            }
        }
    }

    /// Resolve a conflict using external merge tool (@ only)
    ///
    /// Similar to execute_split: temporarily exits TUI mode for interactive tool.
    pub(crate) fn execute_resolve_external(&mut self, file_path: &str) {
        let (change_id, is_wc) = match self.resolve_view {
            Some(ref v) => (v.revision.clone(), v.is_working_copy),
            None => return,
        };

        if !is_wc {
            self.notify_warning("External merge tool only works for working copy (@)");
            return;
        }

        let _guard = suspend_tui();

        // Run jj resolve (blocking)
        let start = Instant::now();
        let result = self.jj.resolve_interactive(file_path, Some(&change_id));
        self.record_interactive_command(
            "Resolve",
            &["resolve", "-r", &change_id, file_path],
            start,
            &result,
        );

        // 4. Handle result
        match result {
            Ok(status) if status.success() => {
                self.notify_success(format!("Resolved {}", file_path));
            }
            Ok(_) => {
                self.notify_info("Resolve cancelled or failed");
            }
            Err(e) => {
                self.set_error(format!("Resolve failed: {}", e));
            }
        }

        // 5. Refresh resolve list
        self.refresh_resolve_list(&change_id, is_wc);
    }

    /// Execute rebase with specified mode
    ///
    /// Supports five modes:
    /// - `Revision` (`-r`): Move single change, descendants rebased onto parent
    /// - `Source` (`-s`): Move change and all descendants together
    /// - `Branch` (`-b`): Move entire branch relative to destination's ancestors
    /// - `InsertAfter` (`-A`): Insert change after target in history
    /// - `InsertBefore` (`-B`): Insert change before target in history
    ///
    /// When `skip_emptied` is true, `--skip-emptied` is appended.
    /// When `simplify_parents` is true, `--simplify-parents` is appended.
    /// On unsupported flag errors, retries without the flag or shows guidance.
    pub(crate) fn execute_rebase(
        &mut self,
        source: &str,
        destination: &str,
        mode: RebaseMode,
        skip_emptied: bool,
        simplify_parents: bool,
        use_revset: bool,
    ) {
        // Prevent rebasing to self (skip for revset — let jj validate)
        if !use_revset && source == destination {
            self.notify_warning("Cannot rebase to itself");
            return;
        }

        let mut extra_flags: Vec<&str> = Vec::new();
        if skip_emptied {
            extra_flags.push(crate::jj::constants::flags::SKIP_EMPTIED);
        }
        if simplify_parents {
            extra_flags.push(crate::jj::constants::flags::SIMPLIFY_PARENTS);
        }

        // Build args for recording
        let mut rebase_args = vec!["rebase"];
        match mode {
            RebaseMode::Revision => {
                rebase_args.extend_from_slice(&["-r", source, "-d", destination])
            }
            RebaseMode::Source => rebase_args.extend_from_slice(&["-s", source, "-d", destination]),
            RebaseMode::Branch => rebase_args.extend_from_slice(&["-b", source, "-d", destination]),
            RebaseMode::InsertAfter => {
                rebase_args.extend_from_slice(&["-r", source, "-A", destination])
            }
            RebaseMode::InsertBefore => {
                rebase_args.extend_from_slice(&["-r", source, "-B", destination])
            }
        }
        rebase_args.extend_from_slice(&extra_flags);

        let result = self.run_and_record("Rebase", &rebase_args);

        match result {
            Ok(output) => {
                self.notify_rebase_success(
                    &output,
                    destination,
                    mode,
                    skip_emptied,
                    simplify_parents,
                );
            }
            Err(e) => {
                let err_msg = format!("{}", e);

                if !is_rebase_flag_unsupported(&err_msg) {
                    self.set_error(format!("Rebase failed: {}", e));
                    return;
                }

                // Fallback: remove optional flags in fixed order
                // Step 1: remove --simplify-parents if ON
                // Step 2: remove --skip-emptied if ON
                // Step 3: -b not supported → warning
                let mut unsupported_notes: Vec<&str> = Vec::new();
                let mut retry_skip = skip_emptied;
                let mut retry_simplify = simplify_parents;

                // Step 1: try without --simplify-parents
                if retry_simplify {
                    retry_simplify = false;
                    let mut retry_flags: Vec<&str> = Vec::new();
                    if retry_skip {
                        retry_flags.push(crate::jj::constants::flags::SKIP_EMPTIED);
                    }
                    let result = self.rebase_with_mode(source, destination, mode, &retry_flags);
                    match result {
                        Ok(output) => {
                            self.notify_rebase_success(
                                &output,
                                destination,
                                mode,
                                retry_skip,
                                false,
                            );
                            self.append_fallback_note("--simplify-parents not supported");
                            return;
                        }
                        Err(e2) => {
                            let msg2 = format!("{}", e2);
                            if !is_rebase_flag_unsupported(&msg2) {
                                self.set_error(format!("Rebase failed: {}", e2));
                                return;
                            }
                            unsupported_notes.push("--simplify-parents");
                        }
                    }
                }

                // Step 2: try without --skip-emptied
                if retry_skip {
                    retry_skip = false;
                    let result = self.rebase_with_mode(source, destination, mode, &[]);
                    match result {
                        Ok(output) => {
                            self.notify_rebase_success(&output, destination, mode, false, false);
                            unsupported_notes.push("--skip-emptied");
                            let note = format!("{} not supported", unsupported_notes.join("/"));
                            self.append_fallback_note(&note);
                            return;
                        }
                        Err(e3) => {
                            let msg3 = format!("{}", e3);
                            if !is_rebase_flag_unsupported(&msg3) {
                                self.set_error(format!("Rebase failed: {}", e3));
                                return;
                            }
                            unsupported_notes.push("--skip-emptied");
                        }
                    }
                }

                // Step 3: no optional flags left — if Branch mode, it's -b not supported
                if !retry_skip && !retry_simplify {
                    // All optional flags already removed, try bare rebase
                    let result = self.rebase_with_mode(source, destination, mode, &[]);
                    match result {
                        Ok(output) => {
                            self.notify_rebase_success(&output, destination, mode, false, false);
                            if !unsupported_notes.is_empty() {
                                let note = format!("{} not supported", unsupported_notes.join("/"));
                                self.append_fallback_note(&note);
                            }
                        }
                        Err(_) if mode == RebaseMode::Branch => {
                            self.notify_warning(
                                "Branch mode (-b) not supported in this jj version. Use Source mode (-s) instead.",
                            );
                        }
                        Err(e_final) => {
                            self.set_error(format!("Rebase failed: {}", e_final));
                        }
                    }
                }
            }
        }
    }

    /// Build and set notification for successful rebase
    fn notify_rebase_success(
        &mut self,
        output: &str,
        destination: &str,
        mode: RebaseMode,
        skip_emptied: bool,
        simplify_parents: bool,
    ) {
        self.mark_dirty_and_refresh_current(DirtyFlags::log_and_status());

        let mut suffixes = Vec::new();
        if skip_emptied {
            suffixes.push("empty commits skipped");
        }
        if simplify_parents {
            suffixes.push("parents simplified");
        }
        let suffix = if suffixes.is_empty() {
            String::new()
        } else {
            format!(" ({})", suffixes.join(", "))
        };

        // Unified conflict detection from jj output
        let has_conflict = output.to_lowercase().contains("conflict");
        let notification = if has_conflict {
            Notification::warning("Rebased with conflicts - resolve with jj resolve")
        } else {
            let msg = match mode {
                RebaseMode::Revision => format!("Rebased successfully{}", suffix),
                RebaseMode::Source => {
                    format!("Rebased source and descendants successfully{}", suffix)
                }
                RebaseMode::Branch => format!("Rebased branch successfully{}", suffix),
                RebaseMode::InsertAfter => {
                    let short = &destination[..8.min(destination.len())];
                    format!("Inserted after {} successfully{}", short, suffix)
                }
                RebaseMode::InsertBefore => {
                    let short = &destination[..8.min(destination.len())];
                    format!("Inserted before {} successfully{}", short, suffix)
                }
            };
            Notification::success(msg)
        };
        self.notification = Some(notification);
    }

    /// Build rebase args for a given mode and run (used by fallback retry)
    fn rebase_with_mode(
        &mut self,
        source: &str,
        destination: &str,
        mode: RebaseMode,
        extra_flags: &[&str],
    ) -> Result<String, crate::jj::JjError> {
        let mut args = vec!["rebase"];
        match mode {
            RebaseMode::Revision => args.extend_from_slice(&["-r", source, "-d", destination]),
            RebaseMode::Source => args.extend_from_slice(&["-s", source, "-d", destination]),
            RebaseMode::Branch => args.extend_from_slice(&["-b", source, "-d", destination]),
            RebaseMode::InsertAfter => args.extend_from_slice(&["-r", source, "-A", destination]),
            RebaseMode::InsertBefore => args.extend_from_slice(&["-r", source, "-B", destination]),
        }
        args.extend_from_slice(extra_flags);
        self.run_and_record("Rebase (retry)", &args)
    }

    /// Append fallback note to existing notification, preserving severity
    fn append_fallback_note(&mut self, note: &str) {
        if let Some(existing) = self.notification.take() {
            let new_msg = format!("{} ({})", existing.message, note);
            self.notification = Some(Notification::new(new_msg, existing.kind));
        }
    }

    /// Update preview cache if selected change has changed.
    ///
    /// Called after key processing, NOT during render.
    /// Skips fetch if:
    /// - Preview is disabled
    /// - Same change_id is already cached (cache hit)
    /// - Preview auto-disabled (small terminal) — tracks pending_id for later
    /// - Rapid movement detected (debounce: skip if last fetch was < 100ms ago)
    pub(crate) fn update_preview_if_needed(&mut self) {
        if !self.preview_enabled {
            return;
        }

        let sel = match SelectedRevision::from_log_view(&self.log_view) {
            Some(s) => s,
            None => return, // No selection — keep cache intact
        };

        // Cache hit — same change_id with matching commit_id
        if let Some(cached) = self.preview_cache.peek(sel.change_id.as_str())
            && cached.commit_id == sel.commit_id.as_str()
        {
            self.preview_cache.touch(sel.change_id.as_str());
            return;
        }
        // commit_id mismatch — stale, need re-fetch

        // Always defer to idle tick — never block key handling with jj show.
        // resolve_pending_preview() will fetch on the next poll timeout.
        self.preview_pending_id = Some(sel.change_id.to_string());
    }

    /// Actually fetch preview content via jj show
    fn fetch_preview(&mut self, change_id: &str) {
        self.preview_pending_id = None;

        // Capture bookmarks and commit_id from the Change model
        let (commit_id, bookmarks) = self
            .log_view
            .selected_change()
            .filter(|c| c.change_id == change_id)
            .map(|c| (c.commit_id.to_string(), c.bookmarks.clone()))
            .unwrap_or_default();

        // Use commit_id for jj show to avoid ambiguity with divergent changes
        let revision = if commit_id.is_empty() {
            change_id
        } else {
            &commit_id
        };
        match self.jj.show(revision) {
            Ok(content) => {
                self.preview_cache.insert(super::state::PreviewCacheEntry {
                    change_id: change_id.to_string(),
                    commit_id,
                    content,
                    bookmarks,
                });
            }
            Err(_) => {
                self.preview_cache.remove(change_id);
            }
        }
    }

    /// Called from the event loop idle handler (when no key is pressed).
    /// Resolves any pending preview fetch that was deferred by debounce or auto-disable.
    pub fn resolve_pending_preview(&mut self) {
        if !self.preview_enabled || self.preview_auto_disabled {
            return;
        }
        if let Some(pending_id) = self.preview_pending_id.take() {
            // Verify the selection hasn't changed
            let still_selected = self
                .log_view
                .selected_change()
                .map(|c| c.change_id == pending_id)
                .unwrap_or(false);
            if still_selected {
                self.fetch_preview(&pending_id);
            }
        }
    }

    // =========================================================================
    // Diff export (clipboard copy & file export)
    // =========================================================================

    /// Copy diff content to system clipboard
    pub(crate) fn copy_diff_to_clipboard(&mut self, full: bool) {
        let Some(ref diff_view) = self.diff_view else {
            return;
        };
        let revision = diff_view.revision.clone();
        let compare_info = diff_view.compare_info.clone();

        let result = if full {
            if let Some(ref ci) = compare_info {
                // Compare mode: jj show doesn't apply, prepend from/to metadata header
                let diff = self
                    .jj
                    .diff_range(ci.from.commit_id.as_str(), ci.to.commit_id.as_str());
                diff.map(|d| {
                    format!(
                        "Compare: {} -> {}\nFrom: {} ({})\nTo:   {} ({})\n\n{}",
                        ci.from.change_id,
                        ci.to.change_id,
                        ci.from.change_id,
                        ci.from.description,
                        ci.to.change_id,
                        ci.to.description,
                        d,
                    )
                })
            } else {
                self.jj.show_raw(&revision)
            }
        } else {
            // jj diff (diff only)
            if let Some(ref ci) = compare_info {
                self.jj
                    .diff_range(ci.from.commit_id.as_str(), ci.to.commit_id.as_str())
            } else {
                self.jj.diff_raw(&revision)
            }
        };

        match result {
            Ok(text) => {
                let line_count = text.lines().count();
                match super::clipboard::copy_to_clipboard(&text) {
                    Ok(()) => {
                        let mode = if full { "show" } else { "diff" };
                        self.notify_success(format!(
                            "Copied to clipboard ({} lines, {})",
                            line_count, mode
                        ));
                    }
                    Err(e) => {
                        self.set_error(e);
                    }
                }
            }
            Err(e) => {
                self.set_error(format!("Failed to get diff: {}", e));
            }
        }
    }

    /// Fetch diff content in the specified format
    ///
    /// Handles the difference between normal and compare modes,
    /// and between ColorWords (which returns DiffContent directly via `jj show`)
    /// and Stat/Git (which return String and need parsing).
    fn fetch_diff_content(
        &self,
        change_id: &str,
        format: DiffDisplayFormat,
        compare: Option<&CompareInfo>,
    ) -> Result<DiffContent, crate::jj::JjError> {
        use crate::jj::parser::Parser;

        if let Some(ci) = compare {
            match format {
                DiffDisplayFormat::ColorWords => self
                    .jj
                    .diff_range(ci.from.commit_id.as_str(), ci.to.commit_id.as_str())
                    .map(|o| Parser::parse_diff_body(&o)),
                DiffDisplayFormat::Stat => self
                    .jj
                    .diff_range_stat(ci.from.commit_id.as_str(), ci.to.commit_id.as_str())
                    .map(|o| Parser::parse_diff_body_stat(&o)),
                DiffDisplayFormat::Git => self
                    .jj
                    .diff_range_git(ci.from.commit_id.as_str(), ci.to.commit_id.as_str())
                    .map(|o| Parser::parse_diff_body_git(&o)),
            }
        } else {
            match format {
                DiffDisplayFormat::ColorWords => self.jj.show(change_id),
                DiffDisplayFormat::Stat => self
                    .jj
                    .show_stat(change_id)
                    .and_then(|o| Parser::parse_show_stat(&o)),
                DiffDisplayFormat::Git => self
                    .jj
                    .show_git(change_id)
                    .and_then(|o| Parser::parse_show_git(&o)),
            }
        }
    }

    /// Cycle the diff display format and re-fetch content
    pub(crate) fn cycle_diff_format(&mut self) {
        use crate::model::DiffDisplayFormat;

        let Some(ref diff_view) = self.diff_view else {
            return;
        };

        let old_format = diff_view.display_format;
        let new_format = old_format.next();
        let revision = diff_view.revision.clone();
        let compare_info = diff_view.compare_info.clone();

        match self.fetch_diff_content(&revision, new_format, compare_info.as_ref()) {
            Ok(content) => {
                let diff_view = self.diff_view.as_mut().unwrap();
                diff_view.set_content(revision, content);
                diff_view.compare_info = compare_info;
                diff_view.display_format = new_format;

                self.notify_info(format!(
                    "Display: {} ({}/{})",
                    new_format.label(),
                    new_format.position(),
                    DiffDisplayFormat::COUNT,
                ));
            }
            Err(e) => {
                self.set_error(format!(
                    "Failed to load {} format: {}",
                    new_format.label(),
                    e
                ));
            }
        }
    }

    /// Export diff content to a .patch file
    pub(crate) fn export_diff_to_file(&mut self) {
        let Some(ref diff_view) = self.diff_view else {
            return;
        };
        let revision = diff_view.revision.clone();
        let compare_info = diff_view.compare_info.clone();

        // Determine filename and content based on mode
        // Uses `jj diff --git` for git-compatible unified patch format (git apply compatible)
        let (short_id, result) = if let Some(ref ci) = compare_info {
            // Compare mode: use diff --git --from --to
            let from_short = short_id(ci.from.change_id.as_str());
            let to_short = short_id(ci.to.change_id.as_str());
            let label = format!("{}_{}", from_short, to_short);
            let result = self
                .jj
                .diff_range_git(ci.from.commit_id.as_str(), ci.to.commit_id.as_str());
            (label, result)
        } else {
            let short = short_id(&revision).to_string();
            let result = self.jj.diff_git_raw(&revision);
            (short, result)
        };

        match result {
            Ok(text) => {
                let filename = unique_patch_filename(&short_id);
                match std::fs::write(&filename, &text) {
                    Ok(()) => {
                        self.notification =
                            Some(Notification::success(format!("Exported to {}", filename)));
                    }
                    Err(e) => {
                        self.set_error(format!("Failed to write {}: {}", filename, e));
                    }
                }
            }
            Err(e) => {
                self.set_error(format!("Failed to get diff: {}", e));
            }
        }
    }
}

/// Generate a unique .patch filename, appending -1, -2, etc. if the file already exists
fn unique_patch_filename(short_id: &str) -> String {
    let base = format!("{}.patch", short_id);
    if !std::path::Path::new(&base).exists() {
        return base;
    }
    for i in 1.. {
        let candidate = format!("{}-{}.patch", short_id, i);
        if !std::path::Path::new(&candidate).exists() {
            return candidate;
        }
    }
    unreachable!()
}

/// Check if a rebase error indicates an unsupported flag
///
/// Older jj versions may not support `--skip-emptied` or `-b`.
/// Detects generic "unexpected argument" / "unrecognized" errors.
fn is_rebase_flag_unsupported(err_msg: &str) -> bool {
    let lower = err_msg.to_lowercase();
    lower.contains("unexpected argument")
        || lower.contains("unrecognized")
        || lower.contains("unknown flag")
        || lower.contains("unknown option")
}

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

    // =========================================================================
    // Describe multi-line detection tests
    //
    // The App::start_describe_input() method uses `desc.lines().nth(1).is_some()`
    // to detect multi-line descriptions and fall through to the external editor.
    // These tests verify the detection logic matches expectations.
    // =========================================================================

    #[test]
    fn test_multiline_detection_single_line() {
        let desc = "single line description";
        assert!(desc.lines().nth(1).is_none());
    }

    #[test]
    fn test_multiline_detection_two_lines() {
        let desc = "first line\nsecond line";
        assert!(desc.lines().nth(1).is_some());
    }

    #[test]
    fn test_multiline_detection_empty_string() {
        let desc = "";
        assert!(desc.lines().nth(1).is_none());
    }

    #[test]
    fn test_multiline_detection_trailing_newline_only() {
        // After trim_end_matches('\n'), a single-line desc with trailing \n becomes single-line
        let desc = "single line\n".trim_end_matches('\n');
        assert!(desc.lines().nth(1).is_none());
    }

    #[test]
    fn test_multiline_detection_two_lines_with_trailing_newline() {
        // After trim_end_matches('\n'), multi-line desc is still multi-line
        let desc = "first\nsecond\n".trim_end_matches('\n');
        assert!(desc.lines().nth(1).is_some());
    }

    // =========================================================================
    // parse_undo_message tests (jj 0.39+ output parsing)
    // =========================================================================

    #[test]
    fn test_parse_undo_message_jj039_format() {
        let output = "Undid operation: 4332678ef1ed (2026-03-06 10:29:59) describe commit 509de9e3\nRestored to operation: 6633e04968e6 (2026-03-06 10:29:58) add workspace 'default'";
        assert_eq!(
            App::parse_undo_message(output),
            "Undo: describe commit 509de9e3"
        );
    }

    #[test]
    fn test_parse_undo_message_fallback() {
        // Pre-0.39 or unexpected format
        let output = "Working copy now at: abc12345";
        assert_eq!(App::parse_undo_message(output), "Undo complete");
    }

    #[test]
    fn test_parse_undo_message_empty() {
        assert_eq!(App::parse_undo_message(""), "Undo complete");
    }

    // =========================================================================
    // Before/after description comparison tests
    //
    // The App::execute_describe_external() method compares descriptions
    // using trim_end() to normalize trailing whitespace.
    // These tests verify the comparison logic.
    // =========================================================================

    #[test]
    fn test_description_comparison_identical() {
        let before = "test description".trim_end().to_string();
        let after = "test description".trim_end().to_string();
        assert_eq!(before, after);
    }

    #[test]
    fn test_description_comparison_trailing_whitespace_normalized() {
        let before = "test description\n".trim_end().to_string();
        let after = "test description\n\n".trim_end().to_string();
        assert_eq!(before, after);
    }

    #[test]
    fn test_description_comparison_different() {
        let before = "old description".trim_end().to_string();
        let after = "new description".trim_end().to_string();
        assert_ne!(before, after);
    }

    // =========================================================================
    // has_force_push tests
    // =========================================================================

    // =========================================================================
    // is_immutable_bookmark tests
    // =========================================================================

    // =========================================================================
    // format_bookmark_status tests (multi-bookmark select dialog labels)
    // =========================================================================

    // =========================================================================
    // truncate_description tests (UTF-8 safe truncation)
    // =========================================================================

    // =========================================================================
    // parse_push_change_bookmark tests
    // =========================================================================

    // =========================================================================
    // push_target_remote cleanup tests
    // =========================================================================

    // =========================================================================
    // duplicate output parsing tests
    // =========================================================================

    #[test]
    fn test_parse_duplicate_output() {
        let output = "Duplicated 0193efbd0b2d as nyowntnw 6abd63b3 no-bookmark change (plain)";
        let result = App::parse_duplicate_output(output);
        assert_eq!(result, Some("nyowntnw".to_string()));
    }

    #[test]
    fn test_parse_duplicate_output_no_match() {
        let result = App::parse_duplicate_output("Some unrelated output");
        assert_eq!(result, None);
    }

    #[test]
    fn test_parse_duplicate_output_empty() {
        let result = App::parse_duplicate_output("");
        assert_eq!(result, None);
    }

    #[test]
    fn test_parse_duplicate_output_multiline() {
        // Warning lines before the actual duplicate output
        let output = "Working copy changes were not restored.\n\
                       Duplicated abc1234567890 as xyzwqrst def5678901 test description";
        let result = App::parse_duplicate_output(output);
        assert_eq!(result, Some("xyzwqrst".to_string()));
    }

    // =========================================================================
    // Revert dialog callback tests
    // =========================================================================

    // =========================================================================
    // is_revisions_unsupported_error tests
    // =========================================================================

    // =========================================================================
    // GitPushRevisions dialog callback tests
    // =========================================================================

    // =========================================================================
    // GitPushMultiBookmarkMode dialog callback tests
    // =========================================================================

    #[test]
    fn test_unique_patch_filename_no_conflict() {
        // When file doesn't exist, returns base name
        // (uses a name unlikely to exist in current dir)
        let name = unique_patch_filename("zzzz_test_nonexistent");
        assert_eq!(name, "zzzz_test_nonexistent.patch");
    }

    #[test]
    fn test_unique_patch_filename_with_conflict() {
        use std::fs;
        let base = "test_unique_patch_tmp";
        let base_file = format!("{}.patch", base);

        // Create the base file to force a conflict
        fs::write(&base_file, "test").unwrap();

        let name = unique_patch_filename(base);
        assert_eq!(name, format!("{}-1.patch", base));

        // Clean up
        let _ = fs::remove_file(&base_file);
    }

    #[test]
    fn test_unique_patch_filename_with_multiple_conflicts() {
        use std::fs;
        let base = "test_unique_multi_tmp";
        let files: Vec<String> = vec![
            format!("{}.patch", base),
            format!("{}-1.patch", base),
            format!("{}-2.patch", base),
        ];

        // Create all conflicting files
        for f in &files {
            fs::write(f, "test").unwrap();
        }

        let name = unique_patch_filename(base);
        assert_eq!(name, format!("{}-3.patch", base));

        // Clean up
        for f in &files {
            let _ = fs::remove_file(f);
        }
    }

    // --- Compare mode export path tests ---

    #[test]
    fn test_export_compare_mode_uses_diff_range_not_show() {
        use crate::model::{ChangeId, CommitId, CompareInfo, CompareRevisionInfo, DiffContent};
        use crate::ui::views::DiffView;

        let mut app = App::new_for_test();

        let compare_info = CompareInfo {
            from: CompareRevisionInfo {
                change_id: ChangeId::new("aaaa1111".to_string()),
                commit_id: CommitId::new("ff001111".to_string()),
                bookmarks: vec![],
                author: "user@test.com".to_string(),
                timestamp: "2024-01-01".to_string(),
                description: "from revision".to_string(),
            },
            to: CompareRevisionInfo {
                change_id: ChangeId::new("bbbb2222".to_string()),
                commit_id: CommitId::new("ff002222".to_string()),
                bookmarks: vec![],
                author: "user@test.com".to_string(),
                timestamp: "2024-01-02".to_string(),
                description: "to revision".to_string(),
            },
        };
        app.diff_view = Some(DiffView::new_compare(DiffContent::default(), compare_info));

        // Export will fail (no jj repo in test), but the error reveals which path was taken.
        // In compare mode, it should attempt `jj diff --git --from --to`.
        app.export_diff_to_file();

        // Should have an error (no jj repo), confirming the code path was executed
        assert!(
            app.error_message.is_some(),
            "Expected error from jj command in test environment"
        );
    }

    #[test]
    fn test_copy_clipboard_compare_mode_uses_diff_range() {
        use crate::model::{ChangeId, CommitId, CompareInfo, CompareRevisionInfo, DiffContent};
        use crate::ui::views::DiffView;

        let mut app = App::new_for_test();

        let compare_info = CompareInfo {
            from: CompareRevisionInfo {
                change_id: ChangeId::new("cccc3333".to_string()),
                commit_id: CommitId::new("ff003333".to_string()),
                bookmarks: vec![],
                author: "user@test.com".to_string(),
                timestamp: "2024-01-01".to_string(),
                description: "from".to_string(),
            },
            to: CompareRevisionInfo {
                change_id: ChangeId::new("dddd4444".to_string()),
                commit_id: CommitId::new("ff004444".to_string()),
                bookmarks: vec![],
                author: "user@test.com".to_string(),
                timestamp: "2024-01-02".to_string(),
                description: "to".to_string(),
            },
        };
        app.diff_view = Some(DiffView::new_compare(DiffContent::default(), compare_info));

        // Both full and diff-only should attempt diff_range in compare mode
        app.copy_diff_to_clipboard(true);
        assert!(
            app.error_message.is_some(),
            "Expected error from jj command in test environment (full)"
        );

        app.error_message = None;
        app.copy_diff_to_clipboard(false);
        assert!(
            app.error_message.is_some(),
            "Expected error from jj command in test environment (diff)"
        );
    }

    #[test]
    fn test_export_normal_mode_uses_diff_git() {
        use crate::model::DiffContent;
        use crate::ui::views::DiffView;

        let mut app = App::new_for_test();
        app.diff_view = Some(DiffView::new(
            "testid12".to_string(),
            DiffContent::default(),
        ));

        // Normal mode: should attempt `jj diff --git`
        app.export_diff_to_file();
        assert!(
            app.error_message.is_some(),
            "Expected error from jj command in test environment"
        );
    }

    // =========================================================================
    // is_private_commit_error tests
    // =========================================================================

    // =========================================================================
    // is_empty_description_error tests
    // =========================================================================

    // =========================================================================
    // is_rebase_flag_unsupported tests
    // =========================================================================

    #[test]
    fn test_rebase_flag_unsupported_unexpected_argument() {
        assert!(is_rebase_flag_unsupported(
            "error: unexpected argument '--skip-emptied'"
        ));
    }

    #[test]
    fn test_rebase_flag_unsupported_unrecognized() {
        assert!(is_rebase_flag_unsupported(
            "error: unrecognized option '-b'"
        ));
    }

    #[test]
    fn test_rebase_flag_unsupported_unknown_flag() {
        assert!(is_rebase_flag_unsupported(
            "error: unknown flag '--skip-emptied'"
        ));
    }

    #[test]
    fn test_rebase_flag_unsupported_unknown_option() {
        assert!(is_rebase_flag_unsupported(
            "error: unknown option '--skip-emptied'"
        ));
    }

    #[test]
    fn test_rebase_flag_unsupported_false_for_normal_error() {
        assert!(!is_rebase_flag_unsupported(
            "Error: Revision abc123 is not reachable from destination"
        ));
    }

    #[test]
    fn test_rebase_flag_unsupported_false_for_conflict() {
        assert!(!is_rebase_flag_unsupported(
            "Rebase produced conflict in src/main.rs"
        ));
    }

    // =========================================================================
    // Rebase fallback: Branch unsupported × skip_emptied=true (Issue #1)
    // =========================================================================

    /// When both `-b` and `--skip-emptied` are unsupported, the retry (without
    /// `--skip-emptied`) also fails with "unsupported flag" for `-b`.
    /// The handler must detect this and show the Branch guidance notification.
    #[test]
    fn test_rebase_branch_unsupported_detected_on_retry_error() {
        // Simulates: first error = "--skip-emptied unsupported", retry error = "-b unsupported"
        let retry_msg = "error: unexpected argument '-b'";
        assert!(is_rebase_flag_unsupported(retry_msg));
        // In execute_rebase, mode == Branch && unsupported → guidance notification (not error_message)
    }

    // =========================================================================
    // Rebase fallback: notification severity preservation (Issue #2)
    // =========================================================================

    /// When --skip-emptied retry succeeds with conflicts, notify_rebase_success
    /// sets a Warning. The skip-emptied suffix must preserve Warning severity.
    #[test]
    fn test_notification_severity_preserved_on_skip_emptied_fallback() {
        use crate::model::{Notification, NotificationKind};

        // Simulate: notify_rebase_success set a Warning for conflicts
        let existing = Notification::warning("Rebased with conflicts - resolve with jj resolve");
        assert_eq!(existing.kind, NotificationKind::Warning);

        // The fallback code takes the existing notification and creates a new one
        // preserving the kind
        let new_msg = format!(
            "{} (--skip-emptied not supported, empty commits may remain)",
            existing.message
        );
        let result = Notification::new(new_msg, existing.kind);

        // Severity must remain Warning (not downgraded to Info)
        assert_eq!(result.kind, NotificationKind::Warning);
        assert!(result.message.contains("conflicts"));
        assert!(result.message.contains("--skip-emptied not supported"));
    }

    /// When --skip-emptied retry succeeds without conflicts, severity is Success.
    #[test]
    fn test_notification_severity_success_on_skip_emptied_fallback() {
        use crate::model::{Notification, NotificationKind};

        let existing = Notification::success("Rebased successfully");
        let new_msg = format!(
            "{} (--skip-emptied not supported, empty commits may remain)",
            existing.message
        );
        let result = Notification::new(new_msg, existing.kind);

        assert_eq!(result.kind, NotificationKind::Success);
        assert!(result.message.contains("Rebased successfully"));
        assert!(result.message.contains("--skip-emptied not supported"));
    }

    // =========================================================================
    // Simplify Parents dialog callback tests
    // =========================================================================

    // =========================================================================
    // Parallelize dialog callback tests
    // =========================================================================

    #[test]
    fn test_parallelize_notification_success() {
        use crate::model::NotificationKind;
        let n = App::parallelize_notification("Rebased 3 commits");
        assert_eq!(n.kind, NotificationKind::Success);
        assert!(n.message.contains("Parallelized"));
    }

    #[test]
    fn test_parallelize_notification_nothing_output() {
        use crate::model::NotificationKind;
        let n = App::parallelize_notification("Nothing changed");
        assert_eq!(n.kind, NotificationKind::Info);
        assert!(n.message.contains("Nothing to parallelize"));
    }

    #[test]
    fn test_parallelize_notification_empty_output_is_success() {
        // jj parallelize outputs nothing to stdout on success
        use crate::model::NotificationKind;
        let n = App::parallelize_notification("");
        assert_eq!(n.kind, NotificationKind::Success);
        assert!(n.message.contains("Parallelized"));
    }

    #[test]
    fn test_parallelize_notification_whitespace_only_is_success() {
        use crate::model::NotificationKind;
        let n = App::parallelize_notification("  \n  ");
        assert_eq!(n.kind, NotificationKind::Success);
        assert!(n.message.contains("Parallelized"));
    }

    // =========================================================================
    // Notification / error helper regression tests (R1)
    // =========================================================================

    #[test]
    fn test_notify_success_sets_notification() {
        let mut app = App::new_for_test();
        app.notify_success("Operation complete");
        let n = app.notification.unwrap();
        assert_eq!(n.message, "Operation complete");
        assert_eq!(n.kind, crate::model::NotificationKind::Success);
    }

    #[test]
    fn test_notify_info_sets_notification() {
        let mut app = App::new_for_test();
        app.notify_info("Some info");
        let n = app.notification.unwrap();
        assert_eq!(n.message, "Some info");
        assert_eq!(n.kind, crate::model::NotificationKind::Info);
    }

    #[test]
    fn test_set_error_sets_error_message() {
        let mut app = App::new_for_test();
        app.set_error("Something failed");
        assert_eq!(app.error_message.as_deref(), Some("Something failed"));
    }

    // =========================================================================
    // Command history recording tests
    // =========================================================================

    #[test]
    fn test_record_command_preserves_args_on_success() {
        use crate::jj::RunResult;

        let mut app = App::new_for_test();
        let start = Instant::now();
        let result: Result<RunResult, JjError> = Ok(RunResult {
            output: "done".to_string(),
            stderr: String::new(),
            args: vec!["describe".to_string(), "-m".to_string(), "test".to_string()],
        });
        app.record_command("Describe", &["describe", "-m", "test"], start, &result);

        assert_eq!(app.command_history.len(), 1);
        let record = &app.command_history.records()[0];
        assert_eq!(record.operation, "Describe");
        assert_eq!(record.args, vec!["describe", "-m", "test"]);
        assert_eq!(record.status, CommandStatus::Success);
        assert!(record.error.is_none());
    }

    #[test]
    fn test_record_command_preserves_args_on_failure() {
        let mut app = App::new_for_test();
        let start = Instant::now();
        let result: Result<RunResult, JjError> = Err(JjError::CommandFailed {
            stderr: "Immutable commit".to_string(),
            exit_code: 1,
        });
        app.record_command("Edit", &["edit", "-r", "abc123"], start, &result);

        assert_eq!(app.command_history.len(), 1);
        let record = &app.command_history.records()[0];
        assert_eq!(record.operation, "Edit");
        // Bug #1 fix: args must be preserved even on failure
        assert_eq!(record.args, vec!["edit", "-r", "abc123"]);
        assert_eq!(record.status, CommandStatus::Failed);
        assert!(
            record
                .error
                .as_deref()
                .unwrap()
                .contains("Immutable commit")
        );
    }

    #[test]
    fn test_record_str_command_preserves_args_on_failure() {
        let mut app = App::new_for_test();
        let start = Instant::now();
        let result: Result<String, JjError> = Err(JjError::CommandFailed {
            stderr: "push failed".to_string(),
            exit_code: 1,
        });
        app.record_str_command(
            "Push",
            &["git", "push", "--bookmark", "main"],
            start,
            &result,
        );

        assert_eq!(app.command_history.len(), 1);
        let record = &app.command_history.records()[0];
        assert_eq!(record.args, vec!["git", "push", "--bookmark", "main"]);
        assert_eq!(record.status, CommandStatus::Failed);
        assert!(record.error.is_some());
    }

    #[test]
    fn test_record_interactive_command_preserves_args_on_failure() {
        let mut app = App::new_for_test();
        let start = Instant::now();
        let result: io::Result<ExitStatus> =
            Err(io::Error::new(io::ErrorKind::NotFound, "editor not found"));
        app.record_interactive_command("Split", &["split", "-r", "abc"], start, &result);

        assert_eq!(app.command_history.len(), 1);
        let record = &app.command_history.records()[0];
        assert_eq!(record.args, vec!["split", "-r", "abc"]);
        assert_eq!(record.status, CommandStatus::Failed);
        assert!(
            record
                .error
                .as_deref()
                .unwrap()
                .contains("editor not found")
        );
    }
}