baraddur 0.1.6

Project-agnostic file watcher that surfaces issues before CI
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
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};

use crossterm::event::{KeyCode, KeyEvent};
use crossterm::{
    cursor, execute,
    terminal::{self, ClearType},
};

use super::style::{Theme, visible_len};
use super::{BrowseAction, Display, Verbosity};
use crate::pipeline::StepResult;

#[cfg(unix)]
mod terminal_io {
    //! Safe wrappers around the termios syscalls we need.
    //!
    //! Factored out of `TtyDisplay` so tests can target these helpers directly
    //! against a pty slave fd, without redirecting the process-wide stdin.
    use rustix::termios::{
        LocalModes, OptionalActions, OutputModes, Termios, tcgetattr, tcsetattr,
    };
    use std::os::fd::AsFd;

    /// Reads termios from `fd`, clears `ECHO`/`ECHOE`, writes back. Returns
    /// the pre-modification termios so the caller can restore later. Returns
    /// `None` if `fd` isn't a tty (tcgetattr/tcsetattr failed).
    pub fn suppress_echo<F: AsFd>(fd: F) -> Option<Termios> {
        let fd = fd.as_fd();
        let mut t = tcgetattr(fd).ok()?;
        let backup = t.clone();
        t.local_modes.remove(LocalModes::ECHO | LocalModes::ECHOE);
        tcsetattr(fd, OptionalActions::Now, &t).ok()?;
        Some(backup)
    }

    /// Re-enables `OPOST` and `ISIG` on `fd`. Called after crossterm's
    /// `enable_raw_mode` so that `println!` still emits `\r` and Ctrl+C
    /// still raises `SIGINT`. Silent on error.
    pub fn restore_signals_and_output<F: AsFd>(fd: F) {
        let fd = fd.as_fd();
        if let Ok(mut t) = tcgetattr(fd) {
            t.output_modes.insert(OutputModes::OPOST);
            t.local_modes.insert(LocalModes::ISIG);
            let _ = tcsetattr(fd, OptionalActions::Now, &t);
        }
    }

    /// Restores `fd`'s termios to a previously saved snapshot. Silent on error.
    pub fn restore<F: AsFd>(fd: F, t: &Termios) {
        let _ = tcsetattr(fd, OptionalActions::Now, t);
    }
}

// ── Shared helpers ───────────────────────────────────────────────────────────

fn timestamp() -> String {
    chrono::Local::now().format("%H:%M:%S").to_string()
}

/// Formats stdout+stderr with head+tail truncation if the output is long.
/// Returns a string with `  ` prefix on each line, ready to print.
fn format_truncated_output(stdout: &str, stderr: &str) -> String {
    let combined = if stderr.is_empty() {
        stdout.to_string()
    } else if stdout.is_empty() {
        stderr.to_string()
    } else if stdout.ends_with('\n') {
        format!("{stdout}{stderr}")
    } else {
        format!("{stdout}\n{stderr}")
    };

    let lines: Vec<&str> = combined.lines().collect();
    const MAX_DISPLAY_LINES: usize = 50;
    const CONTEXT_LINES: usize = 25;

    let mut out = String::new();
    if lines.len() <= MAX_DISPLAY_LINES {
        for line in &lines {
            out.push_str(&format!("  {line}\n"));
        }
    } else {
        for line in &lines[..CONTEXT_LINES] {
            out.push_str(&format!("  {line}\n"));
        }
        let elided = lines.len() - (CONTEXT_LINES * 2);
        out.push_str(&format!(
            "  ... [{elided} lines elided — see .baraddur/last-run.log] ...\n"
        ));
        for line in &lines[lines.len() - CONTEXT_LINES..] {
            out.push_str(&format!("  {line}\n"));
        }
    }
    out
}

/// Builds a short inline diagnostic from a failing step's output.
fn short_diagnostic(result: &StepResult) -> String {
    if result.success {
        return String::new();
    }
    match result.exit_code {
        None => "command not found".into(),
        Some(_) => {
            let combined = format!("{}{}", result.stdout, result.stderr);
            let non_empty: Vec<&str> = combined.lines().filter(|l| !l.trim().is_empty()).collect();
            match non_empty.len() {
                0 => String::new(),
                1 => {
                    let line = non_empty[0];
                    let truncated: String = line.chars().take(40).collect();
                    if line.chars().count() > 40 {
                        format!("{truncated}")
                    } else {
                        truncated
                    }
                }
                n => format!("{n} lines"),
            }
        }
    }
}

/// Default `EditorSpawn` implementation. Resolves the editor via
/// `$VISUAL` → `$EDITOR` → `vi`, parses it through `shell_words` so users
/// can set things like `EDITOR="code --wait"`, and passes `+LINE FILE`.
/// `col` is ignored — most editors only accept the line number with the `+`
/// flag.
fn default_editor_spawn(path: &Path, line: u32, _col: Option<u32>) -> std::io::Result<()> {
    let editor = std::env::var("VISUAL")
        .or_else(|_| std::env::var("EDITOR"))
        .unwrap_or_else(|_| "vi".into());

    let parts = shell_words::split(&editor).unwrap_or_else(|_| vec![editor.clone()]);
    let (program, args) = parts.split_first().ok_or_else(|| {
        std::io::Error::new(std::io::ErrorKind::InvalidInput, "empty $EDITOR / $VISUAL")
    })?;

    // Non-zero exit (user quit with :cq, etc.) isn't an error from baraddur's
    // perspective; only failure to launch is.
    let _ = std::process::Command::new(program)
        .args(args)
        .arg(format!("+{line}"))
        .arg(path)
        .status()?;
    Ok(())
}

/// Formats the trigger suffix for a run divider/header.
/// Single file → `"  ·  lib/foo.ex"`, multiple → `"  ·  3 files"`, none → `""`.
fn format_trigger_suffix(paths: Option<&[PathBuf]>) -> String {
    match paths {
        Some([p]) => format!("  ·  {}", p.display()),
        Some(ps) => format!("  ·  {} files", ps.len()),
        None => String::new(),
    }
}

/// Outcome of `redraw_strategy`: tells the caller how to erase the previous
/// render before painting fresh content.
#[derive(Debug, PartialEq, Eq)]
enum RedrawStrategy {
    /// Nothing on screen to erase — first paint of a run. The caller leaves
    /// any pre-existing content (banner, log history) alone and appends.
    Skip,
    /// Resize-since-last-paint or rendered region exceeds the viewport. The
    /// caller wipes the whole screen and repaints from `(0, 0)`.
    FullClear,
    /// Steady-state incremental clear: move the cursor up `n` rows and clear
    /// from there to the bottom of the screen.
    MoveUp(u16),
}

/// Picks the safe clear strategy for the next paint given the previous
/// render's row count, the terminal size when that render happened, and the
/// current terminal size.
///
/// Falls back to `FullClear` whenever the incremental `MoveUp` would land in
/// the wrong row — i.e., the terminal was resized between paints (tmux pane
/// drag, window resize) or the previous render no longer fits in the visible
/// viewport (content has scrolled into scrollback). Both cases would leave
/// stale content behind (duplicate dividers) or crop the top of the new
/// render without this guard.
fn redraw_strategy(
    rendered_lines: u16,
    last_size: (u16, u16),
    current_size: (u16, u16),
) -> RedrawStrategy {
    if rendered_lines == 0 {
        return RedrawStrategy::Skip;
    }
    let (_, h) = current_size;
    if last_size != current_size || rendered_lines + 1 > h {
        return RedrawStrategy::FullClear;
    }
    RedrawStrategy::MoveUp(rendered_lines)
}

// ── Non-TTY display (append-only) ───────────────────────────────────────────

/// Append-only line output for non-TTY contexts (piped, CI, `--no-tty`).
/// No cursor movement, no screen clearing.
pub struct PlainDisplay {
    theme: Theme,
    verbosity: Verbosity,
    trigger_paths: Option<Vec<PathBuf>>,
    run_start: Option<Instant>,
    run_count: usize,
    /// True if the run that just started was triggered by file changes;
    /// used by `run_finished` to emit "no steps match changed paths" when
    /// the trigger left zero applicable steps.
    last_run_triggered: bool,
}

impl PlainDisplay {
    pub fn new(theme: Theme, verbosity: Verbosity) -> Self {
        Self {
            theme,
            verbosity,
            trigger_paths: None,
            run_start: None,
            run_count: 0,
            last_run_triggered: false,
        }
    }
}

impl Display for PlainDisplay {
    fn set_trigger(&mut self, paths: &[PathBuf]) {
        self.trigger_paths = Some(paths.to_vec());
    }

    fn banner(
        &mut self,
        root: &Path,
        config_path: &Path,
        _step_count: usize,
        profile: Option<&str>,
    ) {
        let profile_suffix = profile
            .map(|p| format!("\n          (profile: {p})"))
            .unwrap_or_default();
        eprintln!(
            "baraddur: watching {}\n          (config: {}){profile_suffix}",
            root.display(),
            config_path.display(),
        );
    }

    fn run_started(&mut self, _step_names: &[String]) {
        self.run_start = Some(Instant::now());
        self.run_count += 1;
        let trigger = self.trigger_paths.take();
        self.last_run_triggered = trigger.is_some();
        if self.verbosity != Verbosity::Quiet {
            let suffix = format_trigger_suffix(trigger.as_deref());
            println!("[{}] run #{} started{suffix}", timestamp(), self.run_count);
        }
    }

    fn step_running(&mut self, name: &str) {
        if self.verbosity != Verbosity::Quiet {
            println!("[{}] ▸ {} running", timestamp(), name);
        }
    }

    fn step_finished(&mut self, result: &StepResult) {
        if self.verbosity == Verbosity::Quiet && result.success {
            return;
        }
        let status = if result.success {
            format!("{}", self.theme.pass_glyph())
        } else {
            format!("{}", self.theme.fail_glyph())
        };
        println!(
            "[{}] ▸ {}  {}  ({:.1}s)",
            timestamp(),
            result.name,
            status,
            result.duration.as_secs_f64()
        );
    }

    fn steps_skipped(&mut self, names: &[String]) {
        if self.verbosity != Verbosity::Quiet {
            let ts = timestamp();
            for name in names {
                println!("[{ts}] ▸ {name}  {}  skipped", self.theme.skip_glyph());
            }
        }
    }

    fn run_cancelled(&mut self) {
        if self.verbosity != Verbosity::Quiet {
            println!("[{}] run cancelled", timestamp());
        }
    }

    fn run_finished(&mut self, results: &[StepResult]) {
        let ts = timestamp();

        // Print failure output blocks.
        for r in results.iter().filter(|r| !r.success) {
            println!("[{ts}] --- {} output ---", r.name);
            print!("{}", format_truncated_output(&r.stdout, &r.stderr));
        }

        // In verbose mode, also show passing step output.
        if self.verbosity >= Verbosity::Verbose {
            for r in results.iter().filter(|r| r.success) {
                if !r.stdout.is_empty() {
                    println!("[{ts}] --- {} output ---", r.name);
                    for line in r.stdout.lines() {
                        println!("  {line}");
                    }
                }
            }
        }

        let failed = results.iter().filter(|r| !r.success).count();
        let passed = results.iter().filter(|r| r.success).count();
        let elapsed = self
            .run_start
            .take()
            .map(|t| t.elapsed().as_secs_f64())
            .unwrap_or_else(|| results.iter().map(|r| r.duration.as_secs_f64()).sum());

        if self.verbosity != Verbosity::Quiet || failed > 0 {
            println!("[{ts}] run complete: {failed} failed, {passed} passed, {elapsed:.1}s");
        }

        // File-change run produced zero applicable steps — surface this so
        // the user knows their save didn't trigger any work.
        if results.is_empty() && self.last_run_triggered && self.verbosity != Verbosity::Quiet {
            println!("[{ts}] no steps match changed paths");
        }

        let _ = std::io::stdout().flush();
    }

    fn hook_output(&mut self, text: &str) {
        if self.verbosity == Verbosity::Quiet {
            return;
        }
        let ts = timestamp();
        println!("[{ts}] --- on_failure ---");
        for line in text.lines() {
            println!("  {line}");
        }
        let _ = std::io::stdout().flush();
    }

    fn hook_started(&mut self) {
        if self.verbosity != Verbosity::Quiet {
            println!("[{}] on_failure hook running…", timestamp());
            let _ = std::io::stdout().flush();
        }
    }
}

// ── TTY display (full-block redraw) ─────────────────────────────────────────

const SPINNER_FRAMES: &[&str] = &["", "", "", "", "", "", "", "", "", ""];

