dextui 0.1.0

A two-pane terminal UI for browsing and triaging dex tasks
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
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
//! Immediate-mode rendering. Everything is redrawn from `App` each frame.
//!
//! This is the only module that knows about colour: `markdown` and `tree` emit
//! neutral descriptions of what things *are*, and this module decides how they
//! look.

use ratatui::layout::{Constraint, Layout, Position, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{
    Block, Clear, List, ListItem, ListState, Paragraph, Scrollbar, ScrollbarOrientation,
    ScrollbarState, Wrap,
};
use ratatui::Frame;

use crate::app::{App, Counts, Focus, HeaderZone, Mode};

/// Colour is used only where it carries meaning. Everything else is left to the
/// terminal, so the app inherits whatever scheme the user runs -- including a
/// light/dark switch at runtime -- instead of imposing its own. The values live
/// in `theme`; this module decides where they go.
use crate::theme::{
    ACCENT, ACCENT_DIM, ACTIVE, BLOCKED, CODE, DIM, DONE, PLAIN, TODO,
};

use crate::icons::Icons;
use crate::dex::{self, age, local_time, Status, Task};
use crate::tree::{self, Progress};

const SHORTCUTS: &str =
    " s start  c done  r rename  e edit  n new  a sub  d del  f filter  o sort  , config  ? help";

/// Width of the inline progress meter, in cells.
const METER_WIDTH: usize = 7;

/// What separates the header's parts, and the detail pane's summary fields.
/// Named because the header's width arithmetic has to account for it, and a
/// bare `+ 3` there is a number nobody can check.
const SEP: &str = " · ";

pub fn draw(frame: &mut Frame, app: &mut App, ic: &Icons) {
    let [top, body, bottom] = Layout::vertical([
        Constraint::Length(1),
        Constraint::Min(0),
        Constraint::Length(1),
    ])
    .areas(frame.area());

    // Set before anything consults `single_pane`, the header included: it reads
    // the published width, and on the first frame -- or the one after a resize --
    // a stale value picks the wrong layout for exactly one frame. The header
    // asks earliest of all, to decide whether to draw the pane tabs.
    app.terminal_width = frame.area().width;
    app.body_top = body.y;
    app.body_bottom = body.y + body.height;

    draw_header(frame, app, ic, top);

    if app.single_pane() {
        // One pane, filling the width, chosen by focus. There is no divider, so
        // `divider_x = 0` makes `App::on_divider` false and a drag inert --
        // rather than leaving a stale x from the last wide frame, which would be
        // an invisible drag target in the middle of the screen.
        app.divider_x = 0;
        match app.focus {
            Focus::Tree => draw_tree(frame, app, ic, body),
            Focus::Detail => draw_detail(frame, app, ic, body),
        }
        draw_status(frame, app, bottom);
        draw_overlays(frame, app);
        return;
    }

    let [left, right] =
        Layout::horizontal([Constraint::Percentage(app.split_percent), Constraint::Fill(1)])
            .areas(body);

    // Published for mouse handling: the divider sits where the two borders meet.
    app.divider_x = right.x;

    draw_tree(frame, app, ic, left);
    draw_detail(frame, app, ic, right);
    draw_status(frame, app, bottom);
    draw_overlays(frame, app);
}

/// Dialogs, drawn last so they sit over whichever layout was used.
fn draw_overlays(frame: &mut Frame, app: &App) {
    match &app.mode {
        Mode::Prompt(prompt) => draw_prompt(frame, prompt),
        Mode::Confirm { message, .. } => draw_message(
            frame,
            "Delete task",
            message,
            "enter delete    esc cancel",
            BLOCKED,
        ),
        Mode::ForceComplete { message, .. } => draw_message(
            frame,
            "Incomplete subtasks",
            message,
            "enter force    esc cancel",
            ACTIVE,
        ),
        Mode::Error(e) => draw_message(frame, "dex error", e, "any key to dismiss", BLOCKED),
        Mode::Help => draw_help(frame),
        _ => {}
    }
}

fn glyph(s: Status, ic: &Icons) -> &'static str {
    match s {
        Status::Completed => ic.done,
        Status::InProgress => ic.active,
        Status::Blocked => ic.blocked,
        Status::Pending => ic.pending,
    }
}

/// The marker for a tree row, turning if it is in progress and turning is on.
///
/// `frame` is `None` when nothing is animating -- animation switched off, or no
/// task running -- and the marker falls back to the still `ic.active`. That
/// still glyph is deliberately *not* one of the spinner's frames: it has to read
/// as "in progress" without any motion to help it, which a play triangle does
/// and a single braille dot does not.
///
/// Only tree rows turn. Everywhere the state is *named* rather than watched --
/// the header counts, the help legend -- keeps `ic.active`, because a glyph
/// changing under a static label reads as a fault.
fn row_glyph(s: Status, ic: &Icons, frame: Option<usize>) -> &'static str {
    match (s, frame) {
        (Status::InProgress, Some(f)) if !ic.spin.is_empty() => ic.spin[f % ic.spin.len()],
        _ => glyph(s, ic),
    }
}

fn status_color(s: Status) -> Color {
    match s {
        Status::Completed => DONE,
        Status::InProgress => ACTIVE,
        Status::Blocked => BLOCKED,
        Status::Pending => TODO,
    }
}

/// The status marker's colour: its state's, and nothing else.
///
/// Colour used to carry the animation, alternating with a bright variant. Motion
/// now lives in the glyph (see [`row_glyph`]), so this holds still -- animating
/// both would make one marker say the same thing twice, and loudly.
fn status_style(s: Status) -> Style {
    Style::default().fg(status_color(s))
}

/// How a stacked bar divides into cells. Tier-independent: the glyph table in
/// `icons` decides what each cell looks like, this decides how many there are.
///
/// Width is a parameter rather than `METER_WIDTH` so a wider bar can reuse it.
#[derive(Debug, Clone, Copy)]
struct Bar {
    done: usize,
    active: usize,
    /// Eighths of a cell spilling past the last whole one, `0..=7`. Drawn once,
    /// at the outer edge, in the colour of the run it extends.
    partial: usize,
    empty: usize,
}

impl Bar {
    /// Both coloured runs are laid out from one rounding of their *combined*
    /// extent, not two separate ones. That is what keeps the sub-cell remainder
    /// at the outer edge: rounding each run on its own would put a fraction at
    /// the done->active boundary too, and colouring that cell would need a
    /// background (fg=green on bg=blue), which the colour policy forbids and the
    /// selected row's styling would invert. So done->active always snaps.
    fn new(progress: Progress, width: usize, partials: bool) -> Bar {
        let Progress {
            done,
            active,
            total,
        } = progress;

        if total == 0 || done + active == 0 {
            return Bar {
                done: 0,
                active: 0,
                partial: 0,
                empty: width,
            };
        }

        let eighths = |n: usize| (n as f64 / total as f64 * width as f64 * 8.0).round() as usize;

        // Anything non-zero gets at least a whole cell, so a single finished or
        // in-flight subtask out of a hundred is never rounded away to nothing.
        let floor = (usize::from(done > 0) + usize::from(active > 0)) * 8;
        let mut outer = eighths(done + active).clamp(floor, width * 8);
        if !partials {
            // No sub-cell glyphs in this tier, so snap to the nearest cell. Both
            // clamp bounds are multiples of 8, so this stays inside them.
            outer = (outer as f64 / 8.0).round() as usize * 8;
        }

        let whole = outer / 8;
        let partial = outer % 8;

        // `whole >= 1` per non-zero run, from the floor above, so neither
        // subtraction can wrap.
        let done_cells = if done == 0 {
            0
        } else if active == 0 {
            // Every whole cell is done's. Without this the snap above can push
            // `outer` past done's own rounding, and the leftover would be handed
            // to `active` -- drawing an in-flight cell for a task with nothing
            // started, which contradicts the row's own status glyph.
            whole
        } else {
            let want = ((done as f64 / total as f64) * width as f64).round().max(1.0) as usize;
            want.min(whole - 1)
        };

        Bar {
            done: done_cells,
            active: whole - done_cells,
            partial,
            // `partial` is 0 whenever `whole == width`, since `outer` is capped
            // at `width * 8`.
            empty: width - whole - usize::from(partial > 0),
        }
    }
}

/// Which of `[left cap, middle, right cap]` a cell at `i` draws.
fn cap(i: usize, width: usize) -> usize {
    if i == 0 {
        0
    } else if i + 1 == width {
        2
    } else {
        1
    }
}

/// A compact meter plus the raw fraction, e.g. `██▋░░░░ 3/8`.
///
/// dex-report's stacked bar, in the colours the rest of the UI uses: green for
/// done, blue for in flight, dim for untouched.
///
/// The number is shown alongside the bar on purpose: at seven cells a bar cannot
/// distinguish 2/7 from 3/7, and for triage the exact count is the useful part.
fn meter_spans(progress: Progress, ic: &Icons) -> Vec<Span<'static>> {
    let mut spans = bar_spans(progress, ic, METER_WIDTH);
    spans.push(Span::styled(
        format!(" {}/{}", progress.done, progress.total),
        Style::default().fg(DIM),
    ));
    spans
}

/// The bar alone, at any width. The header draws one too, without the fraction.
fn bar_spans(progress: Progress, ic: &Icons, width: usize) -> Vec<Span<'static>> {
    let m = &ic.meter;
    let bar = Bar::new(progress, width, !m.partial.is_empty());

    let run = |glyphs: [&'static str; 3], from: usize, len: usize| -> String {
        (from..from + len).map(|i| glyphs[cap(i, width)]).collect()
    };

    let mut spans = Vec::new();
    let mut at = 0;

    if bar.done > 0 {
        spans.push(Span::styled(
            run(m.done, at, bar.done),
            Style::default().fg(DONE),
        ));
        at += bar.done;
    }
    if bar.active > 0 {
        spans.push(Span::styled(
            run(m.active, at, bar.active),
            Style::default().fg(ACTIVE),
        ));
        at += bar.active;
    }
    if bar.partial > 0 {
        // Extends whichever run reaches the outer edge, so the fraction reads
        // as more of that state rather than as a state of its own.
        let fg = if bar.active > 0 { ACTIVE } else { DONE };
        spans.push(Span::styled(m.partial[bar.partial - 1], Style::default().fg(fg)));
        at += 1;
    }
    if bar.empty > 0 {
        spans.push(Span::styled(
            run(m.empty, at, bar.empty),
            Style::default().fg(DIM),
        ));
    }

    spans
}

/// The header's count block, widest layout that fits in `room` cells.
///
/// Dropped in order of what carries least: the bar first, then the percentage,
/// then the words -- at which point the status glyphs stand in for them, which
/// is why the tier is needed here. A zero `active` or `blocked` is omitted
/// rather than shown as `0`, following dex-report.
///
/// Returns one group per `·`-separated part; the caller inserts the separators.
/// Cells a run of spans will occupy.
fn span_width(spans: &[Span]) -> usize {
    spans.iter().map(|s| s.content.chars().count()).sum()
}

/// What a `·`-separated group of parts will occupy once the caller has joined
/// them, separators included.
///
/// Shared with the test that asserts the header never exceeds its room -- if the
/// test re-derived this, the two would agree about a wrong answer and it would
/// prove nothing.
fn parts_width(parts: &[Vec<Span<'static>>]) -> usize {
    parts.iter().map(|p| span_width(p)).sum::<usize>() + parts.len() * SEP.chars().count()
}

/// The narrowest room in which the counts still draw something.
///
/// Every rung of the header's ladder reserves this much, so the right-hand menu
/// can never outbid the numbers the header exists to show.
fn counts_floor(c: Counts, ic: &Icons) -> usize {
    count_candidates(c, ic)
        .iter()
        .filter(|parts| !parts.is_empty())
        .map(|parts| parts_width(parts))
        .min()
        .unwrap_or(0)
}

/// Where each clickable word of the right-hand block ended up.
///
/// Derived by walking the spans that were *actually rendered*, so the header's
/// degradation ladder does not need restating here -- a rung that dropped the
/// menu simply contains no filter words, and one that dropped the sort contains
/// no sort word. The block's vocabulary is closed and tiny (one sort label plus
/// filter names, which never collide), so matching on content is exact.
///
/// A single filter word means the header fell back to naming the current filter
/// with no menu around it. There is nothing to pick from, so that word cycles.
fn right_zones(right: &[Span], x0: u16, sort_label: &str) -> Vec<(u16, u16, HeaderZone)> {
    let mut found: Vec<(u16, u16, HeaderZone)> = Vec::new();
    let mut x = x0;

    for span in right {
        let w = span.content.chars().count() as u16;
        if w > 0 {
            let zone = if span.content == sort_label {
                Some(HeaderZone::Sort)
            } else if let Some(pane) = tab_zone(&span.content) {
                Some(pane)
            } else {
                tree::Filter::MENU
                    .iter()
                    .find(|f| f.name() == span.content)
                    .map(|f| HeaderZone::Filter(*f))
            };
            if let Some(z) = zone {
                found.push((x, x + w - 1, z));
            }
        }
        x += w;
    }

    let filters = found
        .iter()
        .filter(|(_, _, z)| matches!(z, HeaderZone::Filter(_)))
        .count();
    if filters == 1 {
        for entry in found.iter_mut() {
            if matches!(entry.2, HeaderZone::Filter(_)) {
                entry.2 = HeaderZone::FilterCycle;
            }
        }
    }
    found
}

/// Which pane a drawn tab span selects, if it is one.
///
/// Matched on content like every other zone here, so a tab that was not drawn
/// offers nothing to click. The vocabulary is four strings and cannot collide
/// with a sort label or a filter name.
fn tab_zone(content: &str) -> Option<HeaderZone> {
    match content {
        "[1]" | " 1 " => Some(HeaderZone::Pane(Focus::Tree)),
        "[2]" | " 2 " => Some(HeaderZone::Pane(Focus::Detail)),
        _ => None,
    }
}

/// The pane tabs, `[1] 2`, drawn only when one pane is hidden.
///
/// LazyGit and gitui both number their panels so you can jump straight to one.
/// The same idea earns its place here only in zoom mode: with both panes on
/// screen there is nothing to navigate *to*, and the numbers would be
/// decoration competing for a row that already sheds elements to fit.
///
/// Both states are three cells wide -- `[1]` against ` 2 ` -- so switching tabs
/// cannot shift anything else in the header sideways.
fn tab_spans(focus: Focus) -> Vec<Span<'static>> {
    let mut out = vec![Span::raw(" ")];
    for (n, f) in [(1, Focus::Tree), (2, Focus::Detail)] {
        if f == focus {
            out.push(Span::styled(
                format!("[{n}]"),
                Style::default().add_modifier(Modifier::BOLD),
            ));
        } else {
            out.push(Span::styled(format!(" {n} "), Style::default().fg(DIM)));
        }
    }
    out
}

