croft-software 0.2.232

VSCode-style TUI written in Rust
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
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
//! Drawing each frame (`render`), the status-bar text, caret visibility and the
//! screen-reader descriptions.

use super::*;

/// The amber a status-bar item takes when it wants attention: the
/// uncommitted-changes dot beside the branch, and the operation git stopped
/// in (`main | MERGING`).
pub(super) const GIT_DIRTY_COLOR: Color = Color::Rgb(0xeb, 0xcb, 0x8b);

/// The dot after the branch name while the working tree has uncommitted
/// changes (VS Code's `main*`): the branch itself keeps its quiet colour, so
/// a dirty tree reads as one small mark rather than a recoloured segment.
pub(super) const GIT_DIRTY_DOT: &str = "\u{2022}";

/// Powerline half circles, the rounded ends of a status-bar pill (as on the
/// update pill, the PROBLEMS badge and the Extensions switches).
pub(super) const PILL_CAP_L: &str = "\u{e0b6}";

pub(super) const PILL_CAP_R: &str = "\u{e0b4}";

/// The terminal cells `s` paints in, as ratatui lays it out. A wide
/// character (`项`, an emoji) takes two, so a click target measured in
/// `char`s would sit left of the text it belongs to.
pub(super) fn status_cells(s: &str) -> u16 {
    unicode_width::UnicodeWidthStr::width(s) as u16
}

/// `area` cut off at column `x`: whole if it ends by then, narrowed if it
/// crosses it, empty if it starts there or later.
pub(super) fn ends_before(area: Rect, x: u16) -> Rect {
    if area.x >= x {
        Rect::default()
    } else {
        Rect {
            width: area.width.min(x - area.x),
            ..area
        }
    }
}

/// Cells left blank after the status bar's last right-hand segment: none,
/// since the language pill's rounded end already reads as an edge.
pub(super) const STATUS_RIGHT_MARGIN: u16 = 0;

impl StatusTones {
    pub(super) fn new(theme: crate::theme::Theme, bar: Color) -> Self {
        // The theme's own foreground is already chosen for its background,
        // light or dark; `theme.ui` would adapt it a second time (on a light
        // theme, flipping dark text to near-white).
        let (r, g, b) = theme.syntax().fg;
        let text = Color::Rgb(r, g, b);
        let muted = match theme.surfaces() {
            Some(s) => s.muted(),
            None => theme.ui(Color::Rgb(0x9a, 0xa4, 0xb8)),
        };
        // A high contrast theme resolves chrome greys to full strength on
        // purpose (#1548); blending toward the bar would undo that.
        let dim = if theme.high_contrast() {
            muted
        } else {
            mix_color(muted, bar, 0.6)
        };
        StatusTones { text, muted, dim }
    }
}

/// `a` blended toward `b` by `t` (0.0 keeps `a`); a non-RGB colour is kept.
pub(super) fn mix_color(a: Color, b: Color, t: f32) -> Color {
    match (a, b) {
        (Color::Rgb(ar, ag, ab), Color::Rgb(br, bg, bb)) => {
            let m = |x: u8, y: u8| (x as f32 + (y as f32 - x as f32) * t).round() as u8;
            Color::Rgb(m(ar, br), m(ag, bg), m(ab, bb))
        }
        _ => a,
    }
}

/// The status bar's background: Croft Loch's chrome surface, a near-black
/// seam on the gradient (OLED) themes, the navy band elsewhere.
pub(super) fn status_bar_bg(theme: crate::theme::Theme) -> Color {
    if let Some(s) = theme.surfaces() {
        s.chrome()
    } else if theme.gradient() {
        theme.ui(Color::Rgb(0x18, 0x18, 0x18))
    } else {
        theme.ui(Color::Rgb(0x1e, 0x3a, 0x6e))
    }
}

/// Build the status-bar spans for the git segment: the branch glyph in the
/// theme accent, the branch name in the bar's text tone, an amber dot while
/// the tree is dirty, and quiet ahead/behind counts. Returns an empty vec
/// outside a git repo so the bar shows nothing.
pub(super) fn git_status_spans<'a>(
    status: &'a crate::git::GitStatus,
    theme: crate::theme::Theme,
) -> Vec<Span<'a>> {
    if !status.in_repo {
        return Vec::new();
    }
    let tones = StatusTones::new(theme, status_bar_bg(theme));
    let mut spans: Vec<Span> = Vec::with_capacity(7);
    spans.push(Span::raw("  "));
    // Codicon `cod-source-control` (U+EA68): the Y-fork that matches the
    // activity-bar Source Control icon, so the status-bar branch indicator
    // and the SCM panel share the same visual mark.
    spans.push(Span::styled(
        "\u{ea68} ",
        Style::default().fg(theme.accent()),
    ));
    spans.push(Span::styled(
        status.head_label(),
        Style::default().fg(tones.text),
    ));
    // The operation git stopped in (#1356), as `main | MERGING`, read as one
    // phrase: the dirty dot comes after it.
    if let Some(op) = status.operation {
        spans.push(Span::styled(
            format!(" | {}", op.label()),
            Style::default()
                .fg(theme.ui(GIT_DIRTY_COLOR))
                .add_modifier(Modifier::BOLD),
        ));
    }
    if status.dirty {
        spans.push(Span::styled(
            format!(" {GIT_DIRTY_DOT}"),
            Style::default()
                .fg(theme.ui(GIT_DIRTY_COLOR))
                .add_modifier(Modifier::BOLD),
        ));
    }
    if status.ahead > 0 {
        spans.push(Span::styled(
            format!(" \u{2191}{}", status.ahead),
            Style::default().fg(tones.muted),
        ));
    }
    if status.behind > 0 {
        spans.push(Span::styled(
            format!(" \u{2193}{}", status.behind),
            Style::default().fg(tones.muted),
        ));
    }
    spans
}

/// The longest workspace name the status bar's cap shows before it elides.
pub(super) const WORKSPACE_CAP_MAX: usize = 24;

/// Fixed-capacity stack string that spills to the heap only if formatted text
/// exceeds `N` bytes, keeping steady-state status-bar formatting allocation-free
/// (#2062).
pub(super) struct StackFmt<const N: usize> {
    buf: [u8; N],
    len: usize,
    overflow: Option<String>,
}

impl<const N: usize> StackFmt<N> {
    pub(super) fn new() -> Self {
        Self {
            buf: [0; N],
            len: 0,
            overflow: None,
        }
    }

    pub(super) fn as_str(&self) -> &str {
        if let Some(ref s) = self.overflow {
            s.as_str()
        } else {
            // SAFETY: only valid UTF-8 `&str` slices are written via `fmt::Write`.
            unsafe { std::str::from_utf8_unchecked(&self.buf[..self.len]) }
        }
    }
}

impl<const N: usize> std::fmt::Write for StackFmt<N> {
    fn write_str(&mut self, s: &str) -> std::fmt::Result {
        if let Some(ref mut ov) = self.overflow {
            ov.push_str(s);
            return Ok(());
        }
        if self.len + s.len() <= N {
            self.buf[self.len..self.len + s.len()].copy_from_slice(s.as_bytes());
            self.len += s.len();
        } else {
            let mut ov = String::with_capacity(self.len + s.len());
            // SAFETY: self.buf[..self.len] holds valid UTF-8 written so far.
            ov.push_str(unsafe { std::str::from_utf8_unchecked(&self.buf[..self.len]) });
            ov.push_str(s);
            self.overflow = Some(ov);
        }
        Ok(())
    }
}

/// Paints styled slices across one status-bar row while tracking logical cell
/// column offsets, without building a `Vec<Span>` or `Paragraph` (#2062).
struct StatusPainter<'a> {
    buf: &'a mut ratatui::buffer::Buffer,
    area: Rect,
    col: u16,
}

impl<'a> StatusPainter<'a> {
    fn new(buf: &'a mut ratatui::buffer::Buffer, area: Rect) -> Self {
        let area = area.intersection(buf.area);
        Self { buf, area, col: 0 }
    }

    fn paint_str(&mut self, text: &str, style: Style) {
        if self.area.height > 0 && self.col < self.area.width && !text.is_empty() {
            self.buf.set_stringn(
                self.area.x + self.col,
                self.area.y,
                text,
                usize::from(self.area.width - self.col),
                style,
            );
        }
        self.col = self.col.saturating_add(status_cells(text));
    }

    fn paint_span(&mut self, span: &Span<'_>) {
        self.paint_str(&span.content, span.style);
    }

    fn paint_spans<'b>(&mut self, spans: impl IntoIterator<Item = Span<'b>>) {
        for span in spans {
            self.paint_span(&span);
        }
    }

    fn paint_usize(&mut self, n: usize, style: Style) {
        let mut digits = [0u8; 20];
        let mut i = digits.len();
        let mut v = n;
        loop {
            i -= 1;
            digits[i] = b'0' + (v % 10) as u8;
            v /= 10;
            if v == 0 {
                break;
            }
        }
        // SAFETY: digits[i..] contains only ASCII '0'..='9'.
        let s = unsafe { std::str::from_utf8_unchecked(&digits[i..]) };
        self.paint_str(s, style);
    }
}

/// Spans for the cap at the left edge of the status bar: the logo's `<>` in
/// the brand orange and the workspace folder's name, on the theme's
/// selection tint with a rounded right end. It anchors the bar the way VS
/// Code's remote indicator does, and says which workspace this window is.
pub(super) fn workspace_cap_spans<'a>(theme: crate::theme::Theme, name: &'a str) -> [Span<'a>; 6] {
    use std::borrow::Cow;
    let fill = theme.selection();
    let tones = StatusTones::new(theme, status_bar_bg(theme));
    // Measured in terminal cells, not chars: a wide name (`项目`) paints
    // twice its char count, and every offset after the cap counts cells.
    let name: Cow<'a, str> = if status_cells(name) as usize > WORKSPACE_CAP_MAX {
        use unicode_width::UnicodeWidthChar;
        let mut s = String::new();
        let mut used = 0;
        for c in name.chars() {
            let w = c.width().unwrap_or(0);
            if used + w > WORKSPACE_CAP_MAX - 1 {
                break;
            }
            used += w;
            s.push(c);
        }
        s.push('\u{2026}');
        Cow::Owned(s)
    } else {
        Cow::Borrowed(name)
    };
    let name_style = Style::default()
        .fg(tones.text)
        .bg(fill)
        .add_modifier(Modifier::BOLD);
    [
        Span::styled(" ", Style::default().bg(fill)),
        Span::styled(
            "<>",
            Style::default()
                .fg(BRAND_ORANGE)
                .bg(fill)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(" ", name_style),
        Span::styled(name, name_style),
        Span::styled(" ", name_style),
        Span::styled(PILL_CAP_R, Style::default().fg(fill)),
    ]
}

/// A status-bar badge (a recording, vim's mode, an attention flag) as a
/// rounded pill: `label` padded by a cell each side, between half-circle
/// caps in `fill`.
pub(super) fn status_pill(label: &str, fill: Color, fg: Color) -> [Span<'static>; 3] {
    [
        Span::styled(PILL_CAP_L, Style::default().fg(fill)),
        Span::styled(
            format!(" {label} "),
            Style::default()
                .fg(fg)
                .bg(fill)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(PILL_CAP_R, Style::default().fg(fill)),
    ]
}

/// The Overwrite badge that follows the workspace cap in the status bar: the
/// continuous-underline symbol (⎁) in the brand orange, so a switched mode is
/// hard to miss. Insert, the default, shows nothing, as in VS Code, and keeps
/// the bar's cells for the segments after it. It sits on the left, away from
/// the clickable position, encoding and language segments on the right.
pub(super) fn overwrite_mode_span() -> Span<'static> {
    Span::styled(
        "\u{2381}",
        Style::default()
            .fg(BRAND_ORANGE)
            .add_modifier(Modifier::BOLD),
    )
}

/// Rotating-arc frames for the in-progress update glyph. Cycled to read as a
/// spinning circular arrow, the universal "working" indicator.
pub(super) const UPDATE_SPINNER_FRAMES: [&str; 6] = [
    "\u{25DC}", "\u{25E0}", "\u{25DD}", "\u{25DE}", "\u{25E1}", "\u{25DF}",
];

/// Milliseconds each spinner frame is held; ~10 frames/second reads as smooth
/// motion while keeping the status-bar-only redraws light over SSH.
pub(super) const UPDATE_SPINNER_FRAME_MS: u128 = 100;

/// Pick the spinner frame for a given elapsed time. Pure so the wrap-around
/// is unit-testable without a clock.
pub(super) fn update_spinner_frame(elapsed_ms: u128) -> &'static str {
    let n = UPDATE_SPINNER_FRAMES.len() as u128;
    UPDATE_SPINNER_FRAMES[((elapsed_ms / UPDATE_SPINNER_FRAME_MS) % n) as usize]
}

impl App {
    /// What a side-bar or panel view draws with now: the theme and pointer
    /// as they are this frame, and whether the view has the keyboard.
    pub(super) fn view_cx(&self, focused: bool) -> crate::widgets::view_cx::ViewCx {
        crate::widgets::view_cx::ViewCx {
            theme: self.theme,
            focused,
            pointer: self.pointer_cell,
        }
    }

    /// Mirrors the predicate used in `App::render` to decide whether to call
    /// `frame.set_cursor_position`. Used by the post-draw overlay writer so
    /// it can re-Show the caret after the OSC-1337 image emit only when the
    /// editor would have shown it this frame.
    pub(super) fn cursor_should_be_visible(&self) -> bool {
        // The connect dialog places its own caret in its field whenever it
        // has one, as `render_connect_dialog` does: put that one back, not
        // a pane's (#2669 review).
        if self
            .connect_dialog
            .as_ref()
            .is_some_and(|d| d.cursor_screen_pos().is_some())
        {
            return self.cursor_visible_phase();
        }
        if self.context_menu.is_some() || self.prompt.is_some() || !self.cursor_visible_phase() {
            return false;
        }
        // On a `surfaces` theme the quick input's query has the terminal's
        // caret (see `quick_input_owns_caret`).
        if self.quick_input_owns_caret() {
            return self.quick_input_caret().is_some();
        }
        // Any other pop-up has the keys: a pane's caret behind it would only
        // point at text it is not about to edit (#2669).
        if self.popup_open() {
            return false;
        }
        let editor_caret = if self.editor.diff.is_some() {
            self.editor.diff_caret_screen_pos()
        } else {
            self.editor.cursor_screen_pos()
        };
        if self.focus == Pane::Editor && editor_caret.is_some() {
            return true;
        }
        if self.focus == Pane::Tree
            && self.sidebar_view == SidebarView::SourceControl
            && self.source_control.cursor_screen_pos(true).is_some()
        {
            return true;
        }
        if self.focus == Pane::Tree
            && self.sidebar_view == SidebarView::Search
            && self.search.cursor_screen_pos(true).is_some()
        {
            return true;
        }
        if self.focus == Pane::Tree
            && self.sidebar_view == SidebarView::Extensions
            && self.extensions.cursor_screen_pos(true).is_some()
        {
            return true;
        }
        false
    }

    /// Whether a quick input (the Command Palette, Go to File, a list
    /// picker or an input prompt) has the terminal's caret: on a `surfaces`
    /// theme, which draws no caret block in the query, the caret goes there
    /// and no pane's caret blinks through the card. A boxed theme paints its
    /// own caret block in the query; no pane's caret shows there either
    /// (#2669).
    pub(super) fn quick_input_owns_caret(&self) -> bool {
        self.theme.surfaces().is_some()
            && (self.command_palette.is_some()
                || self.file_finder.is_some()
                || self.list_picker.is_some()
                || self.input_prompt.is_some())
    }