/// Status of a single step, tracked by the display for redraw.
#[derive(Debug, Clone)]
enum StepStatus {
    Queued,
    Running,
    Passed(Duration),
    Failed(Duration, String), // (duration, short diagnostic)
    Skipped,
}

/// Interactive terminal display. On each state change, erases the previous
/// step-status block and reprints it.
pub struct TtyDisplay {
    theme: Theme,
    verbosity: Verbosity,
    no_clear: bool,
    step_names: Vec<String>,
    statuses: Vec<StepStatus>,
    name_width: usize,
    /// How many lines the last `redraw()` or `browse_redraw()` printed.
    rendered_lines: u16,
    /// Terminal `(width, height)` at the last successful paint. Used to
    /// detect resizes (e.g., tmux pane drag) between renders so the next
    /// redraw can fall back to a full clear instead of a stale `MoveUp`.
    last_term_size: (u16, u16),
    spinner_frame: usize,
    has_running: bool,
    /// Original termios saved on construction so we can restore on drop.
    /// Suppressing echo prevents typed characters from corrupting the redrawn
    /// step-status block while a pipeline is running.
    #[cfg(unix)]
    original_termios: Option<rustix::termios::Termios>,
    // ── Browse mode state ────────────────────────────────────────────────────
    /// Pre-formatted output per step, captured in `run_finished`.
    step_outputs: Vec<String>,
    /// Whether each step's output is shown inline in browse mode.
    expanded: Vec<bool>,
    /// Tracks the `O` toggle: true when all steps are expanded.
    all_expanded: bool,
    /// Index of the currently highlighted row.
    cursor: usize,
    /// True while in the post-run interactive navigation state.
    browse_active: bool,
    /// Last key code pressed — used for `gg` double-tap detection.
    last_key: Option<KeyCode>,
    /// Whether raw mode is currently enabled (used by Drop for cleanup).
    raw_mode_active: bool,
    /// File(s) that triggered this run. Set by `set_trigger`, consumed by `run_started`.
    trigger_paths: Option<Vec<PathBuf>>,
    /// Monotonically increasing counter incremented on each `run_started`.
    run_count: usize,
    /// Plain (unstyled) divider text from `run_started`. Printed as the first line
    /// of every `redraw()` and `browse_redraw()`, colored live from `statuses`.
    run_divider: String,
    /// Wall-clock start time of the current run, for accurate elapsed time in the footer.
    run_start: Option<Instant>,
    /// Pre-formatted summary line from `run_finished`, shown persistently in browse mode.
    run_summary: String,
    /// Terminal row offset for browse-mode viewport scrolling.
    /// Ensures the cursor step is always visible even when output overflows the screen.
    browse_scroll: usize,
    /// Captured output from the `[on_failure]` hook for the current run, if any.
    /// Rendered as a dim block between the run summary and the help bar.
    hook_output_text: String,
    /// One-shot status message shown below the help bar (e.g., "no failures
    /// to rerun" when the user presses `f` with no failed steps). Cleared at
    /// the start of any recognized recognized key press and on `run_started`.
    transient_message: Option<String>,
    /// Snapshot of `trigger_paths` consumed by `run_started`, preserved so
    /// `run_finished` can detect "file change → 0 steps matched" and surface
    /// a `no steps match changed paths` message.
    last_trigger_paths: Option<Vec<PathBuf>>,
    /// True while an `[on_failure]` hook task is in flight. Renders a dim
    /// "running on_failure hook…" line between the summary and help bar.
    hook_running: bool,
    /// Root directory of the pipeline (captured from `banner`). Used to
    /// resolve diagnostic paths emitted relative to the runner cwd.
    root: PathBuf,
    /// Diagnostics parsed from each step's output (`run_finished`). Empty
    /// when a step had no parseable diagnostics or hasn't completed yet.
    parsed_diagnostics: Vec<Vec<crate::output::diagnostic::Diagnostic>>,
    /// Index of the "current" diagnostic *within the cursor step's list*.
    /// Per-step so that moving the cursor away and back preserves the spot.
    current_diagnostic: Vec<usize>,
    /// Editor spawn closure — injectable for tests so we can assert the
    /// command without actually exec'ing a subprocess. Default uses
    /// `$VISUAL` → `$EDITOR` → `vi` with `+LINE FILE`.
    editor_spawn: EditorSpawn,
    /// True while the `?` help modal is showing. The modal is rendered as
    /// a centered bordered overlay on top of the normal browse view. Any
    /// key dismisses.
    help_modal_active: bool,
    /// Whether the modal overlay was painted during the previous redraw.
    /// Used to force a `FullClear` on the next paint so overlay rows above
    /// the main content's tracked `rendered_lines` are erased properly.
    help_painted_last: bool,
}

/// `(file, line, col?)` → spawn-and-wait outcome. Returns `Ok(())` when the
/// editor was launched (even if the user quit it non-zero); `Err` only when
/// we couldn't start it at all.
type EditorSpawn = Box<dyn Fn(&Path, u32, Option<u32>) -> std::io::Result<()> + Send + Sync>;

impl Drop for TtyDisplay {
    fn drop(&mut self) {
        if self.raw_mode_active {
            let _ = terminal::disable_raw_mode();
            let _ = execute!(std::io::stdout(), cursor::Show);
        }
        #[cfg(unix)]
        if let Some(t) = &self.original_termios {
            terminal_io::restore(std::io::stdin(), t);
        }
        // Non-unix: crossterm disable_raw_mode above is sufficient.
    }
}

impl TtyDisplay {
    pub fn new(theme: Theme, verbosity: Verbosity, no_clear: bool) -> Self {
        // Disable terminal echo so that keystrokes typed while the pipeline is
        // running do not appear in the output and corrupt the step-status block.
        // We clear only ECHO/ECHOE and leave everything else (ISIG, OPOST, …)
        // untouched so that Ctrl+C still generates SIGINT and println! still
        // works normally.
        #[cfg(unix)]
        let original_termios = terminal_io::suppress_echo(std::io::stdin());

        Self {
            theme,
            verbosity,
            no_clear,
            step_names: Vec::new(),
            statuses: Vec::new(),
            name_width: 0,
            rendered_lines: 0,
            last_term_size: (0, 0),
            spinner_frame: 0,
            has_running: false,
            #[cfg(unix)]
            original_termios,
            step_outputs: Vec::new(),
            expanded: Vec::new(),
            all_expanded: false,
            cursor: 0,
            browse_active: false,
            last_key: None,
            raw_mode_active: false,
            trigger_paths: None,
            run_count: 0,
            run_divider: String::new(),
            run_start: None,
            run_summary: String::new(),
            browse_scroll: 0,
            hook_output_text: String::new(),
            transient_message: None,
            last_trigger_paths: None,
            hook_running: false,
            root: PathBuf::new(),
            parsed_diagnostics: Vec::new(),
            current_diagnostic: Vec::new(),
            editor_spawn: Box::new(default_editor_spawn),
            help_modal_active: false,
            help_painted_last: false,
        }
    }

    /// Replaces the default editor spawner. Tests use this to record the
    /// `(path, line, col)` triple without actually launching an editor.
    pub fn set_editor_spawn(&mut self, f: EditorSpawn) {
        self.editor_spawn = f;
    }

    fn term_width() -> usize {
        crossterm::terminal::size()
            .map(|(c, _)| c as usize)
            .unwrap_or(80)
    }

    /// Returns the number of terminal rows a single printed line will occupy,
    /// accounting for line wrapping at `width` columns.
    fn visual_rows_for(text: &str, width: usize) -> u16 {
        let vlen = visible_len(text);
        if width == 0 || vlen == 0 {
            1
        } else {
            vlen.div_ceil(width) as u16
        }
    }

    fn term_height() -> u16 {
        crossterm::terminal::size().map(|(_, r)| r).unwrap_or(24)
    }

    /// Erases the previous render in preparation for a fresh paint.
    ///
    /// Delegates the choice between fast incremental clear and full-screen
    /// clear to `redraw_strategy` (which is pure and unit-tested), then
    /// applies the chosen strategy via crossterm and updates the tracked
    /// terminal size.
    fn prepare_redraw_region(&mut self) {
        let mut stdout = std::io::stdout();
        let current = (Self::term_width() as u16, Self::term_height());

        match redraw_strategy(self.rendered_lines, self.last_term_size, current) {
            RedrawStrategy::Skip => {}
            RedrawStrategy::FullClear => {
                execute!(
                    stdout,
                    terminal::Clear(ClearType::All),
                    cursor::MoveTo(0, 0)
                )
                .ok();
                self.rendered_lines = 0;
            }
            RedrawStrategy::MoveUp(n) => {
                execute!(
                    stdout,
                    cursor::MoveUp(n),
                    terminal::Clear(ClearType::FromCursorDown)
                )
                .ok();
            }
        }

        self.last_term_size = current;
    }

    fn raw_mode_on(&mut self) {
        if terminal::enable_raw_mode().is_ok() {
            self.raw_mode_active = true;
            // cfmakeraw() clears two flags we need:
            // - OPOST: breaks println! because \n no longer implies \r
            // - ISIG:  breaks Ctrl+C because it no longer generates SIGINT
            // Re-enable both immediately after so the display and signal
            // handling continue to work correctly.
            #[cfg(unix)]
            terminal_io::restore_signals_and_output(std::io::stdin());
        }
    }

    fn raw_mode_off(&mut self) {
        if self.raw_mode_active {
            let _ = terminal::disable_raw_mode();
            self.raw_mode_active = false;
        }
    }

    /// Releases the terminal (raw mode off, cursor visible) for the duration
    /// of `f`, then restores browse-mode state and redraws. Used by `e` to
    /// hand the terminal off to `$EDITOR` cleanly.
    fn with_terminal_released<F, R>(&mut self, f: F) -> R
    where
        F: FnOnce(&mut Self) -> R,
    {
        let was_browse = self.browse_active;
        if was_browse {
            self.raw_mode_off();
            let _ = execute!(std::io::stdout(), cursor::Show);
        }
        let result = f(self);
        if was_browse {
            self.raw_mode_on();
            let _ = execute!(std::io::stdout(), cursor::Hide);
            self.browse_redraw();
        }
        result
    }

    /// Builds the rendered, styled lines of the `?` help modal. Two-column
    /// vertical key reference; section headers in cyan, body dim. Returned
    /// as `Vec<String>` so the caller can size each line individually.
    fn help_modal_lines(&self) -> Vec<String> {
        // Each row is `(left, right)`; either may be empty for spacers and
        // section headers that only occupy one column.
        let rows: &[(&str, &str)] = &[
            ("Navigation", "Diagnostics"),
            ("  j / ↓   down", "  n   next"),
            ("  k / ↑   up", "  p   prev"),
            ("  g g     top", "  e   open in editor"),
            ("  G       bottom", ""),
            ("", ""),
            ("Output", "Rerun"),
            ("  Enter / o  toggle", "  r   pipeline"),
            ("  O          expand", "  f   failed steps"),
            ("", "  c   step under cursor"),
        ];

        let col_width = 26usize;
        let mut out = Vec::with_capacity(rows.len() + 4);

        // Header.
        out.push(format!("  {}", self.theme.cyan("Help")));
        out.push(String::new());

        for (left, right) in rows {
            let is_header = !left.is_empty() && !left.starts_with(' ');
            let is_right_header = !right.is_empty() && !right.starts_with(' ');

            let left_styled = if left.is_empty() {
                String::new()
            } else if is_header {
                format!("{}", self.theme.cyan(left))
            } else {
                format!("{}", self.theme.dim(left))
            };
            let right_styled = if right.is_empty() {
                String::new()
            } else if is_right_header {
                format!("{}", self.theme.cyan(right))
            } else {
                format!("{}", self.theme.dim(right))
            };

            // Pad left to `col_width` visible columns so right column lines up.
            let left_pad = col_width.saturating_sub(visible_len(&left_styled));
            out.push(format!("  {left_styled}{:left_pad$}{right_styled}", ""));
        }

        out.push(String::new());
        out.push(format!("  {}", self.theme.dim("press any key to dismiss")));
        out
    }

    /// Moves the diagnostic cursor for the current step by `delta`, wrapping
    /// around the list. Returns `false` when the step has no diagnostics.
    fn advance_diagnostic(&mut self, delta: i32) -> bool {
        let len = match self.parsed_diagnostics.get(self.cursor) {
            Some(d) if !d.is_empty() => d.len() as i32,
            _ => return false,
        };
        let cur = self
            .current_diagnostic
            .get(self.cursor)
            .copied()
            .unwrap_or(0) as i32;
        let next = (cur + delta).rem_euclid(len) as usize;
        self.current_diagnostic[self.cursor] = next;
        true
    }