/// One filter's name, marked if it is the one in force.
///
/// The mark is weight plus the colour of the state it shows -- yellow for
/// pending, blue for active -- so the menu speaks the same colour language as
/// the rows beneath it. `all` is not a state and gets no colour of its own; it
/// is marked by weight alone.
///
/// This replaced UPPERCASING the active one, which was the only mark available
/// when the whole menu was a single baked string.
fn filter_name(f: tree::Filter, current: bool) -> Span<'static> {
    if !current {
        return Span::styled(f.name(), Style::default().fg(DIM));
    }
    let fg = match f {
        tree::Filter::Pending => TODO,
        tree::Filter::InProgress => ACTIVE,
        tree::Filter::All => PLAIN,
    };
    Span::styled(f.name(), Style::default().fg(fg).add_modifier(Modifier::BOLD))
}

/// The whole menu, `[ all  pending  active ]`, as one span per word.
///
/// Per-word spans are what let the current one be styled differently *and* what
/// let a click be resolved to the word under it -- the two asks that produced
/// this turned out to need the same thing.
fn filter_menu(current: tree::Filter) -> Vec<Span<'static>> {
    let dim = || Style::default().fg(DIM);
    let mut spans = vec![Span::styled("[ ", dim())];
    for (i, f) in tree::Filter::MENU.iter().enumerate() {
        if i > 0 {
            spans.push(Span::raw("  "));
        }
        spans.push(filter_name(*f, *f == current));
    }
    spans.push(Span::styled(" ]", dim()));
    spans
}

/// A leading icon and its trailing space, or nothing in the tiers that have none.
fn icon_span(glyph: &str) -> Vec<Span<'static>> {
    if glyph.is_empty() {
        Vec::new()
    } else {
        vec![Span::styled(
            format!("{glyph} "),
            Style::default().fg(DIM),
        )]
    }
}

/// The narrowest identity worth drawing: which store you are in, and nothing
/// else. The right-hand block yields to this rather than the reverse.
fn identity_store(store: &str, ic: &Icons) -> Vec<Span<'static>> {
    [
        vec![Span::raw(" ")],
        icon_span(ic.project),
        vec![Span::styled(store.to_string(), Style::default().fg(PLAIN))],
    ]
    .concat()
}

/// App identity plus the store, dropped to just the store when the row is tight.
///
/// "Wrong tasks" is this app's most common confusion -- dex resolves its store
/// from the working directory and falls back to a global one outside a git repo
/// -- and this label is the only thing on screen that answers it. The app's own
/// name goes first: you know what you launched.
fn header_identity(store: &str, ic: &Icons, room: usize) -> Vec<Span<'static>> {
    let full = [
        vec![Span::raw(" ")],
        icon_span(ic.app),
        vec![
            Span::styled("dextui", Style::default().add_modifier(Modifier::BOLD)),
            Span::styled(SEP, Style::default().fg(DIM)),
        ],
        icon_span(ic.project),
        vec![Span::styled(store.to_string(), Style::default().fg(PLAIN))],
    ]
    .concat();

    for candidate in [full, identity_store(store, ic)] {
        if span_width(&candidate) <= room {
            return candidate;
        }
    }

    // Last resort: the label alone, elided, so a clipped one cannot be mistaken
    // for a whole one -- which is exactly how `dexA-Z` used to read.
    let keep = room.saturating_sub(2); // the leading space, and the ellipsis
    if keep == 0 {
        return Vec::new();
    }
    let short: String = store.chars().take(keep).collect();
    let text = if short.chars().count() < store.chars().count() {
        format!("{short}")
    } else {
        short
    };
    vec![
        Span::raw(" "),
        Span::styled(text, Style::default().fg(PLAIN)),
    ]
}

/// The sort order and filter, hard right, widest first. They shed what carries
/// least: the menu collapses to the active filter's name, then the sort order
/// goes, because it only reorders what you can already see.
///
/// The leading space is a gutter this block owns, so the left side can fill its
/// own Rect to the last cell without the two ending up flush against each other
/// -- which read as `2 readyA-Z` and looked exactly like the overlap this
/// replaced.
fn right_candidates(sort: &str, filter: tree::Filter) -> [Vec<Span<'static>>; 4] {
    let dim = || Style::default().fg(DIM);
    let with_sort = |rest: Vec<Span<'static>>| -> Vec<Span<'static>> {
        [
            vec![
                Span::raw(" "),
                Span::styled(sort.to_string(), dim()),
                Span::raw("  "),
            ],
            rest,
            vec![Span::raw(" ")],
        ]
        .concat()
    };

    [
        with_sort(filter_menu(filter)),
        with_sort(vec![filter_name(filter, true)]),
        vec![Span::raw(" "), filter_name(filter, true), Span::raw(" ")],
        Vec::new(),
    ]
}

/// The two ends of the header, chosen as a pair.
///
/// Sizing them one after the other looks obvious and is wrong. The right-hand
/// block's steps are large -- a 24-cell menu collapsing to a 3-cell name -- so
/// narrowing the terminal can free more room than the narrowing cost, and an
/// element already dropped would come *back*: at 44 columns the app name was
/// gone and at 36 it was there again. Choosing from one ladder fixes that
/// structurally rather than arithmetically. Every element occupies a *prefix* of
/// the ladder and the ladder descends in width, so first-fit can only ever shed.
///
/// The order encodes what each fact is worth. The store label is in every rung
/// (see `identity_store`). Which filter is active outlives the menu around it and
/// outlives the sort order, because it is the only one of the three that changes
/// *what you can see*. The app's own name outlives none of them: you know what
/// you launched.
fn header_sides(
    store: &str,
    ic: &Icons,
    sort: &str,
    filter: tree::Filter,
    counts_floor: usize,
    width: usize,
) -> (Vec<Span<'static>>, Vec<Span<'static>>) {
    let full = header_identity(store, ic, usize::MAX);
    let short = identity_store(store, ic);
    let rights = right_candidates(sort, filter);

    // Every rung leaves the counts room to say *something*. Without that the
    // 24-cell menu outbid them: at 52 columns the header showed the whole filter
    // menu and no numbers at all, while at 44 it showed "2 ready" -- so widening
    // the terminal lost the headline. The menu is an affordance for a key you
    // press; the numbers are what the header is for.
    for (ident, right) in [
        (&full, &rights[0]),
        (&full, &rights[1]),
        (&short, &rights[1]),
        (&short, &rights[2]),
        (&short, &rights[3]),
    ] {
        if span_width(ident) + span_width(right) + counts_floor <= width {
            return (ident.clone(), right.clone());
        }
    }

    // Too narrow for any of that. The label alone still beats an elided one.
    if span_width(&short) <= width {
        return (short, Vec::new());
    }
    (header_identity(store, ic, width), Vec::new())
}

/// Every layout the counts can take, widest first, ending in nothing.
///
/// Built once and shared by both callers: [`header_counts`] takes the first that
/// fits, and [`counts_floor`] measures the narrowest that still says something.
fn count_candidates(c: Counts, ic: &Icons) -> Vec<Vec<Vec<Span<'static>>>> {
    const BAR: usize = 10;

    let numbers = |worded: bool| -> Vec<Vec<Span<'static>>> {
        let mut out: Vec<Vec<Span<'static>>> = Vec::new();
        let mut push = |n: usize, word: &str, glyph: &'static str, fg: Color| {
            let text = if worded {
                format!("{n} {word}")
            } else {
                format!("{glyph} {n}")
            };
            out.push(vec![Span::styled(text, Style::default().fg(fg))]);
        };
        if c.active > 0 {
            push(c.active, "active", ic.active, ACTIVE);
        }
        push(c.ready, "ready", ic.pending, TODO);
        if c.blocked > 0 {
            push(c.blocked, "blocked", ic.blocked, BLOCKED);
        }
        out
    };

    let pct = || -> Vec<Span<'static>> {
        vec![Span::styled(
            format!("{}%", c.percent),
            Style::default().add_modifier(Modifier::BOLD),
        )]
    };

    let bar = || -> Vec<Span<'static>> {
        let mut s = bar_spans(
            Progress {
                done: c.completed,
                active: c.active,
                total: c.total,
            },
            ic,
            BAR,
        );
        s.push(Span::raw(" "));
        s.extend(pct());
        s
    };

    vec![
        [vec![bar()], numbers(true)].concat(),
        [vec![pct()], numbers(true)].concat(),
        numbers(true),
        numbers(false),
        vec![pct()],
        vec![],
    ]
}

/// The widest layout of the counts that fits in `room`.
fn header_counts(c: Counts, room: usize, ic: &Icons) -> Vec<Vec<Span<'static>>> {
    for parts in count_candidates(c, ic) {
        if parts_width(&parts) <= room {
            return parts;
        }
    }
    Vec::new()
}

/// The header: app identity, which store you are in, and what is outstanding.
///
/// Plain text with dim separators, no coloured bands. The app does not impose a
/// look; the terminal's own scheme shows through.
///
/// While searching, the search box takes the whole line over. That is why the
/// header costs no vertical space: the two are never needed at once.
fn draw_header(frame: &mut Frame, app: &mut App, ic: &Icons, area: Rect) {
    // Nothing in the header is on screen while the search box owns the row, so a
    // stale zone would act on a menu that is not there.
    app.header_zones.clear();

    if matches!(app.mode, Mode::Search) {
        frame.render_widget(
            Paragraph::new(Line::from(vec![
                Span::styled(" search ", Style::default().fg(DIM)),
                Span::styled(app.query.value.clone(), Style::default().fg(ACTIVE)),
            ])),
            area,
        );
        frame.set_cursor_position(Position {
            x: (area.x + 8 + app.query.cursor as u16).min(area.right().saturating_sub(1)),
            y: area.y,
        });
        return;
    }

    let c = app.counts();
    let sep = || Span::styled(SEP, Style::default().fg(DIM));

    // These were once two Paragraphs over the *same* Rect -- identity left,
    // sort/filter right-aligned -- with only the counts reserving any room for
    // the other. Below ~48 columns they overwrote each other: the store label
    // vanished leaving a dangling " · ", and narrower still the row read
    // `dexA-Z`. Splitting the row first means an overlap cannot be expressed,
    // and each side is then free to degrade honestly inside its own space.
    // Reserved before the ladder runs rather than competing inside it, so the
    // tabs outlive the sort label and the filter menu. In zoom mode they are the
    // only thing on screen saying the other pane exists; a rung that dropped
    // them would hide the way back.
    // Room the identity needs to say *something* -- a glyph, a letter or two of
    // the store, an ellipsis. Below that the tabs would take the whole row and
    // the store label would vanish with nothing marking it as clipped, which
    // the ladder's own rule forbids: the label is in every rung because "wrong
    // tasks" is this app's most common confusion.
    const IDENTITY_FLOOR: usize = 8;

    let tabs = match app.single_pane() {
        true => tab_spans(app.focus),
        false => Vec::new(),
    };
    let tabs = if span_width(&tabs) + IDENTITY_FLOOR <= area.width as usize {
        tabs
    } else {
        Vec::new()
    };

    let (mut spans, right) = header_sides(
        &app.store_label,
        ic,
        app.sort.label(app.sort_reversed),
        app.filter,
        counts_floor(c, ic),
        (area.width as usize).saturating_sub(span_width(&tabs)),
    );
    let right = [tabs, right].concat();
    let [left_area, right_area] = Layout::horizontal([
        Constraint::Min(0),
        Constraint::Length(span_width(&right) as u16),
    ])
    .areas(area);

    // Whatever the pair left over goes to the counts, which are built to shed.
    let room = (left_area.width as usize).saturating_sub(span_width(&spans));
    for part in header_counts(c, room, ic) {
        spans.push(sep());
        spans.extend(part);
    }

    app.header_zones = right_zones(&right, right_area.x, app.sort.label(app.sort_reversed));

    frame.render_widget(Paragraph::new(Line::from(spans)), left_area);
    frame.render_widget(Paragraph::new(Line::from(right)), right_area);
}