    /// Where the terminal's caret goes while a quick input is open: the
    /// query caret of the topmost one (drawn last: list picker, input
    /// prompt, palette, finder), as its last render placed it. `None` on a
    /// boxed theme, whose quick inputs paint their own caret block.
    pub(super) fn quick_input_caret(&self) -> Option<(u16, u16)> {
        if let Some(p) = &self.list_picker {
            return p.last_caret;
        }
        if let Some(p) = &self.input_prompt {
            return p.last_caret;
        }
        if let Some(p) = &self.command_palette {
            return p.last_caret;
        }
        self.file_finder.as_ref().and_then(|f| f.last_caret)
    }

    /// True iff the caret is currently in its visible half of the blink
    /// cycle. VS Code uses a 530ms half-period; we match. We blink in
    /// software (by toggling whether `frame.set_cursor_position` is called
    /// each frame) instead of relying on the host terminal's own blink
    /// support, which iTerm2 / Terminal.app may have disabled in user
    /// preferences.
    pub(super) fn cursor_visible_phase(&self) -> bool {
        // A screen reader follows the cursor; one that vanishes half the
        // time is lost half the time.
        self.screen_reader || self.cursor_blink.visible_phase()
    }

    /// Croft Loch's seams: a hairline on each boundary between two surfaces,
    /// drawn over the frame cells the panes left as padding. The layout
    /// knows where its boundaries are; the panes do not.
    pub(super) fn paint_surface_seams(
        &self,
        frame: &mut ratatui::Frame,
        s: crate::theme::Surfaces,
        activity_bar: Option<Rect>,
        side_bars: [Option<Rect>; 2],
        panel: Option<Rect>,
        status_bar: Option<Rect>,
    ) {
        use crate::widgets::surface::{Edge, paint_seam};
        let full = frame.area();
        let hair = s.hairline();
        let buf = frame.buffer_mut();
        let column = |x: u16, r: Rect| Rect {
            x,
            y: r.y,
            width: 1,
            height: r.height,
        };
        let row = |y: u16, r: Rect| Rect {
            x: r.x,
            y,
            width: r.width,
            height: 1,
        };
        // A side bar against the activity bar on one side and the editor
        // column on the other; nothing at the frame's own edge.
        for bar in side_bars.into_iter().flatten().filter(|r| !r.is_empty()) {
            if bar.x > full.x {
                paint_seam(buf, column(bar.x, bar), Edge::Left, hair);
            }
            if bar.right() < full.right() {
                paint_seam(buf, column(bar.right() - 1, bar), Edge::Right, hair);
            }
        }
        // Editor groups side by side or stacked: the seam the user drags.
        for seam in &self.editor_seams {
            let span = seam.cross_end.saturating_sub(seam.cross_start);
            let rect = match seam.dir {
                editor_layout::SplitDir::Horizontal => Rect {
                    x: seam.pos,
                    y: seam.cross_start,
                    width: 1,
                    height: span,
                },
                editor_layout::SplitDir::Vertical => Rect {
                    x: seam.cross_start,
                    y: seam.pos,
                    width: span,
                    height: 1,
                },
            };
            let edge = match seam.dir {
                editor_layout::SplitDir::Horizontal => Edge::Left,
                editor_layout::SplitDir::Vertical => Edge::Top,
            };
            paint_seam(buf, rect, edge, hair);
        }
        if let Some(p) = panel.filter(|p| !p.is_empty()) {
            // The panel against the editor above it.
            if p.y > full.y {
                paint_seam(buf, row(p.y - 1, p), Edge::Bottom, hair);
            }
            // Split terminal panes against each other and the terminal rail.
            for t in &self.terminals {
                let r = t.last_area;
                if !r.is_empty() && r.right() < p.right() {
                    paint_seam(buf, column(r.right() - 1, r), Edge::Right, hair);
                }
            }
        }
        // Everything above the status bar against it, except the activity
        // bar, which is chrome like the status bar and whose cells an icon
        // image may own.
        if let Some(bar) = status_bar.filter(|b| b.y > full.y) {
            let y = bar.y - 1;
            match activity_bar.filter(|a| !a.is_empty()) {
                Some(a) => {
                    let left = Rect::new(full.x, y, a.x - full.x, 1);
                    let right = Rect::new(a.right(), y, full.right() - a.right(), 1);
                    paint_seam(buf, left, Edge::Bottom, hair);
                    paint_seam(buf, right, Edge::Bottom, hair);
                }
                None => paint_seam(buf, row(y, full), Edge::Bottom, hair),
            }
        }
    }

    /// Render the frame the terminal is sent: [`Self::render`], with every
    /// colour fitted to the terminal's depth (#1433), and no underline
    /// colour for a terminal that would misread one (#2661).
    pub(super) fn render_for_terminal(&mut self, frame: &mut ratatui::Frame) {
        self.render(frame);
        self.color_depth.fit_buffer(frame.buffer_mut());
        if !self.underline_colors {
            crate::color_depth::drop_underline_colors(frame.buffer_mut());
        }
    }