    /// Opens the current diagnostic's `(file, line, col)` in the configured
    /// editor. No-op when the step has no diagnostics; reports spawn errors
    /// via the transient-message slot.
    fn open_current_diagnostic(&mut self) {
        let Some(diags) = self.parsed_diagnostics.get(self.cursor) else {
            return;
        };
        if diags.is_empty() {
            self.transient_message = Some("no diagnostics on this step".into());
            return;
        }
        let idx = self
            .current_diagnostic
            .get(self.cursor)
            .copied()
            .unwrap_or(0);
        let diag = diags[idx].clone();
        let abs = if diag.path.is_absolute() {
            diag.path.clone()
        } else {
            self.root.join(&diag.path)
        };
        let result = self.with_terminal_released(|s| (s.editor_spawn)(&abs, diag.line, diag.col));
        if let Err(e) = result {
            self.transient_message = Some(format!("editor: {e}"));
        }
    }

    /// Redraws the step block in place during a pipeline run (no highlight, no
    /// expanded output). Uses `rendered_lines` to erase the previous render.
    fn redraw(&mut self) {
        if self.verbosity == Verbosity::Quiet {
            return;
        }

        let mut stdout = std::io::stdout();
        let width = Self::term_width();

        self.prepare_redraw_region();

        let mut lines = 0u16;

        if !self.run_divider.is_empty() {
            let divider = self.divider_styled();
            println!("{divider}");
            lines += Self::visual_rows_for(&divider, width);
        }

        for (i, name) in self.step_names.iter().enumerate() {
            let (glyph, diagnostic, duration_str) = match &self.statuses[i] {
                StepStatus::Queued => (
                    format!("{}", self.theme.queued_glyph()),
                    String::new(),
                    String::new(),
                ),
                StepStatus::Running => {
                    let frame = SPINNER_FRAMES[self.spinner_frame];
                    let g = format!("{}", self.theme.yellow(frame));
                    (g, String::new(), String::new())
                }
                StepStatus::Passed(d) => (
                    format!("{}", self.theme.pass_glyph()),
                    String::new(),
                    format!("{:.1}s", d.as_secs_f64()),
                ),
                StepStatus::Failed(d, diag) => {
                    let d_str = format!("{:.1}s", d.as_secs_f64());
                    let diag_str = if diag.is_empty() {
                        String::new()
                    } else {
                        format!("{}", self.theme.dim(diag))
                    };
                    (format!("{}", self.theme.fail_glyph()), diag_str, d_str)
                }
                StepStatus::Skipped => (
                    format!("{}", self.theme.skip_glyph()),
                    format!("{}", self.theme.dim("skipped")),
                    String::new(),
                ),
            };

            // Build left portion: "▸ name    glyph   diagnostic"
            let left = if diagnostic.is_empty() {
                format!("▸ {:nw$}  {glyph}", name, nw = self.name_width)
            } else {
                format!(
                    "▸ {:nw$}  {glyph}   {diagnostic}",
                    name,
                    nw = self.name_width
                )
            };

            let line = if duration_str.is_empty() {
                left
            } else {
                let right = format!("{}", self.theme.dim(&duration_str));
                let left_vis = visible_len(&left);
                let right_vis = visible_len(&right);
                let pad = width.saturating_sub(left_vis + right_vis);
                format!("{left}{:pad$}{right}", "")
            };

            println!("{line}");
            lines += Self::visual_rows_for(&line, width);
        }

        self.rendered_lines = lines;
        let _ = stdout.flush();
    }

    /// Builds the single status row for step index `i`: glyph + name + optional
    /// inline diagnostic + optional right-justified duration, with cursor
    /// highlight when in browse mode. Returns `(rendered_line, terminal_rows)`.
    fn step_row(&self, i: usize, width: usize) -> (String, usize) {
        let (glyph, diagnostic, duration_str) = match &self.statuses[i] {
            StepStatus::Queued => (
                format!("{}", self.theme.queued_glyph()),
                String::new(),
                String::new(),
            ),
            StepStatus::Running => {
                let frame = SPINNER_FRAMES[self.spinner_frame];
                (
                    format!("{}", self.theme.yellow(frame)),
                    String::new(),
                    String::new(),
                )
            }
            StepStatus::Passed(d) => (
                format!("{}", self.theme.pass_glyph()),
                String::new(),
                format!("{:.1}s", d.as_secs_f64()),
            ),
            StepStatus::Failed(d, diag) => {
                let d_str = format!("{:.1}s", d.as_secs_f64());
                let diag_str = if diag.is_empty() {
                    String::new()
                } else {
                    format!("{}", self.theme.dim(diag))
                };
                (format!("{}", self.theme.fail_glyph()), diag_str, d_str)
            }
            StepStatus::Skipped => (
                format!("{}", self.theme.skip_glyph()),
                format!("{}", self.theme.dim("skipped")),
                String::new(),
            ),
        };

        let arrow = if i == self.cursor && !self.theme.color_enabled() {
            ""
        } else {
            ""
        };
        let raw_prefix = format!("{arrow} {:nw$}", self.step_names[i], nw = self.name_width);
        let styled_prefix = if i == self.cursor && self.browse_active {
            format!("{}", self.theme.selected(&raw_prefix))
        } else {
            raw_prefix
        };

        let left = if diagnostic.is_empty() {
            format!("{styled_prefix}  {glyph}")
        } else {
            format!("{styled_prefix}  {glyph}   {diagnostic}")
        };

        if duration_str.is_empty() {
            let r = Self::visual_rows_for(&left, width) as usize;
            (left, r)
        } else {
            let right = format!("{}", self.theme.dim(&duration_str));
            let left_vis = visible_len(&left);
            let right_vis = visible_len(&right);
            let pad = width.saturating_sub(left_vis + right_vis);
            let line = format!("{left}{:pad$}{right}", "");
            let r = Self::visual_rows_for(&line, width) as usize;
            (line, r)
        }
    }

    /// Builds the expanded inline-output lines for step `i`. Lines that parse
    /// as a diagnostic are highlighted; the "current" diagnostic on the cursor
    /// step gets the strongest highlight (cyan underline, or `▶` in NO_COLOR).
    /// Returns an empty Vec when the step is not expanded or has no captured
    /// output.
    fn expanded_output_lines(&self, i: usize, width: usize) -> Vec<(String, usize)> {
        if !self.expanded.get(i).copied().unwrap_or(false) {
            return Vec::new();
        }
        let Some(output) = self.step_outputs.get(i).filter(|o| !o.is_empty()) else {
            return Vec::new();
        };

        let diags: &[crate::output::diagnostic::Diagnostic] = self
            .parsed_diagnostics
            .get(i)
            .map(Vec::as_slice)
            .unwrap_or(&[]);
        let current = self.current_diagnostic.get(i).copied().unwrap_or(0);
        let is_cursor_step = i == self.cursor;

        let mut out = Vec::new();
        for line in output.lines() {
            // Output lines have a two-space prefix from
            // `format_truncated_output`. Strip before pattern matching.
            let raw = line.strip_prefix("  ").unwrap_or(line);
            let diag_idx = crate::output::diagnostic::extract_line(raw)
                .and_then(|d| diags.iter().position(|x| x == &d));
            let (display_line, r) = if let Some(idx) = diag_idx {
                let is_current = is_cursor_step && idx == current;
                let styled = if is_current {
                    // Color: cyan marker + cyan underlined body.
                    // NO_COLOR: distinct `▶` glyph stands in for the
                    // underline, matching the cursor-row fallback at
                    // the step-list level.
                    if self.theme.color_enabled() {
                        format!(
                            "{} {}",
                            self.theme.cyan(""),
                            self.theme.cyan_underline(raw)
                        )
                    } else {
                        format!("{raw}")
                    }
                } else {
                    format!("{} {raw}", self.theme.dim(""))
                };
                let r = Self::visual_rows_for(&styled, width) as usize;
                (styled, r)
            } else {
                let r = Self::visual_rows_for(line, width) as usize;
                (line.to_string(), r)
            };
            out.push((display_line, r));
        }
        out
    }

    /// Builds the persistent browse-mode footer: post-run summary, optional
    /// `[on_failure]` hook block, help bar (or help modal when active), and
    /// the transient one-shot status message. Returns an empty Vec when
    /// browse mode is not active so the caller can append unconditionally.
    fn footer_lines(&self, width: usize) -> Vec<(String, usize)> {
        if !self.browse_active {
            return Vec::new();
        }

        let mut out: Vec<(String, usize)> = Vec::new();
        out.push((String::new(), 1)); // spacer before the footer

        if !self.run_summary.is_empty() {
            let r = Self::visual_rows_for(&self.run_summary, width) as usize;
            out.push((self.run_summary.clone(), r));
            out.push((String::new(), 1));
        }

        // Hook slot: "running…" while in flight; output once settled. Only
        // one of the two is shown at a time.
        if self.hook_running {
            let line = format!("  {}", self.theme.dim("running on_failure hook…"));
            let r = Self::visual_rows_for(&line, width) as usize;
            out.push((line, r));
            out.push((String::new(), 1));
        } else if !self.hook_output_text.is_empty() {
            for line in self.hook_output_text.lines() {
                let styled = format!("  {}", self.theme.dim(line));
                let r = Self::visual_rows_for(&styled, width) as usize;
                out.push((styled, r));
            }
            out.push((String::new(), 1));
        }

        // Grouped, symbol-led, fits ~80 cols. Stays visible even when the
        // `?` modal is open — the modal floats on top as an overlay.
        let help = "  ↕ j/k   ⏎ toggle   ▸ n/p/e   ↺ r/f/c   ? help · q quit";
        let help_styled = format!("{}", self.theme.dim(help));
        let r = Self::visual_rows_for(&help_styled, width) as usize;
        out.push((help_styled, r));

        if let Some(msg) = &self.transient_message {
            let line = format!("  {}", self.theme.yellow(msg));
            let r = Self::visual_rows_for(&line, width) as usize;
            out.push((line, r));
        }

        out
    }

    /// Assembles the full content of the browse-mode view as `(text, rows)`
    /// pairs, alongside the cursor step's vertical anchor (top row and row
    /// height in the buffer). Pure over `&self` so scroll math and paint
    /// can be tested or invoked independently.
    fn compute_lines(&self, width: usize) -> (Vec<(String, usize)>, usize, usize) {
        let mut all_lines: Vec<(String, usize)> = Vec::new();
        let mut cursor_top_row = 0usize;
        let mut cursor_row_height = 1usize;
        let mut cumulative = 0usize;

        if !self.run_divider.is_empty() {
            all_lines.push((self.divider_styled(), 1));
            cumulative += 1;
        }

        for i in 0..self.step_names.len() {
            let (step_text, step_rows) = self.step_row(i, width);

            if i == self.cursor {
                cursor_top_row = cumulative;
                cursor_row_height = step_rows;
            }
            cumulative += step_rows;
            all_lines.push((step_text, step_rows));

            for (line, r) in self.expanded_output_lines(i, width) {
                cumulative += r;
                all_lines.push((line, r));
            }
        }

        // Footer rows aren't tracked here — `cumulative` was only needed to
        // anchor the cursor, which is always above the footer.
        for (line, r) in self.footer_lines(width) {
            all_lines.push((line, r));
        }
        let _ = cumulative;

        (all_lines, cursor_top_row, cursor_row_height)
    }

    /// Clamps the scroll offset so the cursor step stays inside the viewport.
    /// Scrolls up when the cursor is above the window, down when its bottom
    /// falls below the window, then caps so the last row never scrolls past
    /// the end of the content. Pure — all of browse_redraw's scroll math.
    fn clamp_scroll(
        scroll: usize,
        cursor_top: usize,
        cursor_h: usize,
        viewport: usize,
        total_rows: usize,
    ) -> usize {
        let mut scroll = scroll;
        if cursor_top < scroll {
            scroll = cursor_top;
        } else if cursor_top + cursor_h > scroll + viewport {
            scroll = cursor_top + cursor_h - viewport;
        }
        scroll.min(total_rows.saturating_sub(viewport))
    }