fn draw_tree(frame: &mut Frame, app: &mut App, ic: &Icons, area: Rect) {
    // No title: the header already says which store this is, and repeating it
    // on the pane border was the same fact twice.
    let block = Block::bordered().border_style(Style::default().fg(if app.focus
        == Focus::Tree
    {
        PLAIN
    } else {
        DIM
    }));

    let inner_width = area.width.saturating_sub(2) as usize;
    let rows = tree::visible_rows(&app.tree, &app.expanded);

    // Hoisted: `selected_row` rebuilds the visible-row list on every call, so
    // asking per row would make each frame quadratic in the size of the tree.
    let selected = app.selected_row();
    let accent = if app.focus == Focus::Tree {
        ACCENT
    } else {
        ACCENT_DIM
    };

    // Once per frame, not per row: this scans every task.
    let spin = app.is_animating().then_some(app.spin_frame);

    let items: Vec<ListItem> = rows
        .iter()
        .enumerate()
        .map(|(i, row)| {
            let t = &row.node.task;
            let is_selected = selected == Some(i);
            // Once per row: deriving this resolves every blocker against the
            // store, and the row needs it three times over.
            let st = dex::status(t, &app.by_id);

            let mut spans = vec![
                // Always two cells, drawn or not, so selecting a row cannot
                // shift its name out of the column its siblings sit in.
                if is_selected {
                    Span::styled(format!("{} ", ic.gutter), Style::default().fg(accent))
                } else {
                    Span::raw("  ")
                },
                Span::styled(row.prefix.clone(), Style::default().fg(DIM)),
                Span::styled(
                    format!("{} ", ic.marker(row.has_children, row.is_open)),
                    Style::default().fg(DIM),
                ),
                Span::styled(
                    format!("{} ", row_glyph(st, ic, spin)),
                    status_style(st),
                ),
            ];

            let mut name_style = if !row.node.is_match {
                // Scaffolding: kept only because a descendant matched.
                Style::default().fg(DIM)
            } else if t.completed {
                Style::default()
                    .fg(DIM)
                    .add_modifier(Modifier::CROSSED_OUT)
            } else {
                Style::default().fg(PLAIN)
            };
            // Weight, not colour: the name has no colour of its own to brighten,
            // and bold is the one emphasis that survives a dim or struck-through
            // name. It stays on when the pane loses focus, so the selection is
            // still findable while you are reading the detail pane.
            if is_selected {
                name_style = name_style.add_modifier(Modifier::BOLD);
            }

            spans.push(Span::styled(t.name.clone(), name_style));

            // Only when the status glyph cannot carry it itself. A started task
            // that is also blocked reads as in progress -- dex's precedence --
            // so there the trailing marker is the only signal. Repeating it on
            // a row whose glyph already says blocked is just noise.
            if st != Status::Blocked && dex::is_blocked(t, &app.by_id) {
                spans.push(Span::styled(
                    format!(" {}", ic.blocked),
                    Style::default().fg(BLOCKED),
                ));
            }

            // Right gutter: a rollup for parents, otherwise how long this has been
            // in flight. Only in-progress tasks get an age -- putting one on every
            // row would bury the signal it exists to give.
            let trailing: Vec<Span> = match app.progress.get(&t.id) {
                Some(progress) => meter_spans(*progress, ic),
                None if t.is_in_progress() => match age(&t.started_at) {
                    Some(a) => vec![Span::styled(a, Style::default().fg(ACTIVE))],
                    None => vec![],
                },
                None => vec![],
            };

            if !trailing.is_empty() {
                let used = span_width(&spans);
                let tail = span_width(&trailing);
                // Drop the gutter rather than wrap when the pane is too narrow.
                if used + tail + 2 <= inner_width {
                    spans.push(Span::raw(" ".repeat(inner_width - used - tail)));
                    spans.extend(trailing);
                }
            }

            ListItem::new(Line::from(spans))
        })
        .collect();

    // The offset is carried across frames rather than recomputed from zero, so
    // the list does not jump and a click maps to the row actually on screen.
    let mut state = ListState::default().with_offset(app.tree_offset);
    // Still selected even though the highlight draws nothing: this is what
    // scrolls the selection into view, and what keeps `tree_offset` truthful so
    // a click lands on the row actually drawn.
    state.select(selected);

    // No `highlight_style`, and no `highlight_symbol`. The row builds its own
    // cursor above, for two reasons. `highlight_style` is stamped across the
    // whole row *after* the item renders, so it could only ever emphasise the
    // meter and the status glyph along with the name -- which is what ruled out
    // the REVERSED this replaces. And `highlight_symbol` narrows the item area
    // by the symbol's width while the right-hand gutter here is measured against
    // the full inner width, so the meter would be pushed off the right edge.
    frame.render_stateful_widget(List::new(items).block(block), area, &mut state);

    app.tree_offset = state.offset();

    // Only worth drawing when there is something off-screen.
    let visible = area.height.saturating_sub(2) as usize;
    if rows.len() > visible {
        let mut sb = ScrollbarState::new(rows.len()).position(app.selected_row().unwrap_or(0));
        frame.render_stateful_widget(
            Scrollbar::new(ScrollbarOrientation::VerticalRight)
                .begin_symbol(None)
                .end_symbol(None)
                .track_style(Style::default().fg(DIM))
                .thumb_style(Style::default().fg(DIM)),
            area,
            &mut sb,
        );
    }
}

/// Rows the content will occupy once wrapped.
///
/// Character-wrapping is assumed, which can under-count against ratatui's
/// word-wrapping, so a small allowance is added: over-estimating merely lets you
/// scroll into blank space, whereas under-estimating would make the last line
/// unreachable.
fn wrapped_height(line_widths: &[u16], width: u16, wrap: bool) -> u16 {
    if !wrap || width == 0 {
        return line_widths.len() as u16;
    }

    let rows: u16 = line_widths
        .iter()
        .map(|w| if *w == 0 { 1 } else { w.div_ceil(width) })
        .sum();

    rows.saturating_add(2)
}

fn draw_detail(frame: &mut Frame, app: &mut App, ic: &Icons, area: Rect) {
    let focused = app.focus == Focus::Detail;
    let block = Block::bordered()
        .title(if app.wrap { "" } else { " no wrap " })
        .title_style(Style::default().fg(DIM))
        .border_style(Style::default().fg(if focused { PLAIN } else { DIM }));

    let inner_w = area.width.saturating_sub(2);
    let inner_h = area.height.saturating_sub(2);
    let scroll = app.detail_scroll;
    let wrap = app.wrap;

    let Some(task) = app.selected_task().cloned() else {
        let msg = if app.tasks.is_empty() {
            "No tasks yet.\n\nPress n to create one."
        } else {
            "No tasks match the current filter.\n\nPress f to change it, or clear the search."
        };
        frame.render_widget(
            Paragraph::new(msg)
                .block(block)
                .style(Style::default().fg(DIM))
                .wrap(Wrap { trim: false }),
            area,
        );
        app.detail_content_height = 0;
        app.detail_viewport_height = inner_h;
        return;
    };

    // Rendered inside its own scope: the lines borrow `app`, and the measured
    // heights cannot be written back until that borrow ends.
    let content_h = {
        let lines = detail_lines(&task, app, ic);
        let widths: Vec<u16> = lines.iter().map(|l| l.width() as u16).collect();
        let height = wrapped_height(&widths, inner_w, wrap);

        let mut paragraph = Paragraph::new(lines).scroll(scroll);
        if wrap {
            paragraph = paragraph.wrap(Wrap { trim: false });
        }
        frame.render_widget(paragraph.block(block), area);
        height
    };

    app.detail_content_height = content_h;
    app.detail_viewport_height = inner_h;

    if content_h > inner_h {
        let mut sb = ScrollbarState::new(content_h.saturating_sub(inner_h) as usize)
            .position(scroll.0 as usize);
        frame.render_stateful_widget(
            Scrollbar::new(ScrollbarOrientation::VerticalRight)
                .begin_symbol(None)
                .end_symbol(None)
                .track_style(Style::default().fg(DIM))
                .thumb_style(Style::default().fg(PLAIN)),
            area,
            &mut sb,
        );
    }
}

/// An age from `dex::age` phrased as time elapsed. Anything under a minute comes
/// back as "now", and "now ago" is not a duration -- it reads as a bug. Both the
/// in-progress summary and the absolute timestamps go through here, because when
/// only one of them did they contradicted each other about the same instant.
///
/// The bare "now" is still what the *tree rows* show, where there is no suffix
/// and a column of ages has to stay narrow.
fn since(age: &str) -> String {
    if age == "now" {
        "just now".to_string()
    } else {
        format!("{age} ago")
    }
}

/// Built entirely from the already-fetched list. `dex show` is never called,
/// because selection changes on every arrow key and a ~180ms process spawn per
/// keypress would make navigation unusable.
fn detail_lines<'a>(t: &'a Task, app: &'a App, ic: &Icons) -> Vec<Line<'a>> {
    let mut lines = vec![
        Line::from(Span::styled(
            t.name.clone(),
            Style::default().fg(PLAIN).add_modifier(Modifier::BOLD),
        )),
        Line::from(Span::styled(
            "".repeat(t.name.chars().count().clamp(8, 60)),
            Style::default().fg(DIM),
        )),
    ];

    // One status line reads faster than three separate label/value rows.
    let st = dex::status(t, &app.by_id);
    let mut summary = vec![Span::styled(
        format!("{} {}", glyph(st, ic), st.label()),
        Style::default().fg(status_color(st)),
    )];

    if t.is_in_progress()
        && let Some(a) = age(&t.started_at) {
            summary.push(Span::styled(SEP, Style::default().fg(DIM)));
            summary.push(Span::styled(
                format!("started {}", since(&a)),
                Style::default().fg(ACTIVE),
            ));
        }

    // How long it actually took, which reads better than two raw timestamps.
    if let Some(took) = t.worked_duration() {
        summary.push(Span::styled(SEP, Style::default().fg(DIM)));
        summary.push(Span::styled(
            format!("took {took}"),
            Style::default().fg(DONE),
        ));
    }

    summary.push(Span::styled(SEP, Style::default().fg(DIM)));
    summary.push(Span::styled(
        format!("priority {}", t.priority),
        Style::default().fg(DIM),
    ));
    lines.push(Line::from(summary));

    if let Some(progress) = app.progress.get(&t.id) {
        lines.push(Line::from(""));
        let mut row = meter_spans(*progress, ic);
        row.push(Span::styled(
            format!(
                "  subtask{} done",
                if progress.total == 1 { "" } else { "s" }
            ),
            Style::default().fg(DIM),
        ));
        lines.push(Line::from(row));
    }

    lines.push(Line::from(""));

    let mut field = |k: &str, v: String, style: Style| {
        lines.push(Line::from(vec![
            Span::styled(format!("{k:<10}"), Style::default().fg(DIM)),
            Span::styled(v, style),
        ]));
    };

    field("id", t.id.clone(), Style::default().fg(DIM));

    if let Some(parent) = t.parent_id.as_ref().and_then(|id| app.by_id.get(id)) {
        field("parent", parent.name.clone(), Style::default().fg(PLAIN));
    }

    if dex::is_blocked(t, &app.by_id) {
        let names: Vec<String> = t
            .blocked_by
            .iter()
            .map(|id| {
                app.by_id
                    .get(id)
                    .map(|b| b.name.clone())
                    .unwrap_or_else(|| id.clone())
            })
            .collect();
        field("blocked", names.join(", "), Style::default().fg(BLOCKED));
    }

    // The reverse relationship. A task holding up three others is a priority
    // signal that `blocked by` alone cannot show.
    if !t.blocks.is_empty() {
        let names: Vec<String> = t
            .blocks
            .iter()
            .map(|id| {
                app.by_id
                    .get(id)
                    .map(|b| b.name.clone())
                    .unwrap_or_else(|| id.clone())
            })
            .collect();
        field("blocks", names.join(", "), Style::default().fg(ACTIVE));
    }

    // Absolute date plus relative age: one for the record, one for the feel.
    let stamp = |iso: &Option<String>| match age(iso) {
        Some(a) => format!("{}  ({})", local_time(iso), since(&a)),
        None => local_time(iso),
    };

    field(
        "created",
        stamp(&t.created_at),
        Style::default().fg(PLAIN),
    );
    if t.started_at.is_some() {
        field("started", stamp(&t.started_at), Style::default().fg(ACTIVE));
    }
    if t.completed_at.is_some() {
        field("done", stamp(&t.completed_at), Style::default().fg(DONE));
    }
    // Only when it is not just an echo of created/started/done.
    if t.has_distinct_update() {
        field("updated", stamp(&t.updated_at), Style::default().fg(DIM));
    }

    // Linked via `dex complete --commit <sha>`. Entirely local -- no sync needed.
    if let Some(c) = t.commit() {
        let mut parts = vec![Span::styled(
            format!("{:<10}", "commit"),
            Style::default().fg(DIM),
        )];
        parts.push(Span::styled(
            c.short_sha().to_string(),
            Style::default().fg(CODE).add_modifier(Modifier::BOLD),
        ));
        if let Some(m) = c.message.as_ref().filter(|m| !m.trim().is_empty()) {
            parts.push(Span::styled(
                format!("  {m}"),
                Style::default().fg(PLAIN),
            ));
        }
        if let Some(b) = c.branch.as_ref().filter(|b| !b.trim().is_empty()) {
            parts.push(Span::styled(
                format!("  ({b})"),
                Style::default().fg(DIM),
            ));
        }
        lines.push(Line::from(parts));
    }

    if let Some(d) = t.description.as_ref().filter(|d| !d.trim().is_empty()) {
        lines.push(Line::from(""));
        lines.extend(markdown_lines(d));
    }

    if let Some(r) = t.result.as_ref().filter(|r| !r.trim().is_empty()) {
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled(
            "result",
            Style::default().fg(DIM),
        )));
        for line in r.lines() {
            lines.push(Line::from(Span::styled(
                line.to_string(),
                Style::default().fg(DONE),
            )));
        }
    }

    lines
}

/// Renders a description as markdown.
///
/// Delegates to `tui-markdown` rather than the small hand-rolled parser this
/// used to have. Tables were the reason: doing them properly needs column
/// measurement and terminal display widths, which that parser deliberately did
/// not attempt, so tables appeared as raw pipes.
///
/// It emits only `Reset`, `dark_gray` and `cyan` — ANSI names the terminal
/// remaps per mode — so it does not reintroduce the fixed-colour problem that
/// made the old theme palettes unreadable on a light background.
fn markdown_lines(text: &str) -> Vec<Line<'static>> {
    crate::markdown::render(text)
}