    pub(super) fn render(&mut self, frame: &mut ratatui::Frame) {
        let _turn = crate::proc::UiTurn::enter();
        // Set again by the welcome panel when it paints the button.
        self.welcome_tour_button = Rect::default();
        self.picture_cover.start_frame();
        // Where the editor tab's tooltip goes, once the focused group is
        // known; it is drawn with the other pop-ups (#2663).
        let mut tab_tooltip_area: Option<Rect> = None;
        let size = frame.area();
        self.last_frame_area = size;
        if let Some(menu) = self.context_menu.as_mut() {
            menu.localize();
        }
        self.update_announcer();
        if self.notes.generation != self.notes_shown_gen {
            self.notes_shown_gen = self.notes.generation;
            let mut counts: std::collections::HashMap<PathBuf, usize> =
                std::collections::HashMap::new();
            for n in self.notes.live().filter(|n| !n.resolved) {
                *counts.entry(self.tree.root.join(&n.file)).or_default() += 1;
            }
            self.tree.note_counts = std::sync::Arc::new(counts);
        }
        // Redaction reveal is app state; each pane paints from its own copy.
        let reveal = self.redactions_revealed();
        for t in self.terminals.iter_mut() {
            t.reveal_redactions = reveal;
        }
        // Hit rects must describe the frame being painted, not the last
        // frame that happened to include a section. A section that stops
        // rendering (Explorer's OPEN EDITORS / TIMELINE / DEPENDENCIES /
        // OUTLINE after a switch to Source Control) otherwise keeps its
        // stale rect, and `handle_mouse`'s containment checks swallow every
        // click the current view paints in those cells — the COMMITS graph
        // sits exactly there and its clicks went dead (#103). Zero them all
        // up front; each section's render re-records the live ones this
        // frame (the OSK does the same for its collapsed band).
        for rect in [
            &mut self.open_editors.last_area,
            &mut self.open_editors.last_scrollbar,
            &mut self.timeline.last_area,
            &mut self.timeline.last_scrollbar,
            &mut self.dependencies.last_area,
            &mut self.dependencies.last_scrollbar,
            &mut self.outline.last_area,
            &mut self.outline.last_scrollbar,
            &mut self.commit_graph.last_area,
            &mut self.commit_graph.last_scrollbar,
        ] {
            *rect = Rect::default();
        }
        self.dress_host_accents();
        self.expire_ssh_offer();
        self.sync_lane_root_badges();
        // Theme background, whole frame. croft's chrome (the sidebar panels,
        // explorer sections, activity bar, gaps) mostly paints `Color::Reset`
        // and leans on the iTerm2 `SetColors` session bg to color it. Ghostty /
        // Kitty / sixel ignore `SetColors`, so those Reset cells fall through to
        // the host terminal's own background (black), leaving only the surfaces
        // that fill an explicit bg (editor, terminal) themed. Prefilling the
        // frame with the theme bg colors every unfilled cell; widgets that set
        // their own bg override it (ratatui patches bg only when `Some`). Gated
        // to exactly the hosts where `SetColors` is NOT emitted (see
        // `apply_theme`): on iTerm2 the session bg already handles this and a
        // full-frame fill would force the OSC-1337 activity images to re-emit
        // every frame.
        if !crate::iterm2_inline::detect_iterm2_inline_support() {
            frame.render_widget(
                ratatui::widgets::Block::default()
                    .style(Style::default().bg(self.theme.editor_bg())),
                size,
            );
        }
        // The on-screen keyboard docks as a band between the panes and the
        // status bar, scaling its keys to thumb size on tall frames; frames
        // too short to host it keep it collapsed so the workspace can't be
        // squeezed into nothing.
        let osk_h = if self.osk.is_some() && size.height >= OSK_MIN_FRAME_HEIGHT {
            crate::widgets::osk::band_height(size.height)
        } else {
            0
        };
        // The bottom status bar can be hidden (Customize Layout / Zen Mode),
        // reclaiming its row for the workspace.
        let status_h: u16 = if self.status_bar_visible { 1 } else { 0 };
        let outer = Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Min(1),
                Constraint::Length(osk_h),
                Constraint::Length(status_h),
            ])
            .split(size);
        let main_area = outer[0];

        // Reserve the activity bar (when shown) and the secondary side bar,
        // then clamp the primary side bar so the editor keeps RIGHT_PANE_MIN.
        let activity_w = if self.activity_bar_visible {
            ACTIVITY_BAR_WIDTH
        } else {
            0
        };
        let secondary_w = if self.secondary_side_bar_visible {
            SECONDARY_SIDEBAR_WIDTH
        } else {
            0
        };
        let max_sidebar = main_area
            .width
            .saturating_sub(activity_w)
            .saturating_sub(secondary_w)
            .saturating_sub(RIGHT_PANE_MIN);
        let sidebar_w = self
            .sidebar_width
            .clamp(SIDEBAR_WIDTH_MIN, max_sidebar.max(SIDEBAR_WIDTH_MIN));
        // Persist the clamped value so subsequent drags start from where
        // the user can actually see the splitter.
        self.sidebar_width = sidebar_w;

        // Panel Alignment = Justify spans the panel across the full content
        // width (under the side bar): carve it off the bottom of `main` BEFORE
        // the horizontal chrome split, so the side bars sit above it.
        let justify_panel = self.show_terminal
            && !self.terminal_maximized
            && osk_h == 0
            && self.panel_alignment == PanelAlignment::Justify;
        let (chrome_area, justify_terminal) = if justify_panel {
            let total_h = main_area.height;
            let max_h = total_h
                .saturating_sub(EDITOR_HEIGHT_MIN)
                .max(TERMINAL_HEIGHT_MIN);
            let term_h = self
                .terminal_height
                .unwrap_or(total_h / 3)
                .clamp(TERMINAL_HEIGHT_MIN, max_h);
            self.terminal_height = Some(term_h);
            let rows = Layout::default()
                .direction(Direction::Vertical)
                .constraints([
                    Constraint::Min(EDITOR_HEIGHT_MIN),
                    Constraint::Length(term_h),
                ])
                .split(main_area);
            (rows[0], Some(rows[1]))
        } else {
            (main_area, None)
        };

        // Pure horizontal split of the workspace chrome (honors activity-bar
        // visibility, side bar position, and the secondary side bar).
        let chrome = compute_chrome_layout(
            chrome_area,
            self.activity_bar_visible,
            self.show_tree,
            self.secondary_side_bar_visible,
            self.side_bar_position,
            sidebar_w,
            SECONDARY_SIDEBAR_WIDTH,
        );
        let activity_area = chrome.activity;
        let side_area = chrome.primary_side;
        let secondary_area = chrome.secondary_side;
        let right_area = chrome.right;
        // Remember the Explorer column so the zoxide jump popup can anchor
        // over it instead of centering on the whole frame.
        self.last_sidebar_area = side_area;
        self.sidebar_splitter_x = chrome.sidebar_splitter_x;
        self.last_content_width = right_area.width;
        self.last_content_height = right_area.height;

        // Editor ↔ terminal split within the editor column. `terminal_band` is
        // the full bottom strip; `terminal_area` is where the terminals draw
        // (narrower than the band under Left/Right alignment).
        let (editor_area, terminal_area, terminal_band) = if let Some(jt) = justify_terminal {
            // The panel was already carved full-width from `main`; the editor
            // fills the rest of its column and the splitter sits at the seam.
            self.terminal_splitter_y = Some(jt.y);
            (right_area, Some(jt), Some(jt))
        } else if osk_h > 0 && self.focus == Pane::Terminal && self.show_terminal {
            let zero_editor = Rect {
                x: right_area.x,
                y: right_area.y,
                width: right_area.width,
                height: 0,
            };
            self.terminal_splitter_y = None;
            (zero_editor, Some(right_area), Some(right_area))
        } else if osk_h > 0 {
            self.terminal_splitter_y = None;
            (right_area, None, None)
        } else if self.show_terminal {
            if self.terminal_maximized {
                // Editor / welcome collapses; terminal fills the entire
                // right column next to the Explorer. Splitter is hidden
                // because there is nothing to drag against.
                let zero_editor = Rect {
                    x: right_area.x,
                    y: right_area.y,
                    width: right_area.width,
                    height: 0,
                };
                self.terminal_splitter_y = None;
                (zero_editor, Some(right_area), Some(right_area))
            } else {
                let total_h = right_area.height;
                let pinned = self.terminal_height.map(|h| {
                    h.clamp(
                        TERMINAL_HEIGHT_MIN,
                        total_h
                            .saturating_sub(EDITOR_HEIGHT_MIN)
                            .max(TERMINAL_HEIGHT_MIN),
                    )
                });
                let rows = if let Some(term_h) = pinned {
                    self.terminal_height = Some(term_h);
                    Layout::default()
                        .direction(Direction::Vertical)
                        .constraints([
                            Constraint::Min(EDITOR_HEIGHT_MIN),
                            Constraint::Length(term_h),
                        ])
                        .split(right_area)
                } else {
                    Layout::default()
                        .direction(Direction::Vertical)
                        .constraints([Constraint::Percentage(65), Constraint::Percentage(35)])
                        .split(right_area)
                };
                self.terminal_splitter_y = Some(rows[1].y);
                let band = rows[1];
                // Left/Right alignment hugs the panel to that half of the band.
                let term = panel_band_rect(band, self.panel_alignment);
                (rows[0], Some(term), Some(band))
            }
        } else {
            self.terminal_splitter_y = None;
            (right_area, None, None)
        };
        // Centered Layout (#1585): the editor keeps its width in the middle
        // of the column and the margins stay plain background.
        let editor_area = if self.centered_layout_active() {
            centered_editor_rect(editor_area, self.centered_layout_width)
        } else {
            editor_area
        };

        if let Some(activity_area) = activity_area {
            self.render_activity_bar(frame, activity_area);
        } else {
            // Hidden activity bar: zero the icon hit-rects so clicks and the
            // post-draw OSC image flush both treat it as absent (no ghosting).
            self.sidebar_areas = SidebarAreas::default();
        }
        crate::startup_trace::mark("activity bar drawn");

        // Secondary side bar: the active file's Outline, on the edge opposite
        // the primary side bar.
        self.render_secondary_side_bar(frame, secondary_area);

        // Whether Source Control is on screen this frame, for its `⋯` menu.
        let mut scm_drawn = false;
        if let Some(area) = side_area {
            // Croft Loch's side bar is one chrome surface: the views and the
            // Explorer's stacked sections paint on it.
            if let Some(s) = self.theme.surfaces() {
                frame.render_widget(
                    ratatui::widgets::Block::default().style(Style::default().bg(s.chrome())),
                    area,
                );
            }
            let usable_area = area;
            // The view drawn below is the side bar's current one, so it has
            // the keyboard exactly when the side bar does.
            let side_cx = self.view_cx(self.focus == Pane::Tree);
            // Explorer stacks its toggled sub-views (Open Editors / Folders /
            // Outline / Timeline / Dependencies) inside the usable strip.
            // Every other sidebar view fills it with its single activity widget.
            match self.sidebar_view {
                SidebarView::Explorer => self.render_explorer_sections(frame, usable_area),
                SidebarView::Search => self.search.draw(&side_cx, usable_area, frame.buffer_mut()),
                SidebarView::SourceControl => {
                    scm_drawn = true;
                    // The COMMITS graph section docks under the change list,
                    // capped at half the strip (like the Explorer sub-views).
                    // Hidden entirely while the repo empty-state hero shows.
                    let graph_h = if self.source_control.status.in_repo {
                        self.commit_graph
                            .desired_height(usable_area.height)
                            .min(usable_area.height.saturating_sub(6))
                    } else {
                        0
                    };
                    let scm_area = Rect {
                        height: usable_area.height - graph_h,
                        ..usable_area
                    };
                    self.sync_nested_repos();
                    self.source_control
                        .draw(&side_cx, scm_area, frame.buffer_mut());
                    if graph_h > 0 {
                        let graph_area = Rect {
                            y: usable_area.y + usable_area.height - graph_h,
                            height: graph_h,
                            ..usable_area
                        };
                        self.commit_graph.has_keys = self.source_control.keys
                            == crate::widgets::source_control::KeyStop::Commits;
                        self.commit_graph
                            .draw(&side_cx, graph_area, frame.buffer_mut());
                    } else {
                        self.commit_graph.last_area = Rect::default();
                    }
                }
                SidebarView::Remote => self.remote.draw(&side_cx, usable_area, frame.buffer_mut()),
                SidebarView::RunDebug => {
                    // Keep active file / runnability / launch.json count synced
                    // whenever the focused file changes while Run & Debug stays
                    // open (#2943), and refresh breakpoints before drawing.
                    self.sync_run_debug_if_file_changed();
                    self.sync_breakpoint_list();
                    self.run_debug
                        .draw(&side_cx, usable_area, frame.buffer_mut())
                }
                SidebarView::Extensions => {
                    self.extensions
                        .draw(&side_cx, usable_area, frame.buffer_mut())
                }
                SidebarView::Testing => {
                    self.testing.draw(&side_cx, usable_area, frame.buffer_mut())
                }
                SidebarView::CodeQL => {
                    let running = self.codeql_jobs.run.as_ref().map(|(_, since)| {
                        (self.codeql_jobs.run_name.clone(), since.elapsed().as_secs())
                    });
                    self.codeql.set_running(running);
                    self.codeql.draw(&side_cx, usable_area, frame.buffer_mut())
                }
            }
        }
        crate::startup_trace::mark("side bar drawn");
        if !self.editor_layout.is_split() && self.editor.is_blank_initial() {
            self.render_welcome(frame, editor_area);
            // The previous frame may have rendered an image-preview tab
            // whose OSC-1337 pixels are still cached in iTerm's image
            // store. Closing that tab brings us here, but ratatui's diff
            // alone doesn't tell iTerm to drop the image — flag it so the
            // main loop wipes the screen on the next pass. Both slots, in
            // case a split was just collapsed back to the welcome screen.
            self.disable_editor_image(0);
            self.disable_editor_image(1);
            // The welcome screen has no minimap (no document to preview).
            self.disable_minimap_image();
            self.editor_seams.clear();
            // Keep the editor's hit-test rectangles fresh so the activity-bar
            // / tree click logic still works even though we skipped the
            // EditorTabs widget this frame.
            self.editor.last_full_area = editor_area;
            self.editor.last_area = Rect {
                x: editor_area.x,
                y: editor_area.y,
                width: editor_area.width,
                height: 0,
            };
        } else {
            // The editor just overdrew whatever cells the welcome image
            // occupied; if the user reopens the welcome screen we'll need
            // to re-emit it.
            self.overlays.welcome.mark_dirty();
            // Feed the render-time pointer cell to every editor group so the
            // tab strip can light the hovered tab body / close-cross pill,
            // mirroring the terminal pane buttons' hover affordance.
            let pointer = self.pointer_cell;
            self.editor.hover_pointer = pointer;
            // A pop-up takes the keyboard without moving focus (no focus
            // sync runs when one opens), so the editor learns each frame to
            // drop its accent marks while one is up (#2679).
            self.editor.overlay_has_keyboard = self.popup_open();
            // Without an inline-image protocol an image tab draws itself in
            // half blocks (#1591).
            let cell_images = !self.inline_images_enabled();
            self.editor.cell_images = cell_images;
            // Every group gets the pointer, not only the focused one, so a
            // preview beside the source lifts its links too (#1939).
            for group in self.editor_layout.inactive_groups_mut() {
                group.cell_images = cell_images;
                group.hover_pointer = pointer;
            }
            // Breadcrumb bar: recompute the path + symbol trail for the active
            // file each frame so it tracks caret moves and outline updates.
            self.editor.breadcrumbs = self.build_breadcrumbs();
            // Sticky scroll: recompute the pinned scope headers from the top
            // visible line each frame so they track scrolling.
            self.editor.sticky_lines = self.build_sticky_lines();
            // Multiplayer ghost carets: other participants' parked carets in
            // the active file, in their colors. The current typist's caret is
            // the live cursor, so it never ghosts; departed participants drop
            // out with the roster.
            self.editor.ghost_carets = match self.editor.path.clone() {
                Some(path) if !self.session_carets.is_empty() => self
                    .session_carets
                    .iter()
                    .filter(|(id, parked)| {
                        Some(**id) != self.session_typist
                            && parked.path == path
                            && self.session_participants.iter().any(|p| p.id == **id)
                    })
                    .map(|(id, parked)| (parked.row, parked.col, participant_color(*id)))
                    .collect(),
                _ => Vec::new(),
            };
            // Collab peers' carets (Phase D independent viewports): same
            // ghost rendering, keyed by workspace-relative file, plus a name
            // tag while the caret is inside its fade window. The seated
            // navigator's caret wears its identity accent.
            self.editor.ghost_caret_labels.clear();
            if !self.collab.carets.is_empty()
                && let Some(active) = self
                    .editor
                    .path
                    .as_ref()
                    .and_then(|p| collab_file_key(&self.tree.root, p))
            {
                let navigator_sites = self
                    .pair
                    .host
                    .as_ref()
                    .map(|h| h.caret_sites())
                    .unwrap_or_default();
                let now = std::time::Instant::now();
                for (site, c) in &self.collab.carets {
                    if c.file != active {
                        continue;
                    }
                    let color = collab_caret_color(&navigator_sites, *site);
                    self.editor.ghost_carets.push((c.row, c.col, color));
                    if !c.name.is_empty() && now.duration_since(c.last_moved) < CARET_LABEL_FADE {
                        self.editor
                            .ghost_caret_labels
                            .push((c.row, c.col, c.name.clone(), color));
                    }
                }
            }
            // Gutter stop button for an AI stream into the active file; the
            // hoisted group is the only one that shows it (clear the rest so
            // a group swap never leaves a stale button behind).
            self.editor.stream_stop_line = self.stream_stop_row();
            // The navigator's comment boxes for the active file, same
            // hoisting rule (rows come from poll_pair's per-tick snapshot).
            let author = self
                .pair
                .host
                .as_ref()
                .map(|h| h.name().to_string())
                .unwrap_or_default();
            self.editor.comment_boxes = self
                .editor
                .path
                .as_ref()
                .and_then(|p| collab_file_key(&self.tree.root, p))
                .and_then(|file| self.pair.navigator_notes.get(&file))
                .map(|notes| {
                    notes
                        .iter()
                        .map(|(id, row, body)| crate::widgets::editor::CommentBox {
                            id: *id,
                            line: *row,
                            author: author.clone(),
                            body: body.clone(),
                        })
                        .collect()
                })
                .unwrap_or_default();
            // Review threads (#366) join the navigator's rather than
            // replacing them: both are comments on the same lines, and a
            // reviewer reading a PR with a navigator session open wants
            // both. Appended after, so a navigator note and a review
            // comment on one line keep a stable order.
            if let Some((path, threads)) = &self.review.boxes
                && self.editor.path.as_deref() == Some(path.as_path())
            {
                let lines = self.editor.lines.len();
                self.editor.comment_boxes.extend(threads.iter().map(|t| {
                    crate::widgets::editor::CommentBox {
                        id: t.id,
                        line: t.box_line(lines),
                        author: t.title_for(lines),
                        body: t.body.clone(),
                    }
                }));
            }
            // Sticky notes (#367) on this file, at their re-found lines.
            self.note_box_ids.clear();
            if let Some(file) = self.note_file_key() {
                let lines = &self.editor.lines;
                let boxes: Vec<(u64, String, crate::widgets::editor::CommentBox)> = self
                    .notes
                    .on_file(&file)
                    .map(|n| {
                        let id = Self::note_box_id(&n.id);
                        (
                            id,
                            n.id.clone(),
                            crate::widgets::editor::CommentBox {
                                id,
                                line: n.place(lines),
                                author: n.title(),
                                body: n.text(),
                            },
                        )
                    })
                    .collect();
                for (id, note_id, b) in boxes {
                    self.note_box_ids.insert(id, note_id);
                    self.editor.comment_boxes.push(b);
                }
            }
            // Pending review comments (#366) on this file, until submitted.
            if !self.review.pending.is_empty()
                && let Some((root, _)) = &self.review.pr
                && let Some(rel) = self.editor.path.as_deref().and_then(|p| {
                    let top = self.git_worker_for_root(root).status().repo_root.clone()?;
                    p.strip_prefix(&top).ok().map(|r| {
                        r.components()
                            .map(|c| c.as_os_str().to_string_lossy())
                            .collect::<Vec<_>>()
                            .join("/")
                    })
                })
            {
                let lines = self.editor.lines.len();
                for (i, c) in self.review.pending.iter().enumerate() {
                    if c.path == rel {
                        self.editor
                            .comment_boxes
                            .push(crate::widgets::editor::CommentBox {
                                id: Self::PENDING_REVIEW_ID + i as u64,
                                line: c.line.min(lines.saturating_sub(1)),
                                author: String::from("you \u{b7} pending"),
                                body: c.body.clone(),
                            });
                    }
                }
            }
            // A focused box that vanished (ignored elsewhere, cleared, or
            // re-anchored away) releases the keyboard back to the buffer.
            if let Some(focus) = &self.editor.comment_focus
                && !self.editor.comment_boxes.iter().any(|b| b.id == focus.id)
            {
                self.editor.comment_focus = None;
            }
            for group in self.editor_layout.inactive_groups_mut() {
                for ed in &mut group.editors {
                    ed.stream_stop_line = None;
                    ed.comment_boxes.clear();
                    ed.comment_focus = None;
                }
            }
            // Render the editor group layout tree. The active group is hoisted
            // into `self.editor`; every other group lives in `editor_layout`.
            // Lay the leaves out and paint each at its rect (depth-first order),
            // reporting the active group's rect so popups anchor there.
            self.editor_layout_area = editor_area;
            let rects = self.editor_layout.leaf_rects(editor_area, EDITOR_SPLIT_MIN);
            // The layout icons sit over the right end of the editor area's top
            // row; any group's tab strip that reaches it stops short of them.
            let icons_left = if editor_area.width >= LAYOUT_ICONS_W {
                editor_area.x + editor_area.width - LAYOUT_ICONS_W
            } else {
                u16::MAX
            };
            let reserve = |r: Rect| -> u16 {
                if r.y == editor_area.y {
                    (r.x + r.width).saturating_sub(icons_left).min(r.width)
                } else {
                    0
                }
            };
            if self.scrub.scrubber.is_some() && self.scrub.view_for != self.editor.path {
                self.rebuild_scrub_view();
            }
            let paint_history = self.scrub.view.is_some();
            let active_idx = self.editor_layout.active_dfs_index();
            let focused_area = if self.editor_layout.is_split() {
                let mut rects = rects;
                // The active group carries the minimap (#1231).
                let minimap = self.carve_minimap(rects[active_idx]);
                if let Some((ed_rect, full_strip, _)) = minimap {
                    frame.render_widget(
                        ratatui::widgets::Block::default()
                            .style(Style::default().bg(self.theme.editor_bg())),
                        full_strip,
                    );
                    rects[active_idx] = ed_rect;
                }
                let active_area = rects[active_idx];
                self.editor.set_tab_reserved_right(reserve(active_area));
                frame.render_widget(&mut self.editor, active_area);
                if let Some((_, full_strip, _)) = minimap {
                    self.paint_minimap_header(frame.buffer_mut(), full_strip);
                }
                let inactive_rects: Vec<Rect> = rects
                    .iter()
                    .enumerate()
                    .filter(|(i, _)| *i != active_idx)
                    .map(|(_, r)| *r)
                    .collect();
                for (group, rect) in self.editor_layout.inactive_groups_mut().zip(inactive_rects) {
                    group.hover_pointer = pointer;
                    group.set_tab_reserved_right(reserve(rect));
                    frame.render_widget(group, rect);
                }
                // Every boundary in the grid is a draggable seam (one per
                // internal child edge of every split node, any depth).
                self.editor_seams = self.editor_layout.seams(editor_area, EDITOR_SPLIT_MIN);
                // Image overlays stay keyed by physical column (0 = left).
                if rects.len() == 2 {
                    self.update_editor_image_overlay(0, rects[0]);
                    self.update_editor_image_overlay(1, rects[1]);
                } else {
                    self.update_editor_image_overlay(0, active_area);
                    self.disable_editor_image(1);
                }
                match minimap {
                    Some((_, _, img_rect)) => self.paint_minimap(frame, img_rect),
                    None => self.disable_minimap_image(),
                }
                active_area
            } else if let Some((ed_rect, full_strip, img_rect)) = self.carve_minimap(editor_area) {
                // Bg-fill the whole strip column so no stale cells show
                // through, then paint the editor into the narrowed rect and
                // bake the minimap raster into the text-aligned sub-rect.
                frame.render_widget(
                    ratatui::widgets::Block::default()
                        .style(Style::default().bg(self.theme.editor_bg())),
                    full_strip,
                );
                self.editor.set_tab_reserved_right(reserve(ed_rect));
                frame.render_widget(&mut self.editor, ed_rect);
                self.paint_minimap_header(frame.buffer_mut(), full_strip);
                self.editor_seams.clear();
                self.update_editor_image_overlay(0, ed_rect);
                self.disable_editor_image(1);
                self.paint_minimap(frame, img_rect);
                ed_rect
            } else {
                self.editor.set_tab_reserved_right(reserve(editor_area));
                frame.render_widget(&mut self.editor, editor_area);
                self.editor_seams.clear();
                self.update_editor_image_overlay(0, editor_area);
                // No right pane: make sure its slot can't ghost an image.
                self.disable_editor_image(1);
                self.disable_minimap_image();
                editor_area
            };
            // The history scrubber's view stands in for the live editor's
            // text (#371); the tab strip stays the live one, while the breadcrumbs
            // and Outline follow the commit (see `sync_outline`).
            if paint_history
                && let Some(view) = self.scrub.view.as_mut()
                && self.editor.last_body.width > 0
            {
                view.theme = self.theme;
                // The editor paints only the rows it has text for, so a
                // shorter historical file would leave the live buffer's
                // lower lines showing through: blank the body first.
                let body = self.editor.last_body;
                frame.render_widget(ratatui::widgets::Clear, body);
                frame.render_widget(
                    ratatui::widgets::Block::default()
                        .style(Style::default().bg(self.theme.editor_bg())),
                    body,
                );
                frame.render_widget(view, body);
            }
            self.render_scrub_slider(frame);
            if self.focus == Pane::Editor
                && self.completion.popup.is_some()
                && let Some((cx, cy)) = self.editor.cursor_screen_pos()
            {
                if let Some(popup) = self.completion.popup.as_mut() {
                    popup.anchor = (cx, cy);
                    popup.theme = self.theme;
                }
                let popup_ref = self.completion.popup.as_ref().unwrap();
                let area = popup_ref.area_for(focused_area);
                if area.width > 0 && area.height > 0 {
                    frame.render_widget(popup_ref, area);
                    // The selected item's signature and documentation (#1527).
                    if let Some(details) = popup_ref.details_area_for(area, focused_area) {
                        frame.render_widget(popup_ref.details().beside(area), details);
                    }
                }
            }
            // Parameter hints sit ABOVE the caret, so they coexist with the
            // completion popup below it.
            if self.focus == Pane::Editor
                && self.signature_help_popup.is_some()
                && let Some((cx, cy)) = self.editor.cursor_screen_pos()
            {
                if let Some(popup) = self.signature_help_popup.as_mut() {
                    popup.anchor = (cx, cy);
                    popup.theme = self.theme;
                }
                let popup_ref = self.signature_help_popup.as_ref().unwrap();
                let area = popup_ref.area_for(focused_area);
                if area.width > 0 && area.height > 0 {
                    frame.render_widget(popup_ref, area);
                }
            }
            // Placed here, where the focused group is known, and drawn with
            // the other pop-ups once the pictures' cells are noted: drawn
            // here, a tooltip over an image's first rows counted as part of
            // the picture, which was then sent over it (Codex, #2664).
            if let Some(popup) = self.tab_tooltip.as_mut() {
                popup.theme = self.theme;
                let area = popup.area_for(focused_area);
                if area.width > 0 && area.height > 0 {
                    tab_tooltip_area = Some(area);
                }
            }
            // Layout-control icons at the top-right of the editor tab strip.
            // A collapsed editor (the panel maximized over it) has no strip,
            // and its row is the panel's tab row: a one-row strip there would
            // leave the icons' hit rects over the panel's buttons (#1980).
            let strip_row = Rect {
                x: editor_area.x,
                y: editor_area.y,
                width: editor_area.width,
                height: editor_area.height.min(1),
            };
            self.paint_layout_icons(frame, strip_row);
        }
        crate::startup_trace::mark("editor drawn");
        // Every tab and button of the panel starts the frame with no area,
        // drawn or not: one that is not drawn this frame must not keep the
        // last frame's, whose cells now belong to whatever is drawn there.
        self.panel_hits.reset();
        if let Some(area) = terminal_area {
            // Left/Right panel alignment narrows the terminal to one half of
            // its band; paint the leftover strip with the editor background so
            // the vacated cells don't ghost the previous frame.
            if let Some(band) = terminal_band
                && (band.width != area.width || band.x != area.x)
            {
                frame.render_widget(
                    ratatui::widgets::Block::default()
                        .style(Style::default().bg(self.theme.editor_bg())),
                    band,
                );
            }
            // The panel group's tab strip (PROBLEMS / TERMINAL) takes the top
            // row; the active tab's view fills the rest. Mirrors VS Code's
            // bottom-panel tab bar.
            // At a one-row window the band is zero rows high just below the
            // frame, and a one-row strip there writes outside the buffer
            // (#1133). A panel of one row gives that row to its view below, so
            // it has no tab row either: one painted there is drawn over, and
            // its tabs and buttons would stay clickable under the panes'
            // cells (#1980 review).
            let strip = Rect {
                x: area.x,
                y: area.y,
                width: area.width,
                height: u16::from(area.height > 1),
            };
            let content = if area.height > 1 {
                Rect {
                    x: area.x,
                    y: area.y + 1,
                    width: area.width,
                    height: area.height - 1,
                }
            } else {
                area
            };
            self.paint_panel_tabs(frame, strip);
            // The panel's views draw with this frame's pointer, so the row
            // under the mouse lights up on every move and goes dark when the
            // pointer leaves (#2068), and with the panel's focus.
            let panel_cx = self.view_cx(self.focus == Pane::Terminal);
            match self.bottom_panel_tab {
                BottomPanelTab::Terminal => {
                    let n = self.terminals.len().max(1);
                    let multi = self.terminals.len() > 1;
                    let maximized = self.terminal_pane_maximized && multi;
                    // Maximize mode: the active pane owns the panel's width
                    // minus a right rail listing every terminal (VS Code's
                    // terminal-tabs list); hidden panes drop their hit rects
                    // so clicks can't phantom-match. Otherwise: even split.
                    let single_col;
                    let multi_cols: Vec<Rect>;
                    let cols: &[Rect] = if maximized {
                        // The rail is a fixed, very narrow switcher column:
                        // icon + 4 label characters, nothing adaptive.
                        let rail_w = TERMINAL_RAIL_W.min(content.width.saturating_sub(20));
                        let pane = Rect {
                            x: content.x,
                            y: content.y,
                            width: content.width - rail_w,
                            height: content.height,
                        };
                        let rail = Rect {
                            x: content.x + pane.width,
                            y: content.y,
                            width: rail_w,
                            height: content.height,
                        };
                        self.paint_terminal_rail(frame, rail);
                        multi_cols = (0..n)
                            .map(|i| {
                                if i == self.active_terminal {
                                    pane
                                } else {
                                    Rect::default()
                                }
                            })
                            .collect();
                        &multi_cols
                    } else if n == 1 {
                        single_col = [content];
                        &single_col
                    } else {
                        // Collapsed panes (#313) keep a one-column strip and
                        // the rest divide what is left. Read off the panes
                        // rather than a list held here, so a reorder or a
                        // close can never leave the flags naming the wrong
                        // terminal.
                        let collapsed: Vec<bool> = (0..n)
                            .map(|i| self.terminals.get(i).is_some_and(|t| t.collapsed))
                            .collect();
                        multi_cols = Layout::default()
                            .direction(Direction::Horizontal)
                            .constraints(terminal_pane_constraints(&collapsed))
                            .split(content)
                            .to_vec();
                        &multi_cols
                    };
                    // Theme the terminal background like VS Code's integrated
                    // terminal: prefill each pane with the theme bg before the
                    // grid paints. Shell-colored cells override it; default-bg
                    // cells (Style bg = None) keep the fill. On iTerm2 this
                    // matches the SetColors session bg; on Ghostty/Kitty (which
                    // ignores SetColors) it's what makes the terminal follow the
                    // theme at all instead of showing the host's own bg.
                    let term_bg = self.theme.editor_bg();
                    for (i, t) in self.terminals.iter_mut().enumerate() {
                        // A collapsed pane is not rendered, and that is what
                        // keeps its shell intact: rendering is what resizes
                        // the PTY, and reflowing a running shell into one
                        // column would mangle everything already on its
                        // screen. It keeps the geometry it had, so expanding
                        // brings the pane back as it was rather than as a
                        // column of broken wrapping. Its `last_area` is
                        // cleared so a click on the strip cannot land in a
                        // grid that is no longer painted there.
                        if cols[i].width == 0 || (t.collapsed && !maximized) {
                            t.last_area = Rect::default();
                            // `last_inner` too (#510): it anchors the image
                            // overlay's raw CUP write, so a stale rect sends
                            // the payload outside the pane with nothing to
                            // catch it. The other terminal-pane clears below
                            // need no counterpart - the overlay returns early
                            // when the panel is hidden or off the Terminal
                            // tab, which is what makes them unreachable for
                            // it. A consumer that drops that guard inherits
                            // this obligation.
                            t.last_inner = Rect::default();
                            t.redacted_on_screen = 0;
                        } else {
                            frame.render_widget(
                                ratatui::widgets::Block::default()
                                    .style(Style::default().bg(term_bg)),
                                cols[i],
                            );
                            frame.render_widget(t, cols[i]);
                        }
                    }
                    let show_close = multi;
                    // Croft Loch hangs a lone terminal's `∨ +` on the tab row,
                    // just left of the panel chevron, as VS Code does: the
                    // panel's controls then share one row instead of stepping
                    // down onto the pane, whose top edge stays a clean rule.
                    // Only when both fit between the last tab and the chevron;
                    // otherwise they keep the pane's top row.
                    let header_slot = (crate::theme::tones(self.theme).is_some()
                        && self.terminals.len() == 1
                        && !self.terminals[0].collapsed
                        && strip.height == 1
                        && !self.panel_hits.maximize_button.is_empty())
                    .then(|| {
                        let tabs_end = [
                            self.panel_hits.problems_tab,
                            self.panel_hits.output_tab,
                            self.panel_hits.terminal_tab,
                            self.panel_hits.ports_tab,
                            self.panel_hits.captures_tab,
                        ]
                        .iter()
                        .map(|r| r.right())
                        .max()
                        .unwrap_or(strip.x);
                        let x0 = tabs_end + 1;
                        // The buttons keep one blank column at their right
                        // edge; ending the slot one cell into the chevron
                        // lays that column on the chevron's own padding, so
                        // `+` sits two cells from the chevron's glyph, the
                        // same step as between `∨` and `+`.
                        let x1 = self.panel_hits.maximize_button.x + 1;
                        Rect::new(x0, strip.y, x1.saturating_sub(x0), 1)
                    })
                    .filter(|slot| {
                        let need = TERMINAL_ADD_LABEL.chars().count()
                            + TERMINAL_PROFILE_LABEL.chars().count()
                            + 2;
                        usize::from(slot.width) >= need
                    });
                    for (i, col) in cols.iter().enumerate().take(self.terminals.len()) {
                        // Hidden panes still push placeholders so a button's
                        // position in each vec names its terminal index.
                        if col.width == 0 {
                            self.panel_hits.add_buttons.push(Rect::default());
                            self.panel_hits.profile_buttons.push(Rect::default());
                            self.panel_hits.close_buttons.push(Rect::default());
                            self.panel_hits.pane_labels.push(Rect::default());
                            self.panel_hits.collapse_buttons.push(Rect::default());
                            self.panel_hits.collapsed_strips.push(Rect::default());
                            continue;
                        }
                        // A collapsed pane's whole chrome is its strip: no
                        // header buttons fit in one column, and the only
                        // gesture it offers is the way back out.
                        if self.terminals[i].collapsed && !maximized {
                            let strip = self.paint_terminal_collapsed_strip(frame, *col, i);
                            self.panel_hits.add_buttons.push(Rect::default());
                            self.panel_hits.profile_buttons.push(Rect::default());
                            self.panel_hits.close_buttons.push(Rect::default());
                            self.panel_hits.pane_labels.push(Rect::default());
                            self.panel_hits.collapse_buttons.push(Rect::default());
                            self.panel_hits.collapsed_strips.push(strip);
                            continue;
                        }
                        self.panel_hits.collapsed_strips.push(Rect::default());
                        let buttons = paint_terminal_pane_buttons(
                            frame,
                            header_slot.unwrap_or(*col),
                            show_close,
                            maximized,
                            self.theme,
                            self.pointer_cell,
                        );
                        self.panel_hits
                            .add_buttons
                            .push(buttons.add.unwrap_or_default());
                        self.panel_hits
                            .profile_buttons
                            .push(buttons.profile.unwrap_or_default());
                        self.panel_hits
                            .close_buttons
                            .push(buttons.close.unwrap_or_default());
                        self.panel_hits
                            .collapse_buttons
                            .push(buttons.collapse.unwrap_or_default());
                        // Auto/manual pane label at top-left, only with 2+ panes
                        // (a lone pane needs no name). Kept clear of the buttons.
                        // The painted pill doubles as the drag-reorder handle,
                        // so its rect is recorded index-aligned with the pane.
                        let mut label_rect = Rect::default();
                        if multi {
                            let label = self.terminals[i].label().to_string();
                            // The pill is painted AFTER the header buttons and
                            // wins the shared cells, so its budget has to
                            // clear the button strip plus the pill's own
                            // widest decoration (a leading `⚠` or `⇶` and the
                            // two spaces every pill carries).
                            let room =
                                col.width.saturating_sub(TERMINAL_BUTTON_STRIP_W + 4) as usize;
                            // While broadcast input is on, every pane that
                            // receives the mirrored keystrokes wears an
                            // unmissable red pill with a ⇶ marker
                            // (Terminator's role colouring); excluded panes
                            // keep the normal pill. The marker paints even
                            // while the pane's auto-label is still empty.
                            let receiving = self.broadcast_input
                                && (i == self.active_terminal
                                    || !self.terminals[i].broadcast_excluded);
                            // An agent pane wears its badge in the pill
                            // (`◆ claude ◐`, #344); the badge takes the room
                            // first and the label is clipped to what is left.
                            let badge = self.terminals[i]
                                .agent()
                                .map(|a| format!("\u{25c6} {} {}", a.name, a.status.glyph()));
                            let label = match &badge {
                                Some(b) if label.is_empty() => b.clone(),
                                Some(b) => format!("{b} {label}"),
                                None => label,
                            };
                            if (!label.is_empty() || receiving) && room >= 3 {
                                let shown: String = label.chars().take(room).collect();
                                let mut text = if receiving && shown.is_empty() {
                                    String::from(" \u{21f6} ")
                                } else if receiving {
                                    format!(" \u{21f6} {shown} ")
                                } else {
                                    format!(" {shown} ")
                                };
                                // A live OSC 9;4 percent joins the pill (the
                                // border gauge is the primary drawing; this
                                // keeps unfocused panes glanceable). The
                                // indeterminate state has no number to show.
                                if let Some((state, pct)) = self.terminals[i].progress()
                                    && state != 3
                                    && text.chars().count() + 6 <= room
                                {
                                    text = format!("{}\u{b7} {pct}% ", text);
                                }
                                let accent = self.terminals[i].accent;
                                let text = if accent.is_some() && !receiving {
                                    format!(" \u{26a0}{text}")
                                } else {
                                    text
                                };
                                let style = if receiving {
                                    Style::default()
                                        .fg(Color::Black)
                                        .bg(self.theme.ui(Color::Rgb(0xe7, 0x70, 0x70)))
                                        .add_modifier(Modifier::BOLD)
                                } else if let Some((r, g, b)) = accent {
                                    Style::default()
                                        .fg(Color::Black)
                                        .bg(Color::Rgb(r, g, b))
                                        .add_modifier(Modifier::BOLD)
                                } else if let Some(t) = crate::theme::tones(self.theme) {
                                    // Croft Loch names the pane with the
                                    // keyboard in the strong ink, the rest
                                    // muted, so the labels say where focus is.
                                    Style::default().fg(if self.terminals[i].focused {
                                        t.strong()
                                    } else {
                                        t.muted()
                                    })
                                } else {
                                    crate::widgets::header_pill::action_style(self.theme, false)
                                };
                                // `room` bounds how much of the name is worth
                                // showing, but it counts CHARACTERS while the
                                // buffer advances by display CELLS, so a CJK
                                // or emoji name is twice as wide as its budget
                                // and would still reach the buttons. Clip the
                                // paint to the cells before the button strip —
                                // `set_stringn` measures grapheme width, which
                                // is the same clamp the rail rows use — and
                                // take the drag handle's width from what was
                                // actually painted.
                                let budget =
                                    col.width.saturating_sub(TERMINAL_BUTTON_STRIP_W) as usize;
                                let (end_x, _) = frame
                                    .buffer_mut()
                                    .set_stringn(col.x, col.y, text, budget, style);
                                label_rect = Rect {
                                    x: col.x,
                                    y: col.y,
                                    width: end_x.saturating_sub(col.x),
                                    height: 1,
                                };
                            }
                        }
                        self.panel_hits.pane_labels.push(label_rect);
                    }
                }
                BottomPanelTab::Problems => {
                    // The terminals are hidden behind the PROBLEMS view.
                    self.hide_terminal_panes();
                    self.problems.draw(&panel_cx, content, frame.buffer_mut());
                    self.paint_panel_view_top(frame, content);
                }
                BottomPanelTab::Output => {
                    self.hide_terminal_panes();
                    // Drawn from the channel as it is now (#2861): the tab may
                    // have been shown since the tick last brought it up to date.
                    self.output.sync();
                    self.output.draw(&panel_cx, content, frame.buffer_mut());
                    self.paint_panel_view_top(frame, content);
                }
                BottomPanelTab::Ports => {
                    self.hide_terminal_panes();
                    self.ports.draw(&panel_cx, content, frame.buffer_mut());
                    self.paint_panel_view_top(frame, content);
                }
                BottomPanelTab::Captures => {
                    self.hide_terminal_panes();
                    self.captures.draw(&panel_cx, content, frame.buffer_mut());
                    self.paint_panel_view_top(frame, content);
                }
            }
        } else {
            self.hide_terminal_panes();
            // The panel's other views likewise: their rows would take the
            // clicks, hover and right-clicks of the editor that now fills
            // their cells (#2740).
            self.problems.last_area = Rect::default();
            self.output.last_area = Rect::default();
            self.ports.last_area = Rect::default();
            self.captures.last_area = Rect::default();
        }

        if let Some(s) = self.theme.surfaces() {
            let status_bar = (status_h > 0 && osk_h == 0).then_some(outer[2]);
            self.paint_surface_seams(
                frame,
                s,
                activity_area,
                [side_area, secondary_area],
                terminal_area,
                status_bar,
            );
        }

        crate::startup_trace::mark("panel drawn");
        // Render the on-screen keyboard band before the status bar so the
        // status bar can borrow `&self` fields without cloning them.
        if let Some(osk) = self.osk.as_mut() {
            if osk_h > 0 {
                crate::widgets::osk::render_osk(osk, outer[1], frame.buffer_mut(), self.theme);
            } else {
                // Collapsed (frame too short): zero the hit rect so the
                // invisible band can't swallow clicks.
                osk.last_area = Rect::default();
            }
        }
        // A message seen for the first time is kept, in full, in the Messages
        // output channel, and may take the whole bar until the next key or
        // click (#1609): elided to fit, its middle was gone for good.
        if self.status != self.status_logged {
            self.status_logged = self.status.clone();
            // The idle "Ready" says nothing worth the cluster's room.
            self.status_wide = !self.status.is_empty() && self.status != "Ready";
            if !self.status.is_empty() {
                crate::output::push(
                    crate::output::CHANNEL_MESSAGES,
                    crate::output::OutputLevel::Info,
                    &crate::i18n::tr(&self.status),
                );
            }
        }
        self.announce_pos = None;
        // Every clickable item of the bar starts with no area and is recorded
        // again below where it is drawn. The update pill's hover below reads
        // the last frame's area before we reset `status_hits`.
        let prev_offer_hit = self.status_hits.offer;
        self.status_hits = StatusHitAreas::default();

        let status_rect = outer[2].intersection(frame.area());
        let status_visible = status_h > 0 && status_rect.height > 0 && status_rect.width > 0;
        let status_bg = status_bar_bg(self.theme);
        let tones = StatusTones::new(self.theme, status_bg);
        let bg_style = Style::default().bg(status_bg);
        if status_visible {
            let buf = frame.buffer_mut();
            for x in status_rect.left()..status_rect.right() {
                let cell = &mut buf[(x, status_rect.y)];
                cell.set_symbol(" ");
                cell.set_style(bg_style);
            }
        }
        use std::borrow::Cow;
        use std::fmt::Write as _;
        let mut left = StatusPainter::new(frame.buffer_mut(), status_rect);
        let workspace_name: Cow<'_, str> = self
            .workspace_root()
            .file_name()
            .map(|n| n.to_string_lossy())
            .unwrap_or_else(|| Cow::Owned(self.workspace_root().display().to_string()));
        left.paint_spans(workspace_cap_spans(self.theme, &workspace_name));
        if self.overwrite_mode {
            left.paint_str(" ", Style::default());
            left.paint_span(&overwrite_mode_span());
        }
        let redacted = self.redacted_on_screen();
        if redacted > 0 || self.redactions_revealed() {
            // How much of what is on screen is masked right now (#360): a
            // screen-share host wants to know the count is non-zero, and
            // that a reveal window is open.
            let (label, bg) = if self.redactions_revealed() {
                (
                    format!("\u{1f441} {redacted} revealed"),
                    Color::Rgb(0xc0, 0x39, 0x2b),
                )
            } else {
                (
                    format!("\u{2022} {redacted} redacted"),
                    Color::Rgb(0x3a, 0x3f, 0x4b),
                )
            };
            left.paint_spans(status_pill(&label, self.theme.ui(bg), Color::White));
            left.paint_str(" ", Style::default());
        }
        if let Some(span) = self.perf.status_span() {
            left.paint_span(&span);
        }
        // The pill the update card rises from and Later folds it into; a
        // click opens or folds the card. Recorded as (start column, width).
        let offer_chip_x = left.col;
        if let Some(toast) = self.update_toast.as_ref().filter(|t| !t.ready) {
            let hovered = crate::widgets::hover::contains(prev_offer_hit, self.pointer_cell);
            left.paint_spans(crate::widgets::update_popup::pill_spans(
                &format!(
                    "{} Update Available: v{}",
                    crate::widgets::update_popup::PACKAGE_GLYPH,
                    toast.release.version
                ),
                crate::widgets::update_popup::pill_fill(self.theme, hovered),
                Color::White,
            ));
        }
        let offer_chip = (left.col > offer_chip_x).then(|| (offer_chip_x, left.col - offer_chip_x));
        if offer_chip.is_some() {
            left.paint_str(" ", Style::default());
        }
        // Both update pills are one click target, doing what the updater
        // chord does (#865); recorded as (start column, width).
        let update_chip_x = left.col;
        if self.any_update_ready() {
            left.paint_spans(crate::widgets::update_popup::pill_spans(
                &format!(
                    "{} Update ready - {UPDATE_CROFT_CHORD} to relaunch",
                    crate::widgets::update_popup::READY_GLYPH
                ),
                self.theme.ui(Color::Rgb(0x1f, 0x7a, 0x33)),
                Color::White,
            ));
        }
        if let Some(current) = self.local_drift.as_ref()
            && self.update_status == UpdateStatus::Idle
            && self.self_install.is_none()
            // The same latch as `update_armed`: while the staged release
            // builds, the chord is not a rebuild, so the hint must not say so.
            && self.staged_status != UpdateStatus::InProgress
            && self.staged_install.is_none()
        {
            // Amber, persistent: the binary predates its own source tree
            // (#242). One keypress rebuilds it in the background.
            left.paint_str(
                &format!(
                    " ⟳ croft {} < repo {current} - {UPDATE_CROFT_CHORD} to rebuild ",
                    env!("CROFT_GIT_HASH")
                ),
                Style::default()
                    .bg(self.theme.ui(Color::Rgb(0x8a, 0x60, 0x00)))
                    .fg(Color::White)
                    .add_modifier(Modifier::BOLD),
            );
        }
        let update_chip =
            (left.col > update_chip_x).then(|| (update_chip_x, left.col - update_chip_x));
        if self.any_update_in_progress() {
            // Red + a spinning circular-arrow glyph to draw the eye to the
            // in-progress background update. It is the update's one progress
            // indicator (#1852), so a staged release names the version the
            // popup offered before it closed.
            let target = self
                .staged_install
                .as_ref()
                .filter(|_| self.staged_status == UpdateStatus::InProgress)
                .map(|s| format!(" to v{}", s.version))
                .unwrap_or_default();
            left.paint_str(
                &format!(
                    " {} Updating croft{target} in the background ",
                    self.update_spinner_glyph()
                ),
                Style::default()
                    .fg(self.theme.ui(Color::Rgb(0xff, 0x45, 0x4d)))
                    .add_modifier(Modifier::BOLD),
            );
        }
        if let Some(progress) = self.lsp_progress_status() {
            // A busy language server (rust-analyzer priming its crate graph,
            // etc.) is otherwise invisible: hover/completion just return empty
            // until it finishes. Surfacing "rust-analyzer: Indexing " tells
            // the user to wait rather than assume the server is dead.
            left.paint_str(
                &format!(" ⟳ {progress} "),
                Style::default()
                    .fg(self.theme.ui(Color::Rgb(0x4e, 0x9a, 0xff)))
                    .add_modifier(Modifier::BOLD),
            );
        }
        if let Some(label) = &self.mcp_busy_label {
            // An in-flight extension command (install + tool call on a worker
            // thread) is otherwise invisible; an animated badge says it's working.
            left.paint_str(
                &format!(" {} {label} ", self.mcp_spinner_glyph()),
                Style::default()
                    .fg(self.theme.ui(Color::Rgb(0x2d, 0xd4, 0xbf)))
                    .add_modifier(Modifier::BOLD),
            );
        }
        if let Some((agent, until)) = &self.auto_approve {
            let left_secs = until
                .saturating_duration_since(std::time::Instant::now())
                .as_secs();
            left.paint_spans(status_pill(
                &format!(
                    "\u{2713} auto-approving {agent} {}:{:02}",
                    left_secs / 60,
                    left_secs % 60
                ),
                self.theme.ui(Color::Rgb(0x8a, 0x60, 0x00)),
                Color::White,
            ));
            left.paint_str(" ", Style::default());
        }
        if let Some(chip) = self.notebook_kernel_chip() {
            left.paint_str(
                &chip,
                Style::default()
                    .fg(self.theme.ui(Color::Rgb(0xf3, 0x9c, 0x12)))
                    .add_modifier(Modifier::BOLD),
            );
        }
        // A running CodeQL query (#578): what runs and for how long, and a
        // click on it cancels the run.
        let mut codeql_chip: Option<(u16, u16)> = None;
        if let Some((_, since)) = &self.codeql_jobs.run {
            let secs = since.elapsed().as_secs();
            let x = left.col;
            left.paint_spans(status_pill(
                &format!(
                    "\u{27f3} CodeQL {} {}:{:02} \u{2715}",
                    self.codeql_jobs.run_name,
                    secs / 60,
                    secs % 60
                ),
                self.theme.ui(Color::Rgb(0x2b, 0x5d, 0x8a)),
                Color::White,
            ));
            codeql_chip = Some((x, left.col - x));
            left.paint_str(" ", Style::default());
        }
        if let Some((_, _, started)) = &self.recording {
            // A terminal recording (#356) is the other state a user can
            // leave on; it is not the macro recorder, so it has its own
            // badge and says how long it has run.
            let secs = started.elapsed().as_secs();
            left.paint_spans(status_pill(
                &format!("\u{25cf} CAST {}:{:02}", secs / 60, secs % 60),
                self.theme.ui(Color::Rgb(0x8a, 0x1c, 0x5a)),
                Color::White,
            ));
            left.paint_str(" ", Style::default());
        }
        if let Some(rec) = &self.macro_recording {
            // Recording is state a user can forget they left on, so it gets a
            // filled red badge rather than a dim hint (#255). A named register
            // shows which one, since vim users keep several.
            let label = match rec.register {
                Some(r) => format!("● REC @{r}"),
                None => String::from("● REC"),
            };
            left.paint_spans(status_pill(
                &label,
                self.theme.ui(Color::Rgb(0xc0, 0x2b, 0x2b)),
                Color::White,
            ));
            left.paint_str(" ", Style::default());
        }
        if self.vim.enabled {
            let (text, bg): (Cow<'_, str>, Color) = match self.vim.command_line() {
                Some(cmd) => (Cow::Owned(cmd), self.theme.ui(Color::Rgb(0x33, 0x33, 0x33))),
                None => {
                    let label = self.vim.mode_label().unwrap_or("NORMAL");
                    let bg = match self.vim.mode() {
                        crate::vim::VimMode::Insert => self.theme.ui(Color::Rgb(0x1f, 0x7a, 0x33)),
                        crate::vim::VimMode::Visual | crate::vim::VimMode::VisualLine => {
                            self.theme.ui(Color::Rgb(0x8a, 0x4f, 0xbf))
                        }
                        _ => self.theme.ui(Color::Rgb(0x4e, 0x9a, 0xff)),
                    };
                    (Cow::Borrowed(label), bg)
                }
            };
            left.paint_spans(status_pill(&text, bg, Color::White));
            left.paint_str(" ", Style::default());
        }
        // Zones are set apart by air rather than by drawn dividers, the way
        // VS Code's status bar spaces its items: the bar reads as a few
        // quiet groups instead of a ruled table. The spacer keeps its one
        // cell, so no click target moves.
        let zone_div = Style::default();
        let div = " ";
        let scm_status = self.scm_worker().status();
        let scm_present = scm_status.in_repo;
        if scm_present {
            left.paint_spans(git_status_spans(scm_status, self.theme));
        }
        // The git spans open with their own air and the cap ends on its
        // rounded edge, so the spacer takes one more cell only when the
        // branch segment painted.
        left.paint_str(if scm_present { "  " } else { div }, zone_div);
        // Persistent orange badge for a remote session with no dtach: it can't
        // survive a transport drop, so flag it for the whole session (rendered
        // before the transient status so a status update never hides it).
        if let Some(warning) = self.persistence_warning {
            left.paint_spans(status_pill(
                &format!("\u{26a0} {warning}"),
                self.theme.ui(Color::Rgb(0xff, 0x9d, 0x2f)),
                self.theme.ui(Color::Rgb(0x10, 0x13, 0x1a)),
            ));
            left.paint_str(" ", Style::default());
        }
        // Multiplayer roster badge: how many clients are attached to this
        // persistent session, painted only when someone else is here
        // (manage them via Session: Participants, Cmd+K A).
        if self.session_participants.len() > 1 {
            left.paint_spans(status_pill(
                &format!("\u{f0c0} {} attached", self.session_participants.len()),
                self.theme.ui(Color::Rgb(0x2f, 0x6f, 0xd0)),
                self.theme.ui(Color::Rgb(0xff, 0xff, 0xff)),
            ));
            left.paint_str(" ", Style::default());
        }
        // AI-stream badge: a pilot is streaming an edit into a shared file;
        // orange like the persistence warning (attention, not decoration),
        // naming the cancel chord so the stop path is one glance away.
        if let Some(stream) = &self.collab.stream {
            left.paint_spans(status_pill(
                &format!(
                    "\u{23f9} {} streaming into {} (Cmd+K X to stop)",
                    stream.name, stream.file
                ),
                self.theme.ui(Color::Rgb(0xff, 0x9d, 0x2f)),
                self.theme.ui(Color::Rgb(0x10, 0x13, 0x1a)),
            ));
            left.paint_str(" ", Style::default());
        } else if let Some(host) = &self.pair.host {
            // Resident navigator seated and idle: presence, not attention —
            // the stream badge above takes over whenever it is typing.
            left.paint_str(
                &format!(" \u{25c6} {} seated ", host.title()),
                Style::default()
                    .fg(self.theme.ui(Color::Rgb(0xff, 0x9d, 0x2f)))
                    .add_modifier(Modifier::BOLD),
            );
            left.paint_str(" ", Style::default());
        }
        // Diagnostics counts (click → PROBLEMS), VS Code-style, after git.
        // Always shown so the bar reads as a health indicator at a glance,
        // but a count of zero stays dim: red and amber are kept for a count
        // that has something to say.
        let err_count = self.problems.error_count();
        let warn_count = self.problems.warning_count();
        let diag_start_col = left.col;
        left.paint_str(
            " \u{ea87} ",
            Style::default().fg(if err_count > 0 {
                self.theme.ui(Color::Rgb(0xf1, 0x4c, 0x4c))
            } else {
                tones.dim
            }),
        );
        left.paint_usize(
            err_count,
            Style::default().fg(if err_count > 0 { tones.text } else { tones.dim }),
        );
        left.paint_str(
            " \u{ea6c} ",
            Style::default().fg(if warn_count > 0 {
                self.theme.ui(Color::Rgb(0xe5, 0xb5, 0x4a))
            } else {
                tones.dim
            }),
        );
        let warn_num_style = Style::default().fg(if warn_count > 0 {
            tones.text
        } else {
            tones.dim
        });
        left.paint_usize(warn_count, warn_num_style);
        left.paint_str(" ", warn_num_style);
        let diag_len = left.col - diag_start_col;

        // ---- Right cluster: document facts, right-justified. Indentation /
        // encoding / EOL / language are clickable to change (hit rects recorded
        // below). Measured into stack buffers so steady-state frames allocate
        // nothing (#2062).
        let mut pos_buf = StackFmt::<96>::new();
        let _ = write!(
            pos_buf,
            " Ln {}, Col {}",
            self.editor.cursor_row + 1,
            self.editor.cursor_visual_col(),
        );
        if let Some(p) = self.editor.coverage.as_ref().and_then(|l| l.percent) {
            let _ = write!(pos_buf, " \u{b7} {p:.0}% covered");
        }
        // The file refuses this user's writes (#1379).
        if self.editor.write_protected {
            let _ = pos_buf.write_str(" \u{b7} Read-only");
        }
        // Column Selection Mode (#1560) rides the same segment, as VS Code
        // shows it beside the position.
        if self.editor.column_selection_mode {
            let _ = pos_buf.write_str(" \u{b7} Column Selection");
        }
        let _ = pos_buf.write_str(" ");
        let pos_str = pos_buf.as_str();

        let indent = self.editor.indent_style();
        let mut indent_buf = StackFmt::<24>::new();
        let _ = write!(
            indent_buf,
            "{}: {}",
            if indent.use_spaces {
                "Spaces"
            } else {
                "Tab Size"
            },
            indent.width,
        );
        let indent_label = indent_buf.as_str();
        let encoding_label = self.editor.encoding.name();
        let eol_label = self.editor.eol.label();
        let lang_label = self.editor.language_label();
        let language_icon = {
            let name: Cow<'_, str> = self
                .editor
                .path
                .as_deref()
                .and_then(|p| p.file_name())
                .map(|n| n.to_string_lossy())
                .unwrap_or(Cow::Borrowed(""));
            let suffix = name.rfind('.').map_or("", |i| &name[i..]);
            crate::icons::for_path(&name, suffix)
        };
        let mut lang_glyph_utf8 = [0u8; 4];
        let lang_glyph_str = language_icon.glyph.encode_utf8(&mut lang_glyph_utf8);

        // `2 agents · 1 waiting` (#344), only while an agent is seated; a
        // click focuses the waiting pane.
        let (seated, waiting) = self.agent_counts();
        // The review queue rides the same chip (#345): reading the cache
        // avoids cloning every path per frame and keeps chip and dots equal.
        let unreviewed = self.tree.agent_touched.len();
        let agents_seg: Option<String> = if seated > 0 || unreviewed > 0 {
            let agents_part = if seated > 0 {
                format!(
                    "{seated} agent{}{}",
                    if seated == 1 { "" } else { "s" },
                    if waiting > 0 {
                        format!(" \u{b7} {waiting} waiting")
                    } else {
                        String::new()
                    }
                )
            } else {
                String::new()
            };
            let review_part = if unreviewed > 0 {
                format!(
                    "{unreviewed}{} to review",
                    if self.agent_ledger.may_be_incomplete() {
                        "+"
                    } else {
                        ""
                    }
                )
            } else {
                String::new()
            };
            let joined = match (agents_part.is_empty(), review_part.is_empty()) {
                (false, false) => format!("{agents_part} \u{b7} {review_part}"),
                (false, true) => agents_part,
                _ => review_part,
            };
            Some(format!(" \u{25c6} {joined} "))
        } else {
            None
        };
        let widths: [u16; 6] = [
            status_cells(pos_str),
            status_cells(indent_label) + 2,
            status_cells(encoding_label) + 2,
            status_cells(eol_label) + 2,
            status_cells(PILL_CAP_L)
                + status_cells(lang_glyph_str)
                + 1
                + status_cells(lang_label)
                + status_cells(PILL_CAP_R),
            agents_seg.as_deref().map_or(0, status_cells),
        ];
        let seg_count: usize = if agents_seg.is_some() { 6 } else { 5 };
        // One cell of margin after the last segment, so the language pill's
        // rounded end does not touch the frame edge.
        let mut right_total: u16 =
            widths[..seg_count].iter().sum::<u16>() + (seg_count as u16 - 1) + STATUS_RIGHT_MARGIN;

        // Transient status message (e.g. "Saved editor.rs"), no keybinding
        // cheat-sheet — those live in F1 / the Command Palette now.
        // Screen reader mode shows the announcement in the status slot, and
        // every status passes through the UI catalog (#621).
        let waiting_owned = self.cmd_k_waiting_line();
        let raw_status: Cow<'_, str> = if let Some(waiting) = waiting_owned.as_deref() {
            crate::i18n::tr(waiting)
        } else if self.screen_reader && !self.announcer.line.is_empty() {
            Cow::Borrowed(self.announcer.line.as_str())
        } else {
            crate::i18n::tr(&self.status)
        };
        let status_line = one_line(raw_status);
        // Paths inside the workspace read relative to it, as Quick Open and
        // the tabs name them: `Saved src/main.rs`, not the absolute path.
        let status_text = workspace_relative(&status_line, self.workspace_root());
        let mut announce_pos = None;
        let mut msg_hit = Rect::default();
        if !status_text.is_empty() {
            left.paint_str("  ", zone_div);
            let status_x = left.col;
            let left_fixed = left.col;
            if status_visible && status_x < status_rect.width {
                announce_pos = Some((status_rect.x + status_x, status_rect.y));
            }
            let fits_beside = |right: u16| {
                status_rect
                    .width
                    .saturating_sub(right)
                    .saturating_sub(left_fixed)
                    .saturating_sub(1)
            };
            // A fresh message that does not fit beside the cluster takes the
            // cluster's room until the next key or click (#1609).
            let text_w = status_cells(&status_text);
            if self.status_wide && text_w > fits_beside(right_total) {
                right_total = 0;
            }
            let avail = fits_beside(right_total);
            let shown_text: Cow<'_, str> = if text_w > avail {
                Cow::Owned(elide_middle(&status_text, avail as usize))
            } else {
                Cow::Borrowed(&status_text)
            };
            left.paint_str(&shown_text, Style::default().fg(tones.muted));
            if status_visible && status_x < status_rect.width {
                let shown = status_cells(&shown_text);
                msg_hit = Rect {
                    x: status_rect.x + status_x,
                    y: status_rect.y,
                    width: shown.min(status_rect.width - status_x),
                    height: status_rect.height,
                };
            }
        }

        self.announce_pos = announce_pos;
        if status_visible {
            let chip = |(x, w): (u16, u16)| {
                (x < status_rect.width).then(|| Rect {
                    x: status_rect.x + x,
                    y: status_rect.y,
                    width: w.min(status_rect.width - x),
                    height: status_rect.height,
                })
            };
            let hits = &mut self.status_hits;
            hits.message = msg_hit;
            hits.codeql = codeql_chip.and_then(chip).unwrap_or_default();
            hits.update = update_chip.and_then(chip).unwrap_or_default();
            hits.offer = offer_chip.and_then(chip).unwrap_or_default();
            hits.diagnostics = Rect {
                x: status_rect.x.saturating_add(diag_start_col),
                y: status_rect.y,
                width: diag_len.min(status_rect.width.saturating_sub(diag_start_col)),
                height: status_rect.height,
            };
        }

        // The right cluster paints OVER the left bar, only when it fits.
        if status_visible && right_total > 0 && right_total <= status_rect.width {
            let rx = status_rect.right() - right_total;
            if self.status_hits.message.right() > rx {
                self.status_hits.message.width = rx.saturating_sub(self.status_hits.message.x);
            }
            // The right cluster paints OVER the left bar, so any hit rect
            // behind it must stop where it starts.
            let hits = &mut self.status_hits;
            for area in [
                &mut hits.codeql,
                &mut hits.update,
                &mut hits.offer,
                &mut hits.diagnostics,
            ] {
                *area = ends_before(*area, rx);
            }
            let right_rect = Rect {
                x: rx,
                y: status_rect.y,
                width: right_total,
                height: status_rect.height,
            };
            {
                let buf = frame.buffer_mut();
                for x in right_rect.left()..right_rect.right() {
                    let cell = &mut buf[(x, right_rect.y)];
                    cell.set_symbol(" ");
                    cell.set_style(bg_style);
                }
            }
            let seg_style = Style::default().fg(tones.muted);
            let lift = match self.theme.surfaces() {
                Some(s) => s.hairline(),
                None => self.theme.ui(Color::Rgb(0x2a, 0x31, 0x40)),
            };
            let hover_style = Style::default().bg(lift).fg(tones.text);
            let mut right = StatusPainter::new(frame.buffer_mut(), right_rect);
            let mut cx = rx;
            for (i, &w) in widths[..seg_count].iter().enumerate() {
                if i > 0 {
                    right.paint_str(div, zone_div);
                    cx = cx.saturating_add(1);
                }
                let r = Rect {
                    x: cx,
                    y: status_rect.y,
                    width: w,
                    height: status_rect.height,
                };
                let hovered = self
                    .pointer_cell
                    .is_some_and(|(pc, pr)| rect_contains(r, pc, pr));
                let style = if hovered { hover_style } else { seg_style };
                match i {
                    0 if !hovered => {
                        // Numbers in the text tone, the words around them dim.
                        let mut run_start = 0;
                        let mut run_digit = false;
                        for (idx, ch) in pos_str.char_indices() {
                            let d = ch.is_ascii_digit();
                            if idx > run_start && d != run_digit {
                                right.paint_str(
                                    &pos_str[run_start..idx],
                                    Style::default().fg(if run_digit {
                                        tones.text
                                    } else {
                                        tones.dim
                                    }),
                                );
                                run_start = idx;
                            }
                            run_digit = d;
                        }
                        if run_start < pos_str.len() {
                            right.paint_str(
                                &pos_str[run_start..],
                                Style::default().fg(if run_digit { tones.text } else { tones.dim }),
                            );
                        }
                    }
                    0 => right.paint_str(pos_str, hover_style),
                    1 => {
                        right.paint_str(" ", style);
                        right.paint_str(indent_label, style);
                        right.paint_str(" ", style);
                    }
                    2 => {
                        right.paint_str(" ", style);
                        right.paint_str(encoding_label, style);
                        right.paint_str(" ", style);
                    }
                    3 => {
                        right.paint_str(" ", style);
                        right.paint_str(eol_label, style);
                        right.paint_str(" ", style);
                    }
                    4 => {
                        // The language pill: lit in the selection tint under
                        // the pointer, so it hovers like the workspace cap reads.
                        let fill = if hovered {
                            self.theme.selection()
                        } else {
                            lift
                        };
                        let cap_style = Style::default().fg(fill);
                        let text_style = Style::default().fg(tones.text).bg(fill);
                        right.paint_str(PILL_CAP_L, cap_style);
                        right.paint_str(
                            lang_glyph_str,
                            Style::default().fg(language_icon.color).bg(fill),
                        );
                        right.paint_str(" ", text_style);
                        right.paint_str(lang_label, text_style);
                        right.paint_str(PILL_CAP_R, cap_style);
                    }
                    5 => {
                        if let Some(ref agents) = agents_seg {
                            right.paint_str(agents, style);
                        }
                    }
                    _ => {}
                }
                match i {
                    0 => self.status_hits.position = r,
                    1 => self.status_hits.indent = r,
                    2 => self.status_hits.encoding = r,
                    3 => self.status_hits.eol = r,
                    4 => self.status_hits.language = r,
                    5 => self.status_hits.agents = r,
                    _ => {}
                }
                cx = cx.saturating_add(w);
            }
        }

        // Terminal-pane inline image: sync after the panes have painted so
        // last_inner and the scroll offset are this frame's (all gating —
        // hidden panel, alt screen, off-screen anchor — is inside).
        self.update_terminal_image_overlay();
        self.update_markdown_image_overlay();
        // The shell's grey history suggestion is part of its typed line, so
        // it is drawn with the panes, under every pop-up (#2667).
        self.paint_terminal_suggestion(frame);
        // Every picture's place is known now and nothing is drawn over the
        // panes yet: what lies under each picture is noted, to compare with
        // the finished frame (#2663).
        self.note_pictures_before_popups(frame.buffer_mut());
        if let (Some(area), Some(popup)) = (tab_tooltip_area, self.tab_tooltip.as_ref()) {
            frame.render_widget(popup, area);
        }

        // Overlays render last so they sit on top of everything else. The port
        // toast goes first so modals/menus paint above it.
        //
        // The hover note popup (editor symbol hover / terminal annotation
        // note) renders here against the WHOLE frame, not the editor's
        // focused_area: its anchor may sit in the terminal panel, and the
        // welcome screen skips the editor-tabs branch entirely, which used to
        // drop a terminal annotation's note without painting it at all.
        if let Some(popup) = self.peek_popup.as_mut() {
            popup.theme = self.theme;
            let area = popup.area_for(frame.area());
            if area.width > 0 && area.height > 0 {
                frame.render_widget(&*popup, area);
            }
        }
        if let Some(popup) = self.hover.popup.as_mut() {
            popup.theme = self.theme;
            let area = popup.area_for(frame.area());
            popup.last_area = area;
            if area.width > 0 && area.height > 0 {
                frame.render_widget(&*popup, area);
            }
        }
        self.render_port_toast(frame);
        self.render_update_toast(frame);
        self.render_zen_hint(frame);
        // Source Control's menus hang from the view's `⋯` pill and the
        // Commit button's `▾`: with the view or what they hang from off
        // screen they close, so they never take keys unseen.
        if !scm_drawn || self.scm_menu_layout().is_none() {
            self.close_scm_menus();
        }
        self.render_context_menu(frame);
        self.render_prompt(frame);
        self.render_local_open_confirm(frame);
        self.render_discard_confirm(frame);
        self.render_revert_hunk_confirm(frame);
        self.render_discard_all_confirm(frame);
        self.render_stash_drop_confirm(frame);
        self.render_unsaved_scm_confirm(frame);
        self.render_replace_all_confirm(frame);
        self.render_broadcast_confirm(frame);
        self.render_terminal_paste_confirm(frame);
        self.render_run_block_confirm(frame);
        self.render_unsaved_confirm(frame);
        self.render_lossy_save_confirm(frame);
        self.render_editor_find(frame);
        self.render_terminal_find(frame);
        self.render_file_finder(frame);
        self.render_command_palette(frame);
        // Above the pickers a tour step opens (#863), so they never hide
        // the caption explaining them.
        self.render_tour_caption(frame);
        self.render_go_to_symbol(frame);
        self.render_workspace_symbols(frame);
        self.render_process_picker(frame);
        self.render_zoxide_jump(frame);
        self.render_command_history_popup(frame);
        self.render_branch_picker(frame);
        // Below the input prompt: Enter on a number or text setting opens
        // the prompt over the editor, and drawn after it the editor hid it.
        self.render_settings_editor(frame);
        self.render_input_prompt(frame);
        self.render_list_picker(frame);
        self.render_shortcuts_modal(frame);
        self.render_connect_dialog(frame);
        // The startup unsupported-terminal nudge renders last so it sits above
        // every other overlay until the user dismisses it.
        self.render_approval_popup(frame);
        self.render_message_card(frame);
        self.render_terminal_warning(frame);
        self.drop_covered_update_controls(frame.buffer_mut());

        // Chrome button-hint tooltip. Rendered at the top level against the
        // whole frame (not the editor's `focused_area`) because the controls it
        // labels live in the activity bar and sidebar, outside the editor pane;
        // clamping it to the editor area would yank it away from the control or,
        // on the welcome screen, drop it entirely.
        let mut tooltip_area = None;
        if let Some(popup) = self.ui_tooltip.as_mut() {
            popup.theme = self.theme;
            let full = frame.area();
            let mut area = popup.area_for(full);
            // Keep the box clear of the activity bar's inline-image column. Those
            // codicon glyphs are a terminal graphics layer that always composites
            // ABOVE text cells, so any overlap would paint over (hide) the left of
            // the tooltip. Shift it to the right of the bar instead, like VS Code
            // floats an activity-icon hint beside the icon.
            if area.x < ACTIVITY_BAR_WIDTH {
                area.x = ACTIVITY_BAR_WIDTH;
                area.width = area.width.min(full.width.saturating_sub(area.x));
            }
            if area.width > 0 && area.height > 0 {
                frame.render_widget(&*popup, area);
                tooltip_area = Some(area);
            }
        }
        // Record the box so the post-draw flush can RE-PAINT it on top of any
        // sidebar OSC-1337 illustration (the no-repo hero / SSH empty-state).
        // Those images are emitted after ratatui's text and would otherwise
        // composite over the tooltip; re-emitting the box last wins the cell.
        self.ui_tooltip_area = tooltip_area;

        self.render_screencast(frame, main_area);
        // The last of the frame's drawing: a picture whose cells changed
        // since the note above has a pop-up over it, and waits (#2663).
        self.note_pictures_after_popups(frame.buffer_mut());

        // A quick input owns the caret while it is open on a `surfaces`
        // theme: its query's, and no pane's caret blinking through the card.
        let quick_input = self.quick_input_owns_caret();
        if quick_input
            && self.context_menu.is_none()
            && self.prompt.is_none()
            && self.cursor_visible_phase()
            && let Some((cx, cy)) = self.quick_input_caret()
        {
            frame.set_cursor_position((cx, cy));
        }

        // A pane's caret shows only while no pop-up or right-click menu is
        // open: an open one has the keys, and a caret blinking through it
        // would point at text it is not about to edit (#2669). The quick
        // inputs, the New File box and the list picker are pop-ups too.
        let pane_caret =
            self.context_menu.is_none() && !self.popup_open() && self.cursor_visible_phase();

        // Show the host terminal's hardware caret when the editor is focused.
        // The DECSCUSR style is set to BlinkingBar at startup, so the
        // terminal blinks a thin vertical line over the cursor cell without
        // replacing its character.
        if self.focus == Pane::Editor && pane_caret {
            let pos = if self.editor.diff.is_some() {
                self.editor.diff_caret_screen_pos()
            } else {
                self.editor.cursor_screen_pos()
            };
            if let Some((cx, cy)) = pos {
                frame.set_cursor_position((cx, cy));
            }
        }

        // Source-control commit-message caret. Same software-blink rule:
        // the user can't see where they're typing in the message box
        // without a visible caret, since `set_string` just lays the text
        // flat with no native caret cell.
        if self.focus == Pane::Tree
            && self.sidebar_view == SidebarView::SourceControl
            && pane_caret
            && let Some((cx, cy)) = self.source_control.cursor_screen_pos(true)
        {
            frame.set_cursor_position((cx, cy));
        }

        // Search-panel field caret and Extensions filter caret. Same software
        // blink as the commit box so all three side-panel inputs share one
        // blinking hardware caret instead of a static block (Search) or no
        // caret at all (Extensions).
        if self.focus == Pane::Tree
            && self.sidebar_view == SidebarView::Search
            && pane_caret
            && let Some((cx, cy)) = self.search.cursor_screen_pos(true)
        {
            frame.set_cursor_position((cx, cy));
        }
        if self.focus == Pane::Tree
            && self.sidebar_view == SidebarView::Extensions
            && pane_caret
            && let Some((cx, cy)) = self.extensions.cursor_screen_pos(true)
        {
            frame.set_cursor_position((cx, cy));
        }
        self.park_screen_reader_cursor(frame);
        crate::startup_trace::mark("status bar and popups drawn");
    }

    /// What screen reader mode describes this frame (#621).
    pub(super) fn a11y_snapshot(&self) -> crate::a11y::Snapshot {
        use crate::a11y::Snapshot;
        let tr = |s: &str| crate::i18n::tr(s).into_owned();
        let status = tr(&self.status);
        if let Some((focus, item)) = self.modal_a11y() {
            return Snapshot {
                focus,
                item: Some(item),
                status,
                ..Default::default()
            };
        }
        if let Some(p) = &self.prompt {
            return Snapshot {
                focus: p.label.clone(),
                item: p.error.clone(),
                status,
                ..Default::default()
            };
        }
        if let Some(menu) = &self.context_menu {
            let item = match menu.cursor_entry() {
                Some(MenuEntry::Item { label, .. } | MenuEntry::Submenu { label, .. }) => {
                    Some(label.clone())
                }
                _ => None,
            };
            return Snapshot {
                focus: tr("Menu"),
                item,
                status,
                ..Default::default()
            };
        }
        // The pickers read like the palette: their title and the selected
        // row (#2670). Without these a reader heard the pane behind.
        let picker = |focus: &str, item: Option<String>| Snapshot {
            focus: tr(focus),
            item,
            status: status.clone(),
            ..Default::default()
        };
        // Named for what Enter does with it (#2670 review): the same picker
        // checks out, deletes, merges, rebases onto or branches from.
        if let Some(p) = &self.branch_picker {
            use super::scm::BranchPurpose;
            use crate::widgets::branch_picker::BranchAction;
            let title = match self.branch_purpose {
                BranchPurpose::Checkout => "Checkout / Create Branch",
                BranchPurpose::CreateFrom => "Create Branch from",
                BranchPurpose::Delete => "Delete Branch",
                BranchPurpose::Merge => "Merge Branch",
                BranchPurpose::Rebase => "Rebase onto Branch",
            };
            let item = if self.branch_purpose == BranchPurpose::Checkout {
                p.selected_action().map(|a| match a {
                    BranchAction::Checkout(name) | BranchAction::Track { name, .. } => name,
                    BranchAction::Create(name) => format!("{} {name}", tr("Create branch")),
                })
            } else {
                // The others act on an existing branch only.
                Some(
                    p.selected_existing_branch()
                        .unwrap_or_else(|| tr("Choose an existing branch")),
                )
            };
            return picker(title, item);
        }
        if let Some(p) = &self.command_history_popup {
            return picker("Command History", p.selected_entry().map(|e| e.cmd.clone()));
        }
        if let Some(j) = &self.zoxide_jump {
            // Asking whether to install zoxide or add its hook: the question,
            // whose last line holds the keys.
            let item = if j.asks_yes_no() {
                let asked = if j.available {
                    crate::widgets::zoxide_jump::hook_offer_message(
                        j.hook_offer.as_deref().unwrap_or_default(),
                    )
                } else {
                    crate::widgets::zoxide_jump::unavailable_message(j)
                };
                Some(asked.split_whitespace().collect::<Vec<_>>().join(" "))
            } else {
                j.selected_path().map(|p| p.display().to_string())
            };
            return picker("Jump to Directory", item);
        }
        if let Some(p) = &self.process_picker {
            return picker(
                "Attach to Python Process",
                p.selected_target().map(|t| t.label.clone()),
            );
        }
        // Where each match is, so two `new`s in two files sound different
        // (#2670 review).
        if let Some(p) = &self.workspace_symbols {
            let item = p.selected_item().map(|i| {
                let path = i.path.strip_prefix(&p.root).unwrap_or(&i.path);
                let mut said = i.name.clone();
                if let Some(c) = &i.container {
                    said.push_str(&format!(", {} {c}", tr("in")));
                }
                format!("{said}, {}:{}", path.display(), i.line + 1)
            });
            return picker("Go to Symbol in Workspace", item);
        }
        // `:42` jumps to a line: say so, not the symbol last selected
        // (#2670 review).
        if let Some(p) = &self.go_to_symbol {
            let item = if p.is_line_mode() {
                Some(match p.line_target() {
                    Some(n) => format!("{} {n}", tr("Go to line")),
                    None => tr("Type a line number"),
                })
            } else {
                p.selected_name().map(String::from)
            };
            return picker("Go to Symbol", item);
        }
        if let Some(p) = &self.command_palette {
            return Snapshot {
                focus: tr("Command Palette"),
                item: p.selected_item().map(|i| tr(i.title())),
                status,
                ..Default::default()
            };
        }
        if let Some(f) = &self.file_finder {
            return Snapshot {
                focus: tr("Go to File"),
                item: f.selected_entry().map(|e| e.rel.clone()),
                status,
                ..Default::default()
            };
        }
        if let Some(p) = &self.list_picker {
            return Snapshot {
                focus: p.title.clone(),
                item: p.selected_row().map(|r| r.label.clone()),
                status,
                ..Default::default()
            };
        }
        match self.focus {
            Pane::Editor => {
                let name = self
                    .editor
                    .path
                    .as_deref()
                    .and_then(|p| p.file_name())
                    .map(|n| n.to_string_lossy().into_owned())
                    .unwrap_or_else(|| tr("Untitled"));
                let row = self.editor.cursor_row;
                let diagnostic = self
                    .editor
                    .diagnostics_at(row, self.editor.cursor_col, self.workspace_root())
                    .into_iter()
                    .next()
                    .map(|(_, m)| m);
                Snapshot {
                    focus: format!("{} {name}", tr("Editor")),
                    line: Some((
                        row + 1,
                        self.editor.lines.get(row).cloned().unwrap_or_default(),
                    )),
                    diagnostic,
                    item: self
                        .completion
                        .popup
                        .as_ref()
                        .and_then(|c| c.selected_item())
                        .map(|c| c.label.clone()),
                    status,
                    event: None,
                }
            }
            Pane::Terminal => {
                let (focus, item) = self.bottom_panel_a11y();
                Snapshot {
                    focus,
                    item,
                    status,
                    ..Default::default()
                }
            }
            Pane::Tree => {
                let (focus, item) = match self.sidebar_view {
                    SidebarView::Explorer => (
                        tr("Explorer"),
                        // The row's label, so a compact row (#1486) reads
                        // as shown, `src/main/java`, not its last folder.
                        self.tree
                            .nodes
                            .get(self.tree.selected)
                            .map(crate::widgets::file_tree::Node::label),
                    ),
                    SidebarView::Search => self.search_a11y(),
                    SidebarView::SourceControl => self.source_control_a11y(),
                    SidebarView::Remote => (tr("Remote"), None),
                    SidebarView::RunDebug => (tr("Run and Debug"), None),
                    SidebarView::Extensions => (tr("Extensions"), None),
                    SidebarView::Testing => (tr("Testing"), None),
                    SidebarView::CodeQL => (tr("CodeQL"), None),
                };
                Snapshot {
                    focus,
                    item,
                    status,
                    ..Default::default()
                }
            }
        }
    }

    /// The dialog waiting for a key, if one is open, as screen reader mode
    /// reads it (#1584): its title, then what it says and which key does
    /// what. Without this a confirmation was silent, so a reader heard
    /// nothing after Ctrl+W and could not know that D throws edits away.
    /// Topmost first, in the order they are drawn; a new dialog that waits
    /// for a key belongs here too, and a test opens every pop-up to check
    /// one is read (#2670).
    pub(super) fn modal_a11y(&self) -> Option<(String, String)> {
        let tr = |s: &str| crate::i18n::tr(s).into_owned();
        // The title, and its sentences joined for speech: a full stop
        // between them unless one already ends in a question mark.
        let join = |parts: &[String]| -> String {
            let mut item = String::new();
            for part in parts.iter().map(|p| p.trim().trim_end_matches('.')) {
                if part.is_empty() {
                    continue;
                }
                if !item.is_empty() {
                    item.push_str(if item.ends_with('?') { " " } else { ". " });
                }
                item.push_str(part);
            }
            item
        };
        // What it says, then which key does what. The announcement is cut
        // at `a11y::MAX_LINE`, so a long path, command or file list is cut
        // here instead: the keys at the end are always read.
        let said = |title: &str, body: &[String], actions: &[String]| -> (String, String) {
            let actions = join(actions);
            let mut item = join(body);
            let room = crate::a11y::MAX_LINE.saturating_sub(actions.chars().count() + 2);
            if item.chars().count() > room {
                item = if room < 2 {
                    String::new()
                } else {
                    let mut cut: String = item.chars().take(room - 1).collect();
                    cut.truncate(cut.trim_end().len());
                    cut.push('…');
                    cut
                };
            }
            if !item.is_empty() && !actions.is_empty() {
                item.push_str(if item.ends_with('?') || item.ends_with('…') {
                    " "
                } else {
                    ". "
                });
            }
            item.push_str(&actions);
            (tr(title), item)
        };
        let yes_no = |yes: &str| format!("{}. {}", tr(yes), tr("N or Escape, no"));
        if let Some(card) = &self.message_card {
            return Some(said(
                &card.title,
                std::slice::from_ref(&card.text),
                &[tr("Escape closes. C copies")],
            ));
        }
        if self.pending_terminal_warning {
            return Some(said(
                "Unsupported terminal",
                &[tr(
                    "Croft's icons and images need an inline-image protocol this terminal does not support",
                )],
                &[tr("Any key dismisses. D, don't show again")],
            ));
        }
        // An agent's edit proposal takes every key while it is up, so it is
        // read before anything it covers: who wants to change which file,
        // and the keys the popup's footer offers in its current state.
        if let (Some(ui), Some(head)) = (&self.approval_ui, self.approvals.front()) {
            let title = crate::widgets::approval_popup::title(
                head,
                self.approvals.len(),
                self.workspace_root(),
            )
            .trim()
            .replace(" · ", ", ");
            let actions = if ui.reason.is_some() {
                "Type the reason. Enter, send. Escape, back"
            } else if ui.target_dirty {
                "Unsaved edits here. Enter, merge them with the agent's. Escape, deny. R, deny with a reason"
            } else {
                "Enter, approve. Escape, deny. A, approve all from this agent for 10 minutes. R, deny with a reason. E, edit, then approve"
            };
            return Some((title, tr(actions)));
        }
        // Connecting to a host (#2670): what it is doing or asking, and the
        // keys for that step. What is typed, a password among it, is left to
        // the reader's echo.
        if let Some(d) = &self.connect_dialog {
            let title = format!("{} {}", tr("Connect to"), d.host);
            let mut body = vec![d.status_line.clone()];
            // What failed, and what a yes to the slow fallback installs: the
            // dialog draws both (#2670 review).
            body.extend(d.error.clone());
            if matches!(
                d.phase,
                crate::widgets::connect_dialog::DialogPhase::AwaitingFallbackConfirmation
            ) {
                body.extend(d.notes.iter().cloned());
            }
            if d.phase.awaits_input() {
                body.push(d.prompt_text.clone());
            }
            let keys = if d.phase.is_terminal() {
                "Enter or Escape, close"
            } else if d.phase.awaits_input() {
                "Type the answer. Enter, send. Escape, cancel"
            } else {
                "Escape, cancel. L, show the log"
            };
            return Some(said(&title, &body, &[tr(keys)]));
        }
        // F1 reads the shortcut at the top of the list, so each scroll is
        // heard (#2670 review).
        if let Some(modal) = &self.shortcuts_modal {
            let row = modal.spoken_row().unwrap_or_default();
            return Some(said(
                "Keyboard Shortcuts",
                &[row],
                &[tr("Arrows, scroll. Escape or F1, close")],
            ));
        }
        // The field's own instruction ("Remote URL") is read with the keys,
        // so a prompt replaced by the next step under the same title is
        // still heard; what is typed is left to the reader's echo.
        if let Some(p) = &self.input_prompt {
            let hint = p
                .hint
                .clone()
                .unwrap_or_else(|| String::from("Enter to confirm, Escape to cancel"));
            return Some(said(&p.title, &[tr(&p.placeholder)], &[tr(&hint)]));
        }
        if let Some(ed) = &self.settings_editor {
            let target = if ed.target == crate::config_layers::LayerKind::Workspace {
                tr("Settings, writing to workspace")
            } else {
                tr("Settings, writing to user")
            };
            let row = ed.selected_row().map_or_else(
                || tr("No matching setting"),
                |r| {
                    format!(
                        "{}, {}, {}",
                        r.key.replace('_', " "),
                        crate::settings_editor::display(&r.value),
                        tr(r.layer.label())
                    )
                },
            );
            return Some((target, row));
        }
        // Over the unsaved-changes prompt when both are up, as it is drawn.
        if let Some(asked) = &self.pending_lossy_save {
            return Some(said(
                "Save would lose data",
                &asked.spoken(),
                &[tr("S, save anyway"), tr("Escape, cancel")],
            ));
        }
        if let Some(exit) = &self.pending_unsaved {
            let (headline, names, save, discard) = self.unsaved_confirm_text(exit);
            // The tab label carries the dirty dot, which a reader would read
            // out as "bullet"; every file named here is unsaved anyway.
            let names = names.replace("● ", "");
            return Some(said(
                "Unsaved changes",
                &[format!("{} {names}", tr(&headline))],
                &[
                    format!("S, {}", tr(&format!("S{save}"))),
                    format!("D, {}", tr(&format!("D{discard}"))),
                    tr("Escape, cancel"),
                ],
            ));
        }
        if let Some(block) = &self.pending_run_block {
            let title = if block.destructive {
                "Run this block? It looks destructive"
            } else {
                "Run this block?"
            };
            return Some(said(
                title,
                &[
                    format!(
                        "{} {} {} {}",
                        tr("in pane"),
                        block.pane_name,
                        tr("at"),
                        block.cwd.display()
                    ),
                    block.code.lines().collect::<Vec<_>>().join("; "),
                ],
                &[yes_no("Y, yes, run")],
            ));
        }
        if let Some(payload) = &self.pending_terminal_paste {
            let lines = super::terminal_panes::pasted_lines(payload);
            let n = lines.len();
            let shown: Vec<String> = lines
                .iter()
                .take(3)
                .map(|l| String::from_utf8_lossy(l).into_owned())
                .collect();
            return Some(said(
                &format!(
                    "{} {n} {}",
                    tr("Paste"),
                    tr(if n == 1 {
                        "line into the terminal?"
                    } else {
                        "lines into the terminal?"
                    })
                ),
                &[
                    tr("Each line break is an Enter here, so the lines run as they land"),
                    shown.join("; "),
                ],
                &[tr(
                    "Y or Enter, paste. L, paste as one line. N or Escape, cancel",
                )],
            ));
        }
        if self.pending_broadcast_enable {
            let receiving = self
                .terminals
                .iter()
                .filter(|t| !t.broadcast_excluded)
                .count()
                .max(1);
            return Some(said(
                "Broadcast input to all panes?",
                &[format!(
                    "{} {receiving} {}",
                    tr("Every keystroke and paste will go to"),
                    tr("terminal panes at once")
                )],
                &[yes_no("Y, yes, broadcast")],
            ));
        }
        if let Some((occurrences, files, skipped)) = self.pending_replace_all {
            let mut parts = vec![
                format!(
                    "Replace {occurrences} occurrence(s) across {files} file(s) with \"{}\"?",
                    self.search.replace
                ),
                tr("Files are rewritten on disk"),
            ];
            if skipped > 0 {
                parts.push(format!(
                    "{skipped} open file(s) with unsaved changes will be skipped"
                ));
            }
            return Some(said(
                "Replace all?",
                &parts,
                &[tr("Enter or Y, replace. Escape, cancel")],
            ));
        }
        if let Some(pending) = &self.pending_unsaved_scm {
            let verb = pending.op.verb();
            let names: Vec<String> = pending
                .files
                .iter()
                .map(|p| {
                    p.strip_prefix(&pending.root)
                        .unwrap_or(p)
                        .display()
                        .to_string()
                })
                .collect();
            let n = names.len();
            return Some(said(
                "Unsaved changes",
                &[format!(
                    "{n} file{} {} unsaved changes: {}",
                    if n == 1 { "" } else { "s" },
                    if n == 1 { "has" } else { "have" },
                    names.join(", ")
                )],
                &[
                    format!("S, Save All & {verb}"),
                    format!("C, {verb} Anyway"),
                    tr("Escape, cancel"),
                ],
            ));
        }
        if let Some(drop) = &self.pending_stash_drop {
            return Some(said(
                "Drop stash?",
                &[
                    drop.label.clone(),
                    tr("This permanently deletes the stash."),
                ],
                &[yes_no("Y, yes, drop it")],
            ));
        }
        if self.pending_discard_all {
            return Some(said(
                "Discard all changes?",
                &[tr(
                    "This reverts every tracked file to HEAD. Untracked files are kept.",
                )],
                &[yes_no("Y, yes, discard all")],
            ));
        }
        if let Some(pr) = &self.pending_revert_hunk {
            return Some(said(
                "Revert hunk?",
                &[
                    tr("This will undo the change hunk under the cursor on disk."),
                    pr.rel_path.clone(),
                ],
                &[yes_no("Y, yes, revert")],
            ));
        }
        if let Some(pd) = &self.pending_discard {
            let warn = if pd.untracked {
                "This will permanently delete the file from disk."
            } else {
                "This will overwrite your local changes from HEAD."
            };
            return Some(said(
                "Discard changes?",
                &[tr(warn), pd.rel_path.clone()],
                &[yes_no("Y, yes, discard")],
            ));
        }
        if let Some(url) = &self.pending_local_open {
            return Some(said(
                "Open on local Mac?",
                &[
                    tr("This URL will open in YOUR LOCAL MAC's browser via the croft relay."),
                    url.clone(),
                ],
                &[format!(
                    "{}. {}",
                    tr("Y, yes once. A, always for this session"),
                    tr("N or Escape, no")
                )],
            ));
        }
        None
    }

    /// What screen reader mode says for the bottom panel's front tab
    /// (#1295): the tab's name with what it holds, and its row in focus.
    /// The panel is one `Pane` whichever tab is in front, so the tab, not
    /// the pane, decides.
    pub(super) fn bottom_panel_a11y(&self) -> (String, Option<String>) {
        let tr = |s: &str| crate::i18n::tr(s).into_owned();
        let with = |name: &str, what: String| format!("{}, {what}", tr(name));
        match self.bottom_panel_tab {
            BottomPanelTab::Terminal => (
                format!("{} {}", tr("Terminal"), self.active_terminal + 1),
                None,
            ),
            BottomPanelTab::Problems => {
                let errors = self.problems.error_count();
                let warnings = self.problems.warning_count();
                let others = self.problems.total_count() - errors - warnings;
                let counts: Vec<String> = [
                    (errors, "error", "errors"),
                    (warnings, "warning", "warnings"),
                    (others, "info", "infos"),
                ]
                .into_iter()
                .filter(|(n, ..)| *n > 0)
                .map(|(n, one, many)| a11y_count(n, one, many))
                .collect();
                let counts = if counts.is_empty() {
                    String::from("no problems")
                } else {
                    counts.join(", ")
                };
                let item = self.problems.top_diagnostic().map(|(group, it)| {
                    let source = match &it.code {
                        Some(code) => code.label(&it.source),
                        None => it.source.clone(),
                    };
                    let source = if source.is_empty() {
                        String::new()
                    } else {
                        format!(" ({source})")
                    };
                    format!(
                        "{} line {}: {}{source}",
                        group.name,
                        it.line + 1,
                        it.message
                    )
                });
                (with("Problems", counts), item)
            }
            BottomPanelTab::Output => (
                match self.output.selected_name() {
                    Some(channel) => with("Output", channel),
                    None => tr("Output"),
                },
                None,
            ),
            BottomPanelTab::Ports => {
                let n = self.ports.len();
                let item = self.ports.selected().map(|p| {
                    let mut said = format!("Port {}", p.port);
                    for part in [&p.process, &p.url].into_iter().flatten() {
                        said.push_str(", ");
                        said.push_str(part);
                    }
                    said
                });
                let count = if n == 0 {
                    String::from("none")
                } else {
                    a11y_count(n, "port", "ports")
                };
                (with("Ports", count), item)
            }
            BottomPanelTab::Captures => {
                let n = self.captures.len();
                let item = self
                    .captures
                    .selected_entry()
                    .map(|c| format!("{}, from {}", c.message, c.pane));
                let count = if n == 0 {
                    String::from("none")
                } else {
                    a11y_count(n, "capture", "captures")
                };
                (with("Captures", count), item)
            }
        }
    }

    /// The Search sidebar for screen reader mode (#1295): how many matches
    /// in how many files, and the selected match as `file line N: text`.
    pub(super) fn search_a11y(&self) -> (String, Option<String>) {
        let name = crate::i18n::tr("Search").into_owned();
        let hits = &self.search.hits;
        if hits.is_empty() {
            return (name, None);
        }
        // The Search header's own totals: a line with two matches counts two.
        let (matches, files) = self.search.result_counts();
        let focus = format!(
            "{name}, {} in {}",
            a11y_count(matches, "match", "matches"),
            a11y_count(files, "file", "files")
        );
        let item = self.search.selected_hit().map(|h| {
            let rel = h
                .path
                .strip_prefix(self.workspace_root())
                .unwrap_or(&h.path);
            format!("{} line {}: {}", rel.display(), h.line_no, h.line_text)
        });
        (focus, item)
    }

    /// The Source Control sidebar for screen reader mode (#1295): how many
    /// changes, and the selected one as `path, what happened to it`. While
    /// COMMITS has the keys (#871) it reads COMMITS instead: how many
    /// commits, and the picked one, which Enter opens.
    pub(super) fn source_control_a11y(&self) -> (String, Option<String>) {
        use crate::git::ChangeKind;
        use crate::widgets::source_control::KeyStop;
        let name = crate::i18n::tr("Source Control").into_owned();
        let sc = &self.source_control;
        if sc.keys == KeyStop::Repositories {
            let focus = format!(
                "{name}, Repositories, {}",
                a11y_count(sc.repositories.len(), "repository", "repositories")
            );
            let item = sc.repo_under_cursor().map(|r| {
                let branch = r.branch.as_deref().unwrap_or("no branch");
                let changes = a11y_count(r.changes, "change", "changes");
                let shown = if r.active { ", selected" } else { "" };
                format!("{}, {branch}, {changes}{shown}", r.label)
            });
            return (focus, item);
        }
        if sc.keys == KeyStop::Card {
            let item = sc
                .keyed_card_label()
                .map(|label| format!("{label}, button"));
            return (format!("{name}, {}", sc.card_title()), item);
        }
        if sc.keys == KeyStop::Commits {
            let graph = &self.commit_graph;
            if graph.collapsed {
                return (format!("{name}, Commits, collapsed"), None);
            }
            let focus = format!(
                "{name}, Commits, {}",
                a11y_count(graph.commit_count(), "commit", "commits")
            );
            let item = graph
                .selected_commit()
                .map(|c| format!("{}, by {}, {}", c.summary, c.author, c.short_hash));
            return (focus, item);
        }
        let entries = &self.source_control.entries;
        if entries.is_empty() {
            return (name, None);
        }
        let focus = format!("{name}, {}", a11y_count(entries.len(), "change", "changes"));
        let item = self
            .source_control
            .selected_change
            .and_then(|i| entries.get(i))
            .map(|e| {
                let what = match e.kind {
                    ChangeKind::StagedAdded => "added, staged",
                    ChangeKind::StagedModified => "modified, staged",
                    ChangeKind::StagedDeleted => "deleted, staged",
                    ChangeKind::StagedRenamed => "renamed, staged",
                    ChangeKind::Modified => "modified",
                    ChangeKind::Deleted => "deleted",
                    ChangeKind::Untracked => "untracked",
                    ChangeKind::Conflicted => "conflicted",
                };
                format!("{}, {what}", e.path)
            });
        (focus, item)
    }

    /// Feed this frame's snapshot to the announcer (#621).
    pub(super) fn update_announcer(&mut self) {
        if !self.screen_reader {
            return;
        }
        let mut snap = self.a11y_snapshot();
        snap.event = self.a11y_event.clone();
        let speak = self.screen_reader_command.clone();
        self.announcer.update(snap, speak.as_deref());
    }

    /// Have screen reader mode read `text` out whatever has focus (#1547):
    /// something that happened, like a debugger pause, rather than
    /// something the user moved to. Kept only while the mode is on, so
    /// turning it on never reads out an old event.
    pub(super) fn announce_event(&mut self, text: String) {
        if !self.screen_reader {
            return;
        }
        let n = self.a11y_event.as_ref().map_or(0, |(n, _)| n + 1);
        self.a11y_event = Some((n, crate::i18n::tr(&text).into_owned()));
    }

    /// What a debugger pause reads as (#1547): why it stopped, where, and
    /// the line's text, as in `Paused on breakpoint, app.py line 3: total
    /// += n`. The line comes from the buffer when the file is the one being
    /// edited, else from disk. A stop with no source location (`at` is
    /// `None`) names its frame instead, as in `Paused on step, in memcpy`.
    pub(super) fn debug_pause_announcement(
        &self,
        reason: &str,
        at: Option<&(PathBuf, usize)>,
        frame: &str,
    ) -> String {
        let what = match reason {
            "" | "pause" => String::from("Paused"),
            r => format!("Paused on {r}"),
        };
        let Some((path, line)) = at else {
            return match frame.trim() {
                "" => what,
                f => format!("{what}, in {f}"),
            };
        };
        let name = path.file_name().map_or_else(
            || path.display().to_string(),
            |n| n.to_string_lossy().into_owned(),
        );
        let index = line.saturating_sub(1);
        let text = if self.editor.path.as_deref() == Some(path.as_path()) {
            self.editor.lines.get(index).cloned()
        } else {
            use std::io::BufRead;
            std::fs::File::open(path).ok().and_then(|f| {
                std::io::BufReader::new(f)
                    .lines()
                    .nth(index)
                    .and_then(Result::ok)
            })
        };
        match text.as_deref().map(str::trim).filter(|t| !t.is_empty()) {
            Some(t) => format!("{what}, {name} line {line}: {t}"),
            None => format!("{what}, {name} line {line}"),
        }
    }

    /// Accessibility: Toggle Screen Reader Mode (#621), persisted.
    pub(super) fn toggle_screen_reader(&mut self) {
        self.set_screen_reader(!self.screen_reader);
        self.status = String::from(if self.screen_reader {
            "Screen reader mode: on"
        } else {
            "Screen reader mode: off"
        });
        let on = self.screen_reader;
        let saved = if cfg!(test) {
            Ok(())
        } else {
            crate::prefs::save_screen_reader(on)
        };
        self.note_saved_setting(saved, |s| s.screen_reader = on);
    }

    /// Turn screen reader mode on or off: the toggle, and a settings reload
    /// that changed it (#2907). What was being announced starts over.
    pub(super) fn set_screen_reader(&mut self, on: bool) {
        self.screen_reader = on;
        self.announcer.reset();
        self.a11y_event = None;
    }

    /// Where screen reader mode parks the cursor when no caret is showing:
    /// the terminal's own cursor, else the start of the announcement.
    pub(super) fn park_screen_reader_cursor(&self, frame: &mut ratatui::Frame) {
        if !self.screen_reader {
            return;
        }
        // A picker covers the caret: read its selection from the status bar.
        // So does a dialog waiting for a key (#1584), except a text prompt,
        // whose own caret is where the typing is.
        let picker = self.command_palette.is_some()
            || self.file_finder.is_some()
            || self.list_picker.is_some()
            || (self.input_prompt.is_none() && self.modal_a11y().is_some());
        if picker && let Some(pos) = self.announce_pos {
            // A `surfaces` quick input draws no caret of its own and lends
            // the query the terminal's caret, which the announcement takes
            // here: paint a block where the typing lands, as boxed themes do.
            if self.quick_input_owns_caret()
                && let Some((cx, cy)) = self.quick_input_caret()
                && frame
                    .area()
                    .contains(ratatui::layout::Position { x: cx, y: cy })
            {
                frame.buffer_mut()[(cx, cy)]
                    .modifier
                    .insert(ratatui::style::Modifier::REVERSED);
            }
            frame.set_cursor_position(pos);
            return;
        }
        if self.cursor_should_be_visible() {
            return;
        }
        // The shell's cursor only while nothing covers it: under a pop-up
        // the reader belongs on what the pop-up says (#2673 review).
        if self.focus == Pane::Terminal
            && !self.popup_open()
            && self.context_menu.is_none()
            && let Some(pos) = self
                .terminals
                .get(self.active_terminal)
                .and_then(|t| t.screen_cursor())
        {
            frame.set_cursor_position(pos);
            return;
        }
        if let Some(pos) = self.announce_pos {
            frame.set_cursor_position(pos);
        }
    }
}