    /// Selects the contiguous slice of laid-out lines to paint for a given
    /// `scroll` (in rows) and `viewport` (in rows). Returns the index range
    /// into `lines` plus the total rendered row count. A line that the scroll
    /// offset would only partially skip is dropped whole — we never paint the
    /// truncated middle of a wrapped line — and selection stops once the
    /// viewport fills. Pure; the subtle partial-skip rule is unit-tested.
    fn viewport_slice(
        lines: &[(String, usize)],
        scroll: usize,
        viewport: usize,
    ) -> (std::ops::Range<usize>, usize) {
        let mut skip = scroll;
        let mut rendered = 0usize;
        let mut start: Option<usize> = None;
        let mut end = lines.len();

        for (i, (_, rows)) in lines.iter().enumerate() {
            if skip > 0 {
                if skip >= *rows {
                    skip -= rows;
                    continue;
                }
                // Partial skip: drop this whole line rather than printing a
                // truncated middle of a wrapped line.
                skip = 0;
                continue;
            }
            if rendered >= viewport {
                end = i;
                break;
            }
            if start.is_none() {
                start = Some(i);
            }
            rendered += rows;
        }

        let start = start.unwrap_or(end);
        (start..end.max(start), rendered)
    }

    /// Redraws the step list for browse mode: includes cursor highlight and
    /// inline expanded output for toggled steps. Clipped to terminal height
    /// via a scroll viewport that always keeps the cursor step visible.
    /// Layout is built by `compute_lines`; this function owns scroll math
    /// and the terminal paint.
    fn browse_redraw(&mut self) {
        let mut stdout = std::io::stdout();
        let width = Self::term_width();
        let term_height = Self::term_height() as usize;

        let (all_lines, cursor_top_row, cursor_row_height) = self.compute_lines(width);
        let total_rows: usize = all_lines.iter().map(|(_, r)| r).sum();

        // Adjust scroll so the cursor step stays in viewport. Reserve 1 row
        // so the last line never hugs the very bottom.
        let viewport = term_height.saturating_sub(1);

        self.browse_scroll = Self::clamp_scroll(
            self.browse_scroll,
            cursor_top_row,
            cursor_row_height,
            viewport,
            total_rows,
        );

        // Force a full clear when the modal is involved (entering, leaving,
        // or while visible). The overlay paints absolute-positioned rows that
        // may sit above the tracked `rendered_lines`, so an incremental
        // `MoveUp` would leave ghost rows behind.
        if self.help_modal_active || self.help_painted_last {
            self.last_term_size = (0, 0);
        }

        // ── Erase previous render, then print the viewport ───────────────
        self.prepare_redraw_region();

        let (range, rendered) = Self::viewport_slice(&all_lines, self.browse_scroll, viewport);
        for (text, _) in &all_lines[range] {
            println!("{text}");
        }

        self.rendered_lines = rendered as u16;

        if self.help_modal_active {
            self.draw_help_modal_overlay();
        }
        self.help_painted_last = self.help_modal_active;

        let _ = stdout.flush();
    }

    /// Paints the `?` help as a centered bordered box on top of the current
    /// view. Uses absolute cursor positioning so the overlay floats over
    /// existing content instead of being clipped at the bottom of the
    /// scroll viewport. The caller is responsible for forcing a `FullClear`
    /// on the next paint so the overlay rows are wiped on dismiss.
    fn draw_help_modal_overlay(&self) {
        let mut stdout = std::io::stdout();
        let term_w = Self::term_width();
        let term_h = Self::term_height() as usize;
        let lines = self.help_modal_lines();

        // Modal width fits the widest content line plus a 1-col border on
        // each side; cap to the terminal so we never spill off-screen.
        let content_w = lines.iter().map(|l| visible_len(l)).max().unwrap_or(0);
        let modal_w = (content_w + 2).min(term_w.saturating_sub(2)).max(8);
        // Plus 2 for top/bottom border. Cap so it always fits.
        let modal_h = (lines.len() + 2).min(term_h.saturating_sub(1)).max(3);
        let top = term_h.saturating_sub(modal_h) / 2;
        let left = term_w.saturating_sub(modal_w) / 2;

        let inner_w = modal_w.saturating_sub(2);
        let top_border = format!("{}", "".repeat(inner_w));
        let bot_border = format!("{}", "".repeat(inner_w));
        let side = format!("{}", self.theme.cyan(""));

        execute!(stdout, cursor::MoveTo(left as u16, top as u16)).ok();
        print!("{}", self.theme.cyan(&top_border));

        // Content rows — clipped to fit inside (modal_h - 2) rows.
        let max_rows = modal_h.saturating_sub(2);
        for (i, line) in lines.iter().take(max_rows).enumerate() {
            let row = (top + 1 + i) as u16;
            execute!(stdout, cursor::MoveTo(left as u16, row)).ok();
            let vis = visible_len(line);
            let pad = inner_w.saturating_sub(vis);
            print!("{side}{line}{:pad$}{side}", "");
        }

        execute!(
            stdout,
            cursor::MoveTo(left as u16, (top + modal_h - 1) as u16)
        )
        .ok();
        print!("{}", self.theme.cyan(&bot_border));
    }

    fn index_of(&self, name: &str) -> usize {
        self.step_names
            .iter()
            .position(|n| n == name)
            .unwrap_or_else(|| panic!("unknown step `{name}`"))
    }

    /// Returns the run divider styled with the appropriate color based on step statuses.
    /// Dim while steps are still running/queued; green when all settled and passed;
    /// red when all settled and any failed.
    fn divider_styled(&self) -> String {
        if self.run_divider.is_empty() {
            return String::new();
        }
        let all_settled = self
            .statuses
            .iter()
            .all(|s| !matches!(s, StepStatus::Running | StepStatus::Queued));
        let any_failed = self
            .statuses
            .iter()
            .any(|s| matches!(s, StepStatus::Failed(..)));

        if all_settled && any_failed {
            format!("{}", self.theme.red(&self.run_divider))
        } else if all_settled {
            format!("{}", self.theme.green(&self.run_divider))
        } else {
            format!("{}", self.theme.dim(&self.run_divider))
        }
    }

    /// Captures stdout/stderr from each result into the browse buffer and
    /// initialises browse-mode state: failed steps are pre-expanded,
    /// diagnostics parsed off the full (untruncated) output, cursor moved
    /// to the first failing step. Mutates `&mut self`; no terminal I/O.
    fn capture_step_outputs(&mut self, results: &[StepResult]) {
        for r in results {
            if let Some(idx) = self.step_names.iter().position(|n| n == &r.name) {
                self.step_outputs[idx] = format_truncated_output(&r.stdout, &r.stderr);
                self.expanded[idx] = !r.success;
                let combined = if r.stderr.is_empty() {
                    r.stdout.clone()
                } else if r.stdout.is_empty() {
                    r.stderr.clone()
                } else {
                    format!("{}\n{}", r.stdout, r.stderr)
                };
                self.parsed_diagnostics[idx] = crate::output::diagnostic::parse(&combined);
                self.current_diagnostic[idx] = 0;
            }
        }
        self.cursor = results
            .iter()
            .find(|r| !r.success)
            .and_then(|r| self.step_names.iter().position(|n| n == &r.name))
            .unwrap_or(0);
        self.all_expanded = results.iter().any(|r| !r.success);
    }

    /// Builds the colored summary line shown after a run — failed/passed/
    /// skipped counts and the elapsed wall-clock, joined by `·`. Pure over
    /// `&self`; output is a single styled string ready for `println!`.
    fn summary_line(&self, results: &[StepResult], elapsed: f64) -> String {
        let failed = results.iter().filter(|r| !r.success).count();
        let passed = results.iter().filter(|r| r.success).count();
        let skipped = self.step_names.len().saturating_sub(results.len());

        let mut parts: Vec<String> = Vec::new();
        if failed > 0 {
            let s = format!("{failed} failed");
            parts.push(format!("{}", self.theme.red(&s)));
        }
        let s = format!("{passed} passed");
        parts.push(format!("{}", self.theme.green(&s)));
        if skipped > 0 {
            let s = format!("{skipped} skipped");
            parts.push(format!("{}", self.theme.dim(&s)));
        }
        let time_str = if failed == 0 {
            format!("all passing · {elapsed:.1}s")
        } else {
            format!("{elapsed:.1}s")
        };
        parts.push(format!("{}", self.theme.dim(&time_str)));

        parts.join(" · ")
    }
}

impl Display for TtyDisplay {
    fn set_trigger(&mut self, paths: &[PathBuf]) {
        self.trigger_paths = Some(paths.to_vec());
    }

    fn banner(
        &mut self,
        root: &Path,
        config_path: &Path,
        step_count: usize,
        profile: Option<&str>,
    ) {
        // Capture for editor-jump path resolution before the early-quiet exit
        // so diagnostic paths still resolve even when banner output is muted.
        self.root = root.to_path_buf();

        if self.verbosity == Verbosity::Quiet {
            return;
        }

        let mut stdout = std::io::stdout();
        execute!(
            stdout,
            terminal::Clear(ClearType::All),
            cursor::MoveTo(0, 0)
        )
        .ok();

        let width = Self::term_width();
        let version = env!("CARGO_PKG_VERSION");
        let prefix = format!("━━━ baraddur {version} ");
        let fill = "".repeat(width.saturating_sub(visible_len(&prefix)));
        let header = format!("{prefix}{fill}");
        println!("{}", self.theme.dim(&header));

        println!("{}  {}", self.theme.dim("watching:"), root.display());

        let config_name = config_path
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_default();
        let profile_suffix = profile
            .map(|p| format!("  (profile: {p})"))
            .unwrap_or_default();
        println!(
            "{}    {}  ({step_count} steps){profile_suffix}",
            self.theme.dim("config:  "),
            config_name
        );
        println!("{}", self.theme.dim("press ^C to exit"));

        let bottom = "".repeat(width);
        println!("{}", self.theme.dim(&bottom));

        let _ = stdout.flush();
    }

    fn run_started(&mut self, step_names: &[String]) {
        self.run_start = Some(Instant::now());
        self.run_count += 1;
        self.step_names = step_names.to_vec();
        self.statuses = vec![StepStatus::Queued; step_names.len()];
        self.name_width = step_names.iter().map(|n| n.len()).max().unwrap_or(0);
        self.rendered_lines = 0;
        self.has_running = false;
        // Reset browse state for the new run.
        self.step_outputs = vec![String::new(); step_names.len()];
        self.expanded = vec![false; step_names.len()];
        self.all_expanded = false;
        self.cursor = 0;
        self.browse_active = false;
        self.last_key = None;
        self.browse_scroll = 0;
        self.hook_output_text.clear();
        self.transient_message = None;
        self.hook_running = false;
        self.parsed_diagnostics = vec![Vec::new(); step_names.len()];
        self.current_diagnostic = vec![0; step_names.len()];
        self.help_modal_active = false;

        // Stash trigger BEFORE moving the value into the divider, so
        // `run_finished` can detect "file change → zero steps matched".
        let trigger = self.trigger_paths.take();
        self.last_trigger_paths = trigger.clone();

        if self.verbosity == Verbosity::Quiet {
            return;
        }

        let mut stdout = std::io::stdout();

        if !self.no_clear {
            execute!(
                stdout,
                terminal::Clear(ClearType::All),
                cursor::MoveTo(0, 0)
            )
            .ok();
        }

        // Build and store the divider text. redraw() will print it (as its first line)
        // and recolor it live based on statuses, so no println! or cursor position needed.
        let ts = chrono::Local::now().format("%H:%M:%S").to_string();
        let trigger_str = format_trigger_suffix(trigger.as_deref());
        let width = Self::term_width();
        let prefix = format!("━━━ #{} {ts}{trigger_str} ", self.run_count);
        let fill = "".repeat(width.saturating_sub(visible_len(&prefix)));
        self.run_divider = format!("{prefix}{fill}");

        self.redraw();
    }

    fn step_running(&mut self, name: &str) {
        let idx = self.index_of(name);
        self.statuses[idx] = StepStatus::Running;
        self.has_running = true;
        self.redraw();
    }

    fn step_finished(&mut self, result: &StepResult) {
        let idx = self.index_of(&result.name);
        let diag = short_diagnostic(result);
        self.statuses[idx] = if result.success {
            StepStatus::Passed(result.duration)
        } else {
            StepStatus::Failed(result.duration, diag)
        };
        self.has_running = self
            .statuses
            .iter()
            .any(|s| matches!(s, StepStatus::Running));
        self.redraw();
    }

    fn steps_skipped(&mut self, names: &[String]) {
        for name in names {
            let idx = self.index_of(name);
            self.statuses[idx] = StepStatus::Skipped;
        }
        self.redraw();
    }

    fn run_cancelled(&mut self) {
        // No-op in TTY mode — the next run_started clears the screen.
        self.rendered_lines = 0;
        self.has_running = false;
    }