fn draw_status(frame: &mut Frame, app: &App, area: Rect) {
    let (text, style) = if app.status.is_empty() {
        (SHORTCUTS.to_string(), Style::default().fg(DIM))
    } else {
        (format!(" {}", app.status), Style::default().fg(ACTIVE))
    };

    frame.render_widget(Paragraph::new(text).style(style), area);
}

fn draw_prompt(frame: &mut Frame, prompt: &crate::app::Prompt) {
    let area = centered(frame.area(), 70, 7);
    frame.render_widget(Clear, area);

    let block = Block::bordered()
        .title(format!(" {} ", prompt.title))
        .border_style(Style::default().fg(ACTIVE));
    let inner = block.inner(area);
    frame.render_widget(block, area);

    let [label_area, input_area, hint_area] = Layout::vertical([
        Constraint::Length(1),
        Constraint::Length(1),
        Constraint::Length(1),
    ])
    .areas(inner);

    frame.render_widget(
        Paragraph::new(prompt.label.clone()).style(Style::default().fg(DIM)),
        label_area,
    );
    frame.render_widget(
        Paragraph::new(prompt.input.value.clone()).style(Style::default().fg(PLAIN)),
        input_area,
    );
    frame.render_widget(
        Paragraph::new("enter confirm    esc cancel").style(Style::default().fg(DIM)),
        hint_area,
    );

    frame.set_cursor_position(Position {
        x: (input_area.x + prompt.input.cursor as u16).min(input_area.right().saturating_sub(1)),
        y: input_area.y,
    });
}

fn draw_message(frame: &mut Frame, title: &str, body: &str, hint: &str, accent: Color) {
    let area = centered(frame.area(), 66, 9);
    frame.render_widget(Clear, area);

    let block = Block::bordered()
        .title(format!(" {title} "))
        .border_style(Style::default().fg(accent));
    let inner = block.inner(area);
    frame.render_widget(block, area);

    let [body_area, hint_area] =
        Layout::vertical([Constraint::Fill(1), Constraint::Length(1)]).areas(inner);

    frame.render_widget(
        Paragraph::new(body.to_string())
            .style(Style::default().fg(PLAIN))
            .wrap(Wrap { trim: false }),
        body_area,
    );
    frame.render_widget(
        Paragraph::new(hint).style(Style::default().fg(DIM)),
        hint_area,
    );
}

/// What `?` shows. Module-level rather than buried in `draw_help`, so a test can
/// hold it against [`SHORTCUTS`] -- the two advertise the same keys to the same
/// person and must not drift.
///
/// Left-aligned on purpose: centring would destroy the column alignment.
const HELP: &str = "\
tab        switch pane       s   start task
↑ ↓ j k    move / scroll     c   complete (prompts for result)
→ ← h l    expand / scroll   r   rename
g / G      first / last      e   edit description in $EDITOR
w / z      wrap / zoom       n   new top-level task
o / O      sort / reverse    a   new subtask of selection
/          search            d   delete (with confirmation)
f          cycle filter      ^R  refresh now
,          edit config       q   quit
- / +      collapse / expand all

Movement follows the focused pane, shown by its brighter border. Turn wrap
off (w) to scroll a wide table sideways -- wrapping removes the overflow
there would otherwise be to scroll to.

Zoom (z) shows one pane at a time, with [1] [2] tabs in the header -- press 1
or 2 to jump, or enter and left to cross over. Narrow terminals zoom on their
own below single_pane_below columns, which makes this usable on a phone.

Mouse: drag the divider to resize, wheel scrolls the pane under the pointer,
click selects. In the header, click a filter to switch to it, or the sort
label to cycle it -- right-click the sort to reverse. Hold Shift to select
text, as capture is enabled.

The view refreshes itself whenever the dex store changes, including when
another process or agent edits it. Your selection, expansion and any open
dialog are never disturbed.";

fn draw_help(frame: &mut Frame) {
    let area = centered(frame.area(), 74, 16);
    frame.render_widget(Clear, area);

    let block = Block::bordered()
        .title(" dextui ")
        .border_style(Style::default().fg(ACTIVE));
    let inner = block.inner(area);
    frame.render_widget(block, area);

    let [body, hint] = Layout::vertical([Constraint::Fill(1), Constraint::Length(1)]).areas(inner);

    frame.render_widget(
        Paragraph::new(HELP).style(Style::default().fg(PLAIN)),
        body,
    );
    frame.render_widget(
        Paragraph::new("any key to dismiss").style(Style::default().fg(DIM)),
        hint,
    );
}

fn centered(area: Rect, width: u16, height: u16) -> Rect {
    let w = width.min(area.width.saturating_sub(2));
    let h = height.min(area.height.saturating_sub(2));
    Rect {
        x: area.x + (area.width.saturating_sub(w)) / 2,
        y: area.y + (area.height.saturating_sub(h)) / 2,
        width: w,
        height: h,
    }
}

/// Plain-text render of the whole pipeline, for `dextui selftest`.
pub fn selftest(app: &App) -> String {
    use std::fmt::Write;
    let mut out = String::new();
    let ic = &crate::icons::UNICODE;

    let c = app.counts();
    let _ = writeln!(out, "label   {}", app.store_label);
    let _ = writeln!(
        out,
        "tasks   {} ({} pending: {} active, {} ready, {} blocked; {}% complete)\n",
        app.tasks.len(),
        c.pending,
        c.active,
        c.ready,
        c.blocked,
        c.percent
    );

    for filter in [
        tree::Filter::All,
        tree::Filter::Pending,
        tree::Filter::InProgress,
    ] {
        let forest = tree::build(&app.tasks, "", filter, app.sort, app.sort_reversed);
        let count = tree::flatten(&forest).len();
        let _ = writeln!(out, "--- filter: {filter:?} ({count} visible) ---");
        for node in &forest {
            print_node(node, 0, app, ic, &mut out);
        }
        let _ = writeln!(out);
    }

    if let Some(first) = app.tasks.first() {
        let _ = writeln!(out, "--- detail pane for {} ---", first.name);
        for line in detail_lines(first, app, ic) {
            let _ = writeln!(
                out,
                "{}",
                line.spans
                    .iter()
                    .map(|s| s.content.as_ref())
                    .collect::<String>()
            );
        }
    }

    out
}

fn print_node(node: &tree::Node, depth: usize, app: &App, ic: &Icons, out: &mut String) {
    use std::fmt::Write;
    let scaffold = if node.is_match { "" } else { "  (scaffold)" };
    let rollup = match app.progress.get(&node.task.id) {
        Some(prog) => format!("  {}/{}", prog.done, prog.total),
        None => String::new(),
    };
    let _ = writeln!(
        out,
        "{}{} {}{}{}",
        "  ".repeat(depth),
        glyph(dex::status(&node.task, &app.by_id), ic),
        node.task.name,
        rollup,
        scaffold
    );
    for c in &node.children {
        print_node(c, depth + 1, app, ic, out);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dex::Task;
    use ratatui::backend::TestBackend;
    use ratatui::Terminal;

    fn task(id: &str, parent: Option<&str>, name: &str) -> Task {
        Task {
            id: id.into(),
            parent_id: parent.map(str::to_string),
            name: name.into(),
            description: Some("a description".into()),
            created_at: Some("2026-01-01T00:00:00Z".into()),
            ..Default::default()
        }
    }

    fn render_tasks(tasks: Vec<Task>, w: u16, h: u16, ic: &Icons) -> Vec<String> {
        let mut app = App::new(tasks, "demo".into(), crate::config::Config::default());
        app.filter = tree::Filter::All;
        app.rebuild();

        let mut terminal = Terminal::new(TestBackend::new(w, h)).unwrap();
        terminal.draw(|f| draw(f, &mut app, ic)).unwrap();
        let buf = terminal.backend().buffer().clone();
        (0..buf.area.height)
            .map(|y| {
                (0..buf.area.width)
                    .map(|x| buf[(x, y)].symbol())
                    .collect::<String>()
            })
            .collect()
    }

    /// The status glyph already says "blocked", so repeating it after the name
    /// is noise -- except when the glyph says something else. A started task
    /// that is also blocked renders as in-progress (dex's own precedence), and
    /// then the trailing marker is the only thing carrying the fact.
    #[test]
    fn the_trailing_blocked_marker_appears_only_when_the_glyph_cannot_say_it() {
        let blocker = task("blocker", None, "Blocker");

        let mut idle = task("idle", None, "Idle and blocked");
        idle.blocked_by = vec!["blocker".into()];

        let mut started = task("started", None, "Started but blocked");
        started.blocked_by = vec!["blocker".into()];
        started.started_at = Some("2026-01-01T00:00:00Z".into());

        let ic = &crate::icons::UNICODE;
        let rows = render_tasks(vec![blocker, idle, started], 100, 12, ic);

        let row_for = |name: &str| -> String {
            rows.iter()
                .find(|r| r.contains(name))
                .unwrap_or_else(|| panic!("no row for {name}:\n{}", rows.join("\n")))
                .clone()
        };

        let idle_row = row_for("Idle and blocked");
        assert_eq!(
            idle_row.matches(ic.blocked).count(),
            1,
            "glyph already says blocked, so the marker should not repeat: {idle_row:?}"
        );

        let started_row = row_for("Started but blocked");
        // The marker is a spinner frame, not `ic.active`: the fixture has work in
        // progress, so the row is animating and frame 0 is what is drawn.
        assert!(
            started_row.contains(ic.spin[0]),
            "a started task reads as in progress: {started_row:?}"
        );
        assert_eq!(
            started_row.matches(ic.blocked).count(),
            1,
            "the glyph cannot say blocked here, so the marker must: {started_row:?}"
        );
    }

    /// Renders a full frame and returns it as plain text, one String per row.
    fn render(w: u16, h: u16, ic: &Icons) -> Vec<String> {
        let mut app = App::new(
            vec![
                task("root", None, "Parent task"),
                task("kid", Some("root"), "Child task"),
            ],
            "demo".into(),
            crate::config::Config::default(),
        );

        let mut terminal = Terminal::new(TestBackend::new(w, h)).unwrap();
        terminal
            .draw(|f| draw(f, &mut app, ic))
            .unwrap();

        let buf = terminal.backend().buffer().clone();
        (0..buf.area.height)
            .map(|y| {
                (0..buf.area.width)
                    .map(|x| buf[(x, y)].symbol())
                    .collect::<String>()
            })
            .collect()
    }

    /// The whole point of the colour work: dex and dextui are used on the same
    /// tasks in the same directory, so disagreeing about what colour a state is
    /// makes them contradictory rather than merely different.
    ///
    /// Source of truth is dex 0.16.0 `dist/cli/formatting.js`:
    ///   completed -> green (32), started_at -> blue (34), else -> yellow (33).
    #[test]
    fn status_colours_match_the_dex_cli() {
        assert_eq!(status_color(Status::Pending), Color::Yellow, "todo");
        assert_eq!(status_color(Status::InProgress), Color::Blue, "in progress");
        assert_eq!(status_color(Status::Completed), Color::Green, "done");
    }

    /// This terminal follows the macOS appearance and flips light/dark *under
    /// the running app*, so any fixed colour value is wrong half the time.
    /// Only ANSI-16 names and Reset are remapped by the user's theme.
    #[test]
    fn every_theme_colour_adapts_to_the_terminal() {
        for (name, c) in crate::theme::ALL {
            let ok = matches!(
                c,
                Color::Reset
                    | Color::Black
                    | Color::Red
                    | Color::Green
                    | Color::Yellow
                    | Color::Blue
                    | Color::Magenta
                    | Color::Cyan
                    | Color::Gray
                    | Color::DarkGray
                    | Color::LightRed
                    | Color::LightGreen
                    | Color::LightYellow
                    | Color::LightBlue
                    | Color::LightMagenta
                    | Color::LightCyan
                    | Color::White
            );
            assert!(ok, "{name} is {c:?}: Indexed/Rgb cannot follow the theme");
        }
    }

    /// The selection accent is a *cursor*, not a state. Every other colour in
    /// the tree means something about the task; if the gutter shared a hue with
    /// one of them, "where am I" and "what is this" would be the same signal and
    /// a selected row could read as blocked.
    #[test]
    fn the_selection_accent_is_not_a_status_colour() {
        use crate::theme::{ACCENT, ACCENT_DIM};
        for (n, c) in [("ACCENT", ACCENT), ("ACCENT_DIM", ACCENT_DIM)] {
            for (sn, s) in [
                ("TODO", TODO),
                ("ACTIVE", ACTIVE),
                            ("DONE", DONE),
                ("BLOCKED", BLOCKED),
            ] {
                assert_ne!(c, s, "{n} is the same colour as {sn}");
            }
        }
        assert_ne!(ACCENT, ACCENT_DIM, "an unfocused pane must look different");
    }

    #[test]
    fn a_frame_actually_draws_something() {
        // Regression: the app once ran happily while painting an empty screen.
        let rows = render(100, 20, &crate::icons::UNICODE);
        let text = rows.join("\n");
        assert!(
            text.contains("Parent task"),
            "nothing was drawn:\n{text}"
        );
    }

    #[test]
    fn the_header_shows_identity_context_and_counts() {
        let rows = render(100, 20, &crate::icons::UNICODE);
        assert!(rows[0].contains("dextui"), "header row: {:?}", rows[0]);
        assert!(rows[0].contains("demo"), "header row: {:?}", rows[0]);
        // "pending" was one opaque number; it is now split into what you can
        // actually pick up and what you cannot.
        assert!(rows[0].contains("ready"), "header row: {:?}", rows[0]);
    }

    /// The status strip and the help dialog advertise the same keys to the same
    /// person, so they must not drift apart. Nothing else checks this: the CLI
    /// has `every_command_in_the_usage_text_is_actually_accepted`, but the
    /// in-app bindings had no equivalent, which is how `e`/`E` could have been
    /// renamed in one surface and not the other.
    #[test]
    fn the_shortcut_strip_and_the_help_dialog_agree() {
        for (key, action) in [
            ("s", "start"),
            ("c", "done"),
            ("r", "rename"),
            ("e", "edit"),
            ("n", "new"),
            ("a", "sub"),
            ("d", "del"),
            ("f", "filter"),
            ("o", "sort"),
        ] {
            assert!(
                SHORTCUTS.contains(&format!("{key} {action}")),
                "the strip does not advertise {key} for {action}: {SHORTCUTS}"
            );
        }

        // Zoom took `z`, so collapse/expand moved and both surfaces must agree.
        assert!(HELP.contains("- / +      collapse / expand all"), "help: -/+");
        assert!(HELP.contains("w / z"), "help: z zooms");
        assert!(!HELP.contains("z Z"), "the old collapse keys are gone");

        // The pair this change exists to remove. `E` must not survive anywhere,
        // and `r` must no longer mean refresh.
        assert!(!SHORTCUTS.contains("E edit"), "`E` is gone: {SHORTCUTS}");
        assert!(!HELP.contains("E   edit"), "`E` is gone from the help");
        assert!(
            !HELP.contains("f          cycle filter      r   refresh"),
            "bare `r` no longer refreshes"
        );

        // Both surfaces name the same key for each of the two that moved.
        assert!(HELP.contains("r   rename"), "help: r renames");
        assert!(HELP.contains("e   edit description"), "help: e edits");
        assert!(HELP.contains("^R  refresh now"), "help: Ctrl-R refreshes");
    }

    /// The tabs are the only thing on screen saying the other pane exists, so
    /// they appear exactly when one is hidden -- and never when both are up,
    /// where they would be decoration on a row that already sheds to fit.
    #[test]
    fn the_pane_tabs_appear_only_when_a_pane_is_hidden() {
        let zoomed = screen(60, 80, Focus::Tree);
        assert!(zoomed.contains("[1]"), "no tabs in zoom mode: {zoomed}");
        assert!(zoomed.contains(" 2 "), "no second tab: {zoomed}");

        let split = screen(100, 80, Focus::Tree);
        assert!(!split.contains("[1]"), "tabs drawn beside both panes: {split}");
    }

    #[test]
    fn the_current_pane_is_the_marked_tab() {
        let on_tree = screen(60, 80, Focus::Tree);
        assert!(on_tree.contains("[1]"), "{on_tree}");
        assert!(!on_tree.contains("[2]"), "two tabs marked at once: {on_tree}");

        let on_detail = screen(60, 80, Focus::Detail);
        assert!(on_detail.contains("[2]"), "{on_detail}");
        assert!(!on_detail.contains("[1]"), "two tabs marked at once: {on_detail}");
    }

    /// Both states must be the same width, or switching tabs would shove the
    /// rest of the header sideways -- the jitter the whole header design avoids.
    #[test]
    fn switching_tabs_does_not_move_anything_else() {
        assert_eq!(
            span_width(&tab_spans(Focus::Tree)),
            span_width(&tab_spans(Focus::Detail))
        );
    }

    /// The tabs are reserved before the ladder runs, so they outlive the sort
    /// label and the filter menu. A rung that dropped them would hide the only
    /// indication that there is a way back.
    #[test]
    fn the_tabs_survive_a_terminal_too_narrow_for_anything_else() {
        for w in [60u16, 50, 40, 30, 24] {
            let s = screen(w, 80, Focus::Detail);
            assert!(
                s.contains("[2]"),
                "{w} columns dropped the tabs, hiding the way back:\n{s}"
            );
        }
    }

    /// At an absurd width the tabs would take the whole row and the store label
    /// would vanish with nothing marking it as clipped. The ladder's rule is
    /// that the label survives everything, so the tabs are what yields.
    #[test]
    fn the_tabs_yield_to_the_store_label_at_absurd_widths() {
        for w in [4u16, 6, 8, 10] {
            let s = screen(w, 80, Focus::Tree);
            let head = s.lines().next().unwrap_or("");
            assert!(
                !head.contains("[1]") || head.trim().len() > 4,
                "{w} columns: tabs took the whole row: {head:?}"
            );
        }
    }

    /// Renders a frame and returns the header zones the renderer published.
    fn zones_for(w: u16, filter: tree::Filter, mode: Mode) -> Vec<(u16, u16, HeaderZone)> {
        let mut app = App::new(
            vec![task("root", None, "Parent task")],
            "demo".into(),
            crate::config::Config::default(),
        );
        app.filter = filter;
        app.mode = mode;
        app.rebuild();

        let mut terminal = Terminal::new(TestBackend::new(w, 12)).unwrap();
        terminal
            .draw(|f| draw(f, &mut app, &crate::icons::UNICODE))
            .unwrap();
        app.header_zones.clone()
    }

    /// The mark on the active filter is weight plus its state's colour, which is
    /// what replaced UPPERCASING it. Every other option stays dim, so exactly one
    /// word can ever read as current.
    #[test]
    fn exactly_one_filter_is_marked_and_it_is_the_current_one() {
        for current in tree::Filter::MENU {
            let menu = filter_menu(current);
            let marked: Vec<&str> = menu
                .iter()
                .filter(|s| s.style.add_modifier.contains(Modifier::BOLD))
                .map(|s| s.content.as_ref())
                .collect();
            assert_eq!(marked, vec![current.name()], "current = {current:?}");

            for f in tree::Filter::MENU {
                if f == current {
                    continue;
                }
                let span = menu.iter().find(|s| s.content == f.name()).unwrap();
                assert_eq!(span.style.fg, Some(DIM), "{f:?} should be dim");
            }
        }

        // The colours are the states', so the menu speaks the same language as
        // the rows below it. `all` is not a state and gets no colour.
        assert_eq!(filter_name(tree::Filter::Pending, true).style.fg, Some(TODO));
        assert_eq!(filter_name(tree::Filter::InProgress, true).style.fg, Some(ACTIVE));
        assert_eq!(filter_name(tree::Filter::All, true).style.fg, Some(PLAIN));
    }

    /// A click has to land on the word you can see, so the zones must match what
    /// was drawn rather than a second calculation of where it should have been.
    #[test]
    fn every_menu_word_is_clickable_where_it_is_drawn() {
        let zones = zones_for(120, tree::Filter::Pending, Mode::Normal);

        for f in tree::Filter::MENU {
            let z = zones
                .iter()
                .find(|(_, _, z)| *z == HeaderZone::Filter(f))
                .unwrap_or_else(|| panic!("no zone for {f:?} in {zones:?}"));
            assert_eq!(
                (z.1 - z.0 + 1) as usize,
                f.name().chars().count(),
                "zone for {f:?} is not the width of its word"
            );
        }

        assert!(
            zones.iter().any(|(_, _, z)| *z == HeaderZone::Sort),
            "the sort label is clickable too: {zones:?}"
        );

        // Zones must not overlap, or a click would be ambiguous.
        let mut spans: Vec<(u16, u16)> = zones.iter().map(|(a, b, _)| (*a, *b)).collect();
        spans.sort();
        for pair in spans.windows(2) {
            assert!(pair[0].1 < pair[1].0, "zones overlap: {spans:?}");
        }
    }

    /// Row 0 belongs to the search box while searching. A zone left over from the
    /// previous frame would act on a menu that is not on screen.
    #[test]
    fn the_header_offers_nothing_to_click_while_searching() {
        assert!(zones_for(120, tree::Filter::Pending, Mode::Search).is_empty());
    }

    /// Too narrow for the menu, the header names the current filter alone. With
    /// no options on screen there is nothing to pick, so that word cycles.
    #[test]
    fn the_collapsed_filter_label_cycles_instead_of_picking() {
        let zones = zones_for(46, tree::Filter::Pending, Mode::Normal);
        assert!(
            zones.iter().any(|(_, _, z)| *z == HeaderZone::FilterCycle),
            "narrow header should offer a cycling zone: {zones:?}"
        );
        assert!(
            !zones
                .iter()
                .any(|(_, _, z)| matches!(z, HeaderZone::Filter(_))),
            "nothing to pick from when only one word is drawn: {zones:?}"
        );
    }

    /// The floor is what every rung of the header's ladder reserves, so it must
    /// be exactly the narrowest layout that still says something -- reserving
    /// more would push the filter menu out early, reserving less would let the
    /// menu outbid the numbers.
    ///
    /// It stays six cells however busy the store is, because the narrowest
    /// layout is the percentage alone and a percentage is at most four
    /// characters. That independence is worth pinning: it is why the reservation
    /// can be a constant-ish cost rather than something that grows with the
    /// task count and squeezes the header on exactly the projects that need it.
    #[test]
    fn the_counts_floor_is_the_narrowest_layout_that_still_says_something() {
        let ic = &crate::icons::UNICODE;

        let small = Counts {
            total: 10,
            completed: 4,
            pending: 6,
            active: 1,
            blocked: 2,
            ready: 3,
            percent: 40,
        };
        let busy = Counts {
            total: 4000,
            completed: 1200,
            pending: 2800,
            active: 137,
            blocked: 421,
            ready: 2242,
            percent: 30,
        };

        for c in [small, busy] {
            let floor = counts_floor(c, ic);
            assert!(floor > 0, "reserved nothing for {c:?}");
            // The floor must actually be enough: at exactly that room the counts
            // draw, and one cell narrower they do not.
            assert!(
                !header_counts(c, floor, ic).is_empty(),
                "floor {floor} draws nothing for {c:?}"
            );
            assert!(
                header_counts(c, floor - 1, ic).is_empty(),
                "floor {floor} is not the narrowest for {c:?}"
            );
        }

        assert_eq!(
            counts_floor(small, ic),
            counts_floor(busy, ic),
            "the floor must not grow with the store"
        );
    }

    /// The header shares its row with the sort and filter labels drawn right-
    /// aligned over the same area, so the counts must yield rather than collide.
    /// They are dropped in order of what carries least: bar, then percentage,
    /// then the words.
    #[test]
    fn the_header_counts_give_way_as_the_terminal_narrows() {
        let c = Counts {
            total: 10,
            completed: 4,
            pending: 6,
            active: 1,
            blocked: 2,
            ready: 3,
            percent: 40,
        };
        let ic = &crate::icons::UNICODE;

        // Deliberately the production helper, not a copy of it: a re-derived
        // formula would agree with a wrong one.
        let width = parts_width;

        let mut seen: Vec<usize> = Vec::new();
        for room in (0..=60).rev() {
            let parts = header_counts(c, room, ic);
            let w = width(&parts);
            assert!(w <= room, "room={room} produced {w} cells: {parts:?}");
            seen.push(w);
        }

        // Widest at 60, and it really does shed content on the way down.
        assert!(seen[0] > 0, "nothing drawn even at 60 cells");
        assert_eq!(*seen.last().unwrap(), 0, "something drawn at zero room");
        assert!(
            seen.windows(2).all(|w| w[0] >= w[1]),
            "width must never grow as room shrinks: {seen:?}"
        );

        // The widest layout carries the bar and the percentage; the narrowest
        // non-empty one still names every non-zero state.
        let widest: String = header_counts(c, 60, ic)
            .iter()
            .flatten()
            .map(|s| s.content.to_string())
            .collect();
        assert!(widest.contains("40%"), "{widest:?}");
        assert!(widest.contains("3 ready"), "{widest:?}");
        assert!(widest.contains("2 blocked"), "{widest:?}");
    }

    /// A zero is not worth a word. dex-report omits its zero sections too.
    #[test]
    fn the_header_omits_states_with_nothing_in_them() {
        let c = Counts {
            total: 4,
            completed: 1,
            pending: 3,
            active: 0,
            blocked: 0,
            ready: 3,
            percent: 25,
        };
        let text: String = header_counts(c, 60, &crate::icons::UNICODE)
            .iter()
            .flatten()
            .map(|s| s.content.to_string())
            .collect();

        assert!(text.contains("3 ready"), "{text:?}");
        assert!(!text.contains("active"), "nothing is active: {text:?}");
        assert!(!text.contains("blocked"), "nothing is blocked: {text:?}");
    }

    /// Renders just the header row, for a given store label and width.
    fn render_header(store: &str, w: u16, ic: &Icons) -> String {
        let mut app = App::new(
            vec![task("root", None, "Parent task")],
            store.into(),
            crate::config::Config::default(),
        );
        // The ladder is the subject here, so zoom mode is switched off: its tabs
        // are reserved ahead of the ladder and would otherwise confound every
        // width below the threshold. The tabs have their own tests.
        app.single_pane_below = 0;
        let mut terminal = Terminal::new(TestBackend::new(w, 8)).unwrap();
        terminal.draw(|f| draw(f, &mut app, ic)).unwrap();
        let buf = terminal.backend().buffer().clone();
        (0..buf.area.width)
            .map(|x| buf[(x, 0)].symbol())
            .collect::<String>()
    }

    /// The two halves of the header used to be two Paragraphs drawn over the
    /// *same* Rect -- identity left-aligned, sort/filter right-aligned -- with
    /// only the counts reserving any room. Below ~48 columns they overwrote each
    /// other: at 44 the store label was eaten and left a dangling " · ", and at
    /// 36 the row read `dexA-Z`. The row is now split into two Rects, so an
    /// overlap can no longer be expressed.
    #[test]
    fn the_headers_two_blocks_never_overwrite_each_other() {
        for ic in crate::icons::ALL {
            // A long label is the same bug at a wide terminal, not just a narrow one.
            for store in ["demo", "a-rather-long-project-name-here"] {
                // The row this narrow shows the store label and nothing else,
                // so it is also the width at which the guarantee below starts.
                let floor = span_width(&identity_store(store, &ic));

                for w in 4u16..=120 {
                    let head = render_header(store, w, &ic);
                    let seen = head.trim_end();
                    let why = format!(
                        "tier {} store {store:?} width {w}: {seen:?}",
                        crate::icons::name(ic.tier)
                    );

                    assert!(
                        !seen.ends_with('·'),
                        "a separator with nothing after it -- {why}"
                    );
                    // The bracketed filter menu is all-or-nothing; half of it
                    // is what being overwritten looked like.
                    assert_eq!(
                        seen.contains('['),
                        seen.contains(']'),
                        "half a filter menu -- {why}"
                    );
                    // Given room for it at all, the store label survives whole.
                    // It is what the right-hand block yields to, and it used to
                    // be the casualty: at 44 columns it was overwritten outright
                    // and at 36 it was gone, in both cases silently.
                    if w as usize >= floor {
                        assert!(
                            seen.contains(store),
                            "the store label did not survive -- {why}"
                        );
                    } else {
                        // Below that, a clipped label must say it is clipped, or
                        // `dexA-Z` reads as the name of something.
                        assert!(
                            seen.is_empty() || seen.contains('') || seen.contains(store),
                            "clipped with nothing to say so -- {why}"
                        );
                    }
                }
            }
        }
    }

    /// "Wrong tasks" is this app's most common confusion and the store label is
    /// the only thing on the screen that answers it, so it outlives the app's
    /// own name.
    #[test]
    fn the_identity_gives_up_its_own_name_before_the_store() {
        let ic = &crate::icons::UNICODE;
        let text = |room: usize| -> String {
            header_identity("my-project", ic, room)
                .iter()
                .map(|s| s.content.to_string())
                .collect()
        };

        assert!(text(30).contains("dextui"), "{:?}", text(30));
        assert!(text(30).contains("my-project"), "{:?}", text(30));

        // Room for one of the two: it is the store.
        let tight = text(11);
        assert!(tight.contains("my-project"), "{tight:?}");
        assert!(!tight.contains("dextui"), "{tight:?}");

        let mut seen: Vec<usize> = Vec::new();
        for room in (0..=40).rev() {
            let w = span_width(&header_identity("my-project", ic, room));
            assert!(w <= room, "room={room} produced {w} cells");
            seen.push(w);
        }
        assert!(
            seen.windows(2).all(|w| w[0] >= w[1]),
            "width must never grow as room shrinks: {seen:?}"
        );
        assert_eq!(*seen.last().unwrap(), 0, "something drawn at zero room");
    }

    /// A filter silently in force with nothing on screen saying so is the most
    /// confusing state this app has, so which filter is active is the last thing
    /// the right-hand block drops -- after the menu around it, and after the
    /// sort order, which only changes the order of what you can already see.
    #[test]
    fn the_right_hand_block_keeps_the_active_filter_longest() {
        let filter = tree::Filter::Pending;
        let cs = right_candidates("priority", filter);
        let text = |i: usize| -> String {
            cs[i].iter().map(|s| s.content.to_string()).collect()
        };

        assert!(text(0).contains("[ all  pending  active ]"), "{:?}", text(0));

        assert!(!text(1).contains('['), "the menu should have gone: {:?}", text(1));
        assert!(text(1).contains("priority"), "{:?}", text(1));
        assert!(text(1).contains(filter.name()), "{:?}", text(1));

        assert!(!text(2).contains("priority"), "sort should have gone: {:?}", text(2));
        assert!(text(2).contains(filter.name()), "{:?}", text(2));

        assert!(cs[3].is_empty(), "the last rung draws nothing: {:?}", text(3));

        // Strictly descending, which is what makes the ladder in `header_sides`
        // monotone: a wider terminal can never pick a narrower rung.
        let widths: Vec<usize> = cs.iter().map(|c| span_width(c)).collect();
        assert!(
            widths.windows(2).all(|w| w[0] > w[1]),
            "candidates must strictly narrow: {widths:?}"
        );
    }

    /// The header must never bring back something it has already dropped. Sizing
    /// the two ends one after the other did exactly that: the right-hand block's
    /// steps are far larger than the identity's, so narrowing the terminal could
    /// free more room than the narrowing cost. The app name was absent at 44
    /// columns and present again at 36 -- which reads as a rendering bug, because
    /// nothing about a smaller window should reveal more.
    #[test]
    fn the_header_never_brings_back_what_it_has_already_dropped() {
        for ic in crate::icons::ALL {
            for store in ["demo", "a-rather-long-project-name-here"] {
                // Everything here is state the header is *reporting*; the counts
                // are excluded on purpose, being the one part built to shed and
                // regain content as room allows.
                let markers = ["dextui", "[", "priority", tree::Filter::Pending.name()];
                let mut last_seen = [0u16; 4];

                for w in 4u16..=140 {
                    let head = render_header(store, w, &ic);
                    for (i, m) in markers.iter().enumerate() {
                        if head.contains(m) {
                            last_seen[i] = w;
                        } else if last_seen[i] != 0 {
                            panic!(
                                "{m:?} was drawn at {} columns and is back to being \
                                 absent at {w} -- tier {}, store {store:?}: {head:?}",
                                last_seen[i],
                                crate::icons::name(ic.tier)
                            );
                        }
                    }
                }
            }
        }
    }

    /// `age` reports "now" for anything under a minute, which reads as a bug the
    /// moment something suffixes it: "started now ago". The absolute timestamp
    /// rows special-cased it from the start; the in-progress summary line did
    /// not, so the two disagreed on the same screen about the same instant.
    #[test]
    fn a_task_started_moments_ago_reads_just_now_not_now_ago() {
        let mut t = task("t", None, "Fresh task");
        t.started_at = Some(chrono::Utc::now().to_rfc3339());

        let rows = render_tasks(vec![t], 120, 16, &crate::icons::UNICODE);
        let text = rows.join("\n");
        assert!(
            !text.contains("now ago"),
            "\"now ago\" is not a duration:\n{text}"
        );

        let summary = rows
            .iter()
            .find(|r| r.contains("in progress"))
            .unwrap_or_else(|| panic!("no status line:\n{text}"));
        assert!(
            summary.contains("started just now"),
            "status line: {summary:?}"
        );
    }

    #[test]
    fn every_icon_tier_renders() {
        for ic in crate::icons::ALL {
            let text = render(100, 20, &ic).join("\n");
            assert!(
                text.contains("Parent task"),
                "tier {} drew nothing",
                crate::icons::name(ic.tier)
            );
        }
    }

    /// Renders one task whose description is `md`, and returns the frame text.
    fn render_description(md: &str, w: u16, h: u16) -> String {
        let mut app = App::new(
            vec![Task {
                id: "t".into(),
                name: "Task".into(),
                description: Some(md.to_string()),
                created_at: Some("2026-01-01T00:00:00Z".into()),
                ..Default::default()
            }],
            "demo".into(),
            crate::config::Config::default(),
        );

        let mut terminal = Terminal::new(TestBackend::new(w, h)).unwrap();
        terminal
            .draw(|f| draw(f, &mut app, &crate::icons::UNICODE))
            .unwrap();

        let buf = terminal.backend().buffer().clone();
        (0..buf.area.height)
            .map(|y| {
                (0..buf.area.width)
                    .map(|x| buf[(x, y)].symbol())
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    #[test]
    fn markdown_tables_are_drawn_as_tables_not_raw_pipes() {
        // The reason tui-markdown replaced the hand-rolled parser: this used to
        // render as literal `|---|---|` rows with unaligned columns.
        let text = render_description(
            "| option | cost |\n|---|---:|\n| hand-rolled | low |\n",
            110,
            24,
        );

        assert!(text.contains('') && text.contains(''), "no table borders:\n{text}");
        assert!(
            !text.contains("|---"),
            "the delimiter row leaked through:\n{text}"
        );
    }

    #[test]
    fn a_wide_table_in_a_narrow_pane_does_not_panic() {
        // Tables are laid out at their natural width, which can exceed the pane.
        let wide = "| a very long column header here | and another one |\n                    |---|---|\n| some long cell value | another long value |\n";
        for w in [40u16, 60, 80] {
            let _ = render_description(wide, w, 20);
        }
    }

    #[test]
    fn a_very_narrow_pane_does_not_panic() {
        // The right-hand gutter must be dropped rather than overflow the row.
        // Every tier, because the nerd cap kit is new geometry in that gutter.
        for ic in crate::icons::ALL {
            for w in [20u16, 30, 40] {
                let _ = render(w, 12, &ic);
            }
        }
    }

    /// Every `Progress` a real store can produce, at both sub-cell settings.
    fn every_bar(mut f: impl FnMut(Progress, Bar, bool)) {
        for total in 1..=60usize {
            for done in 0..=total {
                for active in 0..=(total - done) {
                    let p = Progress {
                        done,
                        active,
                        total,
                    };
                    for partials in [false, true] {
                        f(p, Bar::new(p, METER_WIDTH, partials), partials);
                    }
                }
            }
        }
    }

    /// The bar is a fixed-width column in the right-hand gutter; a run that does
    /// not add up shifts everything after it. This is also the underflow guard:
    /// the cell arithmetic subtracts `usize`s, so a slip panics here rather than
    /// wrapping to a four-billion-cell `repeat` in the renderer.
    #[test]
    fn a_bar_always_fills_exactly_the_meter_width() {
        every_bar(|p, b, partials| {
            assert_eq!(
                b.done + b.active + usize::from(b.partial > 0) + b.empty,
                METER_WIDTH,
                "{p:?} partials={partials} -> {b:?}"
            );
            assert!(
                b.done + b.active <= METER_WIDTH,
                "coloured runs overflow the bar: {p:?} partials={partials} -> {b:?}"
            );
        });
    }

    /// The mirror of `a_non_zero_count_never_rounds_away_to_nothing`, and the
    /// more dangerous direction: a run that does not exist must never be drawn.
    ///
    /// In a tier without sub-cell glyphs the bar snaps to whole cells, and the
    /// snap can push the combined extent past the done run's own rounding. The
    /// leftover cell was handed to `active` unconditionally, so a task with
    /// nothing started painted an in-flight cell -- the meter and the status
    /// glyph describing the same task in contradictory terms, which is the exact
    /// failure this whole epic exists to remove.
    #[test]
    fn a_zero_count_is_never_drawn() {
        every_bar(|p, b, partials| {
            if p.active == 0 {
                assert_eq!(b.active, 0, "phantom in-flight: {p:?} partials={partials} -> {b:?}");
            }
            if p.done == 0 {
                assert_eq!(b.done, 0, "phantom done: {p:?} partials={partials} -> {b:?}");
            }
        });

        // The smallest real case, found by brute force over the arithmetic: 7 of
        // 9 done and nothing started rendered `#####+.` in ascii, with the `+`
        // in blue.
        let b = Bar::new(
            Progress {
                done: 7,
                active: 0,
                total: 9,
            },
            METER_WIDTH,
            false,
        );
        assert_eq!(b.active, 0, "7 of 9 done, none started -> {b:?}");
    }

    /// One finished subtask out of a hundred is the single most useful thing a
    /// meter can say, and rounding would erase it. The rule predates this bar;
    /// moving to eighths must not quietly downgrade it to a 1/8 sliver.
    #[test]
    fn a_non_zero_count_never_rounds_away_to_nothing() {
        every_bar(|p, b, partials| {
            if p.done > 0 {
                assert!(b.done >= 1, "{p:?} partials={partials} -> {b:?}");
            }
            if p.active > 0 {
                assert!(b.active >= 1, "{p:?} partials={partials} -> {b:?}");
            }
        });

        let one = Bar::new(Progress { done: 1, active: 0, total: 100 }, METER_WIDTH, true);
        assert_eq!((one.done, one.partial), (1, 0), "{one:?}");

        let both = Bar::new(Progress { done: 1, active: 1, total: 100 }, METER_WIDTH, true);
        assert_eq!((both.done, both.active), (1, 1), "{both:?}");
    }

    /// `partial` indexes `Meter::partial[eighths - 1]`, a seven-entry table, so
    /// an eighth of 8 would panic. It cannot arise because the remainder is
    /// taken modulo 8 rather than patched after rounding whole cells -- the
    /// naive scheme reaches 8/8 at, for instance, 16 done and 16 active of 45.
    #[test]
    fn the_partial_cell_never_exceeds_seven_eighths() {
        every_bar(|p, b, partials| {
            assert!(b.partial <= 7, "{p:?} partials={partials} -> {b:?}");
        });

        let b = Bar::new(Progress { done: 16, active: 16, total: 45 }, METER_WIDTH, true);
        assert!(b.partial <= 7, "{b:?}");
    }

    /// Nerd and ascii have no eighth-blocks, so their bars must land on whole
    /// cells -- and still round to the nearest one rather than truncating.
    #[test]
    fn a_tier_without_partial_glyphs_snaps_to_whole_cells() {
        every_bar(|p, b, partials| {
            if !partials {
                assert_eq!(b.partial, 0, "{p:?} -> {b:?}");
            }
        });

        let b = Bar::new(Progress { done: 3, active: 0, total: 8 }, METER_WIDTH, false);
        assert_eq!((b.done, b.active, b.partial, b.empty), (3, 0, 0, 4), "{b:?}");
    }

    /// A true sub-cell colour boundary would need fg=green on bg=blue, which
    /// introduces a background the colour policy forbids and which the selected
    /// row's styling would invert. So the fraction lives at the outer edge only
    /// and done->active snaps.
    ///
    /// This also pins a deliberate behaviour change: the outer edge rounds on
    /// the *combined* extent (1+1 of 3 is 4.67 cells, so 5) rather than summing
    /// two separately-rounded runs (2 + 2 = 4).
    #[test]
    fn the_partial_sits_at_the_outer_edge_not_the_done_active_boundary() {
        let b = Bar::new(Progress { done: 1, active: 1, total: 3 }, METER_WIDTH, true);
        assert_eq!((b.done, b.active, b.partial, b.empty), (2, 2, 5, 2), "{b:?}");
    }

    /// The reason the sub-cell edge exists at all: without it 13 of 14 fills
    /// every cell and reads as finished.
    #[test]
    fn the_outer_edge_carries_the_sub_cell_remainder() {
        let b = Bar::new(Progress { done: 3, active: 0, total: 8 }, METER_WIDTH, true);
        assert_eq!((b.done, b.active, b.partial, b.empty), (2, 0, 5, 4), "{b:?}");

        let nearly = Bar::new(Progress { done: 13, active: 0, total: 14 }, METER_WIDTH, true);
        assert_eq!(nearly.done, 6, "{nearly:?}");
        assert!(nearly.partial > 0, "a full bar would read as finished: {nearly:?}");
        assert_eq!(nearly.empty, 0, "{nearly:?}");
    }

    #[test]
    fn an_untouched_parent_is_all_trough_and_a_finished_one_is_all_bar() {
        let none = Bar::new(Progress { done: 0, active: 0, total: 4 }, METER_WIDTH, true);
        assert_eq!((none.done, none.active, none.partial, none.empty), (0, 0, 0, METER_WIDTH));

        let all = Bar::new(Progress { done: 7, active: 0, total: 7 }, METER_WIDTH, true);
        assert_eq!((all.done, all.partial, all.empty), (METER_WIDTH, 0, 0));
    }

    /// The bar's spans, without the trailing ` n/total`, as (text, foreground).
    fn meter_bar(p: Progress, ic: &Icons) -> Vec<(String, Option<Color>)> {
        let mut spans = meter_spans(p, ic);
        spans.pop();
        spans
            .into_iter()
            .map(|s| (s.content.into_owned(), s.style.fg))
            .collect()
    }

    /// The bar sits in a fixed column in the tree's right gutter, and the gutter
    /// is sized with `chars().count()`. A glyph the terminal measures as double
    /// width would shift every row -- the exact failure already documented for
    /// `▾ ▸ ⊘`, and the live risk with the nerd tier's Private Use Area kit.
    /// `Span::width` goes through unicode-width, so this catches both that and a
    /// plain arithmetic slip.
    #[test]
    fn the_meter_is_exactly_seven_cells_wide_in_every_tier() {
        let cases = [
            Progress { done: 0, active: 0, total: 4 },
            Progress { done: 3, active: 0, total: 8 },
            Progress { done: 1, active: 1, total: 3 },
            Progress { done: 1, active: 0, total: 100 },
            Progress { done: 13, active: 0, total: 14 },
            Progress { done: 7, active: 0, total: 7 },
        ];
        for ic in crate::icons::ALL {
            for p in cases {
                let bar = meter_bar(p, &ic);
                let cells: usize = bar.iter().map(|(t, _)| Span::raw(t.clone()).width()).sum();
                let chars: usize = bar.iter().map(|(t, _)| t.chars().count()).sum();
                assert_eq!(
                    cells,
                    METER_WIDTH,
                    "tier {} {p:?}: {bar:?}",
                    crate::icons::name(ic.tier)
                );
                assert_eq!(
                    chars,
                    METER_WIDTH,
                    "tier {} {p:?}: the gutter is measured in chars: {bar:?}",
                    crate::icons::name(ic.tier)
                );
            }
        }
    }

    /// The point of the whole change: the one place progress is quantified now
    /// speaks the same colour language as the status glyphs.
    #[test]
    fn the_meter_paints_done_in_flight_and_untouched_in_the_status_colours() {
        let p = Progress { done: 2, active: 2, total: 7 };
        for ic in crate::icons::ALL {
            let fgs: Vec<_> = meter_bar(p, &ic).into_iter().map(|(_, fg)| fg).collect();
            assert_eq!(
                fgs,
                vec![Some(DONE), Some(ACTIVE), Some(DIM)],
                "tier {}",
                crate::icons::name(ic.tier)
            );
        }

        let spans = meter_spans(p, &crate::icons::UNICODE);
        assert_eq!(spans.last().unwrap().style.fg, Some(DIM), "the fraction is secondary");
    }

    /// The fraction is a sliver of *more of the same state*, not a state of its
    /// own, so it takes the colour of whichever run reaches the outer edge.
    #[test]
    fn the_partial_cell_takes_the_colour_of_the_run_it_extends() {
        let ic = &crate::icons::UNICODE;

        let done_only = meter_bar(Progress { done: 3, active: 0, total: 8 }, ic);
        assert_eq!(
            done_only.iter().map(|(_, fg)| *fg).collect::<Vec<_>>(),
            vec![Some(DONE), Some(DONE), Some(DIM)],
            "{done_only:?}"
        );
        assert_eq!(done_only[1].0, "\u{258b}", "5/8 of a cell: {done_only:?}");

        let mixed = meter_bar(Progress { done: 1, active: 1, total: 3 }, ic);
        assert_eq!(
            mixed.iter().map(|(_, fg)| *fg).collect::<Vec<_>>(),
            vec![Some(DONE), Some(ACTIVE), Some(ACTIVE), Some(DIM)],
            "{mixed:?}"
        );
    }

    /// Position, not just fill, chooses the glyph: the nerd kit's caps are what
    /// make seven cells read as one bar rather than seven stamps.
    #[test]
    fn the_nerd_meter_is_capped_at_both_ends() {
        let bar: String = meter_bar(Progress { done: 2, active: 0, total: 7 }, &crate::icons::NERD)
            .into_iter()
            .map(|(t, _)| t)
            .collect();
        assert_eq!(
            bar,
            "\u{ee03}\u{ee04}\u{ee01}\u{ee01}\u{ee01}\u{ee01}\u{ee02}",
            "{bar:?}"
        );
    }

    /// At seven cells a bar cannot distinguish 2/7 from 3/7, so the exact count
    /// is the part that is actually useful for triage.
    #[test]
    fn the_fraction_stays_beside_the_bar() {
        let spans = meter_spans(Progress { done: 3, active: 0, total: 8 }, &crate::icons::UNICODE);
        assert_eq!(spans.last().unwrap().content.as_ref(), " 3/8");
    }

    fn started(id: &str, name: &str) -> Task {
        Task {
            started_at: Some("2026-01-01T00:00:00Z".into()),
            ..task(id, None, name)
        }
    }

    /// A whole frame as a `Buffer`, which keeps the per-cell styling the plain
    /// `render` helper throws away -- and styling is half the subject here.
    fn render_frame(tasks: Vec<Task>, frame: usize, ic: &Icons) -> ratatui::buffer::Buffer {
        let mut app = App::new(tasks, "demo".into(), crate::config::Config::default());
        app.filter = tree::Filter::All;
        app.rebuild();
        app.spin_frame = frame;

        let mut terminal = Terminal::new(TestBackend::new(80, 12)).unwrap();
        terminal.draw(|f| draw(f, &mut app, ic)).unwrap();
        terminal.backend().buffer().clone()
    }

    /// Renders at `width` and returns the whole screen as text.
    fn screen(width: u16, single_pane_below: u16, focus: Focus) -> String {
        let mut app = App::new(
            vec![
                Task {
                    // Only the detail pane renders a description, so this is an
                    // unambiguous marker for it. "priority" is not: that is the
                    // sort label, and it sits in the header in both layouts.
                    description: Some("DETAIL-ONLY-MARKER".into()),
                    ..task("a", None, "A task in the tree")
                },
                task("b", None, "Another one"),
            ],
            "demo".into(),
            crate::config::Config::default(),
        );
        app.filter = tree::Filter::All;
        app.single_pane_below = single_pane_below;
        app.focus = focus;
        app.selected = Some("a".into());
        app.rebuild();

        let mut terminal = Terminal::new(TestBackend::new(width, 14)).unwrap();
        terminal
            .draw(|f| draw(f, &mut app, &crate::icons::UNICODE))
            .unwrap();
        let buf = terminal.backend().buffer().clone();
        (0..buf.area.height)
            .map(|y| {
                (0..buf.area.width)
                    .map(|x| buf[(x, y)].symbol())
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    /// Below the threshold `focus` stops meaning "which border is brighter" and
    /// starts meaning "which pane you are looking at". Both panes carry content
    /// the other does not, so each is identifiable in the output.
    #[test]
    fn below_the_threshold_focus_decides_which_pane_is_drawn() {
        let tree_view = screen(60, 80, Focus::Tree);
        assert!(tree_view.contains("Another one"), "no tree: {tree_view}");
        assert!(
            !tree_view.contains("DETAIL-ONLY-MARKER"),
            "the detail pane leaked in: {tree_view}"
        );

        let detail_view = screen(60, 80, Focus::Detail);
        assert!(
            detail_view.contains("DETAIL-ONLY-MARKER"),
            "no detail pane: {detail_view}"
        );
        assert!(
            !detail_view.contains("Another one"),
            "the tree leaked in: {detail_view}"
        );
    }

    /// Above it, focus goes back to meaning emphasis and both are on screen.
    #[test]
    fn above_the_threshold_both_panes_are_drawn_whichever_has_focus() {
        for focus in [Focus::Tree, Focus::Detail] {
            let s = screen(100, 80, focus);
            assert!(s.contains("Another one"), "{focus:?}: no tree: {s}");
            assert!(
                s.contains("DETAIL-ONLY-MARKER"),
                "{focus:?}: no detail: {s}"
            );
        }
    }

    /// A dialog has to survive the layout it is drawn over, and the single-pane
    /// path returns early -- so this is the assertion that stops it returning
    /// before the overlays.
    #[test]
    fn dialogs_still_draw_over_a_single_pane() {
        let mut app = App::new(
            vec![task("a", None, "A task")],
            "demo".into(),
            crate::config::Config::default(),
        );
        app.single_pane_below = 80;
        app.mode = Mode::Help;
        app.rebuild();

        let mut terminal = Terminal::new(TestBackend::new(60, 14)).unwrap();
        terminal
            .draw(|f| draw(f, &mut app, &crate::icons::UNICODE))
            .unwrap();
        let buf = terminal.backend().buffer().clone();
        let text: String = (0..buf.area.height)
            .flat_map(|y| (0..buf.area.width).map(move |x| (x, y)))
            .map(|(x, y)| buf[(x, y)].symbol())
            .collect();

        assert!(text.contains("switch pane"), "the help dialog is missing");
    }

    /// The glyph changes every frame now, so the assertion that matters is that
    /// its **column** does not. That is the whole risk of a spinner whose frames
    /// are font-fallbacked, and the reason this was rejected twice before.
    #[test]
    fn the_spinner_turns_without_moving_the_column() {
        for ic in [
            &crate::icons::NERD,
            &crate::icons::UNICODE,
            &crate::icons::ASCII,
        ] {
            let tasks = || vec![task("a", None, "Idle task"), started("b", "Running task")];

            let mut columns = std::collections::HashSet::new();
            let mut seen = std::collections::HashSet::new();

            for f in 0..ic.spin.len() {
                let buf = render_frame(tasks(), f, ic);

                // Scoped to the running task's own row, then located by colour.
                //
                // Neither half is optional. Searching the whole buffer finds the
                // header's own `1 active`, which is ACTIVE-coloured too; and
                // searching by symbol matches tree scaffolding that shares a
                // character, which is how the ascii tier's `|` frame was caught
                // colliding with the selection gutter.
                let row = (0..buf.area.height)
                    .find(|&y| {
                        (0..buf.area.width)
                            .map(|x| buf[(x, y)].symbol())
                            .collect::<String>()
                            .contains("Running task")
                    })
                    .unwrap_or_else(|| panic!("{:?}: no row for the running task", ic.tier));

                let (at, style) = (0..buf.area.width)
                    .map(|x| ((x, row), buf[(x, row)].style()))
                    .find(|(_, s)| s.fg == Some(ACTIVE))
                    .unwrap_or_else(|| panic!("{:?}: no in-progress marker drawn", ic.tier));

                assert_eq!(
                    buf[at].symbol(),
                    ic.spin[f],
                    "{:?}: frame {f} drew the wrong glyph",
                    ic.tier
                );
                columns.insert(at.0);
                seen.insert(ic.spin[f]);

                // Colour no longer carries the motion, so it must stay put.
                assert!(
                    !style.add_modifier.contains(Modifier::BOLD),
                    "{:?}: frame {f} changed weight",
                    ic.tier
                );
            }

            assert_eq!(
                columns.len(),
                1,
                "{:?}: the marker moved between frames: {columns:?}",
                ic.tier
            );
            assert_eq!(
                seen.len(),
                ic.spin.len(),
                "{:?}: frames repeated within one cycle",
                ic.tier
            );
        }
    }

    /// With animation off the marker must be the still glyph -- the same one the
    /// header counts and help legend show -- not whichever spinner frame happens
    /// to sit at index 0. A lone braille dot does not read as "in progress"
    /// without motion behind it; a play triangle does.
    #[test]
    fn with_animation_off_the_marker_is_the_still_glyph() {
        for ic in [
            &crate::icons::NERD,
            &crate::icons::UNICODE,
            &crate::icons::ASCII,
        ] {
            assert_eq!(row_glyph(Status::InProgress, ic, None), ic.active);
            // And it is genuinely a different glyph from the rotation, or this
            // assertion would pass by coincidence.
            assert!(
                !ic.spin.contains(&ic.active),
                "{:?}: the still glyph is also a spinner frame",
                ic.tier
            );
        }
    }

    /// Every frame must be exactly one character wide. A multi-character frame
    /// would shift the column outright, before any font question arises.
    #[test]
    fn every_spinner_frame_is_a_single_character() {
        for ic in [
            &crate::icons::NERD,
            &crate::icons::UNICODE,
            &crate::icons::ASCII,
        ] {
            for f in ic.spin {
                assert_eq!(
                    f.chars().count(),
                    1,
                    "{:?}: frame {f:?} is not one character",
                    ic.tier
                );
            }
            assert!(ic.spin.len() >= 2, "{:?}: nothing to animate", ic.tier);
        }
    }

    /// Without this the pulse could quietly become a whole-screen flicker rather
    /// than a signal about one row.
    #[test]
    fn only_the_in_progress_glyph_pulses() {
        let mut done = task("done", None, "Finished task");
        done.completed = true;
        let mut blocked = task("blocked", None, "Blocked task");
        blocked.blocked_by = vec!["pending".into()];

        let tasks = || {
            vec![
                task("pending", None, "Pending task"),
                done.clone(),
                blocked.clone(),
            ]
        };

        for ic in crate::icons::ALL {
            assert_eq!(
                render_frame(tasks(), 0, &ic),
                render_frame(tasks(), 3, &ic),
                "tier {} repaints with nothing running",
                crate::icons::name(ic.tier)
            );
        }
    }

    /// A pulse repaint can now land while a dialog is open, which never happened
    /// before. Immediate-mode rendering makes it safe by construction -- the
    /// prompt is redrawn from `app.mode` with the same value -- but "safe by
    /// construction" is an argument, and this is a check.
    #[test]
    fn a_pulse_repaint_does_not_disturb_an_open_prompt() {
        let ic = &crate::icons::UNICODE;

        let frame = |pulse_on: bool| {
            let mut app = App::new(
                vec![started("b", "Running task")],
                "demo".into(),
                crate::config::Config::default(),
            );
            app.mode = Mode::Prompt(crate::app::Prompt {
                title: "Rename: Running task".into(),
                label: "Name".into(),
                input: crate::app::TextInput::new("half-typed"),
                pending: crate::app::Pending::EditName { id: "b".into() },
            });
            app.spin_frame = if pulse_on { 1 } else { 0 };

            let mut terminal = Terminal::new(TestBackend::new(80, 12)).unwrap();
            terminal.draw(|f| draw(f, &mut app, ic)).unwrap();
            let cursor = terminal.get_cursor_position().unwrap();
            (terminal.backend().buffer().clone(), cursor)
        };

        let (off, off_cursor) = frame(false);
        let (on, on_cursor) = frame(true);

        assert_eq!(off_cursor, on_cursor, "the cursor moved mid-typing");
        let text = |b: &ratatui::buffer::Buffer| {
            (0..b.area.height)
                .map(|y| {
                    (0..b.area.width)
                        .map(|x| b[(x, y)].symbol())
                        .collect::<String>()
                })
                .collect::<Vec<_>>()
        };
        assert_eq!(text(&off), text(&on), "the prompt redrew differently");
    }

    /// Draws a real frame with `select` selected and `focus` focused, and hands
    /// back both the styled buffer and the `App` the renderer wrote its geometry
    /// into. Styling is the entire subject of the selection tests, and the plain
    /// `render` helper throws it away.
    fn render_selection(
        tasks: Vec<Task>,
        select: &str,
        focus: Focus,
        ic: &Icons,
        w: u16,
        h: u16,
    ) -> (ratatui::buffer::Buffer, App) {
        let mut app = App::new(tasks, "demo".into(), crate::config::Config::default());
        app.filter = tree::Filter::All;
        app.rebuild();
        app.selected = Some(select.to_string());
        app.focus = focus;

        let mut terminal = Terminal::new(TestBackend::new(w, h)).unwrap();
        terminal.draw(|f| draw(f, &mut app, ic)).unwrap();
        let buf = terminal.backend().buffer().clone();
        (buf, app)
    }

    /// The buffer row `name` was drawn on.
    fn row_of(buf: &ratatui::buffer::Buffer, name: &str) -> u16 {
        for y in 0..buf.area.height {
            let line: String = (0..buf.area.width).map(|x| buf[(x, y)].symbol()).collect();
            if line.contains(name) {
                return y;
            }
        }
        panic!("{name:?} was never drawn");
    }

    /// The column `name` starts at on row `y`.
    ///
    /// Counted in cells, not bytes: the tree draws multibyte box characters, and
    /// a byte offset would differ between two rows whose names line up perfectly
    /// on screen.
    fn col_of(buf: &ratatui::buffer::Buffer, y: u16, name: &str) -> usize {
        let cells: Vec<&str> = (0..buf.area.width).map(|x| buf[(x, y)].symbol()).collect();
        let line: String = cells.concat();
        let byte = line
            .find(name)
            .unwrap_or_else(|| panic!("{name:?} is not on row {y}: {line:?}"));
        let mut at = 0;
        for (i, c) in cells.iter().enumerate() {
            if at == byte {
                return i;
            }
            at += c.len();
        }
        panic!("{name:?} does not start on a cell boundary on row {y}")
    }

    /// Every cell of row `y` that lies inside the tree pane.
    fn tree_cells<'a>(
        buf: &'a ratatui::buffer::Buffer,
        app: &App,
        y: u16,
    ) -> Vec<&'a ratatui::buffer::Cell> {
        (1..app.divider_x).map(|x| &buf[(x, y)]).collect()
    }

    /// Selection is carried by a rail in the left margin and a bold name, not by
    /// inverting the row. Inversion is the thing being replaced, so its absence
    /// is asserted rather than assumed -- and the gutter is a *reserved* column
    /// on every row, so selecting one must not shift its name relative to its
    /// siblings.
    #[test]
    fn the_selected_row_is_marked_by_a_gutter_not_by_inverting_it() {
        let ic = &crate::icons::UNICODE;
        let tasks = vec![
            task("alpha", None, "Alpha task"),
            task("beta", None, "Beta task"),
        ];

        let (buf, app) = render_selection(tasks, "alpha", Focus::Tree, ic, 100, 20);
        let sel = row_of(&buf, "Alpha task");
        let other = row_of(&buf, "Beta task");

        // x = 0 is the pane border, so the gutter is the first cell inside it.
        assert_eq!(buf[(1, sel)].symbol(), ic.gutter, "no gutter on the selection");
        assert_eq!(buf[(1, other)].symbol(), " ", "an unselected row drew a gutter");

        for cell in tree_cells(&buf, &app, sel) {
            assert!(
                !cell.style().add_modifier.contains(Modifier::REVERSED),
                "the selected row still inverts: {cell:?}"
            );
        }

        assert_eq!(
            col_of(&buf, sel, "Alpha task"),
            col_of(&buf, other, "Beta task"),
            "selecting a row moved its name out of the column"
        );

        let name_x = col_of(&buf, sel, "Alpha task") as u16;
        assert!(
            buf[(name_x, sel)]
                .style()
                .add_modifier
                .contains(Modifier::BOLD),
            "the selected name is not bold"
        );
        assert!(
            !buf[(col_of(&buf, other, "Beta task") as u16, other)]
                .style()
                .add_modifier
                .contains(Modifier::BOLD),
            "an unselected name is bold"
        );
    }

    /// Focus follows the border, and the gutter has to agree with it -- otherwise
    /// two panes both claim a cursor. Easy to forget, because the tree is focused
    /// by default and every other test would pass without this.
    #[test]
    fn the_selection_gutter_dims_when_the_tree_is_unfocused() {
        let ic = &crate::icons::UNICODE;
        let tasks = || vec![task("alpha", None, "Alpha task")];

        let (focused, _) = render_selection(tasks(), "alpha", Focus::Tree, ic, 100, 20);
        let y = row_of(&focused, "Alpha task");
        assert_eq!(focused[(1, y)].style().fg, Some(crate::theme::ACCENT));

        let (unfocused, _) = render_selection(tasks(), "alpha", Focus::Detail, ic, 100, 20);
        let y = row_of(&unfocused, "Alpha task");
        assert_eq!(unfocused[(1, y)].style().fg, Some(crate::theme::ACCENT_DIM));
        assert_eq!(
            unfocused[(1, y)].symbol(),
            ic.gutter,
            "an unfocused pane still knows where the cursor is"
        );
    }

    /// The reason inversion had to go. The status glyph and all three meter runs
    /// set explicit foregrounds, and `REVERSED` swapped every one of them with
    /// the background -- so on the selected row the colour language inverted
    /// exactly where progress is quantified. This is the row that has both.
    #[test]
    fn selection_does_not_recolour_the_meter_or_the_status_glyph() {
        let ic = &crate::icons::UNICODE;

        let mut finished = task("done", Some("root"), "Finished child");
        finished.completed = true;
        let mut running = task("run", Some("root"), "Running child");
        running.started_at = Some("2026-01-01T00:00:00Z".into());

        let tasks = vec![
            task("root", None, "Parent task"),
            finished,
            running,
            task("todo", Some("root"), "Pending child"),
        ];

        let (buf, app) = render_selection(tasks, "root", Focus::Tree, ic, 120, 20);
        let y = row_of(&buf, "Parent task");
        let cells = tree_cells(&buf, &app, y);

        assert_eq!(buf[(1, y)].symbol(), ic.gutter, "fixture: the parent is selected");

        let fg_of = |sym: &str| -> Vec<Option<Color>> {
            cells
                .iter()
                .filter(|c| c.symbol() == sym)
                .map(|c| c.style().fg)
                .collect()
        };

        // 1 done + 1 in flight of 3 gives two green cells, two blue, a blue
        // partial and a dim remainder -- every colour the meter can speak.
        assert!(
            fg_of("\u{2588}").contains(&Some(DONE)),
            "no green in the meter: {:?}",
            fg_of("\u{2588}")
        );
        assert!(
            fg_of("\u{2588}").contains(&Some(ACTIVE)),
            "no blue in the meter: {:?}",
            fg_of("\u{2588}")
        );
        assert_eq!(
            fg_of("\u{2591}"),
            vec![Some(DIM); 2],
            "the untouched remainder lost its colour"
        );

        // The parent is neither started nor completed nor blocked, so its own
        // marker is the yellow todo glyph.
        assert_eq!(
            fg_of(ic.pending),
            vec![Some(status_color(Status::Pending))],
            "the status glyph was recoloured by the selection"
        );

        for cell in &cells {
            assert!(
                !cell.style().add_modifier.contains(Modifier::REVERSED),
                "inversion would swap every one of those foregrounds: {cell:?}"
            );
        }
    }

    /// Nothing else ties the renderer's actual output to the hit test: the
    /// `app.rs` click tests use a hand-written geometry stand-in. Written before
    /// the selection gutter existed, so a layout change that broke click
    /// mapping would show up here as a flip from green to red.
    #[test]
    fn a_click_still_selects_the_row_that_was_drawn() {
        let ic = &crate::icons::UNICODE;
        let tasks = vec![
            task("alpha", None, "Alpha task"),
            task("beta", None, "Beta task"),
        ];

        let (buf, mut app) = render_selection(tasks, "alpha", Focus::Tree, ic, 100, 20);
        let y = row_of(&buf, "Beta task");

        app.select_at_row(y);
        assert_eq!(
            app.selected.as_deref(),
            Some("beta"),
            "clicking row {y} selected {:?}",
            app.selected
        );
    }

    /// The tree pane's content for each row, without the two pane borders.
    fn tree_rows(rows: &[String]) -> Vec<String> {
        rows.iter()
            .map(|r| {
                let mut it = r.match_indices('');
                match (it.next(), it.next()) {
                    (Some((a, _)), Some((b, _))) => r[a + ''.len_utf8()..b].to_string(),
                    _ => String::new(),
                }
            })
            .collect()
    }

    /// A rollup over nothing is meaningless, so a leaf gets no meter at all.
    /// `░` is safe to look for: ratatui's scrollbar draws `█` and `│`, never it.
    #[test]
    fn a_leaf_gets_no_meter() {
        let rows = tree_rows(&render(120, 20, &crate::icons::UNICODE));
        let row = |name: &str| {
            rows.iter()
                .find(|r| r.contains(name))
                .unwrap_or_else(|| panic!("no row for {name}:\n{}", rows.join("\n")))
                .clone()
        };
        assert!(row("Parent task").contains(''), "{:?}", row("Parent task"));
        assert!(!row("Child task").contains(''), "{:?}", row("Child task"));
    }

    /// Rollups come from the *unfiltered* task list: hiding completed subtasks
    /// is exactly when you most want to see how many there were.
    #[test]
    fn a_meter_counts_the_unfiltered_tree() {
        let mut finished = task("done", Some("root"), "Finished child");
        finished.completed = true;

        let app_tasks = vec![
            task("root", None, "Parent task"),
            finished,
            task("kid", Some("root"), "Pending child"),
        ];
        let mut app = App::new(app_tasks, "demo".into(), crate::config::Config::default());
        assert_eq!(app.filter, tree::Filter::Pending, "fixture assumes the default filter");

        let mut terminal = Terminal::new(TestBackend::new(120, 20)).unwrap();
        terminal
            .draw(|f| draw(f, &mut app, &crate::icons::UNICODE))
            .unwrap();
        let buf = terminal.backend().buffer().clone();
        let rows: Vec<String> = (0..buf.area.height)
            .map(|y| (0..buf.area.width).map(|x| buf[(x, y)].symbol()).collect())
            .collect();
        let rows = tree_rows(&rows);
        let text = rows.join("\n");

        assert!(!text.contains("Finished child"), "the filter should hide it:\n{text}");
        let parent = rows.iter().find(|r| r.contains("Parent task")).unwrap();
        assert!(
            parent.contains("1/2"),
            "the rollup must count the hidden child: {parent:?}"
        );
    }
}