    fn run_finished(&mut self, results: &[StepResult]) {
        // Keep rendered_lines intact (holds the step-list row count from the last
        // redraw) so browse_redraw can MoveUp over the step list + footer together
        // and replace them cleanly in one pass.
        self.has_running = false;

        self.capture_step_outputs(results);

        if self.verbosity == Verbosity::Quiet && results.iter().all(|r| r.success) {
            self.rendered_lines = 0;
            return;
        }

        let elapsed = self
            .run_start
            .take()
            .map(|t| t.elapsed().as_secs_f64())
            .unwrap_or_else(|| results.iter().map(|r| r.duration.as_secs_f64()).sum());

        println!();
        self.rendered_lines += 1;

        let summary = self.summary_line(results, elapsed);
        self.run_summary = summary.clone();
        println!("{summary}");
        let width = Self::term_width();
        self.rendered_lines += Self::visual_rows_for(&summary, width);

        // File-change run with zero applicable steps after path filtering —
        // surface this so a save doesn't look like a silent no-op. Shown in
        // the transient-message slot below the help bar.
        if results.is_empty() && self.last_trigger_paths.is_some() {
            self.transient_message = Some(match self.last_trigger_paths.as_deref() {
                Some([p]) => format!("no steps match changed path: {}", p.display()),
                Some(ps) if ps.len() > 1 => {
                    format!("no steps match {} changed paths", ps.len())
                }
                _ => "no steps match changed paths".into(),
            });
        }

        let _ = std::io::stdout().flush();
    }

    fn tick(&mut self) {
        if self.has_running {
            self.spinner_frame = (self.spinner_frame + 1) % SPINNER_FRAMES.len();
            self.redraw();
        }
    }

    fn enter_browse_mode(&mut self) {
        self.browse_active = true;
        self.raw_mode_on();
        let _ = execute!(std::io::stdout(), cursor::Hide);
        self.browse_redraw();
    }

    fn exit_browse_mode(&mut self) {
        // Set browse_active false before the final redraw so the cursor
        // highlight is not shown in the static post-browse state.
        self.browse_active = false;
        self.browse_redraw();
        self.raw_mode_off();
        let _ = execute!(std::io::stdout(), cursor::Show);
    }

    fn browse_redraw_if_active(&mut self) {
        if self.browse_active {
            self.browse_redraw();
        }
    }

    fn hook_output(&mut self, text: &str) {
        self.hook_output_text = text.to_string();
        // Receiving output implies the hook settled; clear the running flag
        // even if `hook_finished` hasn't been called yet.
        self.hook_running = false;
        if self.browse_active {
            self.browse_redraw();
        }
    }

    fn hook_started(&mut self) {
        self.hook_running = true;
        if self.browse_active {
            self.browse_redraw();
        }
    }

    fn hook_finished(&mut self) {
        self.hook_running = false;
        if self.browse_active {
            self.browse_redraw();
        }
    }

    fn handle_key(&mut self, key: KeyEvent) -> BrowseAction {
        // Modal capture: while the `?` help is up, any key dismisses it and
        // does nothing else — the key isn't forwarded to normal handling so
        // users don't accidentally rerun or quit while reading the keys.
        if self.help_modal_active {
            self.help_modal_active = false;
            self.last_key = None;
            return BrowseAction::Redraw;
        }

        let n = self.step_names.len();
        if n == 0 {
            return if matches!(key.code, KeyCode::Char('q')) {
                BrowseAction::Quit
            } else {
                BrowseAction::Noop
            };
        }

        // Any recognized key dismisses a prior transient message. The 'f'-no-
        // failures arm re-sets it below. If we cleared a visible message but
        // the resulting action is Noop, promote to Redraw so the message
        // actually disappears from the screen.
        let had_message = self.transient_message.take().is_some();

        let action = match key.code {
            KeyCode::Char('j') | KeyCode::Down => {
                self.cursor = (self.cursor + 1).min(n - 1);
                self.last_key = None;
                BrowseAction::Redraw
            }
            KeyCode::Char('k') | KeyCode::Up => {
                self.cursor = self.cursor.saturating_sub(1);
                self.last_key = None;
                BrowseAction::Redraw
            }
            KeyCode::Char('g') => {
                if self.last_key == Some(KeyCode::Char('g')) {
                    self.cursor = 0;
                    self.last_key = None;
                    BrowseAction::Redraw
                } else {
                    self.last_key = Some(KeyCode::Char('g'));
                    BrowseAction::Noop
                }
            }
            KeyCode::Char('G') => {
                self.cursor = n - 1;
                self.last_key = None;
                BrowseAction::Redraw
            }
            KeyCode::Enter | KeyCode::Char('o') => {
                self.expanded[self.cursor] = !self.expanded[self.cursor];
                self.last_key = None;
                BrowseAction::Redraw
            }
            KeyCode::Char('O') => {
                self.all_expanded = !self.all_expanded;
                for e in &mut self.expanded {
                    *e = self.all_expanded;
                }
                self.last_key = None;
                BrowseAction::Redraw
            }
            KeyCode::Char('r') => {
                self.last_key = None;
                BrowseAction::Rerun
            }
            KeyCode::Char('f') => {
                self.last_key = None;
                // Only meaningful if there were failures to retry. Otherwise
                // surface a one-shot message so the user knows the key was
                // received but had nothing to act on.
                if self
                    .statuses
                    .iter()
                    .any(|s| matches!(s, StepStatus::Failed(..)))
                {
                    BrowseAction::RerunFailed
                } else {
                    self.transient_message = Some("no failures to re-run".into());
                    BrowseAction::Redraw
                }
            }
            KeyCode::Char('c') => {
                self.last_key = None;
                // Rerun the step under the cursor in isolation. Always
                // emitted — a skipped step runs alone (matches "rerun
                // exactly what you pointed at"), and a passing step reruns
                // freshly which is useful after edits.
                BrowseAction::RerunCursor(self.step_names[self.cursor].clone())
            }
            KeyCode::Char('n') => {
                self.last_key = None;
                if self.advance_diagnostic(1) {
                    BrowseAction::Redraw
                } else {
                    self.transient_message = Some("no diagnostics on this step".into());
                    BrowseAction::Redraw
                }
            }
            KeyCode::Char('p') => {
                self.last_key = None;
                if self.advance_diagnostic(-1) {
                    BrowseAction::Redraw
                } else {
                    self.transient_message = Some("no diagnostics on this step".into());
                    BrowseAction::Redraw
                }
            }
            KeyCode::Char('e') => {
                self.last_key = None;
                self.open_current_diagnostic();
                BrowseAction::Redraw
            }
            KeyCode::Char('?') => {
                self.last_key = None;
                self.help_modal_active = true;
                BrowseAction::Redraw
            }
            KeyCode::Char('q') => BrowseAction::Quit,
            _ => {
                // Any unrecognized key clears the pending `g` chord.
                self.last_key = None;
                BrowseAction::Noop
            }
        };

        // Hide a just-cleared message even when no other state changed.
        if matches!(action, BrowseAction::Noop) && had_message {
            BrowseAction::Redraw
        } else {
            action
        }
    }
}

// ── Tests ────────────────────────────────────────────────────────────────────

#[cfg(test)]
#[cfg(unix)]
mod tests {
    use super::*;
    use rustix::termios::{LocalModes, OutputModes, tcgetattr};
    use rustix_openpty::openpty;
    use std::os::fd::AsFd;

    /// suppress_echo must clear ECHO/ECHOE on the target fd and return a
    /// backup whose Termios can be used to restore the original state.
    #[test]
    fn suppress_echo_clears_echo_and_restore_brings_it_back() {
        let pty = openpty(None, None).expect("openpty failed");
        let user = pty.user.as_fd();

        // Pty user side starts with echo enabled.
        let before = tcgetattr(user).unwrap();
        assert!(
            before.local_modes.contains(LocalModes::ECHO),
            "pty should start with echo on"
        );

        let backup = terminal_io::suppress_echo(user).expect("suppress_echo failed");

        let during = tcgetattr(user).unwrap();
        assert!(
            !during.local_modes.contains(LocalModes::ECHO),
            "ECHO should be cleared after suppress_echo"
        );
        assert!(
            !during.local_modes.contains(LocalModes::ECHOE),
            "ECHOE should also be cleared"
        );

        terminal_io::restore(user, &backup);

        let after = tcgetattr(user).unwrap();
        assert!(
            after.local_modes.contains(LocalModes::ECHO),
            "ECHO should be restored after restore()"
        );
    }

    /// Pressing `c` in browse mode returns `RerunCursor` carrying the name
    /// of the step under the cursor. Verifies the third rerun key alongside
    /// `r` (full) and `f` (failed).
    #[test]
    fn handle_key_c_returns_rerun_cursor_for_step_under_cursor() {
        use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Quiet, true);
        // Populate step list via the normal lifecycle so internal vectors are
        // sized correctly. Cursor lands at index 0 by default.
        d.run_started(&["alpha".to_string(), "beta".to_string(), "gamma".to_string()]);
        d.cursor = 1;

        let action = d.handle_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::NONE));
        match action {
            BrowseAction::RerunCursor(name) => assert_eq!(name, "beta"),
            other => panic!("expected RerunCursor(\"beta\"), got {other:?}"),
        }
    }

    /// `n` / `p` wrap around the diagnostic list for the cursor step, and
    /// `e` hands the *current* `(path, line, col)` to the injected editor
    /// spawn — proving the navigation index correctly drives editor jump.
    #[test]
    fn diagnostic_navigation_and_editor_spawn() {
        use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
        use std::sync::{Arc, Mutex};

        type EditorCall = (std::path::PathBuf, u32, Option<u32>);

        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Quiet, true);
        d.banner(
            std::path::Path::new("/tmp/repo"),
            std::path::Path::new("/tmp/repo/.baraddur.toml"),
            1,
            None,
        );
        d.run_started(&["step".to_string()]);

        d.parsed_diagnostics[0] = vec![
            crate::output::diagnostic::Diagnostic {
                path: std::path::PathBuf::from("a.rs"),
                line: 1,
                col: Some(1),
            },
            crate::output::diagnostic::Diagnostic {
                path: std::path::PathBuf::from("b.rs"),
                line: 2,
                col: Some(2),
            },
            crate::output::diagnostic::Diagnostic {
                path: std::path::PathBuf::from("c.rs"),
                line: 3,
                col: None,
            },
        ];

        // Recorder captures (path, line, col) on each invocation.
        let calls: Arc<Mutex<Vec<EditorCall>>> = Arc::new(Mutex::new(Vec::new()));
        let recorder = calls.clone();
        d.set_editor_spawn(Box::new(move |path, line, col| {
            recorder
                .lock()
                .unwrap()
                .push((path.to_path_buf(), line, col));
            Ok(())
        }));

        // Initial diag is index 0 → a.rs.
        d.handle_key(KeyEvent::new(KeyCode::Char('e'), KeyModifiers::NONE));
        // n n → 1 → 2; one more n wraps back to 0.
        d.handle_key(KeyEvent::new(KeyCode::Char('n'), KeyModifiers::NONE));
        d.handle_key(KeyEvent::new(KeyCode::Char('e'), KeyModifiers::NONE));
        d.handle_key(KeyEvent::new(KeyCode::Char('n'), KeyModifiers::NONE));
        d.handle_key(KeyEvent::new(KeyCode::Char('e'), KeyModifiers::NONE));
        // p wraps 2 → 1.
        d.handle_key(KeyEvent::new(KeyCode::Char('p'), KeyModifiers::NONE));
        d.handle_key(KeyEvent::new(KeyCode::Char('e'), KeyModifiers::NONE));

        let recorded = calls.lock().unwrap().clone();
        assert_eq!(recorded.len(), 4);
        assert_eq!(
            recorded[0],
            (std::path::PathBuf::from("/tmp/repo/a.rs"), 1, Some(1))
        );
        assert_eq!(
            recorded[1],
            (std::path::PathBuf::from("/tmp/repo/b.rs"), 2, Some(2))
        );
        assert_eq!(
            recorded[2],
            (std::path::PathBuf::from("/tmp/repo/c.rs"), 3, None)
        );
        assert_eq!(
            recorded[3],
            (std::path::PathBuf::from("/tmp/repo/b.rs"), 2, Some(2))
        );
    }

    /// `?` opens the help modal; any subsequent key dismisses it without
    /// forwarding the keypress to the normal handlers (so the user can read
    /// the keys without accidentally rerunning or quitting).
    #[test]
    fn help_modal_opens_on_question_mark_and_dismisses_on_any_key() {
        use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Quiet, true);
        d.run_started(&["step".to_string()]);
        assert!(!d.help_modal_active);

        d.handle_key(KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE));
        assert!(d.help_modal_active, "? should open the modal");

        // Pressing `q` while the modal is up should dismiss it instead of
        // quitting — that's the modal-capture guarantee.
        let action = d.handle_key(KeyEvent::new(KeyCode::Char('q'), KeyModifiers::NONE));
        assert!(matches!(action, BrowseAction::Redraw));
        assert!(!d.help_modal_active, "any key should dismiss the modal");
    }

    /// `e` on a step with no diagnostics surfaces a transient message and
    /// never invokes the spawn closure.
    #[test]
    fn editor_key_with_no_diagnostics_is_no_op() {
        use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
        use std::sync::{Arc, Mutex};

        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Quiet, true);
        d.run_started(&["step".to_string()]);

        let invoked = Arc::new(Mutex::new(false));
        let flag = invoked.clone();
        d.set_editor_spawn(Box::new(move |_, _, _| {
            *flag.lock().unwrap() = true;
            Ok(())
        }));

        d.handle_key(KeyEvent::new(KeyCode::Char('e'), KeyModifiers::NONE));

        assert!(!*invoked.lock().unwrap(), "editor should not be invoked");
        assert_eq!(
            d.transient_message.as_deref(),
            Some("no diagnostics on this step")
        );
    }

    fn mk_step_result(
        success: bool,
        exit_code: Option<i32>,
        stdout: &str,
        stderr: &str,
    ) -> StepResult {
        StepResult {
            name: "s".into(),
            success,
            exit_code,
            stdout: stdout.into(),
            stderr: stderr.into(),
            duration: Duration::from_secs(0),
            stdout_truncated: false,
            stderr_truncated: false,
        }
    }

    #[test]
    fn short_diagnostic_empty_when_step_succeeded() {
        let r = mk_step_result(true, Some(0), "anything\n", "");
        assert_eq!(short_diagnostic(&r), "");
    }

    #[test]
    fn short_diagnostic_reports_command_not_found_for_no_exit_code() {
        let r = mk_step_result(false, None, "", "");
        assert_eq!(short_diagnostic(&r), "command not found");
    }

    #[test]
    fn short_diagnostic_empty_when_no_non_blank_output() {
        let r = mk_step_result(false, Some(1), "  \n\n   \n", "");
        assert_eq!(short_diagnostic(&r), "");
    }

    #[test]
    fn short_diagnostic_returns_single_short_line_untouched() {
        let r = mk_step_result(false, Some(1), "boom\n", "");
        assert_eq!(short_diagnostic(&r), "boom");
    }

    #[test]
    fn short_diagnostic_truncates_single_long_line_at_40_chars() {
        let line = "x".repeat(50);
        let r = mk_step_result(false, Some(1), &line, "");
        let out = short_diagnostic(&r);
        assert_eq!(out.chars().filter(|c| *c == 'x').count(), 40);
        assert!(out.ends_with(''));
    }

    #[test]
    fn short_diagnostic_summarizes_multiple_lines_as_count() {
        let r = mk_step_result(false, Some(2), "error one\nerror two\nerror three\n", "");
        assert_eq!(short_diagnostic(&r), "3 lines");
    }

    #[test]
    fn short_diagnostic_merges_stdout_and_stderr_for_line_count() {
        let r = mk_step_result(false, Some(1), "a\n", "b\nc\n");
        // stdout "a\n" + stderr "b\nc\n" concatenated → 3 non-blank lines.
        assert_eq!(short_diagnostic(&r), "3 lines");
    }

    /// Quiet mode + an all-passing run takes the early return: no summary is
    /// printed and `rendered_lines` is zeroed so nothing is left on screen.
    #[test]
    fn run_finished_quiet_all_pass_renders_nothing() {
        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Quiet, true);
        d.run_started(&["a".to_string(), "b".to_string()]);
        // Pretend a previous redraw left rows on screen; the early return must
        // reset this to 0.
        d.rendered_lines = 5;

        d.run_finished(&[
            mk_step_result(true, Some(0), "", ""),
            mk_step_result(true, Some(0), "", ""),
        ]);

        assert_eq!(d.rendered_lines, 0);
        assert!(
            d.run_summary.is_empty(),
            "no summary should be built in the quiet early return"
        );
    }

    /// A normal failing run builds and stashes the summary line and clears the
    /// running flag so browse mode can take over.
    #[test]
    fn run_finished_failing_run_sets_summary_and_clears_running() {
        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Normal, true);
        d.run_started(&["s".to_string()]);
        d.has_running = true;

        d.run_finished(&[mk_step_result(false, Some(1), "boom\n", "")]);

        assert!(!d.run_summary.is_empty(), "summary line should be stashed");
        assert!(d.run_summary.contains("1 failed"));
        assert!(!d.has_running, "has_running must be cleared at run end");
    }

    /// Empty results from a single-path file-change run surface the singular
    /// "no steps match changed path: <path>" transient message.
    #[test]
    fn run_finished_no_match_message_single_path() {
        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Normal, true);
        d.set_trigger(&[PathBuf::from("src/foo.rs")]);
        d.run_started(&[]); // moves trigger_paths → last_trigger_paths
        d.run_finished(&[]);

        assert_eq!(
            d.transient_message.as_deref(),
            Some("no steps match changed path: src/foo.rs")
        );
    }

    /// Empty results from a multi-path file-change run report the count.
    #[test]
    fn run_finished_no_match_message_multiple_paths() {
        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Normal, true);
        d.set_trigger(&[PathBuf::from("a.rs"), PathBuf::from("b.rs")]);
        d.run_started(&[]);
        d.run_finished(&[]);

        assert_eq!(
            d.transient_message.as_deref(),
            Some("no steps match 2 changed paths")
        );
    }

    /// A trigger with an empty path list still flags the no-match case via the
    /// fallback arm.
    #[test]
    fn run_finished_no_match_message_no_paths() {
        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Normal, true);
        d.set_trigger(&[]); // Some(vec![]) → last_trigger_paths is Some but empty
        d.run_started(&[]);
        d.run_finished(&[]);

        assert_eq!(
            d.transient_message.as_deref(),
            Some("no steps match changed paths")
        );
    }

    #[test]
    fn clamp_scroll_snaps_up_when_cursor_above_window() {
        // Cursor at row 2 is above a scroll of 5 → snap the window up to it.
        assert_eq!(TtyDisplay::clamp_scroll(5, 2, 1, 10, 20), 2);
    }

    #[test]
    fn clamp_scroll_pulls_down_when_cursor_below_window() {
        // Cursor bottom 15+2=17 exceeds window 0+10 → scroll to 17-10=7.
        assert_eq!(TtyDisplay::clamp_scroll(0, 15, 2, 10, 20), 7);
    }

    #[test]
    fn clamp_scroll_unchanged_when_cursor_inside_window() {
        // Cursor at 3 sits within [2, 12); scroll stays, capped at total-viewport.
        assert_eq!(TtyDisplay::clamp_scroll(2, 3, 1, 10, 20), 2);
    }

    #[test]
    fn clamp_scroll_caps_to_zero_when_content_shorter_than_viewport() {
        // total (3) < viewport (10): saturating_sub floors the cap at 0.
        assert_eq!(TtyDisplay::clamp_scroll(5, 5, 1, 10, 3), 0);
    }

    fn rows_lines(rows: &[usize]) -> Vec<(String, usize)> {
        rows.iter()
            .enumerate()
            .map(|(i, r)| (format!("line{i}"), *r))
            .collect()
    }

    #[test]
    fn viewport_slice_renders_everything_when_it_fits() {
        let lines = rows_lines(&[1, 1, 1, 1, 1]);
        let (range, rendered) = TtyDisplay::viewport_slice(&lines, 0, 10);
        assert_eq!(range, 0..5);
        assert_eq!(rendered, 5);
    }

    #[test]
    fn viewport_slice_skips_whole_lines_on_clean_scroll_boundary() {
        let lines = rows_lines(&[1, 1, 1, 1, 1]);
        let (range, rendered) = TtyDisplay::viewport_slice(&lines, 2, 10);
        assert_eq!(range, 2..5);
        assert_eq!(rendered, 3);
    }

    #[test]
    fn viewport_slice_stops_when_viewport_fills() {
        let lines = rows_lines(&[1, 1, 1, 1, 1]);
        let (range, rendered) = TtyDisplay::viewport_slice(&lines, 0, 2);
        assert_eq!(range, 0..2);
        assert_eq!(rendered, 2);
    }

    #[test]
    fn viewport_slice_drops_a_partially_skipped_wrapped_line() {
        // A 3-row wrapped line followed by two 1-row lines. A scroll of 2 lands
        // inside the wrapped line — it must be dropped whole, not painted from
        // its middle, so rendering starts at the next line.
        let lines = rows_lines(&[3, 1, 1]);
        let (range, rendered) = TtyDisplay::viewport_slice(&lines, 2, 10);
        assert_eq!(range, 1..3);
        assert_eq!(rendered, 2);
    }

    #[test]
    fn viewport_slice_empty_lines_is_empty_range() {
        let lines: Vec<(String, usize)> = Vec::new();
        let (range, rendered) = TtyDisplay::viewport_slice(&lines, 0, 10);
        assert_eq!(range, 0..0);
        assert_eq!(rendered, 0);
    }

    /// Headless smoke test of the browse paint shell: crossterm calls are
    /// `.ok()`'d and term size falls back to 80x24 with no tty, so the full
    /// scroll-clamp → viewport-slice → paint path runs and sets rendered_lines.
    /// Also exercises the help-modal overlay branch.
    #[test]
    fn browse_redraw_smoke_paints_headless() {
        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Normal, true);
        d.run_started(&["alpha".to_string(), "beta".to_string()]);
        d.run_finished(&[mk_step_result(false, Some(1), "boom\n", "")]);

        d.browse_active = true;
        d.browse_redraw();
        assert!(
            d.rendered_lines > 0,
            "browse_redraw should paint at least the step rows"
        );

        // Modal path: forces a full clear and draws the overlay.
        d.help_modal_active = true;
        d.browse_redraw();
        assert!(
            d.help_painted_last,
            "modal paint should record help_painted_last"
        );
    }

    #[test]
    fn help_modal_lines_has_header_columns_and_dismiss_footer() {
        use super::super::style::strip_ansi;

        let d = TtyDisplay::new(Theme::new(false), Verbosity::Normal, true);
        let lines = d.help_modal_lines();

        // 1 header + 1 blank + 10 rows + 1 blank + 1 footer = 14 lines.
        assert_eq!(lines.len(), 14, "unexpected line count: {lines:#?}");

        let plain: Vec<String> = lines.iter().map(|l| strip_ansi(l)).collect();
        assert_eq!(plain[0].trim(), "Help");
        assert_eq!(plain[1], "");
        assert!(
            plain[2].contains("Navigation") && plain[2].contains("Diagnostics"),
            "first row should carry both section headers, got {:?}",
            plain[2]
        );
        assert!(
            plain
                .iter()
                .any(|l| l.contains("Output") && l.contains("Rerun")),
            "expected a row pairing Output / Rerun"
        );
        assert!(plain.last().unwrap().contains("press any key to dismiss"));
    }

    #[test]
    fn help_modal_lines_pads_left_column_to_align_right_column() {
        use super::super::style::{strip_ansi, visible_len};

        let d = TtyDisplay::new(Theme::new(false), Verbosity::Normal, true);
        let lines = d.help_modal_lines();

        // Find the "j / ↓ down  …  n   next" row and confirm the right column
        // starts at the same visible offset as on the section-header row.
        let plain: Vec<String> = lines.iter().map(|l| strip_ansi(l)).collect();
        let header_row = plain
            .iter()
            .find(|l| l.contains("Navigation") && l.contains("Diagnostics"))
            .expect("header row");
        let body_row = plain
            .iter()
            .find(|l| l.contains("down") && l.contains("next"))
            .expect("body row");

        // Right column starts at offset 2 (prefix) + 26 (col_width) = 28.
        let header_right = visible_len(&header_row[..header_row.find("Diagnostics").unwrap()]);
        // The body row's right column literally begins with `"  n   next"`,
        // so the first occurrence of `"  n"` marks its start.
        let body_right = visible_len(&body_row[..body_row.find("  n").unwrap()]);
        assert_eq!(header_right, 28);
        assert_eq!(body_right, 28);
    }

    #[test]
    fn divider_styled_returns_empty_when_divider_is_empty() {
        let d = TtyDisplay::new(Theme::new(true), Verbosity::Normal, true);
        // Default state: run_divider is empty, statuses is empty.
        assert_eq!(d.divider_styled(), "");
    }

    #[test]
    fn divider_styled_is_dim_while_steps_still_running() {
        use super::super::style::strip_ansi;

        let mut d = TtyDisplay::new(Theme::new(true), Verbosity::Normal, true);
        d.run_divider = "── run ──".into();
        d.statuses = vec![
            StepStatus::Passed(Duration::from_secs(0)),
            StepStatus::Running,
        ];

        let out = d.divider_styled();
        assert_eq!(strip_ansi(&out), "── run ──");
        // Dim is rendered via ESC[2m in the theme; green/red use ESC[32m/[31m.
        assert!(out.contains("\x1b[2m"), "expected dim ANSI, got {out:?}");
        assert!(!out.contains("\x1b[32m") && !out.contains("\x1b[31m"));
    }

    #[test]
    fn divider_styled_is_green_when_all_settled_and_passing() {
        let mut d = TtyDisplay::new(Theme::new(true), Verbosity::Normal, true);
        d.run_divider = "── run ──".into();
        d.statuses = vec![
            StepStatus::Passed(Duration::from_secs(0)),
            StepStatus::Skipped,
        ];

        let out = d.divider_styled();
        // crossterm renders `.green()` as the 256-color code 10.
        assert!(
            out.contains("[38;5;10m"),
            "expected green ANSI, got {out:?}"
        );
        assert!(!out.contains("[38;5;9m") && !out.contains("[2m"));
    }

    #[test]
    fn divider_styled_is_red_when_all_settled_and_any_failed() {
        let mut d = TtyDisplay::new(Theme::new(true), Verbosity::Normal, true);
        d.run_divider = "── run ──".into();
        d.statuses = vec![
            StepStatus::Passed(Duration::from_secs(0)),
            StepStatus::Failed(Duration::from_secs(0), "boom".into()),
        ];

        let out = d.divider_styled();
        // crossterm renders `.red()` as the 256-color code 9.
        assert!(out.contains("[38;5;9m"), "expected red ANSI, got {out:?}");
        assert!(!out.contains("[38;5;10m") && !out.contains("[2m"));
    }

    #[test]
    fn step_row_queued_shows_glyph_only() {
        use super::super::style::strip_ansi;

        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Normal, true);
        d.run_started(&["check".to_string()]);
        // Default status after run_started is Queued.

        let (line, rows) = d.step_row(0, 80);
        let plain = strip_ansi(&line);
        assert_eq!(rows, 1);
        assert!(
            plain.contains("check"),
            "row should contain step name: {plain:?}"
        );
        // Queued state: no duration, no diagnostic.
        assert!(
            !plain.contains('s'),
            "queued row should not show duration: {plain:?}"
        );
    }

    #[test]
    fn step_row_passed_appends_right_aligned_duration() {
        use super::super::style::{strip_ansi, visible_len};

        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Normal, true);
        d.run_started(&["check".to_string()]);
        d.statuses[0] = StepStatus::Passed(Duration::from_millis(1500));

        let (line, rows) = d.step_row(0, 80);
        let plain = strip_ansi(&line);
        assert_eq!(rows, 1);
        assert!(plain.contains("check"));
        assert!(
            plain.ends_with("1.5s"),
            "duration should be right-aligned: {plain:?}"
        );
        // Total width should match the requested width (padded between cols).
        assert_eq!(visible_len(&line), 80);
    }

    #[test]
    fn step_row_failed_with_diagnostic_includes_diag_text() {
        use super::super::style::strip_ansi;

        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Normal, true);
        d.run_started(&["check".to_string()]);
        d.statuses[0] = StepStatus::Failed(Duration::from_millis(2300), "boom".into());

        let (line, _rows) = d.step_row(0, 80);
        let plain = strip_ansi(&line);
        assert!(plain.contains("check"));
        assert!(plain.contains("boom"), "diagnostic text missing: {plain:?}");
        assert!(plain.ends_with("2.3s"));
    }

    #[test]
    fn step_row_cursor_uses_filled_arrow_in_no_color_mode() {
        use super::super::style::strip_ansi;

        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Normal, true);
        d.run_started(&["a".to_string(), "b".to_string()]);
        d.cursor = 1;

        let (cursor_line, _) = d.step_row(1, 80);
        let (other_line, _) = d.step_row(0, 80);
        assert!(
            strip_ansi(&cursor_line).contains(""),
            "NO_COLOR cursor row should use filled `▶`: {cursor_line:?}"
        );
        assert!(
            !strip_ansi(&other_line).contains(""),
            "non-cursor rows should use hollow `▸`: {other_line:?}"
        );
    }

    #[test]
    fn expanded_output_lines_empty_when_not_expanded() {
        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Normal, true);
        d.run_started(&["check".to_string()]);
        d.step_outputs[0] = "  some output\n".into();
        // expanded[0] stays false.

        assert!(d.expanded_output_lines(0, 80).is_empty());
    }

    #[test]
    fn expanded_output_lines_empty_when_no_captured_output() {
        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Normal, true);
        d.run_started(&["check".to_string()]);
        d.expanded[0] = true;
        // step_outputs[0] is empty by default.

        assert!(d.expanded_output_lines(0, 80).is_empty());
    }

    #[test]
    fn expanded_output_lines_emits_one_entry_per_line() {
        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Normal, true);
        d.run_started(&["check".to_string()]);
        d.expanded[0] = true;
        d.step_outputs[0] = "  line one\n  line two\n  line three\n".into();

        let lines = d.expanded_output_lines(0, 80);
        assert_eq!(lines.len(), 3);
        // Non-diagnostic lines pass through unchanged (with their leading "  ").
        assert_eq!(lines[0].0, "  line one");
        assert_eq!(lines[1].0, "  line two");
        assert_eq!(lines[2].0, "  line three");
    }

    #[test]
    fn expanded_output_lines_highlights_current_diagnostic_on_cursor_step() {
        use super::super::style::strip_ansi;
        use crate::output::diagnostic::Diagnostic;
        use std::path::PathBuf;

        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Normal, true);
        d.run_started(&["check".to_string()]);
        d.cursor = 0;
        d.expanded[0] = true;
        d.step_outputs[0] = "  src/foo.rs:10:5: error: bad\n".into();
        d.parsed_diagnostics[0] = vec![Diagnostic {
            path: PathBuf::from("src/foo.rs"),
            line: 10,
            col: Some(5),
        }];
        d.current_diagnostic[0] = 0;

        let lines = d.expanded_output_lines(0, 80);
        assert_eq!(lines.len(), 1);
        // In NO_COLOR mode the current-diagnostic marker is the filled `▶`.
        let plain = strip_ansi(&lines[0].0);
        assert!(
            plain.starts_with(""),
            "current diag should lead with `▶ `: {plain:?}"
        );
        assert!(plain.contains("src/foo.rs:10:5"));
    }

    #[test]
    fn footer_lines_empty_when_browse_not_active() {
        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Normal, true);
        d.run_started(&["check".to_string()]);
        d.run_summary = "1 passed".into();
        // browse_active stays false.

        assert!(d.footer_lines(80).is_empty());
    }

    #[test]
    fn footer_lines_includes_summary_help_bar_and_spacer() {
        use super::super::style::strip_ansi;

        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Normal, true);
        d.run_started(&["check".to_string()]);
        d.browse_active = true;
        d.run_summary = "1 passed in 1.2s".into();

        let lines = d.footer_lines(80);
        let plain: Vec<String> = lines.iter().map(|(s, _)| strip_ansi(s)).collect();
        // Leading spacer, then summary, then blank, then help bar.
        assert_eq!(plain[0], "");
        assert!(plain.iter().any(|l| l.contains("1 passed in 1.2s")));
        assert!(
            plain.iter().any(|l| l.contains("q quit")),
            "help bar missing from footer: {plain:#?}"
        );
    }

    #[test]
    fn footer_lines_keeps_help_bar_when_modal_is_active() {
        use super::super::style::strip_ansi;

        // The modal is now a floating overlay painted on top of the browse
        // view; the one-line help bar in the footer stays put so layout
        // doesn't reflow when toggling `?`.
        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Normal, true);
        d.run_started(&["check".to_string()]);
        d.browse_active = true;
        d.help_modal_active = true;

        let lines = d.footer_lines(80);
        let plain: Vec<String> = lines.iter().map(|(s, _)| strip_ansi(s)).collect();
        assert!(
            plain.iter().any(|l| l.contains("q quit")),
            "help bar should remain in footer while modal is active: {plain:#?}"
        );
        assert!(
            !plain.iter().any(|l| l.contains("press any key to dismiss")),
            "modal content should not be inlined into the footer: {plain:#?}"
        );
    }

    #[test]
    fn footer_lines_renders_hook_running_block_while_in_flight() {
        use super::super::style::strip_ansi;

        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Normal, true);
        d.run_started(&["check".to_string()]);
        d.browse_active = true;
        d.hook_running = true;

        let lines = d.footer_lines(80);
        let plain: Vec<String> = lines.iter().map(|(s, _)| strip_ansi(s)).collect();
        assert!(
            plain.iter().any(|l| l.contains("running on_failure hook")),
            "in-flight hook line missing: {plain:#?}"
        );
    }

    #[test]
    fn footer_lines_appends_transient_message_at_end() {
        use super::super::style::strip_ansi;

        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Normal, true);
        d.run_started(&["check".to_string()]);
        d.browse_active = true;
        d.transient_message = Some("no failures to rerun".into());

        let lines = d.footer_lines(80);
        let last = strip_ansi(&lines.last().unwrap().0);
        assert!(
            last.contains("no failures to rerun"),
            "transient message should be the last footer entry: {last:?}"
        );
    }

    #[test]
    fn compute_lines_empty_state_returns_empty_layout() {
        let d = TtyDisplay::new(Theme::new(false), Verbosity::Normal, true);
        let (lines, top, h) = d.compute_lines(80);
        assert!(lines.is_empty());
        assert_eq!(top, 0);
        assert_eq!(h, 1);
    }

    #[test]
    fn compute_lines_anchors_cursor_to_step_offset() {
        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Normal, true);
        d.run_started(&["a".to_string(), "b".to_string(), "c".to_string()]);
        // `run_started` populates `run_divider`; clear it so the test exercises
        // pure step-offset math without divider arithmetic.
        d.run_divider.clear();
        d.cursor = 2;

        let (lines, top, h) = d.compute_lines(80);
        assert_eq!(lines.len(), 3, "expected one row per step");
        // Each step row is 1 terminal row at width 80, so cursor at index 2
        // sits at rows 0+1 = 2.
        assert_eq!(top, 2);
        assert_eq!(h, 1);
    }

    #[test]
    fn compute_lines_offsets_cursor_by_run_divider() {
        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Normal, true);
        d.run_started(&["a".to_string(), "b".to_string()]);
        d.cursor = 0;
        d.run_divider = "── run ──".into();

        let (lines, top, _) = d.compute_lines(80);
        // [divider, step a, step b] = 3 entries; cursor on step a is at
        // row 1, after the 1-row divider.
        assert_eq!(lines.len(), 3);
        assert_eq!(top, 1);
    }

    #[test]
    fn compute_lines_shifts_cursor_anchor_by_earlier_step_expansion() {
        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Normal, true);
        d.run_started(&["a".to_string(), "b".to_string()]);
        d.run_divider.clear(); // isolate from the run_started divider
        d.cursor = 1;
        d.expanded[0] = true;
        d.step_outputs[0] = "  line one\n  line two\n  line three\n".into();

        let (lines, top, _) = d.compute_lines(80);
        // [step a, exp1, exp2, exp3, step b] = 5 entries.
        assert_eq!(lines.len(), 5);
        // Cursor on step b: row 0 (step a) + rows 1..=3 (expansion) = 4.
        assert_eq!(top, 4);
    }

    #[test]
    fn compute_lines_appends_footer_after_step_block() {
        use super::super::style::strip_ansi;

        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Normal, true);
        d.run_started(&["a".to_string()]);
        d.browse_active = true;
        d.run_summary = "1 passed in 1.2s".into();

        let (lines, _, _) = d.compute_lines(80);
        // Step row first, then the footer (spacer + summary + spacer + help bar).
        assert!(lines.len() > 1, "expected step + footer entries");
        let plain: Vec<String> = lines.iter().map(|(s, _)| strip_ansi(s)).collect();
        // Step row comes before the summary line.
        let summary_idx = plain
            .iter()
            .position(|l| l.contains("1 passed in 1.2s"))
            .expect("summary line missing");
        let step_idx = plain
            .iter()
            .position(|l| l.contains('a'))
            .expect("step row missing");
        assert!(step_idx < summary_idx, "footer should follow step block");
    }

    #[test]
    fn capture_step_outputs_expands_failed_steps_and_points_cursor_to_first_fail() {
        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Normal, true);
        d.run_started(&["a".to_string(), "b".to_string(), "c".to_string()]);

        let results = vec![
            mk_step_result(true, Some(0), "", ""),
            mk_step_result(false, Some(1), "boom\n", ""),
            mk_step_result(true, Some(0), "", ""),
        ];
        // Names need to match step_names for the lookup to find them.
        let results: Vec<StepResult> = results
            .into_iter()
            .enumerate()
            .map(|(i, mut r)| {
                r.name = d.step_names[i].clone();
                r
            })
            .collect();

        d.capture_step_outputs(&results);

        assert_eq!(d.expanded, vec![false, true, false]);
        // Cursor lands on step "b" (the first failing step).
        assert_eq!(d.cursor, 1);
        assert!(d.all_expanded, "any failure should set all_expanded");
        assert!(
            d.step_outputs[1].contains("boom"),
            "captured output should preserve content: {:?}",
            d.step_outputs[1]
        );
    }

    #[test]
    fn capture_step_outputs_keeps_cursor_at_zero_when_all_passed() {
        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Normal, true);
        d.run_started(&["a".to_string(), "b".to_string()]);

        let mut results = vec![
            mk_step_result(true, Some(0), "", ""),
            mk_step_result(true, Some(0), "", ""),
        ];
        results[0].name = "a".into();
        results[1].name = "b".into();

        d.capture_step_outputs(&results);

        assert_eq!(d.cursor, 0);
        assert!(!d.all_expanded);
        assert_eq!(d.expanded, vec![false, false]);
    }

    #[test]
    fn summary_line_formats_all_passing_branch() {
        use super::super::style::strip_ansi;

        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Normal, true);
        d.run_started(&["a".to_string(), "b".to_string()]);
        let mut results = vec![
            mk_step_result(true, Some(0), "", ""),
            mk_step_result(true, Some(0), "", ""),
        ];
        results[0].name = "a".into();
        results[1].name = "b".into();

        let line = strip_ansi(&d.summary_line(&results, 1.2));
        assert!(line.contains("2 passed"), "missing pass count: {line:?}");
        assert!(
            line.contains("all passing · 1.2s"),
            "missing time suffix: {line:?}"
        );
        assert!(!line.contains("failed"));
    }

    #[test]
    fn summary_line_leads_with_failed_count_when_any_failed() {
        use super::super::style::strip_ansi;

        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Normal, true);
        d.run_started(&["a".to_string(), "b".to_string()]);
        let mut results = vec![
            mk_step_result(false, Some(1), "boom\n", ""),
            mk_step_result(true, Some(0), "", ""),
        ];
        results[0].name = "a".into();
        results[1].name = "b".into();

        let line = strip_ansi(&d.summary_line(&results, 0.5));
        // Failed count comes first, then passed, then time without
        // the "all passing" prefix.
        assert!(
            line.starts_with("1 failed"),
            "wrong leading token: {line:?}"
        );
        assert!(line.contains("1 passed"));
        assert!(
            line.ends_with("0.5s"),
            "expected bare time suffix: {line:?}"
        );
        assert!(!line.contains("all passing"));
    }

    #[test]
    fn summary_line_includes_skipped_when_some_steps_missing_from_results() {
        use super::super::style::strip_ansi;

        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Normal, true);
        d.run_started(&["a".to_string(), "b".to_string(), "c".to_string()]);
        // Only one result for a 3-step pipeline → 2 skipped.
        let mut results = vec![mk_step_result(true, Some(0), "", "")];
        results[0].name = "a".into();

        let line = strip_ansi(&d.summary_line(&results, 1.0));
        assert!(line.contains("1 passed"));
        assert!(
            line.contains("2 skipped"),
            "missing skipped count: {line:?}"
        );
    }

    /// Convenience: drive a single key through `handle_key` against a
    /// `TtyDisplay` already initialised with the named steps.
    fn dispatch(d: &mut TtyDisplay, ch: char) -> BrowseAction {
        use crossterm::event::{KeyEvent, KeyModifiers};
        d.handle_key(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::NONE))
    }

    #[test]
    fn handle_key_j_moves_cursor_down_and_clamps_at_last_step() {
        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Quiet, true);
        d.run_started(&["a".to_string(), "b".to_string(), "c".to_string()]);

        assert!(matches!(dispatch(&mut d, 'j'), BrowseAction::Redraw));
        assert_eq!(d.cursor, 1);
        dispatch(&mut d, 'j');
        dispatch(&mut d, 'j'); // would overshoot — should clamp at n-1.
        assert_eq!(d.cursor, 2);
    }

    #[test]
    fn handle_key_k_moves_cursor_up_and_clamps_at_zero() {
        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Quiet, true);
        d.run_started(&["a".to_string(), "b".to_string()]);
        d.cursor = 1;

        assert!(matches!(dispatch(&mut d, 'k'), BrowseAction::Redraw));
        assert_eq!(d.cursor, 0);
        dispatch(&mut d, 'k'); // saturating — stays at 0.
        assert_eq!(d.cursor, 0);
    }

    #[test]
    fn handle_key_gg_chord_jumps_cursor_to_top() {
        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Quiet, true);
        d.run_started(&["a".to_string(), "b".to_string(), "c".to_string()]);
        d.cursor = 2;

        // First `g` is a Noop, just primes the chord.
        assert!(matches!(dispatch(&mut d, 'g'), BrowseAction::Noop));
        assert_eq!(d.cursor, 2);
        // Second `g` triggers the jump.
        assert!(matches!(dispatch(&mut d, 'g'), BrowseAction::Redraw));
        assert_eq!(d.cursor, 0);
    }

    #[test]
    fn handle_key_capital_g_jumps_cursor_to_bottom() {
        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Quiet, true);
        d.run_started(&["a".to_string(), "b".to_string(), "c".to_string()]);
        d.cursor = 0;

        assert!(matches!(dispatch(&mut d, 'G'), BrowseAction::Redraw));
        assert_eq!(d.cursor, 2);
    }

    #[test]
    fn handle_key_enter_toggles_expansion_at_cursor() {
        use crossterm::event::{KeyEvent, KeyModifiers};
        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Quiet, true);
        d.run_started(&["a".to_string(), "b".to_string()]);
        d.cursor = 1;
        assert!(!d.expanded[1]);

        d.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
        assert!(d.expanded[1]);
        assert!(!d.expanded[0], "only the cursor step should toggle");
        d.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
        assert!(!d.expanded[1], "second press should toggle off");
    }

    #[test]
    fn handle_key_o_toggles_same_as_enter() {
        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Quiet, true);
        d.run_started(&["a".to_string()]);
        assert!(!d.expanded[0]);
        dispatch(&mut d, 'o');
        assert!(d.expanded[0]);
    }

    #[test]
    fn handle_key_capital_o_toggles_expansion_for_all_steps() {
        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Quiet, true);
        d.run_started(&["a".to_string(), "b".to_string(), "c".to_string()]);
        assert!(d.expanded.iter().all(|e| !e));

        dispatch(&mut d, 'O');
        assert!(d.expanded.iter().all(|e| *e), "all should expand");
        dispatch(&mut d, 'O');
        assert!(d.expanded.iter().all(|e| !e), "all should collapse");
    }

    #[test]
    fn handle_key_q_returns_quit() {
        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Quiet, true);
        d.run_started(&["a".to_string()]);
        assert!(matches!(dispatch(&mut d, 'q'), BrowseAction::Quit));
    }

    #[test]
    fn handle_key_q_returns_quit_even_with_no_steps() {
        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Quiet, true);
        // No run_started → step_names is empty.
        assert!(matches!(dispatch(&mut d, 'q'), BrowseAction::Quit));
    }

    #[test]
    fn handle_key_r_returns_rerun() {
        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Quiet, true);
        d.run_started(&["a".to_string()]);
        assert!(matches!(dispatch(&mut d, 'r'), BrowseAction::Rerun));
    }

    #[test]
    fn handle_key_f_with_failures_returns_rerun_failed() {
        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Quiet, true);
        d.run_started(&["a".to_string()]);
        d.statuses[0] = StepStatus::Failed(Duration::from_secs(0), "boom".into());

        assert!(matches!(dispatch(&mut d, 'f'), BrowseAction::RerunFailed));
    }

    #[test]
    fn handle_key_f_without_failures_sets_transient_message_and_redraws() {
        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Quiet, true);
        d.run_started(&["a".to_string()]);
        d.statuses[0] = StepStatus::Passed(Duration::from_secs(0));

        assert!(matches!(dispatch(&mut d, 'f'), BrowseAction::Redraw));
        assert_eq!(
            d.transient_message.as_deref(),
            Some("no failures to re-run")
        );
    }

    #[test]
    fn handle_key_unknown_key_clears_visible_message_and_promotes_to_redraw() {
        let mut d = TtyDisplay::new(Theme::new(false), Verbosity::Quiet, true);
        d.run_started(&["a".to_string()]);
        d.transient_message = Some("stale".into());

        // `x` is unrecognised — would normally be Noop, but the visible
        // message needs a redraw to disappear.
        assert!(matches!(dispatch(&mut d, 'x'), BrowseAction::Redraw));
        assert!(d.transient_message.is_none());
    }

    #[test]
    fn redraw_strategy_skips_when_nothing_was_rendered() {
        // First paint of a run: leave whatever's on screen alone.
        assert_eq!(redraw_strategy(0, (80, 24), (80, 24)), RedrawStrategy::Skip,);
        // Skip wins even if the size also changed — there's still nothing
        // to erase.
        assert_eq!(
            redraw_strategy(0, (80, 24), (100, 30)),
            RedrawStrategy::Skip,
        );
    }

    #[test]
    fn redraw_strategy_uses_move_up_when_size_unchanged_and_fits() {
        assert_eq!(
            redraw_strategy(5, (80, 24), (80, 24)),
            RedrawStrategy::MoveUp(5),
        );
    }

    #[test]
    fn redraw_strategy_falls_back_to_full_clear_on_width_change() {
        assert_eq!(
            redraw_strategy(5, (80, 24), (100, 24)),
            RedrawStrategy::FullClear,
        );
    }

    #[test]
    fn redraw_strategy_falls_back_to_full_clear_on_height_change() {
        assert_eq!(
            redraw_strategy(5, (80, 24), (80, 30)),
            RedrawStrategy::FullClear,
        );
    }

    #[test]
    fn redraw_strategy_treats_first_call_as_size_change() {
        // last_size starts as (0, 0); any real terminal differs.
        assert_eq!(
            redraw_strategy(5, (0, 0), (80, 24)),
            RedrawStrategy::FullClear,
        );
    }

    #[test]
    fn redraw_strategy_falls_back_to_full_clear_when_rendered_exceeds_viewport() {
        // rendered_lines + 1 > term_height means MoveUp would have to enter
        // scrollback — fall back to full clear instead.
        assert_eq!(
            redraw_strategy(24, (80, 24), (80, 24)),
            RedrawStrategy::FullClear,
        );
        assert_eq!(
            redraw_strategy(100, (80, 24), (80, 24)),
            RedrawStrategy::FullClear,
        );
    }

    #[test]
    fn redraw_strategy_move_up_at_height_boundary() {
        // rendered_lines + 1 == term_height: previous render exactly fits
        // with one row of headroom; MoveUp is still safe.
        assert_eq!(
            redraw_strategy(23, (80, 24), (80, 24)),
            RedrawStrategy::MoveUp(23),
        );
    }

    /// restore_signals_and_output must turn OPOST and ISIG back on, even if
    /// they had been cleared (as crossterm's enable_raw_mode would).
    #[test]
    fn restore_signals_and_output_reenables_opost_and_isig() {
        use rustix::termios::{OptionalActions, tcsetattr};

        let pty = openpty(None, None).expect("openpty failed");
        let user = pty.user.as_fd();

        // Clear OPOST and ISIG to simulate raw-mode setup.
        let mut t = tcgetattr(user).unwrap();
        t.output_modes.remove(OutputModes::OPOST);
        t.local_modes.remove(LocalModes::ISIG);
        tcsetattr(user, OptionalActions::Now, &t).unwrap();

        terminal_io::restore_signals_and_output(user);

        let after = tcgetattr(user).unwrap();
        assert!(
            after.output_modes.contains(OutputModes::OPOST),
            "OPOST should be re-enabled"
        );
        assert!(
            after.local_modes.contains(LocalModes::ISIG),
            "ISIG should be re-enabled"
        );
    }
}