mnml-rs 0.2.13

A NvChad-style terminal IDE in Rust — vim or standard editing, LSP, git, and an embedded HTTP client.
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
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
//! The render path — backend-agnostic, so the same `draw` serves the real
//! terminal (`tui.rs`) and the headless virtual screen (`headless.rs`). Layout
//! mirrors NvChad: the file-tree rail is a full-height column on the left (the
//! buffer tabs do NOT sit above it); the right column is a one-line bufferline
//! over the pane body; the statusline spans the full width at the bottom.
//!
//! ```text
//! ┌──────────┬────────────────────────────────────┐
//! │  tree    │ bufferline (open buffers)        h1 │
//! │  rail    ├────────────────────────────────────┤
//! │ (full    │ active pane body                   │
//! │  height) │ (editor view / welcome)            │
//! ├──────────┴────────────────────────────────────┤
//! │ statusline (mode · git · file … Ln:Col · lang) │
//! └───────────────────────────────────────────────┘
//! ```
//!
//! "active pane body" is actually a recursive split tree (`render_layout`) — one
//! editor per `Layout::Leaf`, 1-cell dividers between splits. Overlays (picker /
//! palette / which-key / popups) draw on top.

pub mod about_overlay;
pub mod activity_bar;
pub mod ai_view;
pub mod claude_usage_view;
pub mod codex_usage_view;
pub mod design_tokens;
pub mod spend_report_view;
pub mod usage_time;

/// 2026-06-21 vscode-mouse SEV-2 — which Claude Agents dashboard
/// topbar chip a click is on. The mouse dispatcher matches this
/// to the corresponding pane-level action.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TopbarChipKind {
    View,
    Sort,
    Group,
    Source,
    Workspace,
}
// Azure DevOps views moved to mnml-forge-azdevops.
pub mod browser_view;
pub mod bufferline;
pub mod cheatsheet_view;
pub mod claude_agents_view;
pub mod close_prompt;
pub mod cmdline_bar;
pub mod cmdline_history_view;
pub mod cmdline_popup_view;
pub mod confirm_modal;
pub mod peek_overlay_view;
pub mod ws_view;
// codebuilds_view moved to mnml-aws-codebuild.
pub mod cloud_agent_run_view;
pub mod completion;
pub mod context_menu;
pub mod dap_repl_view;
pub mod debug_rects;
pub mod debug_view;
pub mod diagnostics_view;
pub mod diff_view;
pub mod discovery;
pub mod editor_view;
pub mod fim_progress_overlay;
pub mod first_launch_overlay;
pub mod flaky_view;
pub mod flash_overlay;
pub mod ghost_overlay;
pub mod git_graph_view;
pub mod git_status_view;
pub mod integration_settings_overlay;
pub mod new_cloud_agent_wizard_view;
pub mod new_cloud_run_wizard_view;
// GitHub views moved to mnml-forge-github.
// GitLab views moved to mnml-forge-gitlab.
pub mod glyph_builder_overlay;
pub mod grep_view;
pub mod help_overlay;
pub mod hover;
pub mod icons;
pub mod image_view;
pub mod integration_detail_view;
pub mod integration_edit_overlay;
// log_tail_view moved to mnml-aws-codebuild.
pub mod md_inline_overlay;
pub mod md_preview;
pub mod outline_view;
pub mod picker;
// pipeline_log_view removed after 2026-06 SCM split.
pub mod agents_panel;
pub mod cloud_agents_panel;
pub mod dock;
pub mod findings_panel;
pub mod git_palette;
pub mod hover_help;
pub mod http_panel;
pub mod info_view;
pub mod info_view_copy;
pub mod md_preview_external;
pub mod menu_bar;
pub mod mount_view;
pub mod notes_panel;
pub mod prompt;
pub mod pty_view;
pub mod rename_preview_overlay;
pub mod request_view;
pub mod scratch_term_view;
pub mod scrollbar;
pub mod sessions_panel;
pub mod settings_overlay;
pub mod signature;
pub mod startup_picker;
pub mod statusline;
pub mod tests_view;
pub mod text_input;
pub mod theme;
pub mod toast_stack;
pub mod todos_panel;
pub mod tooltip;
pub mod workspace_picker;
pub mod workspaces_editor;
// `trace_view` moved to mnml-test-playwright in 2026-06.
pub mod tree_view;
pub mod welcome;
pub mod welcome_overlay;
pub mod whichkey;
pub mod yank_flash_overlay;

use ratatui::Frame;
use ratatui::layout::{Constraint, Layout as RLayout, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Paragraph};

use crate::app::App;
use crate::focus::Focus;
use crate::layout::{Layout, SplitDir, split_rects};

/// Task #954 — Shared expand/collapse glyph. Honors `[ui]
/// expand_indicator` (`"chevron"` default, `"triangle"` alt). Used
/// across the ~4 mnml-core render sites that draw a section header
/// with an expand affordance (diff hunks, DAP debug pane, DAP REPL,
/// help overlay sections). File tree has its own helper
/// (`section_chev_with_pref` in `tree_view.rs`) that consults the
/// same pref, so triangle mode is a whole-app swap as of #970.
///
/// Chevron mode uses Nerd Font glyphs (`U+F460` / `U+F47C` — same as
/// `tree_view::section_chev_with_pref`) unless `[ui] ascii_icons =
/// true`, in which case it falls back to ASCII `>`/`v`. Triangle
/// mode uses small filled triangles (`▸`/`▾`) regardless of ascii
/// mode — those are BMP glyphs available everywhere.
pub fn expand_glyph(app: &App, expanded: bool) -> &'static str {
    let use_triangle = app.config.ui.expand_indicator == "triangle";
    let nerd = !app.config.ui.ascii_icons;
    match (expanded, use_triangle, nerd) {
        (true, true, _) => "",
        (false, true, _) => "",
        // Chevron branch: Nerd Font glyphs when available, ASCII
        // otherwise. Codepoints match tree_view::section_chev.
        (true, false, true) => "\u{F47C}",
        (false, false, true) => "\u{F460}",
        (true, false, false) => "v",
        (false, false, false) => ">",
    }
}

pub fn draw(frame: &mut Frame, app: &mut App) {
    let area = frame.area();
    frame.render_widget(
        Block::default().style(Style::default().bg(theme::cur().bg_dark)),
        area,
    );
    // 2026-07-19 STRUCTURAL FIX — wipe every rect at frame start
    // and let each painter repopulate fresh. `PaneRects` is
    // documented as "screen regions captured during render,
    // consumed for mouse routing on the next event" — nothing is
    // meant to survive across frames. Every prior stale-rect bug
    // (session_tabs, integration_icon_rects, launcher_icon_rects,
    // ai_placeholder_card, and several others we hand-patched)
    // came from a panel that cleared its own rects at draw-entry
    // but stopped drawing when the panel wasn't active — the
    // rects then persisted into subsequent frames and stole
    // clicks. Resetting the whole struct in ONE place kills the
    // entire class of bug: no matter which painter runs or
    // doesn't, `app.rects` reflects THIS frame's paint only.
    //
    // The per-frame cost is a `*self = Self::default()` on a
    // struct with ~256 fields — trivial (well under 1µs on any
    // machine that runs mnml). Trades a hand-maintained clearing
    // list for a guarantee.
    app.rects.reset_for_frame();

    // Full-screen mode: skip the tree, bufferline, and statusline — the editor takes
    // the full window. Returning early keeps the toggle a flat opt-out from
    // the rest of the layout pipeline.
    if app.fullscreen_mode {
        app.rects.body = Some(area);
        // Reserve a 1-row hint footer at the bottom so the user can
        // always find their way out of full-screen mode. The chrome row
        // costs ~1% of the screen but eliminates the "I'm stuck"
        // failure mode the user reported.
        let (body_area, hint_area) = if area.height >= 4 {
            (
                Rect {
                    x: area.x,
                    y: area.y,
                    width: area.width,
                    height: area.height - 1,
                },
                Some(Rect {
                    x: area.x,
                    y: area.y + area.height - 1,
                    width: area.width,
                    height: 1,
                }),
            )
        } else {
            (area, None)
        };
        let layout = app.effective_layout_for_render();
        let cursor_pos: Option<(u16, u16)> = if matches!(layout, Layout::Empty) {
            welcome::draw(frame, app, body_area);
            None
        } else {
            let mut path = Vec::new();
            render_layout(frame, app, &layout, body_area, &mut path)
        };
        if let Some(hint) = hint_area {
            let t = theme::cur();
            let label = " Full screen  ·  Esc to exit  ·  :view.fullscreen toggle ";
            let pad = (hint.width as usize).saturating_sub(label.chars().count());
            let line = Line::from(vec![
                Span::styled(
                    label,
                    Style::default()
                        .fg(t.comment)
                        .bg(t.bg_dark)
                        .add_modifier(Modifier::DIM),
                ),
                Span::styled(" ".repeat(pad), Style::default().bg(t.bg_dark)),
            ]);
            frame.render_widget(Paragraph::new(line), hint);
        }
        // Overlays still work in zen — picker, prompt, which-key, popups.
        if app.picker.is_some() {
            picker::draw(frame, app, area);
        }
        if app.whichkey.is_some() {
            whichkey::draw(frame, app, area);
        }
        if app.prompt.is_some() {
            prompt::draw(frame, app, area);
        }
        if app.hover.is_some() {
            hover::draw(frame, app, area, cursor_pos);
        }
        if app.signature.is_some() {
            signature::draw(frame, app, area, cursor_pos);
        }
        if app.completion.is_some() {
            completion::draw(frame, app, area, cursor_pos);
        }
        if let Some((x, y)) = app.rects.prompt_caret.or(app.rects.picker_caret) {
            frame.set_cursor_position((x, y));
        } else if app.focus == Focus::Pane
            && let Some((x, y)) = cursor_pos
        {
            frame.set_cursor_position((x, y));
        }
        return;
    }

    // Clear the split-strip button rects at the top of every
    // non-zen frame so two populating call sites (`bufferline::draw`
    // for single-leaf, `paint_leaf_tab_strip` for multi-leaf) can
    // BOTH push their entries this frame without one wiping the
    // other's contribution.
    app.rects.split_strip_buttons.clear();
    app.rects.split_strip_term_buttons.clear();
    app.rects.split_strip_ai_buttons.clear();
    app.rects.split_strip_maximize_buttons.clear();

    // Split off the bottom statusline + cmdline bar (each 1 row, full width).
    // Cmdline bar sits BELOW the statusline (vim/neovim convention: the
    // statusline shows steady state, the cmdline below it shows the live `:`
    // line + transient echo messages). The top row is a 1-row palette bar
    // (VS Code-style centered "search files, run commands…" chip) — visible
    // when the window is wide enough.
    let palette_bar_visible = area.width >= 80;
    let palette_bar_h: u16 = if palette_bar_visible { 1 } else { 0 };
    // 2026-08-09 — hover-help footer strip retired. Now renders as an
    // Ableton-style info BOX docked at the bottom of the left panel
    // (see `ui::tree_view` + `ui::hover_help`). Same on/off gate via
    // `app.config.ui.hover_help`; the top-level layout no longer
    // reserves a row for it.
    let v = RLayout::vertical([
        Constraint::Length(palette_bar_h),
        Constraint::Min(1),
        Constraint::Length(1),
        Constraint::Length(1),
    ])
    .split(area);
    let (palette_bar_area, mut upper, statusline_area, cmdline_bar_area) = (v[0], v[1], v[2], v[3]);

    // 2026-08-07 — bottom panel (dockable panes Phase 1). Carve
    // `bottom_panel_height` rows off the bottom of `upper` if
    // visible. Clamped so it never eats more than 2/3 of the
    // upper area (leaves reasonable editor room even at silly
    // heights). See docs/design/dockable-panes.md.
    let bottom_panel_area: Option<Rect> = if app.bottom_panel_visible && upper.height >= 6 {
        let requested = app.bottom_panel_height.max(3);
        let max_allowed = (upper.height as u32 * 2 / 3) as u16;
        let h = requested.min(max_allowed).max(3);
        let split_y = upper.y + upper.height - h;
        let panel = Rect {
            x: upper.x,
            y: split_y,
            width: upper.width,
            height: h,
        };
        upper = Rect {
            x: upper.x,
            y: upper.y,
            width: upper.width,
            height: upper.height - h,
        };
        Some(panel)
    } else {
        None
    };

    if palette_bar_visible {
        draw_palette_bar(frame, app, palette_bar_area);
    } else {
        // render-reviewer #1 — narrow-terminal stale rects bug.
        // Previously cleared only palette_search_chip; the other
        // chrome rects survived from the last frame and stole
        // clicks at row 0 once the terminal shrank below 80 cols.
        app.rects.palette_search_chip = None;
        app.rects.palette_sidebar_button = None;
        app.rects.palette_right_panel_button = None;
        app.rects.palette_back_button = None;
        app.rects.palette_forward_button = None;
        app.rects.palette_dropdown_button = None;
        app.rects.palette_add_integration_button = None;
        app.rects.menu_bar_words.clear();
        app.rects.bufferline_new_tab_button = None;
        app.rects.bufferline_tab_page_chips.clear();
        app.rects.bufferline_tab_page_close.clear();
        app.rects.bufferline_theme_toggle = None;
        app.rects.bufferline_window_close = None;
    }

    // tree rail | right column. `tree_visible` here means "the rail itself is
    // showing" (toggled by `Ctrl+B`); a separate `tree_root_expanded` flag,
    // read by `tree_view::draw`, controls whether the file list under the
    // workspace-name header is shown (the VS-Code-style section collapse).
    // Right-panel split: carve a fixed-width column off the right
    // edge BEFORE we do the left rail split, so widths stay
    // independent. `upper` shrinks to the remaining middle column.
    //
    // Task #891 — `[ui] auto_hide_narrow_width` (0=disabled). When the
    // terminal width falls below the threshold, override both panel
    // visibility flags to `false` for THIS DRAW ONLY — persistent
    // `tree_visible` / `right_panel_visible` state is untouched, so
    // widening the window restores whatever the user had toggled.
    let narrow_auto_hide = app.side_panels_auto_hidden(upper.width);
    let show_right = app.right_panel_visible && !narrow_auto_hide;
    let show_tree = app.tree_visible && !narrow_auto_hide;
    let (right_panel_area, right_panel_edge_area, upper) = if show_right {
        // 2026-07-08 — DEDICATED 1-cell divider column between the
        // upper (editor) area and the right panel, mirroring the
        // tree edge treatment. Editor keeps its scrollbar
        // unaffected; the divider gets its own column that can
        // light up on hover / drag without stomping content.
        let w = app
            .right_panel_width
            .min(upper.width.saturating_sub(21))
            .max(8);
        let cols = RLayout::horizontal([
            Constraint::Min(1),
            Constraint::Length(1),
            Constraint::Length(w),
        ])
        .split(upper);
        // 1-cell hit zone matching the divider column — same
        // rationale as the tree edge (scrollbar of the pane on
        // the LEFT stays free for wheel / drag).
        app.rects.right_panel_edge = Some(cols[1]);
        (Some(cols[2]), Some(cols[1]), cols[0])
    } else {
        app.rects.right_panel_edge = None;
        app.rects.right_panel_close = None;
        (None, None, upper)
    };

    let (tree_area, tree_edge_area, right) = if show_tree {
        // 2026-07-08 — carve a DEDICATED 1-cell resize divider
        // column between the tree body and the editor area, same
        // shape as `layout::split_rects` does for a split. The
        // tree gets its own `w` cells (scrollbar in its own
        // rightmost column, unaffected); the divider takes 1
        // cell to the right; the editor takes what's left. This
        // matches the split-pane pattern instead of overpainting
        // the tree's scrollbar with the hover-highlight.
        let w = app.tree_width.min(upper.width.saturating_sub(21)).max(8);
        let cols = RLayout::horizontal([
            Constraint::Length(w),
            Constraint::Length(1),
            Constraint::Min(1),
        ])
        .split(upper);
        // Resize hit zone is ONLY the divider column (1 cell wide).
        // User 2026-07-08: earlier a 3-cell wide zone extended 1
        // cell to the left into the SCROLLBAR column, so clicking
        // the scrollbar started a resize instead of a scroll drag.
        // The 1-cell divider column is small but distinct — the
        // hover cyan makes it easy to spot; the scrollbar has its
        // own dedicated column immediately to the left.
        app.rects.tree_edge = Some(cols[1]);
        (Some(cols[0]), Some(cols[1]), cols[2])
    } else {
        app.rects.tree_edge = None;
        (None, None, upper)
    };

    // 2026-08-16 — empty-state top-strip re-instated (user request).
    // When no panes are open the welcome screen fills the body, but
    // there's nowhere for the `+ new-tab` chip + right cluster to
    // live. Reserve the top 1-row strip in that case, matching the
    // visual position where a pane's own tab strip would appear as
    // soon as the first pane opens — so opening a tab replaces this
    // row with the tab strip at the same y, no layout jump. When
    // any pane exists, `bufferline_area = None` and body_area gets
    // the full `right` — per-pane tab strips carry the cluster then.
    //
    // The 2026-08-08 delete note is preserved above for context: the
    // top-strip was retired then because "produced no visually
    // distinct outcome vs. hiding it". User asks for it back on the
    // empty-state case.
    let (bufferline_area, body_area) = if app.panes.is_empty() && right.height > 1 {
        let strip = Rect {
            x: right.x,
            y: right.y,
            width: right.width,
            height: 1,
        };
        let body = Rect {
            x: right.x,
            y: right.y + 1,
            width: right.width,
            height: right.height - 1,
        };
        (Some(strip), body)
    } else {
        (None, right)
    };

    // ── tree rail (full height of `upper`) ──
    // The rail is split into two columns: a 4-cell activity-bar
    // strip on the far left + the larger content pane that hosts
    // whichever ActivitySection is active. tree_view continues to
    // render the Explorer mode; other modes paint a stub.
    if let Some(ta) = tree_area {
        let bar_w = crate::ui::activity_bar::ACTIVITY_BAR_WIDTH.min(ta.width);
        let bar_area = Rect {
            x: ta.x,
            y: ta.y,
            width: bar_w,
            height: ta.height,
        };
        let content_area = Rect {
            x: ta.x + bar_w,
            y: ta.y,
            width: ta.width.saturating_sub(bar_w),
            height: ta.height,
        };
        crate::ui::activity_bar::draw(frame, app, bar_area);
        // qa-feature 2026-06-30 — clear the repo-switch rect when
        // the Git palette isn't the active section so a stale rect
        // from a previous frame doesn't catch clicks elsewhere.
        if !matches!(app.active_section, crate::app::ActivitySection::Git) {
            app.rects.git_graph_repo_switch = None;
        }
        // qa-feature 2026-07-01 — clear `scrollbars` BEFORE the
        // tree renders. The main clear at ~L1251 runs later in
        // this fn, AFTER `tree_view::draw` has already pushed
        // its scrollbar hit rects — so the tree registrations
        // got wiped every frame and the mouse dispatcher saw
        // an empty list. Clearing here + skipping the later
        // clear preserves tree + editor + everyone's
        // registrations for one full frame.
        app.rects.scrollbars.clear();
        // mouse-round-11 SEV-2 2026-07-12 → user report 2026-07-15
        // ("previously viewed screen is getting the clicks") — clear
        // EVERY activity-panel click-rect up front so a stale rect
        // from a previously-visible panel can't hijack a click.
        // Whichever panel dispatches below repopulates its own
        // rects; anything else stays cleared. Round-11 only covered
        // filter-input rects — this generalizes to all activity-
        // panel rects. See `PaneRects::clear_activity_panel_rects`
        // for the full list and the maintenance note.
        app.rects.clear_activity_panel_rects();
        // R10 api-workflow SEV-2 — hover-help info box used to live
        // only inside `tree_view::draw`, so switching from Explorer
        // to Http / Git / Integrations / Agents / anything else made
        // the info panel vanish. Reserve `app.hover_help_height` here
        // (user-tunable via drag-resize, seeded from `[ui] hover_help_height`
        // whose default is `DEFAULT_INFO_BOX_HEIGHT`, regardless of
        // section), pass the reduced `panel_area` to every
        // section-draw, then paint the info box below at the
        // consistent bottom position. `tree_view` no longer
        // reserves internally.
        let (panel_area, hover_help_area): (Rect, Option<Rect>) =
            if app.config.ui.hover_help && content_area.height >= app.hover_help_height + 8 {
                let box_h = app.hover_help_height;
                let body = Rect {
                    x: content_area.x,
                    y: content_area.y,
                    width: content_area.width,
                    height: content_area.height - box_h,
                };
                let boxed = Rect {
                    x: content_area.x,
                    y: content_area.y + content_area.height - box_h,
                    width: content_area.width,
                    height: box_h,
                };
                (body, Some(boxed))
            } else {
                app.rects.hover_help_strip = None;
                // If a drag was in flight when the panel became too
                // small to render (window shrink mid-drag), abort it
                // — the drag target no longer exists, and leaving
                // `hover_help_drag = Some` would silently intercept
                // the next unrelated left-drag anywhere in the UI.
                app.hover_help_drag = None;
                (content_area, None)
            };
        let content_area = panel_area;
        match app.active_section {
            crate::app::ActivitySection::Explorer => {
                tree_view::draw(frame, app, content_area);
            }
            crate::app::ActivitySection::Integrations => {
                draw_integrations_section(frame, app, content_area);
            }
            crate::app::ActivitySection::Search => {
                draw_search_section(frame, app, content_area);
            }
            crate::app::ActivitySection::Debug => {
                draw_debug_section(frame, app, content_area);
            }
            crate::app::ActivitySection::Git => {
                git_palette::draw(frame, app, content_area);
            }
            crate::app::ActivitySection::Sessions => {
                sessions_panel::draw(frame, app, content_area);
            }
            crate::app::ActivitySection::Agents => {
                agents_panel::draw(frame, app, content_area);
            }
            crate::app::ActivitySection::CloudAgents => {
                cloud_agents_panel::draw(frame, app, content_area);
            }
            crate::app::ActivitySection::Http => {
                http_panel::draw(frame, app, content_area);
            }
            crate::app::ActivitySection::Notes => {
                notes_panel::draw(frame, app, content_area);
            }
            crate::app::ActivitySection::Todos => {
                todos_panel::draw(frame, app, content_area);
            }
            crate::app::ActivitySection::Findings => {
                findings_panel::draw(frame, app, content_area);
            }
            crate::app::ActivitySection::Mount(idx) => {
                // Rail content for a manifest-mounted integration is
                // intentionally minimal in slice 3 — the integration's
                // real UI is the Pane::Mount in the editor body,
                // not in the rail. We surface the manifest name +
                // a "Re-open" hint so the user can re-spawn if
                // they closed the pane.
                let t = theme::cur();
                let manifest = app.mount_manifests.get(idx as usize).cloned();
                let label = manifest
                    .as_ref()
                    .map(|m| m.name.clone())
                    .unwrap_or_else(|| "Mount".to_string());
                let body = vec![
                    ratatui::text::Line::from(vec![ratatui::text::Span::styled(
                        format!(" {label} "),
                        ratatui::style::Style::default()
                            .fg(t.fg)
                            .bg(t.bg_darker)
                            .add_modifier(ratatui::style::Modifier::BOLD),
                    )]),
                    ratatui::text::Line::from(""),
                    ratatui::text::Line::from(vec![ratatui::text::Span::styled(
                        " click the icon again to re-spawn ",
                        ratatui::style::Style::default()
                            .fg(t.comment)
                            .bg(t.bg_darker),
                    )]),
                ];
                frame.render_widget(
                    ratatui::widgets::Block::default()
                        .style(ratatui::style::Style::default().bg(t.bg_darker)),
                    content_area,
                );
                frame.render_widget(ratatui::widgets::Paragraph::new(body), content_area);
            }
            crate::app::ActivitySection::LauncherIcon(_) => {
                // 2026-07-20 — LauncherIcon has no side panel; the
                // click already fired the chip command. This arm
                // shouldn't render in practice (the click handler
                // never enters set_activity_section for
                // LauncherIcon), but keep it exhaustive.
            }
        }
        // Info-View panel — paint once, below whichever section drew
        // its body above. Reserved by the pre-match slicing so no
        // panel needs to know about it.
        if let Some(r) = hover_help_area {
            hover_help::draw(frame, app, r);
        }
        // For non-Explorer sections the tree_view click rects aren't
        // populated; ensure they're at least cleared so a stale click
        // from a prior frame doesn't fire.
        if app.active_section != crate::app::ActivitySection::Explorer {
            app.rects.tree = None;
            app.rects.tree_toggle = None;
            app.rects.tree_icon_buttons.clear();
        }
        // Resize divider — its own 1-cell column, sibling to the
        // scrollbar (not overlapping). Idle = subtle `│` in
        // `t.line`; hover / drag = cyan. Same `draw_divider` helper
        // that split panes use.
        if let Some(divider) = tree_edge_area {
            let hover = app.hover_tree_edge || app.dragging_tree_edge;
            draw_divider(frame, divider, crate::layout::SplitDir::Horizontal, hover);
        }
    } else {
        app.rects.tree = None;
        app.rects.tree_toggle = None;
        app.rects.git_section_toggle = None;
        app.rects.git_rail_rows.clear();
    }

    // ── right panel ──
    // v1: scaffold only. Carved a column already; paint a header
    // + empty-state hint here so the user can see + resize the
    // panel. v2 will host outline / chat / dock-as-rail content
    // pluggable via user config.
    if let Some(rpa) = right_panel_area {
        let t = theme::cur();
        frame.render_widget(
            ratatui::widgets::Block::default().style(Style::default().bg(t.bg_darker)),
            rpa,
        );
        // Right-panel v3 (2026-06-28): the panel can host multiple
        // panes as TABS. `right_panel_panes` is the canonical list;
        // the active index references that list directly so click
        // routing and × close stay in sync with the data model.
        // Dead panes (removed from app.panes via other paths) are
        // skipped during paint via the per-iteration filter inside
        // the loop — using right_panel_panes-relative indices throughout
        // avoids the index-divergence bug render-reviewer flagged.
        let panes_len = app.right_panel_panes.len();
        let active_idx = if panes_len == 0 {
            0
        } else {
            app.right_panel_active_idx.min(panes_len - 1)
        };
        let active_pane: Option<usize> = app
            .right_panel_panes
            .get(active_idx)
            .copied()
            .filter(|id| app.panes.get(*id).is_some());
        let has_any_hosted = app
            .right_panel_panes
            .iter()
            .any(|id| app.panes.get(*id).is_some());

        // Header row. design-critic v3 #2 — use the pane's own
        // tab_title() so the chip shows live state (e.g.
        // "main.rs ⌥3" / "problems ✗2") instead of static labels.
        // Falls back to a generic label for unsupported kinds.
        // design-critic 2026-06-28 #1: when budget tightens (3
        // tabs in 32-cell column ≈ 7 chars/chip), prefer info-dense
        // short forms (counts + status glyphs) over truncated
        // nouns. `max_chars: None` → full title; Some(n) → short.
        let tab_label = |pane: &crate::pane::Pane, max_chars: Option<usize>| -> String {
            let full: String = match pane {
                crate::pane::Pane::Outline(o) => o.tab_title(),
                crate::pane::Pane::Diagnostics(d) => d.tab_title(),
                crate::pane::Pane::Ai(a) => a.tab_title(),
                crate::pane::Pane::Tests(t) => t.tab_title(),
                crate::pane::Pane::Grep(g) => g.tab_title(),
                crate::pane::Pane::IntegrationDetail(d) => d.tab_title(),
                _ => "PANEL".to_string(),
            };
            let Some(budget) = max_chars else { return full };
            if full.chars().count() <= budget {
                return full;
            }
            // Short form picks per pane kind: keep the count glyphs,
            // drop the noun.
            match pane {
                crate::pane::Pane::Outline(o) => {
                    // "main.rs ⌥42" → "main.rs" or "main.r…" — file name only.
                    o.target
                        .file_stem()
                        .and_then(|s| s.to_str())
                        .map(|s| s.chars().take(budget).collect::<String>())
                        .unwrap_or_else(|| "outline".to_string())
                }
                crate::pane::Pane::Diagnostics(d) => {
                    // "problems ✗2 ⚠1" → "✗2⚠1" (4-6 chars).
                    let (e, w) = d.counts();
                    match (e, w) {
                        (0, 0) => "".to_string(),
                        (e, 0) => format!("{e}"),
                        (0, w) => format!("{w}"),
                        (e, w) => format!("{e}{w}"),
                    }
                }
                crate::pane::Pane::Tests(t) => {
                    // "tests Done ✓15 ✗0" → "✓15" / "✗1" / "…" / "✗".
                    match &t.state {
                        crate::playwright::TestsState::Running => "".to_string(),
                        crate::playwright::TestsState::Failed(_) => "".to_string(),
                        crate::playwright::TestsState::Done(r) => {
                            let f = r.failed();
                            if f > 0 {
                                format!("{f}")
                            } else {
                                format!("{}", r.passed())
                            }
                        }
                    }
                }
                crate::pane::Pane::Grep(g) => {
                    // "grep:query (24)" → "(24)" or "g:q…" — count only at tightest.
                    let n = g.hits.len();
                    if budget >= 5 {
                        // Try a leading "q…" with count: "ab… 24"
                        let q: String = g.query.chars().take(budget.saturating_sub(3)).collect();
                        format!("{q}{n}")
                    } else {
                        format!("({n})")
                    }
                }
                crate::pane::Pane::Ai(a) => {
                    // "AI: explain — done" → "AI ✦" (preserve the
                    // status marker — it's the live info; the
                    // noun is what's lost when budget tightens).
                    let marker = match a.state {
                        crate::ai::AiState::Asking | crate::ai::AiState::Streaming(_) => "",
                        crate::ai::AiState::Failed(_) => "",
                        crate::ai::AiState::Done(_) => "",
                        crate::ai::AiState::Live { .. } => "",
                    };
                    if budget >= 4 {
                        format!("AI {marker}")
                    } else {
                        marker.to_string()
                    }
                }
                _ => {
                    let mut s: String = full.chars().take(budget.saturating_sub(1)).collect();
                    s.push('');
                    s
                }
            }
        };
        app.rects.right_panel_tabs.clear();
        if rpa.height >= 1 && rpa.width >= 4 {
            let header_rect = Rect {
                x: rpa.x,
                y: rpa.y,
                width: rpa.width,
                height: 1,
            };
            frame.render_widget(
                ratatui::widgets::Block::default().style(Style::default().bg(t.bg_darker)),
                header_rect,
            );
            if !has_any_hosted {
                // Empty state: still paint the section label.
                // design-critic 2026-06-28 #5: lowercase "right panel"
                // matches the vocabulary used by palette title,
                // tooltips, whichkey, context menu, toast. Bold
                // modifier alone preserves visual hierarchy without
                // shouting.
                // mouse-round-7 SEV-3 2026-07-12 — narrow-panel
                // truncation used to render as bare `right p` with
                // no ellipsis. Clip with `…` so the truncation
                // reads as intentional, and swap to the FEATURES-
                // documented "too narrow" hint below 16 cells.
                let label = if header_rect.width < 16 {
                    " tight"
                } else {
                    " right panel"
                };
                let clipped = clip_to_cells(label, header_rect.width as usize);
                frame.render_widget(
                    ratatui::widgets::Paragraph::new(clipped).style(
                        Style::default()
                            .fg(t.comment)
                            .bg(t.bg_darker)
                            .add_modifier(Modifier::BOLD),
                    ),
                    header_rect,
                );
                app.rects.right_panel_close = None;
            } else {
                // Tab strip — one chip per LIVE hosted pane. We
                // walk `right_panel_panes` (not a filtered copy) so
                // the index stored in `right_panel_tabs` matches
                // the data model's index. Dead panes are skipped
                // in the loop body.
                let reserve_close: u16 = 2;
                let mut x = rpa.x;
                let strip_end = rpa.x + rpa.width.saturating_sub(reserve_close);
                let panes_snapshot: Vec<usize> = app.right_panel_panes.clone();
                // design-critic #1 (2026-06-28): track the active tab's
                // right edge AND whether it was the LAST chip painted,
                // so we can paint a bg2 connector from there to the ×
                // close button. Visually merges the × with the chip it
                // acts on; falls back to a detached corner × when the
                // active tab isn't the rightmost.
                let mut active_end_x: Option<u16> = None;
                let mut last_painted_active = false;
                // design-critic 2026-06-28 #1: budget per chip so
                // tab_label can pick a short form when truncation
                // would otherwise nuke the count glyphs that are
                // the whole point of a live tab title.
                let n_chips = panes_snapshot.len().max(1) as u16;
                let avail_per_chip = strip_end
                    .saturating_sub(rpa.x)
                    .saturating_sub(n_chips.saturating_sub(1)) // gaps
                    / n_chips;
                let per_chip_label_budget = avail_per_chip.saturating_sub(2) as usize;
                for (i, pid) in panes_snapshot.iter().copied().enumerate() {
                    let Some(pane) = app.panes.get(pid) else {
                        continue;
                    };
                    // Pass the per-chip budget so the label fn
                    // chooses short-form when it would otherwise be
                    // truncated past the count.
                    let full_label = tab_label(pane, None);
                    let mut label = if full_label.chars().count() <= per_chip_label_budget {
                        full_label
                    } else {
                        tab_label(pane, Some(per_chip_label_budget))
                    };
                    // Truncate long labels (file paths) to fit chip
                    // within remaining strip space. Reserve `…` cell
                    // if we truncate. Min sensible chip = " X… " = 4.
                    let chip = format!(" {label} ");
                    let mut chip_w = chip.chars().count() as u16;
                    if x + chip_w > strip_end {
                        // Try to truncate the label to fit.
                        let avail = strip_end.saturating_sub(x + 3);
                        if avail >= 2 {
                            let take = avail as usize - 1;
                            label = label.chars().take(take).collect::<String>() + "";
                            chip_w = (label.chars().count() + 2) as u16;
                            if x + chip_w > strip_end {
                                break;
                            }
                        } else {
                            break;
                        }
                    }
                    let chip = format!(" {label} ");
                    let chip_rect = Rect {
                        x,
                        y: rpa.y,
                        width: chip_w,
                        height: 1,
                    };
                    // Active tab is fully opaque (bg2 lighter than the
                    // panel column's bg_darker), inactive uses bg_dark
                    // (slightly lighter than bg_darker but darker than
                    // bg2) so it READS as a tab — render-reviewer #4
                    // flagged that inactive == panel bg made them
                    // invisible.
                    let bg = if i == active_idx { t.bg2 } else { t.bg_dark };
                    let fg = if i == active_idx { t.fg } else { t.comment };
                    frame.render_widget(
                        ratatui::widgets::Paragraph::new(chip)
                            .style(Style::default().fg(fg).bg(bg).add_modifier(Modifier::BOLD)),
                        chip_rect,
                    );
                    app.rects.right_panel_tabs.push((chip_rect, i));
                    x = x.saturating_add(chip_w);
                    // Track if THIS chip was the active one and
                    // whether it's still the most-recent painted.
                    if i == active_idx {
                        active_end_x = Some(x);
                        last_painted_active = true;
                    } else {
                        last_painted_active = false;
                    }
                    // 1-cell gap between chips so the bg_darker
                    // background reads as a separator. design-critic
                    // #1 — mirrors paint_leaf_tab_strip.
                    if x < strip_end {
                        x = x.saturating_add(1);
                    }
                }
                // design-critic #1 — when the active tab is the
                // last painted chip, fill the cells between its
                // right edge and the close button with bg2 so the
                // × visually merges with the chip it acts on.
                if last_painted_active && let Some(end) = active_end_x {
                    let close_x = rpa.x + rpa.width.saturating_sub(2);
                    if end < close_x {
                        let bridge_rect = Rect {
                            x: end,
                            y: rpa.y,
                            width: close_x - end,
                            height: 1,
                        };
                        frame.render_widget(
                            ratatui::widgets::Block::default().style(Style::default().bg(t.bg2)),
                            bridge_rect,
                        );
                    }
                }
                // #polish 2026-07-06 — `+` chip at the end of the
                // tab strip (just before ×), matching bufferline
                // parity. Only paints when there's at least 1 cell
                // of room past the tabs before the × slot.
                let close_x = rpa.x + rpa.width.saturating_sub(2);
                if x + 3 <= close_x {
                    let plus_rect = Rect {
                        x,
                        y: rpa.y,
                        width: 3,
                        height: 1,
                    };
                    let glyph = if app.config.ui.ascii_icons {
                        " + "
                    } else {
                        " \u{F0415} "
                    };
                    frame.render_widget(
                        ratatui::widgets::Paragraph::new(glyph).style(
                            Style::default()
                                .fg(t.green)
                                .bg(t.bg_dark)
                                .add_modifier(Modifier::BOLD),
                        ),
                        plus_rect,
                    );
                    app.rects.right_panel_new_button = Some(plus_rect);
                } else {
                    app.rects.right_panel_new_button = None;
                }
                // `×` close button on the rightmost cell.
                // design-critic 2026-06-28 #2: when the active tab
                // is the rightmost chip, the bg2 bridge ties × to
                // it visually (good). When the active is NOT
                // rightmost, the bridge doesn't paint and the ×
                // sits next to an inactive chip — risk of reading
                // as a close-this-inactive-chip target. Paint × in
                // bg_dark (matches inactive chip bg) + comment fg
                // in that case, so it visually signals "modal —
                // acts on the active tab" rather than "local close
                // for this chip".
                if rpa.width > reserve_close {
                    let close_x = rpa.x + rpa.width.saturating_sub(2);
                    let close_rect = Rect {
                        x: close_x,
                        y: rpa.y,
                        width: 1,
                        height: 1,
                    };
                    let glyph = if app.config.ui.ascii_icons { "x" } else { "×" };
                    let (close_fg, close_bg) = if last_painted_active {
                        (t.fg, t.bg2)
                    } else {
                        (t.comment, t.bg_dark)
                    };
                    frame.render_widget(
                        ratatui::widgets::Paragraph::new(glyph)
                            .style(Style::default().fg(close_fg).bg(close_bg)),
                        close_rect,
                    );
                    app.rects.right_panel_close = Some(close_rect);
                } else {
                    app.rects.right_panel_close = None;
                }
            }
        }
        // Width hint — if user dragged the panel too narrow, show
        // a one-line warning instead of the cramped pane render.
        // Threshold of 16 cells matches outline_view's min readable
        // width (gutter + a few chars).
        // render-reviewer N-5 2026-06-28: was `rpa.height >= 3`
        // but the hint paints 2 rows starting at rpa.y + 2 → needs
        // rpa.y + 2 + 2 = rpa.y + 4 of panel space, i.e. height
        // >= 4 to show both rows. At height == 3 the second row
        // clipped silently.
        if active_pane.is_some() && rpa.width < 16 && rpa.height >= 4 {
            let hint = Rect {
                x: rpa.x + 1,
                y: rpa.y + 2,
                width: rpa.width.saturating_sub(2),
                height: 2,
            };
            frame.render_widget(
                ratatui::widgets::Paragraph::new("too narrow — drag edge wider")
                    .style(Style::default().fg(t.comment).bg(t.bg_darker))
                    .wrap(ratatui::widgets::Wrap { trim: false }),
                hint,
            );
        } else if let Some(pid) = active_pane {
            // Body is the area below the tab strip.
            let body = Rect {
                x: rpa.x,
                y: rpa.y + 1,
                width: rpa.width,
                height: rpa.height.saturating_sub(1),
            };
            let focused = app.active == Some(pid);
            match app.panes.get(pid) {
                Some(crate::pane::Pane::Outline(_)) => {
                    outline_view::draw(frame, app, pid, body, focused);
                }
                Some(crate::pane::Pane::Diagnostics(_)) => {
                    diagnostics_view::draw(frame, app, pid, body, focused);
                }
                Some(crate::pane::Pane::IntegrationDetail(_)) => {
                    integration_detail_view::draw(frame, app, pid, body, focused);
                }
                Some(crate::pane::Pane::ClaudeUsage(_)) => {
                    claude_usage_view::draw(frame, app, pid, body, focused);
                }
                Some(crate::pane::Pane::CodexUsage(_)) => {
                    codex_usage_view::draw(frame, app, pid, body, focused);
                }
                Some(crate::pane::Pane::Tests(_)) => {
                    tests_view::draw(frame, app, pid, body, focused);
                }
                Some(crate::pane::Pane::Grep(_)) => {
                    grep_view::draw(frame, app, pid, body, focused);
                }
                Some(crate::pane::Pane::Ai(_)) => {
                    // Right-panel v4: AI chat hosted in the column.
                    // Code blocks + prose need width — at <40 cells
                    // every code line wraps to 3+ rows. Toast-style
                    // hint at the top reminds the user to widen.
                    if body.width < 40 && body.height >= 3 {
                        let hint = Rect {
                            x: body.x + 1,
                            y: body.y,
                            width: body.width.saturating_sub(2),
                            height: 1,
                        };
                        frame.render_widget(
                            ratatui::widgets::Paragraph::new("AI chat reads better at 40+ cells")
                                .style(
                                    Style::default()
                                        .fg(t.yellow)
                                        .bg(t.bg_darker)
                                        .add_modifier(Modifier::DIM),
                                ),
                            hint,
                        );
                        let body_shrunk = Rect {
                            x: body.x,
                            y: body.y + 1,
                            width: body.width,
                            height: body.height.saturating_sub(1),
                        };
                        ai_view::draw(frame, app, pid, body_shrunk, focused);
                    } else {
                        ai_view::draw(frame, app, pid, body, focused);
                    }
                }
                _ => {
                    // design-critic v3 #8 — a future pane type
                    // pushed into the panel without a renderer arm
                    // would silently blank. Print a developer hint
                    // so the gap is loud, not silent.
                    if body.height >= 2 {
                        let msg_rect = Rect {
                            x: body.x + 1,
                            y: body.y + 1,
                            width: body.width.saturating_sub(2),
                            height: body.height.saturating_sub(1),
                        };
                        frame.render_widget(
                            ratatui::widgets::Paragraph::new(
                                "(pane type not supported in right panel — close with ×)",
                            )
                            .style(Style::default().fg(t.comment).bg(t.bg_darker))
                            .wrap(ratatui::widgets::Wrap { trim: false }),
                            msg_rect,
                        );
                    }
                }
            }
        } else if rpa.height >= 5 && rpa.width >= 16 {
            // design-critic 2026-06-28 #3: list ALL routable
            // commands, not just 2 of 5. v5 routes ai.chat,
            // find.grep, test.run into the panel too.
            let hint_height: u16 = 9;
            let hint_rect = Rect {
                x: rpa.x + 1,
                y: rpa.y + 2,
                width: rpa.width.saturating_sub(2),
                height: hint_height.min(rpa.height.saturating_sub(2)),
            };
            use ratatui::text::{Line, Span};
            // #polish 2026-07-06 — friendlier empty state. Was 5
            // raw `:cmd` lines (unfriendly); now human labels
            // with the palette command as an inline dim hint.
            let hint_style = Style::default().fg(t.comment).bg(t.bg_darker);
            let label_style = Style::default().fg(t.fg).bg(t.bg_darker);
            let make_row = |label: &str, cmd: &str| -> Line<'static> {
                Line::from(vec![
                    Span::styled(label.to_string(), label_style),
                    Span::styled(format!("  {cmd}"), hint_style.add_modifier(Modifier::DIM)),
                ])
            };
            let lines = vec![
                Line::from(Span::styled("Add a panel:", hint_style)),
                Line::from(""),
                make_row("▸ Outline", ":outline.show"),
                make_row("▸ Problems", ":lsp.diagnostics"),
                make_row("▸ AI chat", ":ai.chat"),
                make_row("▸ Grep", ":find.grep"),
                make_row("▸ Tests", ":test.run"),
                Line::from(""),
                Line::from(Span::styled("Hide: Ctrl+Shift+B", hint_style)),
            ];
            // render-reviewer 3rd 2026-06-29 SEV-2 W-2: disable
            // wrapping. At rpa.width 16–18 the "Nothing here yet."
            // prose line word-wraps to 2 rows, shifting every
            // command's row out of sync with its click rect. With
            // wrap off, lines overflow to a horizontal-clip but the
            // y mapping stays stable.
            frame.render_widget(
                ratatui::widgets::Paragraph::new(lines).style(Style::default().bg(t.bg_darker)),
                hint_rect,
            );
            // mouse-polish F-2 — register click rects so a mouse-
            // first user can populate the panel without typing.
            // design-critic 2026-06-28 #3: extended to all 5
            // routable commands.
            //
            // render-reviewer 3rd 2026-06-29 SEV-2 W-1: gate each
            // rect on the rendered y being INSIDE rpa, otherwise
            // a click in the statusline column (same x-range, but
            // below the panel) fires the empty-state command.
            // panel_bottom = rpa.y + rpa.height; row y is OK iff
            // y < panel_bottom.
            let panel_bottom = rpa.y.saturating_add(rpa.height);
            let row_in_panel = |y: u16| y < panel_bottom;
            let rect_at = |y_offset: u16, width: u16| -> Option<Rect> {
                let y = hint_rect.y.saturating_add(y_offset);
                if row_in_panel(y) {
                    Some(Rect {
                        x: hint_rect.x,
                        y,
                        width: width.min(hint_rect.width),
                        height: 1,
                    })
                } else {
                    None
                }
            };
            app.rects.right_panel_empty_outline = rect_at(2, 13);
            app.rects.right_panel_empty_diagnostics = rect_at(3, 16);
            app.rects.right_panel_empty_ai = rect_at(4, 8);
            app.rects.right_panel_empty_grep = rect_at(5, 10);
            app.rects.right_panel_empty_test = rect_at(6, 9);
        } else {
            app.rects.right_panel_empty_outline = None;
            app.rects.right_panel_empty_diagnostics = None;
            app.rects.right_panel_empty_ai = None;
            app.rects.right_panel_empty_grep = None;
            app.rects.right_panel_empty_test = None;
        }
        // Hover-highlight edge (same idiom as the tree rail — no
        // persistent grip glyph). Per-row Paragraph so the paint
        // Resize divider — dedicated column (same shape as split
        // dividers). Idle = subtle line; hover / drag = cyan.
        if let Some(divider) = right_panel_edge_area {
            let hover = app.hover_right_panel_edge || app.dragging_right_panel_edge;
            draw_divider(frame, divider, crate::layout::SplitDir::Horizontal, hover);
        }
        let _ = t;
    }

    // ── bufferline ──
    // #polish 2026-07-06 — clear the md mode-chip rects BEFORE
    // bufferline draws, so its own registrations survive. The
    // general per-frame clear at ~L1284 used to run AFTER
    // bufferline::draw, silently wiping the rects for the
    // single-pane (top bufferline) case; only the per-leaf split
    // strips (which paint later, in render_layout) refilled them.
    // Bug user report 2026-07-06.
    app.rects.md_preview_edit_buttons.clear();
    app.rects.editor_md_preview_buttons.clear();
    if let Some(ba) = bufferline_area {
        bufferline::draw(frame, app, ba);
        app.rects.bufferline = Some(ba);
    } else {
        app.rects.bufferline = None;
        app.rects.bufferline_tabs.clear();
        app.rects.bufferline_tab_close.clear();
        app.rects.bufferline_overflow_left = None;
        app.rects.bufferline_overflow_right = None;
        // NOTE: do NOT clear `bufferline_new_tab_button`,
        // `bufferline_tab_page_*`, `bufferline_theme_toggle`, or
        // `bufferline_window_close` here. Since the 2026-07-18
        // one-tab-type refactor, those rects belong to the PALETTE
        // BAR's right cluster (paint_right_cluster called from
        // draw_palette_bar), which already ran EARLIER this frame.
        // Clearing them here nuked the palette bar's `+ ▤ ×`
        // click targets whenever any pane was open — user reported
        // "the plus, slider, red x — none do anything".
    }

    // ── the split-tree of pane bodies ──
    // If the scratch terminal is open, reserve its strip at the bottom
    // before laying out the split tree so panes don't overlap it.
    let mut body_area = body_area;
    let mut scratch_strip: Option<Rect> = None;
    if app.scratch_term.is_some() {
        let want_h = crate::app::SCRATCH_TERM_ROWS;
        if body_area.height > want_h + 2 {
            let strip_h = want_h;
            scratch_strip = Some(Rect {
                x: body_area.x,
                y: body_area.y + body_area.height - strip_h,
                width: body_area.width,
                height: strip_h,
            });
            body_area.height -= strip_h;
        }
    }
    app.rects.scratch_term_strip = scratch_strip;
    // Inline dock widgets — claim a top + bottom strip based on
    // the max heights of inline widgets at top / bottom corners.
    // Widgets at BL/BR contribute to the BOTTOM strip; TL/TR to
    // the TOP strip. Multiple inline widgets at the same edge
    // tile horizontally — they don't stack — so the strip height
    // is the MAX of their heights (not the sum).
    let mut inline_bottom_strip: Option<Rect> = None;
    let mut inline_top_strip: Option<Rect> = None;
    {
        let area_h = body_area.height;
        let area_w = body_area.width;
        let mut top_h: u16 = 0;
        let mut bottom_h: u16 = 0;
        for w in &app.dock_widgets {
            if !matches!(w.layout, crate::dock::Layout::Inline) {
                continue;
            }
            let h_frac = w.height_frac.clamp(0.15, 0.9);
            let h = (area_h as f32 * h_frac) as u16;
            match w.corner {
                crate::dock::DockCorner::BottomLeft | crate::dock::DockCorner::BottomRight => {
                    if h > bottom_h {
                        bottom_h = h;
                    }
                }
                crate::dock::DockCorner::TopLeft | crate::dock::DockCorner::TopRight => {
                    if h > top_h {
                        top_h = h;
                    }
                }
            }
        }
        // Cap combined strip height at 50% of editor body so the
        // editor never gets crushed to a single row.
        let cap = area_h / 2;
        if top_h + bottom_h > cap {
            // Proportional shrink.
            let scale = cap as f32 / (top_h + bottom_h) as f32;
            top_h = (top_h as f32 * scale) as u16;
            bottom_h = (bottom_h as f32 * scale) as u16;
        }
        if top_h > 0 && area_h > top_h + 2 {
            inline_top_strip = Some(Rect {
                x: body_area.x,
                y: body_area.y,
                width: area_w,
                height: top_h,
            });
            body_area.y += top_h;
            body_area.height -= top_h;
        }
        if bottom_h > 0 && body_area.height > bottom_h + 2 {
            inline_bottom_strip = Some(Rect {
                x: body_area.x,
                y: body_area.y + body_area.height - bottom_h,
                width: area_w,
                height: bottom_h,
            });
            body_area.height -= bottom_h;
        }
    }
    app.rects.inline_dock_top_strip = inline_top_strip;
    app.rects.inline_dock_bottom_strip = inline_bottom_strip;
    // The native mixr panel — an overlay docked at the bottom-left of
    // the body (from the file-tree edge across). `BottomStrip` is a
    // short strip; `Full` is full body height. Width is capped at
    // `MAX_WIDTH` so a very wide screen doesn't blow it out.
    // `Minimized` = hidden (just the ♪ chip).
    app.rects.body = Some(body_area);
    app.rects.editor_panes.clear();
    // (md preview / editor chip rects are cleared earlier — see the
    // note above `bufferline::draw`.)
    app.rects.pane_bodies.clear();
    app.rects.editor_gutters.clear();
    app.rects.fold_chips.clear();
    app.rects.fold_arrows.clear();
    app.rects.pty_exit_close_buttons.clear();
    app.rects.code_lens_chips.clear();
    app.rects.wip_buttons.clear();
    app.rects.wip_file_rows.clear();
    app.rects.wip_commit_textarea = None;
    app.rects.git_toolbar_buttons.clear();
    app.rects.commit_file_rows.clear();
    app.rects.diff_toolbar_buttons.clear();
    app.rects.diff_hunk_buttons.clear();
    // qa-feature 2026-07-01 — scrollbars are cleared BEFORE
    // `tree_view::draw` (~L500) so the tree's registrations
    // survive the frame. See note there.
    app.rects.git_graph_detail_dividers.clear();
    app.rects.git_graph_column_headers.clear();
    app.rects.git_graph_lane_cells.clear();
    // git_graph_repo_switch is cleared at the top of
    // git_palette::draw (which runs BEFORE this point in ui flow).
    app.rects.request_tabs.clear();
    app.rects.request_fields.clear();
    app.rects.completion_rows.clear();
    app.rects.list_rows.clear();
    app.rects.claude_drill_files.clear();
    app.rects.split_dividers.clear();
    app.rects.pty_tabs.clear();
    app.rects.pty_tab_new.clear();
    app.rects.pty_tab_close.clear();
    let layout = app.effective_layout_for_render();
    // 2026-06-22 — clear per-split tab chip rects before the
    // recursive walk re-populates them. Without this, frames
    // would accumulate stale chip rects from prior layouts and
    // clicks would target deleted leaves.
    app.rects.split_tab_chips.clear();
    app.rects.split_tab_close.clear();
    app.rects.split_tab_strip_areas.clear();
    app.rects.split_tab_plus_buttons.clear();
    app.rects.ai_placeholder_card = None;
    app.rects.tab_insert_hint = None;
    // Note: `split_strip_buttons` / `split_strip_term_buttons` are
    // NOT cleared here — they were cleared earlier in ui::draw,
    // before `bufferline::draw` populated them for the single-leaf
    // case. Clearing here would wipe the bufferline's rects before
    // mouse dispatch reads them. The per-leaf strip in
    // `paint_leaf_tab_strip` pushes additional entries on top for
    // the multi-leaf case.
    let cursor_pos: Option<(u16, u16)> = if matches!(layout, Layout::Empty) {
        welcome::draw(frame, app, body_area);
        None
    } else {
        let mut path = Vec::new();
        render_layout(frame, app, &layout, body_area, &mut path)
    };

    // Corner-pinned dock widgets — painted AFTER the editor body so
    // they overlay it when they overlap, BEFORE the drop-hint /
    // ghost / overlays so a drag-target can still draw on top.
    dock::draw(frame, app, body_area);

    // Drag-to-split: while a bufferline tab is dragged over a pane body, paint
    // a hint showing where the pane will land.
    draw_tab_drop_hint(frame, app);
    // 2026-06-22 — drag ghost (paints near the cursor while a
    // file drag is in flight). Comes AFTER the drop-zone hint so
    // the ghost reads on top of the highlighted zone.
    draw_tree_drag_ghost(frame, app);
    // Same idea for the bufferline tab drag — show a small chip
    // following the cursor so the user has visual confirmation
    // that the drag is in flight (the drop-zone overlay alone is
    // easy to miss when the cursor is far from any pane edge).
    draw_tab_drag_ghost(frame, app);
    // Insertion bar — thin vertical line at the position the
    // dragged tab will land if dropped on a strip. Painted after
    // the ghost so it sits on top.
    draw_tab_insert_hint(frame, app);

    // Scratch terminal strip — paints below the body. Resizes the pty
    // so the shell knows about the new viewport.
    if let Some(strip) = scratch_strip
        && app.scratch_term.is_some()
    {
        scratch_term_view::draw(frame, app, strip);
    }

    // Inline-rendered markdown overlay: paints heading-line bold + colored,
    // `**bold**` / `*italic*` / `` `code` `` / `[label](url)` decorations
    // IN the editor pane for markdown buffers. Off by default.
    if app.config.ui.render_markdown {
        md_inline_overlay::draw(frame, app);
    }
    // Yank flash overlay: tints the yanked byte range yellow for ~200ms
    // (vim.highlight.on_yank() equivalent).
    yank_flash_overlay::draw(frame, app);
    // AI ghost-text: paint the active editor's pending suggestion in
    // grey starting at the cursor cell.
    ghost_overlay::draw(frame, app, cursor_pos);
    // Local-model download progress — bottom-centered bar during the
    // one-time fim-engine model pull.
    fim_progress_overlay::draw(frame, app, area);
    // Stacked toasts: top-right vertical column when more than one toast
    // is live (rapid-fire toasts no longer clobber each other).
    toast_stack::draw(frame, app);
    // qa-6th nvchad SEV-2 (originally) + qa-8th design HIGH-1
    // (2026-06-30 fix) — the :%s/.../.../c confirm bar. Moved
    // BELOW the statusline + cmdline_bar draws (further down)
    // so neither overwrites it; rendered on the cmdline row
    // (area.height - 1) which is vim's canonical position.
    // Flash overlay: paints label glyphs over the editor body when a
    // `s<a><b>` jump is armed.
    if app.flash_state.is_some() {
        flash_overlay::draw(frame, app);
    }
    // Inline rename preview: while an `lsp.rename` prompt is open, paint
    // the new identifier at every whole-word occurrence in the active editor.
    if app.rename_preview_state.is_some() {
        rename_preview_overlay::draw(frame, app);
    }

    // ── statusline ──
    // 2026-08-07 — bottom panel body (Phase 1 slice B). Empty
    // placeholder for now; slice C wires "dock focused pane here"
    // via right-click and a palette command. Docs:
    // docs/design/dockable-panes.md.
    if let Some(panel_area) = bottom_panel_area {
        draw_bottom_panel(frame, app, panel_area);
    }
    statusline::draw(frame, app, statusline_area);
    app.rects.statusline = Some(statusline_area);

    // ── cmdline bar (below statusline) ──
    cmdline_bar::draw(frame, app, cmdline_bar_area);

    // qa-8th design HIGH-1: :%s/.../.../c confirm bar paints on
    // the cmdline row AFTER cmdline_bar::draw so nothing
    // overwrites it. The `{}` Display formatting (qa-8th LOW-6)
    // avoids Rust debug-string quoting.
    if let Some(rc) = app.replace_confirm.as_ref()
        && area.height >= 1
        && cmdline_bar_area.height >= 1
    {
        // Position = which match we're currently looking at (1-based).
        // Was `applied + 1` — but `applied` only increments on `y`;
        // `n` (skip) advances the current match without applying, so
        // the counter froze. nvchad-user SEV-3 2026-07-11 fix: use
        // total - remaining.len() + 1 to reflect the CURRENT match
        // regardless of accept/skip. Clamped to `total` for the
        // terminal state (remaining is empty).
        let position = (rc.total - rc.remaining.len() + 1).min(rc.total);
        let prompt = format!(
            " replace {}{}? [{}/{}]  y · n · a · q ",
            rc.find, rc.replace, position, rc.total,
        );
        let t = theme::cur();
        let prompt_w = (prompt.chars().count() as u16).min(cmdline_bar_area.width);
        let prompt_rect = ratatui::layout::Rect {
            x: cmdline_bar_area.x,
            y: cmdline_bar_area.y,
            width: prompt_w,
            height: 1,
        };
        frame.render_widget(ratatui::widgets::Clear, prompt_rect);
        frame.render_widget(
            ratatui::widgets::Paragraph::new(prompt).style(
                Style::default()
                    .fg(t.fg)
                    .bg(t.bg2)
                    .add_modifier(Modifier::BOLD),
            ),
            prompt_rect,
        );
    }

    // ── cmdline completion popup (floats UP from the cmdline bar
    //     over the editor pane content while a `:` cmdline is open
    //     and has ≥2 matches). 2026-06-19 — discoverability gold:
    //     auto-shows on type so users don't have to know Tab cycles.
    cmdline_popup_view::draw(frame, app, cmdline_bar_area);

    // ── overlays (picker / palette, then which-key) ──
    if app.picker.is_some() {
        picker::draw(frame, app, area);
    } else {
        app.rects.picker_box = None;
        app.rects.picker_items.clear();
        app.rects.picker_caret = None;
    }
    if app.whichkey.is_some() {
        whichkey::draw(frame, app, area);
    } else if app.vim_operator_menu().is_some() {
        // 2026-06-21 — vim-operator whichkey popup. Only paints
        // when leader-whichkey isn't already showing (leader
        // takes priority on the unlikely overlap).
        whichkey::draw_vim_operators(frame, app, area);
    }
    // Workspaces editor — modal overlay opened from Settings →
    // Manage workspaces. Drawn BEFORE prompts + context menus so
    // those still appear on top when the user opens them from a
    // workspace row (Edit name → prompt, kebab → context menu).
    workspaces_editor::draw(frame, app);
    if app.close_prompt.is_some() {
        close_prompt::draw(frame, app, area);
    } else {
        app.rects.close_prompt_buttons.clear();
    }
    if app.prompt.is_some() {
        prompt::draw(frame, app, area);
    } else {
        app.rects.prompt_caret = None;
    }
    // #20 Pattern B — confirm modal paints ABOVE prompts + context
    // menus. Blocks input in the tui loop.
    if app.pending_confirm.is_some() {
        confirm_modal::draw(frame, app, area);
    } else {
        app.rects.confirm_modal_cancel = None;
        app.rects.confirm_modal_confirm = None;
    }
    if app.context_menu.is_some() {
        context_menu::draw(frame, app, area);
    } else {
        app.rects.context_menu_box = None;
        app.rects.context_menu_items.clear();
    }
    if app.hover.is_some() {
        hover::draw(frame, app, area, cursor_pos);
    }
    if app.signature.is_some() {
        signature::draw(frame, app, area, cursor_pos);
    }
    if app.completion.is_some() {
        completion::draw(frame, app, area, cursor_pos);
    }
    if app.peek_overlay.is_some() {
        peek_overlay_view::draw(frame, app, area);
    }
    // Hover-help now renders inside `tree_view::draw` as a boxed
    // info panel docked to the bottom of the left panel — moved off
    // the full-width footer strip 2026-08-09.
    //
    // Hover tooltip — sits above everything else (chip popups can't conflict
    // with picker/prompt/etc. because the hover_chip is only set when the
    // mouse moves freely outside any modal).
    if app.hover_chip.is_some() {
        tooltip::draw(frame, app, area);
    }
    // F1 discovery overlay — sits on top of everything else.
    discovery::draw(frame, app, area);
    // Welcome overlay — peer of discovery; auto-open on first launch.
    welcome_overlay::draw(frame, app, area);
    // About overlay — `:about` / view.about.
    about_overlay::draw(frame, app, area);
    // (Retired 2026-08-16: the AI usage overlay is now `Pane::AiUsage`.)
    // Settings overlay — `:settings` / view.settings.
    settings_overlay::draw(frame, app, area);
    // First-launch wizard — auto-opens if `[ui] first_launch_complete`
    // is false (default). Manual reopen: `first_launch.show`.
    first_launch_overlay::draw(frame, app, area);
    // Per-integration Settings pane — right-click chip → "Configure…"
    // or `integration_settings.show <id>`.
    integration_settings_overlay::draw(frame, app, area);
    // Integration edit panel — freestanding overlay opened from
    // the chip right-click context menu (Edit / Add custom).
    // Reads `App::integration_edit`. Painted BEFORE the picker is
    // re-drawn on top (below) so ↵ / → / Ctrl+G on the Glyph field
    // (which opens the icon picker) lands the picker over the
    // edit panel, not under it.
    integration_edit_overlay::draw(frame, app, area);
    // Glyph builder — same freestanding overlay pattern; sits behind
    // the picker (which handles Ctrl+G glyph search) but on top of
    // most other overlays.
    glyph_builder_overlay::draw(frame, app, area);
    // Re-paint the picker on top of the edit panel so Ctrl+G /
    // Enter / → from the Glyph field surfaces the picker instead
    // of hiding it behind the edit box. Cheap no-op when the
    // picker isn't open.
    if app.picker.is_some() {
        picker::draw(frame, app, area);
    }
    // Help overlay — `?` / view.help (auto-generated keymap reference).
    help_overlay::draw(frame, app, area);
    // Startup picker — drawn last among modal overlays so it sits on
    // top of welcome/about/etc. when launched from the .app.
    startup_picker::draw(frame, app, area);
    // Menu-bar dropdown — paints on top of everything else so it
    // overlays the editor body / overlays when open. Mouse-up
    // outside the dropdown closes it (see tui.rs dispatch).
    menu_bar::draw_dropdown(frame, app);
    // Workspace-picker dropdown — same overlay treatment, anchored
    // below the workspace header chevron.
    workspace_picker::draw(frame, app);
    // …and the flash highlight paints last so it can sit on top of even
    // the discovery panel (if the user picks a category whose rect lies
    // beneath the panel, the highlight will still flash through).
    discovery::draw_flash(frame, app, area);

    // `:debug.rects` overlay — paints colored borders around every
    // registered click rect so the user can SEE where clicks are caught.
    // Runs last so the borders sit on top of every other paint layer.
    debug_rects::draw(frame, app);

    // ── terminal cursor ──
    // An overlay's text caret (picker query, prompt input) wins when it's open;
    // otherwise the editor caret when the editor pane has focus and no overlay is
    // up; otherwise nothing.
    if let Some((x, y)) = app.rects.prompt_caret.or(app.rects.picker_caret) {
        frame.set_cursor_position((x, y));
    } else if app.focus == Focus::Pane
        && app.whichkey.is_none()
        && app.close_prompt.is_none()
        && app.prompt.is_none()
        && let Some((x, y)) = cursor_pos
    {
        frame.set_cursor_position((x, y));
    }

    // 2026-07-23 — subtle click-echo v4. Underline the WORD /
    // TOKEN under the click for ~120ms, not just the single cell.
    // Reads as "I saw you click this thing" instead of a random
    // single-char blip. Walks left/right from the click point
    // until a non-word char (space / punctuation-only-if-surrounded
    // by whitespace) or a row edge. Preserves the underline
    // fallback single-cell if the click landed on whitespace.
    if let Some((x, y, started)) = app.click_echo {
        const ECHO_MS: u128 = 120;
        let elapsed = started.elapsed().as_millis();
        if elapsed < ECHO_MS {
            let area = frame.area();
            if x < area.x + area.width && y < area.y + area.height {
                let (x0, x1) = word_bounds_at(frame.buffer_mut(), x, y);
                let buf = frame.buffer_mut();
                for cx in x0..=x1 {
                    let cell = &mut buf[(cx, y)];
                    cell.set_style(
                        cell.style()
                            .add_modifier(ratatui::style::Modifier::UNDERLINED),
                    );
                }
            }
        } else {
            app.click_echo = None;
        }
    }
}

/// Return the inclusive column range of the "word" the click cell
/// is on. A word here is any run of NON-whitespace cells — chip
/// labels ("Slack Channels" underlines "Slack" or "Channels"), row
/// text, chevrons — all clean-bounded by the surrounding space.
/// Whitespace click → returns the single cell.
fn word_bounds_at(buf: &ratatui::buffer::Buffer, x: u16, y: u16) -> (u16, u16) {
    let is_word = |ch: &str| -> bool {
        // Multi-char (emoji-ish) always counts as a word cell.
        // Single-char: any non-whitespace.
        if ch.chars().count() > 1 {
            return true;
        }
        ch.chars().next().is_some_and(|c| !c.is_whitespace())
    };
    let here = buf[(x, y)].symbol().to_string();
    if !is_word(&here) {
        return (x, x);
    }
    let mut lo = x;
    while lo > buf.area.x {
        let prev = lo - 1;
        if !is_word(buf[(prev, y)].symbol()) {
            break;
        }
        lo = prev;
    }
    let right_edge = buf.area.x + buf.area.width;
    let mut hi = x;
    while hi + 1 < right_edge {
        let next = hi + 1;
        if !is_word(buf[(next, y)].symbol()) {
            break;
        }
        hi = next;
    }
    (lo, hi)
}

/// Recursively render a layout subtree into `area`: leaves draw their editor;
/// splits draw a 1-cell divider and recurse. Only the focused leaf returns a
/// cursor cell, so the `.or` chain bubbles it up. `path` accumulates the
/// first(false)/second(true) choices to the current node, recorded with each
/// divider so the mouse can drag-resize a specific split.
fn render_layout(
    frame: &mut Frame,
    app: &mut App,
    layout: &Layout,
    area: Rect,
    path: &mut Vec<bool>,
) -> Option<(u16, u16)> {
    match layout {
        Layout::Empty => {
            // Empty leaves inside a Split are the BR quadrant of the
            // Claude 2×2 auto-tile (see `App::open_claude_code_new`).
            // Paint a `+ Add Claude Code` card + record the click
            // rect. An Empty at the root (no path) is the empty-
            // workspace state — handled higher up by the bufferline
            // `+` chip; leave it blank.
            if !path.is_empty() && app.ai_placeholder_slot.is_some() {
                paint_ai_placeholder_card(frame, app, area);
            }
            None
        }
        Layout::Leaf { active: id, tabs } => {
            let focused = app.active == Some(*id);
            // 2026-07-21 — filter the tab strip by active activity
            // section. In Http activity, only Request panes show
            // (their Response is part of the same pane, so no
            // duplication); other activities show everything.
            // Panes are NOT closed — they're just hidden from this
            // strip. Switching activity brings them back. User asked
            // for this on 2026-07-21: "we don't show files in the
            // http area? what do you think we should do".
            let tabs_owned: Vec<crate::layout::PaneId> =
                if matches!(app.active_section, crate::app::ActivitySection::Http) {
                    tabs.iter()
                        .filter(|&&pid| {
                            matches!(app.panes.get(pid), Some(crate::pane::Pane::Request(_)))
                        })
                        .copied()
                        .collect()
                } else {
                    tabs.clone()
                };
            // 2026-08-01 — count non-Request tabs that were hidden
            // by the HTTP-section filter, so `paint_leaf_tab_strip`
            // can render a `+N hidden` chip. User asked "just make
            // it work and hide" — hiding stays, but the chip tells
            // the user their tabs weren't lost.
            let hidden_tab_count: usize =
                if matches!(app.active_section, crate::app::ActivitySection::Http) {
                    tabs.len().saturating_sub(tabs_owned.len())
                } else {
                    0
                };
            // 2026-06-21 — VS Code-style per-split tab strip. When
            // this leaf is INSIDE a split (path non-empty) AND the
            // pane isn't a Pty (which has its own tab strip in
            // pty_view), carve out the top row of `area` and paint
            // a horizontal row of tab chips (one per pane in the
            // leaf's `tabs`). The body area shrinks by 1 row.
            // one-tab-type 2026-07-18 — per-leaf tab strips are now
            // the ONLY tab UI. Drop the `is_split_leaf` gate so the
            // strip renders for every leaf including the single-
            // leaf state. Top bufferline's tab loop is being
            // retired in this branch; the launcher cluster
            // (H/V/Term/Claude/Codex) stays on that row via the
            // palette-bar-drawn chips.
            let _ = path; // still passed in for future use
            let body_area = if area.height >= 2 {
                let strip = ratatui::layout::Rect {
                    x: area.x,
                    y: area.y,
                    width: area.width,
                    height: 1,
                };
                // Record the strip's bounding rect so tab drags
                // can drop ONTO the strip — inserting the dragged
                // tab into this leaf at the cursor's x position.
                // Matches Chrome / VS Code tab-bar drop. The
                // `pane_id` keys the strip to its leaf so the
                // drop handler can find the right tab list.
                app.rects.split_tab_strip_areas.push((strip, *id));
                paint_leaf_tab_strip_with_hidden(
                    frame,
                    app,
                    *id,
                    &tabs_owned,
                    hidden_tab_count,
                    strip,
                    focused,
                );
                ratatui::layout::Rect {
                    x: area.x,
                    y: area.y + 1,
                    width: area.width,
                    height: area.height - 1,
                }
            } else {
                area
            };
            // Record this leaf's body rect (all pane kinds) for tab drag-drop
            // hit-testing (drag-to-split). Uses the post-strip body
            // so drag-to-split zones don't overlap the per-leaf tab.
            app.rects.pane_bodies.push((body_area, *id));
            let area = body_area;
            // Resolve the variant first so the immutable peek doesn't outlive into
            // the `&mut App` draw call.
            let kind: u8 = match app.panes.get(*id) {
                Some(crate::pane::Pane::MdPreview(_)) => 1,
                Some(crate::pane::Pane::Diff(_)) => 2,
                Some(crate::pane::Pane::Request(_)) => 3,
                Some(crate::pane::Pane::Pty(_)) => 4,
                Some(crate::pane::Pane::Ai(_)) => 5,
                Some(crate::pane::Pane::Tests(_)) => 6,
                Some(crate::pane::Pane::GitGraph(_)) => 7,
                Some(crate::pane::Pane::GitStatus(_)) => 8,
                Some(crate::pane::Pane::Diagnostics(_)) => 9,
                Some(crate::pane::Pane::Browser(_)) => 11,
                Some(crate::pane::Pane::Grep(_)) => 12,
                Some(crate::pane::Pane::Flaky(_)) => 13,
                Some(crate::pane::Pane::Outline(_)) => 14,
                Some(crate::pane::Pane::CmdlineHistory(_)) => 15,
                Some(crate::pane::Pane::Quickfix(_)) => 16,
                Some(crate::pane::Pane::Cheatsheet(_)) => 29,
                Some(crate::pane::Pane::Debug(_)) => 30,
                Some(crate::pane::Pane::DapRepl(_)) => 31,
                Some(crate::pane::Pane::Image(_)) => 32,
                Some(crate::pane::Pane::ClaudeAgents(_)) => 34,
                Some(crate::pane::Pane::Websocket(_)) => 35,
                Some(crate::pane::Pane::SpendReport(_)) => 36,
                Some(crate::pane::Pane::Mount(_)) => 37,
                Some(crate::pane::Pane::CloudAgentRun(_)) => 38,
                Some(crate::pane::Pane::NewCloudAgentWizard(_)) => 39,
                Some(crate::pane::Pane::NewCloudRunWizard(_)) => 40,
                Some(crate::pane::Pane::IntegrationDetail(_)) => 41,
                Some(crate::pane::Pane::ClaudeUsage(_)) => 42,
                Some(crate::pane::Pane::CodexUsage(_)) => 43,
                _ => 0,
            };
            match kind {
                1 => md_preview::draw(frame, app, *id, area, focused),
                2 => diff_view::draw(frame, app, *id, area, focused),
                3 => request_view::draw(frame, app, *id, area, focused),
                4 => pty_view::draw(frame, app, *id, area, focused),
                5 => ai_view::draw(frame, app, *id, area, focused),
                6 => tests_view::draw(frame, app, *id, area, focused),
                7 => git_graph_view::draw(frame, app, *id, area, focused),
                8 => git_status_view::draw(frame, app, *id, area, focused),
                9 => diagnostics_view::draw(frame, app, *id, area, focused),
                11 => browser_view::draw(frame, app, *id, area, focused),
                12 => grep_view::draw(frame, app, *id, area, focused),
                13 => flaky_view::draw(frame, app, *id, area, focused),
                14 => outline_view::draw(frame, app, *id, area, focused),
                15 => cmdline_history_view::draw(frame, app, *id, area, focused),
                // Quickfix shares the Grep view — same shape, different
                // pane identity so `:grep` results don't clobber it.
                16 => grep_view::draw(frame, app, *id, area, focused),
                29 => {
                    cheatsheet_view::draw(frame, app, *id, area, focused);
                    None
                }
                30 => {
                    debug_view::draw(frame, app, *id, area);
                    None
                }
                31 => {
                    dap_repl_view::draw(frame, app, *id, area, focused);
                    None
                }
                32 => image_view::draw(frame, app, *id, area, focused),
                34 => {
                    claude_agents_view::draw(frame, app, *id, area, focused);
                    None
                }
                35 => {
                    ws_view::draw(frame, app, *id, area, focused);
                    None
                }
                36 => {
                    spend_report_view::draw(frame, app, *id, area, focused);
                    None
                }
                37 => {
                    if let Some(crate::pane::Pane::Mount(m)) = app.panes.get_mut(*id) {
                        mount_view::draw(frame, m, area);
                    }
                    None
                }
                38 => {
                    cloud_agent_run_view::draw(frame, app, *id, area, focused);
                    None
                }
                39 => {
                    new_cloud_agent_wizard_view::draw(frame, app, *id, area, focused);
                    None
                }
                40 => {
                    new_cloud_run_wizard_view::draw(frame, app, *id, area, focused);
                    None
                }
                41 => integration_detail_view::draw(frame, app, *id, area, focused),
                42 => {
                    claude_usage_view::draw(frame, app, *id, area, focused);
                    None
                }
                43 => {
                    codex_usage_view::draw(frame, app, *id, area, focused);
                    None
                }
                _ => editor_view::draw_pane(frame, app, *id, area, focused),
            }
        }
        Layout::Split {
            dir,
            ratio,
            first,
            second,
        } => {
            let (a, divider, b) = split_rects(area, *dir, *ratio);
            if divider.width > 0 && divider.height > 0 {
                let divider_idx = app.rects.split_dividers.len();
                let is_hover = app.hover_divider_idx == Some(divider_idx) || app.dragging.is_some();
                draw_divider(frame, divider, *dir, is_hover);
                app.rects.split_dividers.push(crate::layout::DividerHit {
                    rect: divider,
                    dir: *dir,
                    area,
                    path: path.clone(),
                });
            }
            path.push(false);
            let c1 = render_layout(frame, app, first, a, path);
            path.pop();
            path.push(true);
            let c2 = render_layout(frame, app, second, b, path);
            path.pop();
            c1.or(c2)
        }
    }
}

/// 2026-06-22 — drag ghost for a tree-file drag. Paints a small
/// chip showing the file's name near the cursor while the drag
/// is armed and the mouse is past the origin row. Cleared
/// automatically when `tree_drag` clears on mouse-up.
/// Paint a thin cyan vertical bar at the insertion-x recorded in
/// `tab_insert_hint`. Shows where the dragged tab will land when
/// dropped on a strip. Tracks both the strip rect (for clipping)
/// and the insertion x (where to paint).
fn draw_tab_insert_hint(frame: &mut Frame, app: &App) {
    use ratatui::style::Style;
    use ratatui::text::{Line, Span};
    use ratatui::widgets::Paragraph;
    let Some((strip_rect, insertion_x, _leaf, _idx)) = app.rects.tab_insert_hint else {
        return;
    };
    if app.rects.bufferline_drag_tab.is_none() {
        return;
    }
    let t = theme::cur();
    let bar_x = insertion_x
        .max(strip_rect.x)
        .min(strip_rect.x + strip_rect.width.saturating_sub(1));
    let bar_rect = Rect {
        x: bar_x,
        y: strip_rect.y,
        width: 1,
        height: 1,
    };
    frame.render_widget(
        Paragraph::new(Line::from(Span::styled(
            "".to_string(),
            Style::default().fg(t.cyan),
        ))),
        bar_rect,
    );
}

/// Floating chip showing the dragged tab's label, painted near
/// the cursor while a bufferline tab drag is in flight. Same
/// pattern as `draw_tree_drag_ghost`. Off when no drag.
fn draw_tab_drag_ghost(frame: &mut Frame, app: &App) {
    use ratatui::style::{Modifier, Style};
    use ratatui::text::{Line, Span};
    use ratatui::widgets::Paragraph;
    let Some((cx, cy)) = app.rects.bufferline_drag_ghost else {
        return;
    };
    let Some(src) = app.rects.bufferline_drag_tab else {
        return;
    };
    let Some(pane) = app.panes.get(src) else {
        return;
    };
    let name = pane.title();
    let label = clip_to_cells(&name, 28);
    let label_w = label.chars().count() as u16;
    let chip_w = label_w + 5; // " ⤴ <name> "
    let area = frame.area();
    let mut chip_x = cx.saturating_add(1);
    let mut chip_y = cy;
    if chip_x + chip_w > area.x + area.width {
        chip_x = (area.x + area.width).saturating_sub(chip_w);
    }
    if chip_y >= area.y + area.height {
        chip_y = cy.saturating_sub(1);
    }
    let chip_rect = Rect {
        x: chip_x,
        y: chip_y,
        width: chip_w,
        height: 1,
    };
    let t = theme::cur();
    let bg = t.purple;
    let fg = t.bg_darker;
    let line = Line::from(vec![
        Span::styled(" ".to_string(), Style::default().bg(bg)),
        Span::styled("".to_string(), Style::default().fg(fg).bg(bg)),
        Span::styled(
            label,
            Style::default().fg(fg).bg(bg).add_modifier(Modifier::BOLD),
        ),
        Span::styled(" ".to_string(), Style::default().bg(bg)),
    ]);
    frame.render_widget(Paragraph::new(line), chip_rect);
}

fn draw_tree_drag_ghost(frame: &mut Frame, app: &App) {
    use ratatui::style::{Modifier, Style};
    use ratatui::text::{Line, Span};
    use ratatui::widgets::Paragraph;
    let Some(drag) = app.tree_drag.as_ref() else {
        return;
    };
    if !drag.armed {
        return;
    }
    let cx = drag.cursor_x;
    let cy = drag.cursor_y;
    let name = drag
        .src_path
        .file_name()
        .map(|s| s.to_string_lossy().into_owned())
        .unwrap_or_else(|| drag.src_path.to_string_lossy().into_owned());
    let label = clip_to_cells(&name, 28);
    let label_w = label.chars().count() as u16;
    // 2026-06-22 — ghost chip: ` ⤴ <icon> <name> ` (5 + name cells).
    // The ⤴ "moving" arrow makes it instantly read as a drag,
    // and the bright bg means the user can't miss it.
    // mouse-round-7 SEV-2 2026-07-12 — Alt-drag copies instead of
    // moves (Finder/VS Code convention). The label was identical
    // to a plain move-drag, so the user had no confirmation the
    // Alt modifier had registered until the file appeared in two
    // places. Prefix with a `⧉ COPY` badge when copying.
    let (prefix, prefix_cells) = if drag.copy_instead_of_move {
        if drag.src_is_dir {
            ("\u{29C9} 📁 ", 5u16)
        } else {
            ("\u{29C9} 📄 ", 5)
        }
    } else if drag.src_is_dir {
        ("📁 ", 3)
    } else {
        ("📄 ", 3)
    };
    let chip_w = label_w + prefix_cells + 2;
    let area = frame.area();
    // Paint the chip RIGHT next to the cursor (1 cell offset to
    // avoid covering the cursor itself). User-feedback 2026-06-22
    // — earlier (+2, +1) offset put the chip too far from the
    // cursor, making it hard to align with the drop zone.
    let mut chip_x = cx.saturating_add(1);
    let mut chip_y = cy;
    if chip_x + chip_w > area.x + area.width {
        chip_x = (area.x + area.width).saturating_sub(chip_w);
    }
    if chip_y >= area.y + area.height {
        chip_y = cy.saturating_sub(1);
    }
    let chip_rect = Rect {
        x: chip_x,
        y: chip_y,
        width: chip_w,
        height: 1,
    };
    let t = theme::cur();
    // Bright accent bg + dark fg so the chip really pops. Copy
    // (Alt-drag) uses green to further signal "non-destructive".
    let bg = if drag.copy_instead_of_move {
        t.green
    } else {
        t.blue
    };
    let fg = t.bg_darker;
    let line = Line::from(vec![
        Span::styled(" ".to_string(), Style::default().bg(bg)),
        Span::styled(prefix.to_string(), Style::default().fg(fg).bg(bg)),
        Span::styled(
            label,
            Style::default().fg(fg).bg(bg).add_modifier(Modifier::BOLD),
        ),
        Span::styled(" ".to_string(), Style::default().bg(bg)),
    ]);
    frame.render_widget(
        Paragraph::new(line).style(Style::default().bg(bg)),
        chip_rect,
    );
}

/// Drag-to-split drop hint. When a bufferline tab is dragged over a pane body,
/// paint the zone it will land in (left/right/top/bottom half for a split, or
/// the center box for a move-in-place) with a tinted fill + accent border and a
/// short label. No-op when no tab is being dragged over a pane.
fn draw_tab_drop_hint(frame: &mut Frame, app: &App) {
    use crate::app::tab_drop::{DropZone, zone_rect};
    let Some((pid, active_zone)) = app.rects.tab_drop_target else {
        return;
    };
    let Some((body, _)) = app
        .rects
        .pane_bodies
        .iter()
        .find(|(_, p)| *p == pid)
        .copied()
    else {
        return;
    };
    let t = theme::cur();
    // 2026-06-22 — VS Code-style drop overlay. Only the ACTIVE
    // zone gets painted; no outlines for the other zones, no
    // labels. For Left/Right/Top/Bottom the overlay covers HALF
    // the pane; for Center it covers the WHOLE pane. Style:
    // translucent gray (preserve some readability of the
    // underlying content). User-feedback 2026-06-22: earlier
    // 5-zone outlined version with labels was too busy.
    let rect = match active_zone {
        DropZone::Center => body,
        _ => zone_rect(body, active_zone),
    };
    if rect.width == 0 || rect.height == 0 {
        return;
    }
    // VS Code's drop indicator is a TRANSLUCENT GRAY overlay
    // (its `editorGroup.dropBackground` token is roughly 18%
    // alpha). A ratatui TUI can't do real alpha, but we can
    // mimic the effect by mutating ONLY the bg color of cells
    // under the overlay — the existing cell content + fg color
    // stay intact, so the user still reads what's underneath,
    // just with a gray tint. User-feedback 2026-06-22: a solid
    // blue paint hid the text entirely; gray-bg-only matches
    // VS Code's behavior.
    let buf = frame.buffer_mut();
    for y in rect.y..rect.y.saturating_add(rect.height) {
        for x in rect.x..rect.x.saturating_add(rect.width) {
            if let Some(cell) = buf.cell_mut((x, y)) {
                cell.set_bg(t.grey);
            }
        }
    }
}

/// VS Code-style top "command palette" strip — a single row across the
/// full window width with three regions, centered as a group:
///
///   `[ ← ][ → ]   [ 🔍  search files, run commands…  ▾ ]`
///
/// * Back / Forward arrows → `buffer.prev` / `buffer.next` (file history).
/// * Center chip → opens the command palette.
/// * Dropdown chevron → opens the recent-files picker.
///
/// Auto-hides when the window is narrower than `MIN_WIDTH`.
/// Paint user-configured integration icons in the gap between the
/// workspace-chip's right edge and the right cluster's left edge.
/// Skips any that won't fit — the cluster never gets pushed off
/// screen by them. Rects append to `integration_icon_rects` so the
/// existing click + right-click handlers in tui.rs fire on hit.
fn paint_integration_chips_in_gap(
    frame: &mut Frame,
    app: &mut App,
    chip_right_edge: u16,
    cluster_left: u16,
    y: u16,
) {
    use ratatui::widgets::Paragraph;
    // Even with no integrations configured, paint the `+` chip
    // so the user has a discoverable entry point. The discovery
    // overlay starts empty until they add their first integration.
    app.rects.palette_add_integration_button = None;
    // Start integrations flush with the workspace chip's right
    // edge (no leading margin) per user request — keeps the
    // icon row tucked tight to the chrome cluster instead of
    // floating in space. Still leave a 1-cell margin before the
    // far-right cluster so the two groups remain visually
    // separable.
    let avail_left = chip_right_edge;
    let avail_right = cluster_left.saturating_sub(1);
    if avail_right <= avail_left {
        return;
    }
    let avail_w = avail_right - avail_left;
    // Each chip takes 3 cells (` glyph `); add a 2-cell trailing
    // gap so chips visually breathe and the `+` add-chip also
    // sits 2 cells off the last icon. Net: 5-cell stride per chip,
    // last chip's trailing gap doubles as the gap before `+`.
    let per_chip: u16 = 3;
    let chip_gap: u16 = 2;
    let chip_stride: u16 = per_chip + chip_gap;
    if avail_w < per_chip {
        return;
    }
    let nerd = !app.config.ui.ascii_icons;
    // Both launcher icons and integration icons paint here, in a
    // single strip close to the palette dropdown. They look the
    // same to the user — the only difference is which dispatcher
    // their click fires. (launcher_icon_rects.clear moved to
    // ui::draw entry — same reason as integration_icon_rects.)
    // Reserve 3 cells at the END for a `+` add-integration chip
    // (opens discovery overlay). The chip preceding it already
    // pads 2 cells of trailing gap, so the `+` sits flush with
    // its own group.
    let plus_w: u16 = per_chip;
    let avail_for_chips = avail_w.saturating_sub(plus_w);
    let chip_count = (avail_for_chips / chip_stride) as usize;
    // Only chips with `enabled = true` show. Everything else is
    // configured-but-hidden until the user opts in (right-click →
    // Enable, or the discovery overlay). Browser is the only
    // default-enabled integration; keeps first-run quiet.
    //
    // 2026-08-01 (P2) — the separate `enabled_launchers` Vec was
    // deleted with the LauncherIcon retirement. Palette bar now
    // paints only integration chips (launcher chips folded in).
    // design-critic Issue 1 — apply the SAME filter as the rail:
    // gate on enabled=true AND binary-present (or built-in). Without
    // the binary check, a chip with enabled=true but uninstalled
    // binary would render in the palette bar and silently fail.
    // 2026-08-06 user pref — `enabled` alone puts the chip on the
    // top bar. `in_palette_bar = false` is now opt-OUT (right-click
    // → "Hide from top bar"). Prior rule required BOTH flags to be
    // true, which meant you enabled both Claude Code and Codex but
    // only Claude appeared because only Claude's saved
    // `in_palette_bar` was true from an earlier manual toggle.
    // The rail panel + right-click menus are unchanged — they
    // always render every enabled integration.
    let enabled_integrations: Vec<(usize, &crate::config::IntegrationIcon)> = app
        .config
        .ui
        .integration_icons
        .iter()
        .enumerate()
        .filter(|(_, i)| {
            if !i.enabled {
                return false;
            }
            // Explicit opt-out — user right-clicked "Hide from top bar"
            // and the persisted flag flipped to false.
            if !i.in_palette_bar {
                return false;
            }
            // 2026-08-06 — claude_code + codex now render in the
            // H/V split cluster (paint_split_buttons), NOT here in
            // the palette-bar gap. User wants them next to the split
            // icons at the far right, not duplicated in both places.
            if matches!(i.id.as_str(), "claude_code" | "codex") {
                return false;
            }
            match crate::integration_detect::integration_binary_for_command(&i.command) {
                None => true,
                Some(bin) => crate::integration_detect::is_binary_installed(bin),
            }
        })
        .collect();
    let n_integration = enabled_integrations.len();
    let integration_paint = n_integration.min(chip_count);
    // qa-feature 2026-07-01 — exactly 1 empty cell between the
    // right-panel toggle's visible glyph and the first chip's
    // visible glyph. Chip starts at avail_left (= toggle rect's
    // right edge); its leading space lands at avail_left and the
    // wide glyph starts at avail_left + 1. The toggle's own wide
    // glyph occupies its rect's cells 1-2, so the visible gap is
    // the single cell at avail_left. Tighter than the earlier
    // 2-cell spacing per user follow-up.
    let mut x = avail_left;
    // 2026-06-27 — chips render WITHOUT a colored background.
    // 2026-07-01 — chips now use `t.comment` FG (matching the
    // split-horiz / split-vert / terminal buttons in the right
    // cluster) instead of the per-icon color slot. The user asked
    // for these top-row icons to read as flat chrome, not
    // decorated app links. Bold is dropped for the same reason.
    for &(i, icon) in enabled_integrations.iter().take(integration_paint) {
        let glyph = if nerd { &icon.glyph } else { &icon.fallback };
        let chip_rect = Rect {
            x,
            y,
            width: 3,
            height: 1,
        };
        frame.render_widget(
            Paragraph::new(crate::ui::design_tokens::chip_bar_span(glyph, false)),
            chip_rect,
        );
        app.rects.integration_icon_rects.push((chip_rect, i));
        x = x.saturating_add(chip_stride);
    }
    // `+` chip — opens the integrations discovery overlay so the
    // user can add another integration without leaving the palette
    // bar. Always painted (as long as the gap had room reserved
    // for it via plus_w above).
    // qa-feature 2026-07-01 — user asked to remove the top `+`
    // integration-add chip. Discovery / add flows are reachable
    // via the Integrations activity-bar section instead.
    let _ = x;
    app.rects.palette_add_integration_button = None;
}

/// 2026-08-07 — bottom panel body (dockable panes Phase 1 slice B).
/// Empty-state renderer for now: a bordered box with a header row and
/// a friendly hint. Slice C wires "dock focused pane here" via
/// right-click + a palette command; slice D adds a proper tab strip
/// for multi-pane hosting like right_panel_panes.
fn draw_bottom_panel(frame: &mut Frame, app: &mut App, area: Rect) {
    if area.height == 0 || area.width == 0 {
        return;
    }
    let t = theme::cur();
    let bg = t.bg;
    use ratatui::style::Color;
    // Fill the whole area with bg so nothing bleeds through.
    let filler = " ".repeat(area.width as usize);
    for row_y in 0..area.height {
        frame.render_widget(
            Paragraph::new(filler.clone()).style(Style::default().bg(bg)),
            Rect {
                x: area.x,
                y: area.y + row_y,
                width: area.width,
                height: 1,
            },
        );
    }
    // 1-row header at the top with the panel title + close chip.
    let header_area = Rect {
        x: area.x,
        y: area.y,
        width: area.width,
        height: 1,
    };
    let hosted = app.bottom_panel_panes.len();
    // 2026-08-07 design-critic r2 #2: was advertising a right-click
    // "Dock to → Bottom" flow that doesn't exist yet (not even on the
    // right panel). Cut to what's true today.
    let title = if hosted == 0 {
        "  BOTTOM".to_string()
    } else {
        format!("  BOTTOM  ·  {hosted} pane(s)")
    };
    frame.render_widget(
        Paragraph::new(title).style(
            Style::default()
                .fg(t.comment)
                .bg(bg)
                .add_modifier(Modifier::BOLD),
        ),
        header_area,
    );
    // Close chip on the top right. 2026-08-07 vscode-user r2 F1 —
    // register the rect so clicks actually close the panel (was
    // painted but never in app.rects, so the ×  was inert).
    if area.width >= 5 {
        let close_rect = Rect {
            x: area.x + area.width - 4,
            y: area.y,
            width: 3,
            height: 1,
        };
        frame.render_widget(
            Paragraph::new(" × ").style(
                Style::default()
                    .fg(Color::Red)
                    .bg(bg)
                    .add_modifier(Modifier::BOLD),
            ),
            close_rect,
        );
        app.rects.bottom_panel_close = Some(close_rect);
    } else {
        app.rects.bottom_panel_close = None;
    }
    // Body: either the empty-state hint OR the active hosted pane
    // rendered via the same per-kind draw fns the right panel uses
    // (design mirror — see the `active_pane` match block in
    // `draw` above). #906 slice C (2026-08-20).
    if area.height < 3 {
        return;
    }
    let body_area = Rect {
        x: area.x,
        y: area.y + 1,
        width: area.width,
        height: area.height.saturating_sub(1),
    };
    if hosted == 0 {
        let hint_area = Rect {
            x: area.x + 2,
            y: area.y + 2,
            width: area.width.saturating_sub(4),
            height: area.height.saturating_sub(3),
        };
        let hint = "Bottom panel is empty. Right-click a pane tab \\"Move to bottom panel\", or run the palette \
                    command `view.host_active_in_bottom_panel`.\n\n\
                    Ctrl+Shift+J hides this panel.";
        frame.render_widget(
            Paragraph::new(hint)
                .style(Style::default().fg(t.comment).bg(bg))
                .wrap(ratatui::widgets::Wrap { trim: false }),
            hint_area,
        );
        return;
    }
    // Active tab from `bottom_panel_active_idx`, clamped to bounds.
    let active_idx = app.bottom_panel_active_idx.min(hosted - 1);
    let Some(pid) = app
        .bottom_panel_panes
        .get(active_idx)
        .copied()
        .filter(|id| app.panes.get(*id).is_some())
    else {
        return;
    };
    let focused = app.active == Some(pid);
    match app.panes.get(pid) {
        Some(crate::pane::Pane::Outline(_)) => {
            outline_view::draw(frame, app, pid, body_area, focused);
        }
        Some(crate::pane::Pane::Diagnostics(_)) => {
            diagnostics_view::draw(frame, app, pid, body_area, focused);
        }
        Some(crate::pane::Pane::IntegrationDetail(_)) => {
            integration_detail_view::draw(frame, app, pid, body_area, focused);
        }
        Some(crate::pane::Pane::ClaudeUsage(_)) => {
            claude_usage_view::draw(frame, app, pid, body_area, focused);
        }
        Some(crate::pane::Pane::CodexUsage(_)) => {
            codex_usage_view::draw(frame, app, pid, body_area, focused);
        }
        Some(crate::pane::Pane::Tests(_)) => {
            tests_view::draw(frame, app, pid, body_area, focused);
        }
        Some(crate::pane::Pane::Grep(_)) => {
            grep_view::draw(frame, app, pid, body_area, focused);
        }
        _ => {
            // Kinds without a right-panel-style draw fn (Editor,
            // Pty, Request, …) aren't wired for host-in-bottom-panel
            // yet — surface why so the user isn't confused by a
            // blank body.
            let msg = "This pane kind isn't hostable in the bottom panel yet.";
            let msg_area = Rect {
                x: body_area.x + 2,
                y: body_area.y + 1,
                width: body_area.width.saturating_sub(4),
                height: body_area.height.saturating_sub(1),
            };
            frame.render_widget(
                Paragraph::new(msg)
                    .style(Style::default().fg(t.comment).bg(bg))
                    .wrap(ratatui::widgets::Wrap { trim: false }),
                msg_area,
            );
        }
    }
}

fn draw_palette_bar(frame: &mut Frame, app: &mut App, area: Rect) {
    if area.height == 0 || area.width == 0 {
        app.rects.palette_search_chip = None;
        app.rects.palette_back_button = None;
        app.rects.palette_forward_button = None;
        app.rects.palette_dropdown_button = None;
        return;
    }
    let t = theme::cur();
    let ascii = app.config.ui.ascii_icons;
    frame.render_widget(Block::default().style(Style::default().bg(t.bg_dark)), area);

    // Menu-bar words (File / Edit / View / …) — far-left of the
    // chrome row, before any centered cluster, matching the
    // standard macOS / Windows / Linux menu-bar position.
    // Visibility per `[ui] menu_bar` mode.
    app.rects.menu_bar_words.clear();
    app.rects.menu_bar_overflow = None;
    let menu_mode = app.config.ui.menu_bar.as_str();
    let menu_visible =
        matches!(menu_mode, "always") || (menu_mode == "auto" && app.menu_open.is_some());
    if menu_visible {
        let menus = crate::menu_bar::bar(app);
        let mut mx = area.x;
        // mouse-verify #4 follow-up — the prior bg-overpaint fix
        // covered the cluster's exact footprint, but menu words
        // that START left of the cluster and EXTEND INTO it had
        // their leading cells survive (the 'Vi' leak). Conservative
        // cluster-left estimate: cluster is dominated by the
        // 30-cell workspace chip; safe overestimate is 50 cells.
        // Stop painting menu words at that x so none of their
        // tail can poke into the cluster footprint.
        const CONSERVATIVE_CLUSTER_W: u16 = 50;
        // Reserve 3 cells for the ` » ` overflow chip so a menu word
        // never occupies the slot where we'd want to render it.
        // R9 vscode-mouse SEV-2: mouse users couldn't reach View / Go
        // / Run / Terminal / Window / Help when narrow terminals
        // clipped them, and there was no visual affordance saying
        // "more menus over here." The chip is only drawn when we
        // actually skip a menu; the reservation just guarantees the
        // slot when we need it.
        const OVERFLOW_RESERVE: u16 = 3;
        let cluster_left_safe = area
            .x
            .saturating_add(area.width.saturating_sub(CONSERVATIVE_CLUSTER_W) / 2);
        let mut first_hidden: Option<usize> = None;
        for (i, m) in menus.iter().enumerate() {
            let label_w = m.label.chars().count() as u16 + 2;
            // Once anything's been skipped, all subsequent menus are
            // hidden too — don't paint a second half after a gap.
            if first_hidden.is_some() {
                break;
            }
            // Reserve the overflow slot when there are still menus
            // left AFTER this one so a chevron can fit.
            let need_overflow_slot = i + 1 < menus.len();
            let effective_area_end = if need_overflow_slot {
                (area.x + area.width).saturating_sub(OVERFLOW_RESERVE)
            } else {
                area.x + area.width
            };
            let effective_cluster_bound = if need_overflow_slot {
                cluster_left_safe.saturating_sub(OVERFLOW_RESERVE)
            } else {
                cluster_left_safe
            };
            if mx.saturating_add(label_w) > effective_area_end {
                first_hidden = Some(i);
                break;
            }
            if mx.saturating_add(label_w) > effective_cluster_bound {
                first_hidden = Some(i);
                break;
            }
            let word_rect = Rect {
                x: mx,
                y: area.y,
                width: label_w,
                height: 1,
            };
            let is_open = app.menu_open.as_ref().is_some_and(|s| s.menu_idx == i);
            // Underlines only show while a menu is open. Brand-menu
            // wordmark is exempt — `mnml` shouldn't have a random
            // letter underlined; its accelerator is the menu icon
            // itself.
            let any_menu_open = app.menu_open.is_some();
            // Foreground matches the palette/search chip's `t.comment`
            // (dim grey); background stays on the chrome row's
            // `t.bg_dark`. When open, invert to a cyan highlight so
            // the active menu reads as the focal target.
            // 2026-06-24 — resting menu text uses `grey` (darker)
            // instead of `comment` so the menu bar feels less
            // prominent. Active (open) row keeps the cyan invert.
            let (word_fg, word_bg) = if is_open {
                (t.bg_dark, t.cyan)
            } else {
                (t.grey, t.bg_dark)
            };
            let base_style = Style::default()
                .fg(word_fg)
                .bg(word_bg)
                .add_modifier(if is_open {
                    Modifier::BOLD
                } else {
                    Modifier::empty()
                });
            // The leading character of an ASCII-letter label is the
            // Alt+<letter> accelerator. Underline it when ANY menu
            // is open so the user discovers the shortcut while
            // browsing.
            let first_alpha_idx = m.label.chars().position(|c| c.is_ascii_alphabetic());
            // The brand menu is the one whose first char isn't an
            // ASCII letter — its leading `>` is the prompt-mark
            // brand, the rest is the wordmark.
            let is_brand_menu = m
                .label
                .chars()
                .next()
                .is_some_and(|c| !c.is_ascii_alphabetic() && c != ' ');
            let mut spans: Vec<Span<'static>> = Vec::with_capacity(m.label.chars().count() + 2);
            spans.push(Span::styled(" ", base_style));
            for (idx, ch) in m.label.chars().enumerate() {
                let mut style = base_style;
                let is_brand_mark = is_brand_menu && first_alpha_idx.is_some_and(|fa| idx < fa);
                // 2026-07-18 — brand mark used to pop in cyan (`❯`
                // and `_` accent). User wanted it toned down to the
                // same darker grey the other menu-bar words use.
                // Inherit base_style unchanged; the bold treatment
                // below still makes it distinctive against the plain
                // menu words without an accent color.
                let _ = is_brand_mark;
                // Brand menu's wordmark is exempt — its identity is
                // the icon, not a letter. Other menus underline the
                // first alpha char as the Alt+letter accelerator.
                if any_menu_open && !is_brand_menu && Some(idx) == first_alpha_idx {
                    style = style.add_modifier(Modifier::UNDERLINED);
                }
                // BOLD the brand icon AND its wordmark text.
                if is_brand_menu && !ch.is_whitespace() {
                    style = style.add_modifier(Modifier::BOLD);
                }
                spans.push(Span::styled(ch.to_string(), style));
            }
            spans.push(Span::styled(" ", base_style));
            frame.render_widget(
                ratatui::widgets::Paragraph::new(Line::from(spans)),
                word_rect,
            );
            app.rects.menu_bar_words.push((word_rect, i));
            mx = mx.saturating_add(label_w);
        }
        // R9 vscode-mouse SEV-2 — `»` chip when we skipped any menu.
        // Click opens the first hidden menu; from there Alt+letter
        // reaches the others (per the v0.2.10 clipped-menu-open fix).
        if let Some(first_hidden_idx) = first_hidden
            && mx + 3 <= area.x + area.width
        {
            let chip_rect = Rect {
                x: mx,
                y: area.y,
                width: 3,
                height: 1,
            };
            frame.render_widget(
                ratatui::widgets::Paragraph::new(Line::from(vec![Span::styled(
                    " » ",
                    Style::default().fg(t.cyan).bg(t.bg_dark),
                )])),
                chip_rect,
            );
            app.rects.menu_bar_overflow = Some((chip_rect, first_hidden_idx));
        }
    }

    // Sidebar toggle — sits left of the back/forward arrows.
    // Single glyph (`layout-sidebar-left-off`, \u{EC02}) in both
    // states. Color carries the state: cyan when sidebar is open,
    // dim comment-fg when closed. The codicon `layout-sidebar-left`
    // (\u{EBA6}) variant rendered poorly at TUI cell scale — its
    // internal lines turned to noise — so we drop it.
    let sidebar_glyph = if ascii { "|" } else { "\u{EC02}" };
    let back_glyph = if ascii { "<" } else { "\u{EA9B}" }; // codicon: arrow-left
    let fwd_glyph = if ascii { ">" } else { "\u{EA9C}" }; // codicon: arrow-right
    let magnify = if ascii { "?" } else { "\u{F0349}" };
    // `\u{EAB4}` is the real codicon `chevron-down` in Nerd Fonts.
    // `\u{EAA1}` (the obvious-looking choice) renders as chevron-UP in
    // this font.
    let dropdown_glyph = if ascii { "v" } else { "\u{EAB4}" };
    // VS Code shows the workspace / repo name as the palette label
    // when no search is active (rather than placeholder text). Fall
    // back to a generic placeholder if the workspace path has no
    // file-name component (root `/`, or a path that fails UTF-8).
    let workspace_label_raw: String = app
        .workspace
        .file_name()
        .and_then(|n| n.to_str())
        .map(|s| s.to_string())
        .unwrap_or_else(|| "search files, run commands…".to_string());
    // Pad the label so the chip has a consistent width (VS Code's chip
    // is fixed-width regardless of repo name). Truncate long names
    // with `…` so the chip never overflows.
    const CHIP_LABEL_W: usize = 24;
    // #polish 2026-07-06 — track the actual visible label
    // width (before padding) so the click rect can shrink to
    // it. Was: whole 24-cell chip fired the picker, including
    // whitespace to the right of a short name.
    let workspace_label_visible_chars = workspace_label_raw.chars().count().min(CHIP_LABEL_W);
    let workspace_label = if workspace_label_raw.chars().count() > CHIP_LABEL_W {
        let mut s: String = workspace_label_raw.chars().take(CHIP_LABEL_W - 1).collect();
        s.push('');
        s
    } else {
        let need = CHIP_LABEL_W - workspace_label_raw.chars().count();
        let mut s = workspace_label_raw;
        s.extend(std::iter::repeat_n(' ', need));
        s
    };

    // Button strings — each ` glyph ` = 3 cells. Sidebar toggle
    // trims its right-side pad so the icon sits one cell closer
    // to the back arrow (less awkward gap there since the sidebar
    // toggle has no NAV_GAP companion of its own).
    let sidebar_str = format!(" {sidebar_glyph}");
    let back_str = format!(" {back_glyph} ");
    let fwd_str = format!(" {fwd_glyph} ");
    let dropdown_str = format!(" {dropdown_glyph} ");
    // Chip text without the dropdown — that's a separate clickable cell.
    let chip_text = format!("  {magnify}  {workspace_label}  ");

    // Forward / back arrows are "enabled" iff there's somewhere to
    // navigate — i.e. there's more than one open buffer (next_buffer
    // / prev_buffer cycle, so a single-buffer click is a no-op).
    // Enabled state uses the bright `fg` slot for max contrast on
    // every theme; disabled drops to the muted `comment` slot so the
    // arrows still read as glyphs but visually recede.
    let nav_enabled = app.panes.len() > 1;
    let nav_fg = if nav_enabled { t.fg } else { t.comment };

    // Right-panel toggle — uses codicon `layout-sidebar-right-off`
    // (\u{EC00}), the visual MIRROR of the left sidebar's
    // `layout-sidebar-left-off` (\u{EC02}). Reads as a matched
    // pair: panel-on-the-left toggle on the left, panel-on-the-
    // right toggle on the right. Full ` icon ` padding (3 cells)
    // gives the icon breathing room from the dropdown chevron.
    let right_panel_glyph = if ascii { "|" } else { "\u{EC00}" };
    let right_panel_str = format!(" {right_panel_glyph} ");
    let sidebar_w = sidebar_str.chars().count() as u16;
    let right_panel_w = right_panel_str.chars().count() as u16;
    let back_w = back_str.chars().count() as u16;
    let fwd_w = fwd_str.chars().count() as u16;
    let dropdown_w = dropdown_str.chars().count() as u16;
    let chip_w = chip_text.chars().count() as u16;
    // Layout: `[☰][←][→] [chip][▾][☰']` — single-cell strip-bg
    // separator between the nav cluster and the chip body. The
    // right-panel toggle sits right after the dropdown chevron
    // (mirror of the sidebar toggle's position on the far left).
    const NAV_GAP: u16 = 1;
    let total_w = sidebar_w
        + NAV_GAP
        + back_w
        + fwd_w
        + NAV_GAP
        + chip_w
        + dropdown_w
        + NAV_GAP
        + right_panel_w;
    if total_w > area.width {
        // Window too narrow for the full layout — fall back to chip only,
        // centered. Skips arrows + dropdown until there's room.
        let chip_only_w = chip_w.min(area.width);
        let cx = area.x + area.width.saturating_sub(chip_only_w) / 2;
        let chip_rect = Rect {
            x: cx,
            y: area.y,
            width: chip_only_w,
            height: 1,
        };
        frame.render_widget(
            ratatui::widgets::Paragraph::new(chip_text)
                .style(Style::default().fg(t.comment).bg(t.bg2)),
            chip_rect,
        );
        app.rects.palette_search_chip = Some(chip_rect);
        app.rects.palette_sidebar_button = None;
        app.rects.palette_right_panel_button = None;
        app.rects.palette_back_button = None;
        app.rects.palette_forward_button = None;
        app.rects.palette_dropdown_button = None;
        return;
    }

    let mut x = area.x + (area.width - total_w) / 2;
    let y = area.y;
    // vscode-user-mouse SEV-2 — paint the chrome-row bg_dark over the
    // span the centered cluster will occupy BEFORE we render the
    // cluster itself, so any menu-bar word characters underneath get
    // wiped instead of leaking ghost letters (the 'Vi' / 'u' leak at
    // 120 cols). The menu_bar_words click rects were registered with
    // wider extents than the visible chars; this overwrites the
    // pixels but the click rects from the menu-bar paint earlier in
    // the frame still survive (chord chain doesn't care about
    // visual overpaint).
    if total_w > 0 {
        frame.render_widget(
            ratatui::widgets::Paragraph::new(" ".repeat(total_w as usize))
                .style(Style::default().bg(t.bg_dark)),
            Rect {
                x,
                y,
                width: total_w,
                height: 1,
            },
        );
    }

    // Sidebar toggle — far left of the nav cluster.
    let sidebar_rect = Rect {
        x,
        y,
        width: sidebar_w,
        height: 1,
    };
    // Task #891 — reflect auto-hide state in the toggle chip. When
    // the terminal is narrower than `[ui] auto_hide_narrow_width`,
    // panels vanish for that frame; the chip must match so users
    // don't see an "active" toggle for a hidden panel. Persistent
    // `tree_visible` still drives what happens on widen.
    let panels_hidden = app.side_panels_auto_hidden(area.width);
    let sidebar_fg = if app.tree_visible && !panels_hidden {
        t.cyan
    } else {
        t.comment
    };
    frame.render_widget(
        ratatui::widgets::Paragraph::new(sidebar_str)
            .style(Style::default().fg(sidebar_fg).bg(t.bg_dark)),
        sidebar_rect,
    );
    app.rects.palette_sidebar_button = Some(sidebar_rect);
    x += sidebar_w + NAV_GAP;

    // Back button.
    let back_rect = Rect {
        x,
        y,
        width: back_w,
        height: 1,
    };
    // Buttons sit on a darker bg than the chip so the back/forward
    // cluster reads as chrome and the chip reads as the focal input.
    let btn_bg = t.bg_dark;
    frame.render_widget(
        ratatui::widgets::Paragraph::new(back_str).style(Style::default().fg(nav_fg).bg(btn_bg)),
        back_rect,
    );
    app.rects.palette_back_button = Some(back_rect);
    x += back_w;

    // Forward button.
    let fwd_rect = Rect {
        x,
        y,
        width: fwd_w,
        height: 1,
    };
    frame.render_widget(
        ratatui::widgets::Paragraph::new(fwd_str).style(Style::default().fg(nav_fg).bg(btn_bg)),
        fwd_rect,
    );
    app.rects.palette_forward_button = Some(fwd_rect);
    x += fwd_w + NAV_GAP;

    // Search chip.
    let chip_rect = Rect {
        x,
        y,
        width: chip_w,
        height: 1,
    };
    frame.render_widget(
        ratatui::widgets::Paragraph::new(chip_text).style(Style::default().fg(t.comment).bg(t.bg2)),
        chip_rect,
    );
    // #polish 2026-07-06 — click rect only spans the actual visible
    // label (magnifier + spacing + name), NOT the trailing padding.
    // Was: chip fires the picker even when clicking blank cells to
    // the right of a short workspace name; misleading hit zone.
    // Layout: `"  {magnify}  {label}  "` = 2 + 1 + 2 + N + 2 cells,
    // with N = visible label chars.
    let hit_w = (2 + 1 + 2 + workspace_label_visible_chars + 2) as u16;
    let hit_rect = Rect {
        x,
        y,
        width: hit_w.min(chip_w),
        height: 1,
    };
    app.rects.palette_search_chip = Some(hit_rect);
    x += chip_w;

    // Dropdown chevron — visually glued to the chip's right edge but
    // dispatches its own command.
    let dropdown_rect = Rect {
        x,
        y,
        width: dropdown_w,
        height: 1,
    };
    frame.render_widget(
        ratatui::widgets::Paragraph::new(dropdown_str)
            .style(Style::default().fg(t.comment).bg(t.bg2)),
        dropdown_rect,
    );
    app.rects.palette_dropdown_button = Some(dropdown_rect);
    x += dropdown_w + NAV_GAP;

    // Right-panel toggle — mirror of sidebar_button.
    let right_panel_rect = Rect {
        x,
        y,
        width: right_panel_w,
        height: 1,
    };
    // Same auto-hide check as the sidebar chip above (#891).
    let right_panel_fg = if app.right_panel_visible && !panels_hidden {
        t.cyan
    } else {
        t.comment
    };
    frame.render_widget(
        ratatui::widgets::Paragraph::new(right_panel_str)
            .style(Style::default().fg(right_panel_fg).bg(t.bg_dark)),
        right_panel_rect,
    );
    app.rects.palette_right_panel_button = Some(right_panel_rect);

    // 2026-06-21 — right-aligned chrome cluster (launcher icons /
    // `+` / TABS chips / theme toggle / close). Right-edge of the
    // workspace chip + dropdown is the leftward bound; if the
    // full cluster would visually overlap them, drop the TABS +
    // tab-page section. If even the compact cluster won't fit,
    // skip the cluster entirely.
    //
    // 2026-06-22 user-reported: at narrow widths the launcher
    // icons + tab-page chips overlapped (rendered on top of each
    // other). Stage the fallback so the most-clicked chips
    // (launchers + close) stay visible the longest.
    // qa-feature 2026-07-01 — `x` at this point is the LEFT edge
    // of the right-panel toggle (line ~2398 already bumped x past
    // dropdown_w + NAV_GAP), so the toggle's right edge is simply
    // `x + right_panel_w`. The prior formula
    // `x + dropdown_w + NAV_GAP + right_panel_w` double-counted
    // dropdown_w + NAV_GAP and pushed palette_right_edge 2 cells
    // past the toggle, which is why the browser globe kept landing
    // way further right than the "2 cells from the toggle" the
    // user asked for.
    let palette_right_edge = x + right_panel_w;
    let full_w = bufferline::right_cluster_width(app);
    // mouse-user SEV-2 — try the full cluster first; fall back to a
    // compact (no TABS / tab-page chips) cluster when the full one
    // would overlap the workspace chip. Net: window-close + theme +
    // new-tab stay reachable at narrow widths instead of vanishing.
    let cluster_pref = bufferline::ClusterModePref::parse(&app.config.ui.top_bar_cluster_mode);
    let cluster_mode = bufferline::pick_cluster_mode_tiered(
        app,
        area.x,
        area.width,
        palette_right_edge,
        full_w,
        4, // gap cells between palette + cluster
        cluster_pref,
    );
    if let Some((w, compact)) = cluster_mode {
        let cluster_area = Rect {
            x: area.x + area.width.saturating_sub(w),
            y: area.y,
            width: w,
            height: 1,
        };
        bufferline::paint_right_cluster(frame, app, cluster_area, t.bg_dark, compact);
        // Integration icons — paint in the gap between the
        // workspace chip's right edge and the cluster. Skip
        // entirely if the gap can't hold even one (3 cells each)
        // so the cluster stays put. Right-aligned just before the
        // cluster so the eye groups them with the chrome.
        paint_integration_chips_in_gap(frame, app, palette_right_edge, cluster_area.x, area.y);
    } else {
        // Cluster hidden entirely — clear the cluster-only rects.
        // launcher_icon_rects is cleared at ui::draw entry now,
        // so we don't repeat it here (the gap painter may still
        // have populated it before this branch ran).
        app.rects.bufferline_new_tab_button = None;
        app.rects.palette_add_integration_button = None;
        app.rects.bufferline_tab_page_chips.clear();
        app.rects.bufferline_tab_page_close.clear();
        app.rects.bufferline_theme_toggle = None;
        app.rects.bufferline_window_close = None;
    }
}

/// Activity-bar Debug section — DAP launcher + at-a-glance status.
/// Shows whether a session is running, the watch + breakpoint counts,
/// and clickable rows for the run/continue/step family. The actual
/// Variables / Call-stack / Watches grid lives in the existing
/// `debug_view.rs` (an editor-body pane); this section is a control
/// panel, not a replacement. v2 follow-up: inline mini-watches list
/// so the user can glance without opening the pane.
fn draw_debug_section(frame: &mut Frame, app: &mut App, area: Rect) {
    let t = theme::cur();
    let bg = t.bg_darker;
    frame.render_widget(Block::default().style(Style::default().bg(bg)), area);
    if area.height < 2 || area.width < 8 {
        return;
    }
    // Header.
    frame.render_widget(
        Paragraph::new(ratatui::text::Line::from(" DEBUG")).style(
            Style::default()
                .fg(t.fg)
                .bg(bg)
                .add_modifier(Modifier::BOLD),
        ),
        Rect {
            x: area.x,
            y: area.y,
            width: area.width,
            height: 1,
        },
    );

    // Session status line.
    let session_active = app.dap.is_some();
    let status_label = if session_active {
        "● session active"
    } else {
        "○ no session"
    };
    let status_color = if session_active { t.green } else { t.comment };
    let watch_n = app.dap_watches.len();
    frame.render_widget(
        Paragraph::new(ratatui::text::Line::from(format!(
            "  {status_label}    {watch_n} watch{}",
            if watch_n == 1 { "" } else { "es" }
        )))
        .style(Style::default().fg(status_color).bg(bg)),
        Rect {
            x: area.x,
            y: area.y + 2,
            width: area.width,
            height: 1,
        },
    );

    // Inline watches list (v2). Each watch gets a row:
    //   <expr> = <value>     (dim error if eval failed)
    // Truncated to fit width; only rendered when there are any.
    let mut y_after_watches = area.y + 4;
    if !app.dap_watches.is_empty() && area.height > 5 {
        let header_y = area.y + 4;
        frame.render_widget(
            Paragraph::new(ratatui::text::Line::from(" WATCHES")).style(
                Style::default()
                    .fg(t.comment)
                    .bg(bg)
                    .add_modifier(Modifier::BOLD | Modifier::DIM),
            ),
            Rect {
                x: area.x,
                y: header_y,
                width: area.width,
                height: 1,
            },
        );
        let mut wy = header_y + 1;
        // Cap to ~5 rows so we don't crowd the launcher actions below.
        for expr in app.dap_watches.iter().take(5) {
            if wy + 1 >= area.y + area.height {
                break;
            }
            let result = app.dap_watch_results.get(expr);
            let (value_text, value_style) = match result {
                Some(r) if r.err.is_some() => (
                    format!("err: {}", r.err.as_deref().unwrap_or("")),
                    Style::default()
                        .fg(t.red)
                        .bg(bg)
                        .add_modifier(Modifier::DIM),
                ),
                Some(r) => (r.value.clone(), Style::default().fg(t.fg).bg(bg)),
                None => (
                    "(not evaluated)".to_string(),
                    Style::default()
                        .fg(t.comment)
                        .bg(bg)
                        .add_modifier(Modifier::DIM),
                ),
            };
            // Truncate the value column so the row stays one line.
            let avail = (area.width as usize).saturating_sub(expr.chars().count() + 5);
            let truncated_value: String = if value_text.chars().count() > avail {
                let take = avail.saturating_sub(1);
                let mut s: String = value_text.chars().take(take).collect();
                s.push('');
                s
            } else {
                value_text
            };
            let line = ratatui::text::Line::from(vec![
                Span::styled(format!("  {expr} = "), Style::default().fg(t.cyan).bg(bg)),
                Span::styled(truncated_value, value_style),
            ]);
            frame.render_widget(
                Paragraph::new(line),
                Rect {
                    x: area.x,
                    y: wy,
                    width: area.width,
                    height: 1,
                },
            );
            wy = wy.saturating_add(1);
        }
        if app.dap_watches.len() > 5 && wy < area.y + area.height {
            frame.render_widget(
                Paragraph::new(ratatui::text::Line::from(format!(
                    "  + {} more (use add/remove)",
                    app.dap_watches.len() - 5
                )))
                .style(
                    Style::default()
                        .fg(t.comment)
                        .bg(bg)
                        .add_modifier(Modifier::DIM),
                ),
                Rect {
                    x: area.x,
                    y: wy,
                    width: area.width,
                    height: 1,
                },
            );
            wy = wy.saturating_add(1);
        }
        y_after_watches = wy.saturating_add(1);
    }

    let rows: &[(&str, &str, &'static str)] = &[
        ("▸ Run", "F5", "dap.run"),
        ("▸ Continue", "F5 (running)", "dap.continue"),
        ("▸ Step over", "F10", "dap.next"),
        ("▸ Step into", "F11", "dap.step_in"),
        ("▸ Step out", "Shift+F11", "dap.step_out"),
        ("▸ Pause", "F6", "dap.pause"),
        ("▸ Toggle breakpoint", "F9", "dap.toggle_breakpoint"),
        ("▸ List breakpoints", "", "dap.list_breakpoints"),
        ("▸ Add watch…", "", "dap.add_watch"),
        ("▸ Remove watch…", "", "dap.remove_watch"),
        ("▸ Clear watches", "", "dap.clear_watches"),
    ];

    let mut y = y_after_watches;
    for (label, chord, cmd_id) in rows {
        if y + 1 >= area.y + area.height {
            break;
        }
        let label_rect = Rect {
            x: area.x,
            y,
            width: area.width,
            height: 1,
        };
        frame.render_widget(
            Paragraph::new(ratatui::text::Line::from(format!("  {label}")))
                .style(Style::default().fg(t.fg).bg(bg)),
            label_rect,
        );
        let chord_rect = Rect {
            x: area.x,
            y: y + 1,
            width: area.width,
            height: 1,
        };
        frame.render_widget(
            Paragraph::new(ratatui::text::Line::from(format!("    {chord}"))).style(
                Style::default()
                    .fg(t.comment)
                    .bg(bg)
                    .add_modifier(Modifier::DIM),
            ),
            chord_rect,
        );
        app.rects.tree_icon_buttons.push((label_rect, *cmd_id));
        app.rects.tree_icon_buttons.push((chord_rect, *cmd_id));
        y = y.saturating_add(2);
    }
}

/// Activity-bar Search section — inline grep with results streaming
/// below the input. Type-then-Enter runs the workspace grep; ↑↓ steps
/// the selection; Enter on a result row jumps to that file+line.
///
/// Layout:
///   SEARCH
///
///    / <query>█
///    <N hits (rg)>  or hint when not run
///
///    src/foo.rs
///      42:5  let x = 1;
///      55:5  let y = 2;
///    src/bar.rs
///      18:9  let z = 3;
///
/// Focus: clicking the Search activity-bar icon auto-focuses the
/// input (handled in `App::set_activity_section`). `Esc` blurs back
/// to the editor; while blurred, Enter on a result still jumps via
/// the editor's normal handling (selection is preserved across the
/// blur).
fn draw_search_section(frame: &mut Frame, app: &mut App, area: Rect) {
    let t = theme::cur();
    let bg = t.bg_darker;
    app.rects.search_section_hit_rects.clear();
    app.rects.search_section_flag_rects.clear();
    frame.render_widget(Block::default().style(Style::default().bg(bg)), area);
    if area.height < 2 || area.width < 8 {
        return;
    }
    // Header row = "SEARCH" title on the left + three flag chips
    // (case / whole-word / regex) right-aligned. #1112 f/u
    // (2026-08-21). Each chip is 3 cells wide (` X `); active
    // chip inverts fg/bg. Register hit rects so click dispatches
    // to the palette command. When the row is too narrow to fit
    // all three chips, skip them silently (title stays visible).
    let header_row = Rect {
        x: area.x,
        y: area.y,
        width: area.width,
        height: 1,
    };
    frame.render_widget(
        Paragraph::new(ratatui::text::Line::from(" SEARCH")).style(
            Style::default()
                .fg(t.fg)
                .bg(bg)
                .add_modifier(Modifier::BOLD),
        ),
        header_row,
    );
    // Right-align the chip cluster. Total width = 3*3 + 2 gaps = 11.
    // Only render when the title has enough breathing room.
    const CHIP_W: u16 = 3;
    const CHIP_GAP: u16 = 0;
    let cluster_w: u16 = 3 * CHIP_W + 2 * CHIP_GAP;
    let title_reserve: u16 = 8; // " SEARCH" + 1 cell of gap
    if area.width >= title_reserve + cluster_w {
        let mut cx = area.x + area.width - cluster_w;
        for (ch, on, label) in [
            ('c', app.search_case_sensitive, "Aa"),
            ('w', app.search_whole_word, "\\b"),
            ('r', app.search_regex, ".*"),
        ] {
            let chip_rect = Rect {
                x: cx,
                y: area.y,
                width: CHIP_W,
                height: 1,
            };
            let (fg, chip_bg, mods) = if on {
                (t.bg, t.yellow, Modifier::BOLD)
            } else {
                (t.comment, bg, Modifier::empty())
            };
            frame.render_widget(
                Paragraph::new(format!(" {label}"))
                    .style(Style::default().fg(fg).bg(chip_bg).add_modifier(mods)),
                chip_rect,
            );
            app.rects.search_section_flag_rects.push((chip_rect, ch));
            cx += CHIP_W + CHIP_GAP;
        }
    }
    let input_y = area.y + 2;
    if input_y >= area.y + area.height {
        return;
    }
    let focused = app.search_input_focused;
    let cursor_glyph = if focused { "" } else { "" };
    let input_line = ratatui::text::Line::from(vec![
        Span::styled(" / ", Style::default().fg(t.yellow).bg(bg)),
        Span::styled(app.search_query.clone(), Style::default().fg(t.fg).bg(bg)),
        Span::styled(
            cursor_glyph.to_string(),
            Style::default().fg(t.yellow).bg(bg),
        ),
    ]);
    frame.render_widget(
        Paragraph::new(input_line),
        Rect {
            x: area.x,
            y: input_y,
            width: area.width,
            height: 1,
        },
    );
    let status_y = input_y + 1;
    if status_y < area.y + area.height {
        let status_text = if app.search_used.is_empty() {
            if focused {
                " type · Enter to run · Esc to blur".to_string()
            } else {
                " click 🔍 icon to focus".to_string()
            }
        } else {
            let n = app.search_hits.len();
            format!(
                " {} hit{} ({})",
                n,
                if n == 1 { "" } else { "s" },
                app.search_used
            )
        };
        frame.render_widget(
            Paragraph::new(ratatui::text::Line::from(status_text)).style(
                Style::default()
                    .fg(t.comment)
                    .bg(bg)
                    .add_modifier(Modifier::DIM),
            ),
            Rect {
                x: area.x,
                y: status_y,
                width: area.width,
                height: 1,
            },
        );
    }
    if app.search_hits.is_empty() {
        return;
    }
    let body_top = status_y.saturating_add(2);
    let body_max = area.y + area.height;
    let mut y = body_top;
    let selected = app.search_selected;
    let mut prev_path: Option<String> = None;
    let visible_rows = (body_max - body_top) as usize;
    if visible_rows == 0 {
        return;
    }
    let scroll_start = if selected >= visible_rows {
        selected + 1 - visible_rows
    } else {
        0
    };
    for (i, hit) in app
        .search_hits
        .iter()
        .enumerate()
        .skip(scroll_start)
        .take(visible_rows)
    {
        if y >= body_max {
            break;
        }
        if prev_path.as_deref() != Some(hit.rel.as_str()) {
            if y >= body_max {
                break;
            }
            frame.render_widget(
                Paragraph::new(ratatui::text::Line::from(format!(" {}", hit.rel)))
                    .style(Style::default().fg(t.cyan).bg(bg)),
                Rect {
                    x: area.x,
                    y,
                    width: area.width,
                    height: 1,
                },
            );
            prev_path = Some(hit.rel.clone());
            y = y.saturating_add(1);
            if y >= body_max {
                break;
            }
        }
        let is_sel = i == selected;
        let line_style = if is_sel {
            Style::default()
                .fg(t.fg)
                .bg(t.bg2)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(t.fg).bg(bg)
        };
        let lineno_color = if is_sel { t.fg } else { t.yellow };
        let row = ratatui::text::Line::from(vec![
            Span::styled(
                format!("   {}:{}  ", hit.line + 1, hit.col + 1),
                Style::default()
                    .fg(lineno_color)
                    .bg(if is_sel { t.bg2 } else { bg }),
            ),
            Span::styled(hit.text.trim().to_string(), line_style),
        ]);
        let row_rect = Rect {
            x: area.x,
            y,
            width: area.width,
            height: 1,
        };
        frame.render_widget(Paragraph::new(row), row_rect);
        app.rects.search_section_hit_rects.push((row_rect, i));
        y = y.saturating_add(1);
    }
}

/// Activity-bar Integrations section — renders the configured
/// `[[ui.integration_icon]]` entries as a vertical list of clickable
/// rows. Each row: large glyph + tooltip/id, with the bound command
/// shown dim below. Clicking a row fires the same command path as
/// the compact icon strip in the Explorer rail (palette command id /
/// `:ex`).
/// Result of probing whether the binary backing an integration's
/// command is actually on the user's PATH. Today only the
/// `:term <binary>` shape is probed; mnml-internal commands
/// (no prefix) are assumed available because they don't shell out.
enum IntegrationAvailability {
    Available,
    /// Binary name (just the leaf, no path) the user would need to
    /// install. Surfaced as `(<bin> not installed)` next to the row.
    Missing(String),
}

/// Walk the `command` string from an `IntegrationIcon` and decide
/// whether the underlying tool is installed. Only `:term <binary>`
/// invocations are probed (built-in palette commands like
/// `:ai.claude_code` always return `Available`). Detection happens in
/// `integration_detect`: in-process `$PATH` walk + per-OS well-known
/// install dirs (`~/.cargo/bin`, Homebrew, etc.), with results cached
/// per-session so this is cheap to call per-frame.
fn integration_availability(command: &str) -> IntegrationAvailability {
    let Some(bin) = crate::integration_detect::integration_binary_for_command(command) else {
        return IntegrationAvailability::Available;
    };
    if crate::integration_detect::is_binary_installed(bin) {
        IntegrationAvailability::Available
    } else {
        IntegrationAvailability::Missing(bin.to_string())
    }
}

fn draw_integrations_section(frame: &mut Frame, app: &mut App, area: Rect) {
    let t = theme::cur();
    let bg = t.bg_darker;
    frame.render_widget(Block::default().style(Style::default().bg(bg)), area);
    if area.height < 2 || area.width < 8 {
        return;
    }
    let nerd = !app.config.ui.ascii_icons;
    // Reset chip rects on every frame — same idiom as the other panels.
    app.rects.integrations_add_chip = None;

    // Header row.
    let header_rect = Rect {
        x: area.x,
        y: area.y,
        width: area.width,
        height: 1,
    };
    frame.render_widget(
        Paragraph::new(ratatui::text::Line::from(" INTEGRATIONS")).style(
            Style::default()
                .fg(t.fg)
                .bg(bg)
                .add_modifier(Modifier::BOLD),
        ),
        header_rect,
    );
    // qa-feature 2026-07-01 — Installed / Marketplace tabs below
    // the header. `Installed` is the daily-driver rail (enabled
    // icons only); `Marketplace` is what the gear link used to open
    // (everything else, so the user can enable more).
    let tab_row = Rect {
        x: area.x,
        y: area.y + 1,
        width: area.width,
        height: 1,
    };
    frame.render_widget(Paragraph::new("").style(Style::default().bg(bg)), tab_row);
    let active_tab = app.integrations_panel_tab;
    // #polish 2026-07-06 — tab labels carry counts so users see
    // how many entries are in each pool without switching tabs.
    // design-critic 2026-08-06 SEV-high: was `.filter(|ic| ic.enabled)`
    // — but the Installed tab now renders EVERY installed integration,
    // enabled AND disabled (with disabled sorted to bottom + dimmed).
    // Counter must include disabled ones or "Inst (4)" reads while
    // 6 rows render.
    let installed_count = app.config.ui.integration_icons.len();
    // Marketplace tab renders TWO groups: (a) installed-but-not-
    // enabled chips at the top, (b) fetched marketplace entries
    // below (dedup'd against installed ids). Counter should reflect
    // both — otherwise the number reads as wrong when a user sees
    // more rows than the label suggests. User report 2026-08-03.
    let installed_ids_lc: std::collections::HashSet<String> = app
        .config
        .ui
        .integration_icons
        .iter()
        .map(|i| i.id.clone())
        .collect();
    // 2026-08-06 — also treat a marketplace entry as installed when
    // its crate id matches an installed integration's underlying
    // binary. mnml-tracker-jira installs THREE manifests
    // (jira_boards / jira_work / jira_fix_versions), so id-only
    // dedup left mnml-tracker-jira listed under Marketplace after
    // install. Now: any installed integration whose command routes
    // through `:term <binary>` blocks a marketplace entry with the
    // same id from appearing.
    let installed_binaries: std::collections::HashSet<String> = app
        .config
        .ui
        .integration_icons
        .iter()
        .filter_map(|i| crate::integration_detect::integration_binary_for_command(&i.command))
        .map(|s| s.to_string())
        .collect();
    // 2026-08-07 — count ALL marketplace entries; installed ones now
    // render dimmed rather than being hidden. Previously subtracted
    // installed to avoid double-counting (they used to show at top
    // of the tab); no longer applies. Keeps the count matching what
    // renders below.
    let _ = (&installed_ids_lc, &installed_binaries);
    // 2026-08-19 (#1055) — count only entries that pass the Ready
    // gate. Was `app.marketplace_entries.len()` — that included
    // unready App entries the render loop hides, so the tab read
    // "Marketplace (48)" while only ~7 rows painted. Launchers /
    // drivers bypass the gate (they show unconditionally).
    let marketplace_count = app
        .marketplace_entries
        .iter()
        .filter(|e| !matches!(e.kind, crate::marketplace::MarketplaceKind::App) || e.ready)
        .count();
    // vscode-mouse SEV-2 2026-08-05 — was
    //   `" Installed ({N}) "` + `" Marketplace ({M}) "`
    // which needs ~32 chars minimum; the activity panel is ~28 wide
    // so `(M)` on Marketplace got truncated ("Installed (1)
    // Marketplace│"). Compress: drop the label word when short on
    // width, keep just the count. `(N) Installed` reads unambiguously
    // even without both words in the strip.
    // 2026-08-22 — labels start with the first letter (not a leading
    // space). The active-tab pill uses bg2 which paints one cell
    // lighter than the surrounding bg, and a leading-space cell reads
    // as an unpainted-looking sliver between the panel edge and the
    // "I"/"M". Dropping the leading space makes the pill hug the
    // character; trailing space stays as inter-tab separation.
    let full_installed = format!("Installed ({installed_count}) ");
    let full_marketplace = format!("Marketplace ({marketplace_count}) ");
    let compact_installed = format!("Inst ({installed_count}) ");
    let compact_marketplace = format!("Mkt ({marketplace_count}) ");
    // 2026-08-07 nvchad-r1 SEV-2: still-clipping refresh at width ≤22.
    // Add a THIRD compactness tier that drops the parenthesized counts,
    // so refresh stays visible down to ~15-cell widths.
    let tiny_installed = "Inst ".to_string();
    let tiny_marketplace = "Mkt ".to_string();
    // 2026-08-19 (#1056) — In-Development tab. Config-gated
    // (`[marketplace] show_dev_tab = true`) so regular users don't see
    // the extra tab. Label is a single Nerd Font glyph (nf-fa-dev at
    // U+EEF4) so all three tabs fit inside the ~28-cell activity
    // panel. Renders App entries that failed the Ready gate — meant
    // for integration authors browsing their own not-yet-shipped work.
    let show_dev_tab = app.config.marketplace.show_dev_tab;
    let in_dev_count = app
        .marketplace_entries
        .iter()
        .filter(|e| matches!(e.kind, crate::marketplace::MarketplaceKind::App) && !e.ready)
        .count();
    let in_dev_label = format!("\u{EEF4} ({in_dev_count}) ");
    let in_dev_w_usize = if show_dev_tab {
        in_dev_label.chars().count()
    } else {
        0
    };
    let full_total =
        full_installed.chars().count() + full_marketplace.chars().count() + in_dev_w_usize;
    let compact_total =
        compact_installed.chars().count() + compact_marketplace.chars().count() + in_dev_w_usize;
    let tiny_total =
        tiny_installed.chars().count() + tiny_marketplace.chars().count() + in_dev_w_usize;
    // Refresh chip is 3 chars (" ⟳ "). Priority ladder: prefer showing
    // refresh over long labels since refresh is a frequent action and
    // Inst/Mkt reads unambiguously.
    let refresh_w_usize: usize = 3;
    let width_usize = area.width as usize;
    #[derive(Clone, Copy)]
    enum Tier {
        Full,
        Compact,
        Tiny,
    }
    let (tier, show_refresh) = if full_total + refresh_w_usize <= width_usize {
        (Tier::Full, true)
    } else if compact_total + refresh_w_usize <= width_usize {
        (Tier::Compact, true)
    } else if tiny_total + refresh_w_usize <= width_usize {
        (Tier::Tiny, true)
    } else if full_total <= width_usize {
        (Tier::Full, false)
    } else if compact_total <= width_usize {
        (Tier::Compact, false)
    } else {
        (Tier::Tiny, false)
    };
    let (installed_label, marketplace_label) = match tier {
        Tier::Full => (full_installed, full_marketplace),
        Tier::Compact => (compact_installed, compact_marketplace),
        Tier::Tiny => (tiny_installed, tiny_marketplace),
    };
    let use_compact = matches!(tier, Tier::Compact | Tier::Tiny);
    let _ = use_compact; // retained for downstream readability
    let installed_w = installed_label.chars().count() as u16;
    let marketplace_w = marketplace_label.chars().count() as u16;
    // 2026-08-22 — 1-cell gutter on the left so the active-tab pill's
    // dark bg doesn't run right up against (or bleed into) the
    // activity-bar column. Same shift is applied to marketplace +
    // in-dev tabs below so the whole strip starts at column area.x+1.
    let gutter: u16 = 1;
    let strip_start_x = area.x.saturating_add(gutter);
    let strip_max_w = area.width.saturating_sub(gutter);
    let installed_rect = Rect {
        x: strip_start_x,
        y: area.y + 1,
        width: installed_w.min(strip_max_w),
        height: 1,
    };
    let marketplace_rect = Rect {
        x: strip_start_x + installed_w,
        y: area.y + 1,
        width: marketplace_w.min(strip_max_w.saturating_sub(installed_w)),
        height: 1,
    };
    let tab_style = |active: bool| {
        if active {
            Style::default()
                .fg(t.fg)
                .bg(t.bg2)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(t.comment).bg(bg)
        }
    };
    frame.render_widget(
        Paragraph::new(installed_label).style(tab_style(
            active_tab == crate::app::IntegrationsPanelTab::Installed,
        )),
        installed_rect,
    );
    frame.render_widget(
        Paragraph::new(marketplace_label).style(tab_style(
            active_tab == crate::app::IntegrationsPanelTab::Marketplace,
        )),
        marketplace_rect,
    );
    app.rects.integrations_tab_installed = Some(installed_rect);
    app.rects.integrations_tab_marketplace = Some(marketplace_rect);
    // 2026-08-19 (#1056) — third tab (In-Development). Rendered
    // only when `show_dev_tab` config is on. Rect registered
    // conditionally so the mouse dispatcher only matches when the
    // tab is actually visible.
    if show_dev_tab {
        let in_dev_w = in_dev_label.chars().count() as u16;
        let in_dev_rect = Rect {
            x: strip_start_x + installed_w + marketplace_w,
            y: area.y + 1,
            width: in_dev_w.min(strip_max_w.saturating_sub(installed_w + marketplace_w)),
            height: 1,
        };
        frame.render_widget(
            Paragraph::new(in_dev_label).style(tab_style(
                active_tab == crate::app::IntegrationsPanelTab::InDev,
            )),
            in_dev_rect,
        );
        app.rects.integrations_tab_in_dev = Some(in_dev_rect);
    } else {
        app.rects.integrations_tab_in_dev = None;
    }

    // Refresh affordance — small ⟳ chip on the far right of the tab
    // row. Clicks fire `marketplace.refresh` when on the Marketplace
    // tab (re-fetches crates.io + GitHub sources) or
    // `integrations.refresh` on the Installed tab (re-scans local
    // manifest dirs). User report 2026-08-04 — the palette commands
    // existed but there was no visible button, so the panel felt
    // stale between launches.
    let refresh_label = "";
    let refresh_w = refresh_label.chars().count() as u16;
    if show_refresh {
        // 2026-08-08 — nudge 1 cell left of the panel edge so the chip
        // isn't jammed against the vertical separator between the
        // Integrations panel and the main content.
        let refresh_rect = Rect {
            x: area.x + area.width.saturating_sub(refresh_w + 1),
            y: area.y + 1,
            width: refresh_w,
            height: 1,
        };
        frame.render_widget(
            Paragraph::new(refresh_label).style(
                Style::default()
                    .fg(t.comment)
                    .bg(bg)
                    .add_modifier(Modifier::BOLD),
            ),
            refresh_rect,
        );
        app.rects.integrations_tab_refresh = Some(refresh_rect);
    } else {
        app.rects.integrations_tab_refresh = None;
    }

    // 2026-08-07 — sort chip on the filter row's right edge.
    // Left-click cycles through the modes for the ACTIVE tab.
    // Label is short so it fits alongside the filter input.
    let sort_label = match active_tab {
        crate::app::IntegrationsPanelTab::Installed => app.installed_sort.label(),
        crate::app::IntegrationsPanelTab::Marketplace | crate::app::IntegrationsPanelTab::InDev => {
            app.marketplace_sort.label()
        }
    };
    let sort_label_owned = format!(" {sort_label} ");
    let sort_w = sort_label_owned.chars().count() as u16;
    // Fit-or-drop guard so a very narrow panel doesn't cause overflow.
    let sort_rect = if area.width > sort_w + 4 {
        Some(Rect {
            x: area.x + area.width.saturating_sub(sort_w),
            y: area.y + 2,
            width: sort_w,
            height: 1,
        })
    } else {
        None
    };
    if let Some(r) = sort_rect {
        frame.render_widget(
            Paragraph::new(sort_label_owned).style(
                Style::default()
                    .fg(t.cyan)
                    .bg(bg)
                    .add_modifier(Modifier::BOLD),
            ),
            r,
        );
        app.rects.integrations_tab_sort = Some(r);
    } else {
        app.rects.integrations_tab_sort = None;
    }

    // qa-feature 2026-07-01 — filter row directly below the tabs.
    // 2026-08-07 vscode-mouse r1 F5: sort chip painted at same y as
    // filter row's rightmost cells. A long filter query would
    // overpaint the sort chip. Constrain filter width so the chip
    // stays visible (chip is still hit-testable regardless — the
    // fix is visual only).
    let sort_reserve = sort_rect.map(|r| r.width).unwrap_or(0);
    let filter_row = Rect {
        x: area.x,
        y: area.y + 2,
        width: area.width.saturating_sub(sort_reserve),
        height: 1,
    };
    let search_glyph = if nerd { "\u{f002}" } else { "/" };
    let filter_focused = app.integrations_panel_filter_focused;
    let filter_display = if app.integrations_panel_filter.is_empty() {
        if filter_focused {
            "type to filter…".to_string()
        } else {
            "/ filter".to_string()
        }
    } else {
        app.integrations_panel_filter.clone()
    };
    let filter_fg = if !app.integrations_panel_filter.is_empty() {
        t.fg
    } else if filter_focused {
        t.cyan
    } else {
        t.comment
    };
    let cursor = if filter_focused { "" } else { "" };
    frame.render_widget(
        Paragraph::new(ratatui::text::Line::from(vec![
            Span::styled(
                format!(" {search_glyph} "),
                Style::default().fg(t.comment).bg(bg),
            ),
            Span::styled(filter_display, Style::default().fg(filter_fg).bg(bg)),
            Span::styled(cursor, Style::default().fg(t.cyan).bg(bg)),
        ])),
        filter_row,
    );
    app.rects.integrations_filter_chip = Some(filter_row);

    // qa-feature 2026-07-01 — first cut by tab (Installed = enabled,
    // Marketplace = the rest), then by the filter query.
    // 2026-07-03 — Marketplace is now sorted alphabetically by
    // tooltip / id so users can scan a very long list. Installed
    // keeps the config-file order because that's the user's own
    // reorder (Move up / Move to top / …) which we must respect.
    let all_icons = app.config.ui.integration_icons.clone();
    let filter_lc = app.integrations_panel_filter.to_ascii_lowercase();
    let mut icons: Vec<(usize, crate::config::IntegrationIcon)> = all_icons
        .iter()
        .enumerate()
        // 2026-08-06 user report — was: Installed → only `enabled`,
        // Marketplace → `!enabled`. That put disabled installed
        // chips on the MARKETPLACE tab, which reads as "you don't
        // have this yet" — wrong. New: Installed = every installed
        // integration (enabled + disabled); disabled ones sort to
        // the bottom + render dimmed (below). Marketplace = only
        // fetched crates.io/launcher entries the user hasn't
        // installed at all (already filtered by `installed_ids`
        // in the entries loop).
        .filter(|(_, _icon)| match active_tab {
            crate::app::IntegrationsPanelTab::Installed => true,
            crate::app::IntegrationsPanelTab::Marketplace
            | crate::app::IntegrationsPanelTab::InDev => false,
        })
        .filter(|(_, icon)| {
            if filter_lc.is_empty() {
                return true;
            }
            let hay = format!(
                "{} {} {}",
                icon.label.as_deref().unwrap_or(""),
                icon.id,
                icon.command,
            )
            .to_ascii_lowercase();
            hay.contains(&filter_lc)
        })
        .map(|(i, icon)| (i, icon.clone()))
        .collect();
    // 2026-08-07 — sort mode chip on the panel header cycles
    // through modes. Default is Name (A-Z) for both tabs (was:
    // hardcoded — alpha on Marketplace, enabled-first on Installed).
    let name_key = |i: &crate::config::IntegrationIcon| -> String {
        i.label
            .clone()
            .filter(|s| !s.is_empty())
            .unwrap_or_else(|| i.id.clone())
            .to_ascii_lowercase()
    };
    match active_tab {
        crate::app::IntegrationsPanelTab::Installed => match app.installed_sort {
            crate::app::InstalledSort::Default => {} // preserve config order
            crate::app::InstalledSort::Name => icons.sort_by_key(|(_, a)| name_key(a)),
            crate::app::InstalledSort::EnabledFirst => icons.sort_by(|(_, a), (_, b)| {
                (!a.enabled)
                    .cmp(&!b.enabled)
                    .then_with(|| name_key(a).cmp(&name_key(b)))
            }),
        },
        crate::app::IntegrationsPanelTab::Marketplace | crate::app::IntegrationsPanelTab::InDev => {
            // Icons list is empty on Marketplace / InDev tabs
            // (filtered above), but keep the sort call for symmetry
            // — the marketplace entries loop applies its own sort
            // further down.
            if matches!(app.marketplace_sort, crate::app::MarketplaceSort::Name) {
                icons.sort_by_key(|(_, a)| name_key(a));
            }
        }
    }

    // Empty-state per tab.
    // 2026-08-01 (P4c) — on Marketplace, only show empty-state when
    // BOTH the icons list AND the marketplace_entries list are
    // empty. If entries are present, we render them below (rows
    // painted after the icons loop).
    let show_empty_state = icons.is_empty()
        && !(matches!(
            active_tab,
            crate::app::IntegrationsPanelTab::Marketplace | crate::app::IntegrationsPanelTab::InDev
        ) && !app.marketplace_entries.is_empty());
    if show_empty_state {
        let msg = if !app.integrations_panel_filter.is_empty() {
            format!(
                " No matches for \"{}\" — Esc clears",
                app.integrations_panel_filter
            )
        } else {
            match active_tab {
                crate::app::IntegrationsPanelTab::Installed => {
                    " Nothing installed yet — try the Marketplace tab".to_string()
                }
                crate::app::IntegrationsPanelTab::Marketplace => {
                    // 2026-08-01 (P4b) — if the user has never fetched
                    // the marketplace, guide them to the refresh
                    // command. Once entries land they get rendered
                    // instead of hitting this empty state.
                    if app.marketplace_entries.is_empty() {
                        " No marketplace entries yet — run `marketplace.refresh`".to_string()
                    } else {
                        " Everything is installed (nice)".to_string()
                    }
                }
                crate::app::IntegrationsPanelTab::InDev => {
                    if app.marketplace_entries.is_empty() {
                        " No entries yet — run `marketplace.refresh`".to_string()
                    } else {
                        " Nothing in development — everything is ready".to_string()
                    }
                }
            }
        };
        let body = Rect {
            x: area.x,
            y: area.y + 4,
            width: area.width,
            height: 1,
        };
        frame.render_widget(
            Paragraph::new(msg).style(
                Style::default()
                    .fg(t.comment)
                    .bg(bg)
                    .add_modifier(Modifier::ITALIC),
            ),
            body,
        );
        return;
    }

    // qa-feature 2026-07-01 — register the panel body area so
    // the wheel dispatcher can scroll `integrations_panel_scroll`
    // when the cursor is over this panel. Body starts below the
    // header + tabs + filter (3 rows) with 1 row of padding.
    let body_area = Rect {
        x: area.x,
        y: area.y + 4,
        width: area.width,
        height: area.height.saturating_sub(4),
    };
    app.rects.integrations_panel_area = Some(body_area);
    // design-critic 2026-08-06 SEV-high: reserve the last column for
    // the scrollbar so row text can never overlap the `│` track or `█`
    // thumb. Was rendering rows at full `area.width` and painting the
    // scrollbar on top, clobbering the last char of every long label.
    // Every other rail pane in the app (`diagnostics_view`, `grep_view`,
    // etc.) reserves this column up-front — matching that idiom here.
    // Reserve TWO cols: one for the scrollbar (at area.width-1),
    // one for a visual gap so long truncated names don't kiss the
    // scrollbar glyph (`✓ Of█` vs `✓ Off █`). 2026-08-07 tester r6.
    let row_width = area.width.saturating_sub(2);

    // Each entry takes 3 rows: glyph+name, command dim, blank.
    // Clamp the scroll so at least one entry stays visible.
    let rows_per = 3usize;
    // 2026-08-05 — per-tab scroll state (previously one shared
    // integrations_panel_scroll for both). Switching Installed ↔
    // Marketplace now preserves each tab's scroll position.
    let scroll = match active_tab {
        crate::app::IntegrationsPanelTab::Installed => &mut app.integrations_panel_scroll_installed,
        crate::app::IntegrationsPanelTab::Marketplace => {
            &mut app.integrations_panel_scroll_marketplace
        }
        crate::app::IntegrationsPanelTab::InDev => &mut app.integrations_panel_scroll_in_dev,
    };
    // 2026-08-06 — max_scroll must include marketplace_entries on
    // the Marketplace tab, else the wheel/drag caps at the (usually
    // tiny) disabled-icon count and the user can't scroll to the
    // real marketplace list. Compute total renderable rows per tab.
    let marketplace_extra_len = if matches!(
        active_tab,
        crate::app::IntegrationsPanelTab::Marketplace | crate::app::IntegrationsPanelTab::InDev
    ) {
        let installed_ids: std::collections::HashSet<String> = app
            .config
            .ui
            .integration_icons
            .iter()
            .map(|i| i.id.clone())
            .collect();
        let installed_binaries: std::collections::HashSet<String> = app
            .config
            .ui
            .integration_icons
            .iter()
            .filter_map(|i| crate::integration_detect::integration_binary_for_command(&i.command))
            .map(|s| s.to_string())
            .collect();
        // Apply the SAME filter the render loop uses so max_scroll
        // and entries_skip stay in sync when the user has an
        // integrations-panel filter active. Reviewer flag on
        // 9670a164 — unfiltered count let scroll run past the
        // last visible row into blank space.
        let filter_lc_mp = app.integrations_panel_filter.to_ascii_lowercase();
        // 2026-08-07 — count includes installed entries (they now
        // render dimmed rather than being hidden). Keep in sync
        // with the marketplace-render loop below.
        let _ = (&installed_ids, &installed_binaries);
        let is_in_dev = matches!(active_tab, crate::app::IntegrationsPanelTab::InDev);
        app.marketplace_entries
            .iter()
            .filter(|e| {
                // #1055 / #1056 — Ready gate: Marketplace tab hides
                // App entries with `ready = false`; InDev tab hides
                // App entries with `ready = true` (mirror image).
                // Launchers / drivers always show on Marketplace but
                // never appear on InDev (they're external tools with
                // their own release cycle).
                if is_in_dev {
                    if !matches!(e.kind, crate::marketplace::MarketplaceKind::App) {
                        return false;
                    }
                    if e.ready {
                        return false;
                    }
                } else if matches!(e.kind, crate::marketplace::MarketplaceKind::App) && !e.ready {
                    return false;
                }
                if filter_lc_mp.is_empty() {
                    return true;
                }
                let hay = format!(
                    "{} {} {}",
                    e.label,
                    e.id,
                    e.description.as_deref().unwrap_or(""),
                )
                .to_ascii_lowercase();
                hay.contains(&filter_lc_mp)
            })
            .count()
    } else {
        0
    };
    let total_row_count = icons.len() + marketplace_extra_len;
    let max_scroll = total_row_count.saturating_sub(1).saturating_mul(rows_per);
    if *scroll > max_scroll {
        *scroll = max_scroll;
    }
    let skip_rows = *scroll;
    // Mirror into the legacy shared field so pre-migration callers
    // (mouse wheel etc.) still bump the currently-visible tab.
    app.integrations_panel_scroll = skip_rows;
    let mut y = area.y + 4;
    // Convert scroll to a "start icon index" that begins on a
    // 3-row boundary so we don't render half of an icon at the top.
    let start_idx = skip_rows / rows_per;
    for (idx, icon) in icons.iter().skip(start_idx) {
        let idx = *idx;
        if y + 1 >= area.y + area.height {
            break;
        }
        let glyph = if nerd {
            icon.glyph.as_str()
        } else {
            icon.fallback.as_str()
        };
        // 2026-08-08 — built-in chips get their color from the
        // single-source-of-truth `brand_color_for_builtin` so this row
        // can't drift from the split-cluster chip, palette-bar chip,
        // or Pty tab glyph. Falls back to the manifest color slot for
        // third-party integrations (and for first-party ids that don't
        // declare a brand color, like browser/http).
        let fg = theme::brand_color_for_builtin(&icon.id)
            .unwrap_or_else(|| theme::color_from_slot(icon.color.as_str(), &t));
        let name = icon
            .label
            .as_deref()
            .filter(|s| !s.is_empty())
            .unwrap_or(icon.id.as_str())
            .to_string();
        // Probe availability for `:term <binary>` commands —
        // a stale or missing binary is the only "broken" state worth
        // surfacing at v1. Internal `mnml` commands (no prefix) are
        // always assumed available.
        let availability = integration_availability(&icon.command);
        let (name_fg, suffix) = match availability {
            IntegrationAvailability::Available => (t.fg, None),
            IntegrationAvailability::Missing(bin) => {
                (t.comment, Some(format!(" ({} not installed)", bin)))
            }
        };
        // 2026-08-06 — disabled (chip-hidden) installed integrations
        // sort to the bottom AND render dimmed so the "still there,
        // just hidden from the rail" state reads at a glance.
        let disabled_dim = if icon.enabled {
            Modifier::empty()
        } else {
            Modifier::DIM
        };
        let disabled_suffix = if icon.enabled { "" } else { " (hidden)" };
        let row1 = Rect {
            x: area.x,
            y,
            width: row_width,
            height: 1,
        };
        let mut name_spans: Vec<Span<'static>> = vec![
            Span::styled(
                format!("  {glyph} "),
                Style::default().fg(fg).bg(bg).add_modifier(disabled_dim),
            ),
            Span::styled(
                name,
                Style::default()
                    .fg(name_fg)
                    .bg(bg)
                    .add_modifier(disabled_dim),
            ),
        ];
        if !disabled_suffix.is_empty() {
            name_spans.push(Span::styled(
                disabled_suffix.to_string(),
                Style::default()
                    .fg(t.comment)
                    .bg(bg)
                    .add_modifier(Modifier::DIM | Modifier::ITALIC),
            ));
        }
        if let Some(suffix) = suffix {
            name_spans.push(Span::styled(
                suffix,
                Style::default()
                    .fg(t.red)
                    .bg(bg)
                    .add_modifier(Modifier::DIM),
            ));
        }
        // #1086 (2026-08-19) — version + update chip.
        // Resolve the installed version via the manifest layer (which
        // reads it from `~/.config/mnml/integrations/<id>.toml` at
        // discovery time). Then consult the background update-check
        // cache: if `latest > current`, append `→ <latest>  [ Update ]`
        // as a clickable chip that fires the same `apply_integration_update`
        // path as the right-click menu. Non-integration built-ins (browser /
        // claude_code / codex / http / search / …) have no manifest so
        // render nothing. Cache-miss just shows `<current>` with no arrow.
        let crate_id = crate::integration_detect::integration_binary_for_command(&icon.command)
            .map(|s| s.to_string())
            .unwrap_or_else(|| icon.id.clone());
        // #1102 f/u (2026-08-20) — prefer the LIVE `<binary> --version`
        // result (in `binary_version_cache`, keyed by binary basename)
        // over the on-disk manifest's `version =` field. The manifest
        // version can go stale when the integration binary is upgraded via
        // `cargo install --force` without re-running `--install`; the
        // live query is source-of-truth.
        let installed_version: Option<String> = app
            .integration_manifests
            .iter()
            .find(|m| m.id == icon.id)
            .and_then(|m| {
                m.binary
                    .as_deref()
                    .and_then(|b| {
                        let basename = b.rsplit('/').next().unwrap_or(b);
                        app.binary_version_cache.get(basename).cloned()
                    })
                    .or_else(|| m.version.clone())
            });
        // Three-state:
        //   Some(Ok(())) — known latest, matches current → "(Current)"
        //   Some(Err(latest)) — known latest, newer than current → arrow + Update chip
        //   None — never checked, no version to compare — nothing extra
        let update_info: Option<Result<(), String>> = app
            .integration_updates
            .lock()
            .ok()
            .and_then(|g| g.get(&crate_id).cloned())
            .and_then(|c| {
                let is_upd = crate::app::integration_updates::is_update_available(&c);
                if is_upd {
                    Some(Err(c.latest.clone()))
                } else if !c.current.is_empty() && !c.latest.is_empty() {
                    Some(Ok(()))
                } else {
                    None
                }
            });
        let mut update_chip_rect: Option<(Rect, String)> = None;
        if let Some(v) = installed_version.as_ref() {
            name_spans.push(Span::styled(
                format!("  {v}"),
                Style::default().fg(t.comment).bg(bg),
            ));
            match update_info {
                Some(Err(latest)) => {
                    name_spans.push(Span::styled(
                        format!(" \u{2192} {latest}"),
                        Style::default().fg(t.green).bg(bg),
                    ));
                    let chip_text = "  [ Update ]".to_string();
                    let chip_style = Style::default()
                        .fg(t.green)
                        .bg(bg)
                        .add_modifier(Modifier::BOLD);
                    let prior_cols: usize = name_spans
                        .iter()
                        .map(|s| {
                            use unicode_width::UnicodeWidthStr;
                            UnicodeWidthStr::width(s.content.as_ref())
                        })
                        .sum();
                    use unicode_width::UnicodeWidthStr;
                    let chip_w = UnicodeWidthStr::width(chip_text.as_str()) as u16;
                    let x0 = row1
                        .x
                        .saturating_add(prior_cols.min(u16::MAX as usize) as u16);
                    let x_end = row1.x.saturating_add(row1.width);
                    if x0 < x_end {
                        update_chip_rect = Some((
                            Rect {
                                x: x0,
                                y: row1.y,
                                width: chip_w.min(x_end.saturating_sub(x0)),
                                height: 1,
                            },
                            crate_id,
                        ));
                    }
                    name_spans.push(Span::styled(chip_text, chip_style));
                }
                Some(Ok(())) => {
                    // #1088 addendum (2026-08-19) — explicit "(Current)"
                    // when we've checked and there IS a known latest that
                    // matches, so the row reads as "already up-to-date"
                    // instead of "no info".
                    name_spans.push(Span::styled(
                        "  (Current)".to_string(),
                        Style::default().fg(t.comment).bg(bg),
                    ));
                }
                None => {}
            }
        }
        frame.render_widget(Paragraph::new(ratatui::text::Line::from(name_spans)), row1);
        if let Some((rect, id)) = update_chip_rect {
            app.rects.update_chip_rects.push((rect, id));
        }
        // Register the whole row as a click target. The mouse
        // dispatcher in tui.rs walks the same `integration_icon_rects`
        // list it uses for the compact rail strip, so adding our row
        // there gives it the existing click semantics for free
        // (palette command / `:ex` prefix handling).
        app.rects.integration_icon_rects.push((row1, idx));

        if y + 1 >= area.y + area.height {
            break;
        }
        let row2 = Rect {
            x: area.x,
            y: y + 1,
            width: row_width,
            height: 1,
        };
        // 2026-08-08 — user asked to show the clean `<id>.open` form
        // instead of the raw `:term …` shell command for integration
        // integrations. `icon.command` still holds the raw string
        // because the "Add to activity bar" flow gates on the
        // `:term ` prefix; only the DISPLAY changes here.
        // Precedence: first manifest command's id (`bitbucket_prs.open`),
        // else derive `<icon.id>.open`, else fall back to raw command.
        let subtitle = icon
            .commands
            .first()
            .map(|c| c.id.clone())
            .filter(|s| !s.is_empty())
            .unwrap_or_else(|| {
                if icon.command.starts_with(":term ") || icon.command.starts_with("term ") {
                    format!("{}.open", icon.id)
                } else {
                    icon.command.clone()
                }
            });
        frame.render_widget(
            Paragraph::new(ratatui::text::Line::from(format!("    {subtitle}"))).style(
                Style::default()
                    .fg(t.comment)
                    .bg(bg)
                    .add_modifier(Modifier::DIM),
            ),
            row2,
        );
        // The second row should be clickable too — same target.
        app.rects.integration_icon_rects.push((row2, idx));

        y = y.saturating_add(3);
    }

    // 2026-08-01 (P4c) — under the icon rows on the Marketplace tab,
    // paint the fetched marketplace_entries as browsable rows.
    // Each entry: 3 rows — label + source tag, description, install
    // hint. Left-click on any row → install action.
    if matches!(
        active_tab,
        crate::app::IntegrationsPanelTab::Marketplace | crate::app::IntegrationsPanelTab::InDev
    ) {
        let filter_lc_mp = app.integrations_panel_filter.to_ascii_lowercase();
        // Skip marketplace entries for ids the user already has
        // installed — those appear in the top section of this same
        // tab (installed-but-not-enabled chips) and rendering them
        // twice reads as a bug (user report 2026-08-03: btop
        // showed up in both places after they clicked [launcher] btop).
        let installed_ids: std::collections::HashSet<String> = app
            .config
            .ui
            .integration_icons
            .iter()
            .map(|i| i.id.clone())
            .collect();
        let installed_binaries: std::collections::HashSet<String> = app
            .config
            .ui
            .integration_icons
            .iter()
            .filter_map(|i| crate::integration_detect::integration_binary_for_command(&i.command))
            .map(|s| s.to_string())
            .collect();
        // vscode-mouse r4 SEV-1 (2026-08-06) — scroll now advances
        // past the icons list into marketplace_entries. Prior code
        // painted entries starting at whatever `y` icons left off,
        // ignoring `start_idx`, so scrolling could push icons off
        // but marketplace entries stayed put — capping the visible
        // scroll at (icons.len() - 1) rows.
        //
        // Global start_idx counts icons + eligible marketplace
        // rows in one virtual list. Skip past the entries the icons
        // loop already displaced.
        let entries_skip = start_idx.saturating_sub(icons.len());
        let mut skipped = 0usize;
        // 2026-08-07 — apply the sort mode to the marketplace entries.
        // Build (original_idx, entry_ref) pairs so the render loop
        // still uses `idx` for `marketplace_row_rects` (which is a
        // stable index into `marketplace_entries`).
        let mut sorted: Vec<(usize, &crate::marketplace::MarketplaceEntry)> =
            app.marketplace_entries.iter().enumerate().collect();
        let sort_key_name = |e: &crate::marketplace::MarketplaceEntry| -> String {
            if e.label.is_empty() {
                e.id.to_ascii_lowercase()
            } else {
                e.label.to_ascii_lowercase()
            }
        };
        match app.marketplace_sort {
            crate::app::MarketplaceSort::Default => {}
            crate::app::MarketplaceSort::Name => sorted.sort_by_key(|(_, a)| sort_key_name(a)),
            crate::app::MarketplaceSort::OfficialFirst => sorted.sort_by(|(_, a), (_, b)| {
                let pa = !matches!(a.provenance, crate::marketplace::Provenance::Official);
                let pb = !matches!(b.provenance, crate::marketplace::Provenance::Official);
                pa.cmp(&pb)
                    .then_with(|| sort_key_name(a).cmp(&sort_key_name(b)))
            }),
            crate::app::MarketplaceSort::Kind => sorted.sort_by(|(_, a), (_, b)| {
                // App < Launcher; drivers (naming convention) get their
                // own bucket sorted last.
                let bucket = |e: &crate::marketplace::MarketplaceEntry| -> u8 {
                    let is_driver = e.id.contains("-driver-") || e.id.ends_with("-driver");
                    if is_driver {
                        2
                    } else {
                        match e.kind {
                            crate::marketplace::MarketplaceKind::App => 0,
                            crate::marketplace::MarketplaceKind::Launcher => 1,
                        }
                    }
                };
                bucket(a)
                    .cmp(&bucket(b))
                    .then_with(|| sort_key_name(a).cmp(&sort_key_name(b)))
            }),
        }
        // 2026-08-19 (#1056) — the InDev tab is the mirror image of
        // the Marketplace gate: instead of hiding App entries with
        // `ready = false`, it hides everything ELSE (launchers,
        // drivers, and ready App entries). Precomputed once so the
        // per-entry check stays cheap.
        let is_in_dev_tab = matches!(active_tab, crate::app::IntegrationsPanelTab::InDev);
        for (idx, entry) in sorted.into_iter() {
            // 2026-08-19 (#1055 / #1056) — Ready gate.
            //  * Marketplace: hide App entries where `ready = false`
            //    (author hasn't declared them ready). Launchers and
            //    drivers bypass — they're external tools with their
            //    own publish criteria, not authored integrations.
            //  * InDev: mirror — show ONLY App entries with
            //    `ready = false`. Launchers/drivers never appear.
            if is_in_dev_tab {
                if !matches!(entry.kind, crate::marketplace::MarketplaceKind::App) {
                    continue;
                }
                if entry.ready {
                    continue;
                }
            } else if matches!(entry.kind, crate::marketplace::MarketplaceKind::App) && !entry.ready
            {
                continue;
            }
            // 2026-08-07 — installed entries stay visible in the
            // Marketplace list but render greyed with an `[installed]`
            // tag replacing `[app]`/`[launcher]`/`[driver]`. Click
            // still opens the detail view (which shows install /
            // uninstall). Was: `continue` here, so installed items
            // disappeared entirely from the marketplace tab and users
            // had no obvious visual for "already installed" (user
            // report 2026-08-07 — "when an integration is installed
            // should it remain on marketplace tab but be greyed out").
            let is_installed =
                installed_ids.contains(&entry.id) || installed_binaries.contains(&entry.id);
            // Filter by the same query string the icon list uses.
            if !filter_lc_mp.is_empty() {
                let hay = format!(
                    "{} {} {}",
                    entry.label,
                    entry.id,
                    entry.description.as_deref().unwrap_or("")
                )
                .to_ascii_lowercase();
                if !hay.contains(&filter_lc_mp) {
                    continue;
                }
            }
            // Advance past scroll offset (post-filter so the count
            // matches marketplace_extra_len used by max_scroll).
            if skipped < entries_skip {
                skipped += 1;
                continue;
            }
            if y + 1 >= area.y + area.height {
                break;
            }
            // 2026-08-05 — driver crates (mnml-db-driver-*) render
            // as `[driver]` in purple (DB family color) so the
            // marketplace visually groups them apart from apps.
            let is_driver = entry.id.contains("-driver-") || entry.id.ends_with("-driver");
            let (kind_tag, kind_fg) = if is_installed {
                // 2026-08-07 design-critic r2 #4: was `t.green` which
                // collided with `✓ Official`'s green two spans over
                // (both at full brightness — the dim modifier only
                // reaches the label text between them). `t.comment`
                // bold matches the "already on your system, secondary
                // information" tone.
                ("[installed]", t.comment)
            } else if is_driver {
                ("[driver]", t.purple)
            } else {
                match entry.kind {
                    crate::marketplace::MarketplaceKind::App => ("[app]", t.orange),
                    crate::marketplace::MarketplaceKind::Launcher => ("[launcher]", t.cyan),
                }
            };
            // Installed entries dim the whole row so they still read
            // as "on your system" at a glance vs. installable options.
            let row_fg = if is_installed { t.comment } else { t.fg };
            let row_mod = if is_installed {
                Modifier::DIM
            } else {
                Modifier::empty()
            };
            let row1 = Rect {
                x: area.x,
                y,
                width: row_width,
                height: 1,
            };
            // #849 UI phase — Official / Community provenance chip
            // between the label and the source-id tag. Green ✓ =
            // an entry from a mnml-shipped default source; grey ~ =
            // any user-added or third-party source.
            let (prov_glyph, prov_label, prov_fg) = match entry.provenance {
                crate::marketplace::Provenance::Official => ("", "Official", t.green),
                crate::marketplace::Provenance::Community => ("~", "Community", t.comment),
            };
            // 2026-08-05 — leading glyph column ONLY when the
            // catalog knows this entry. Unknown entries skip the
            // glyph entirely (previous attempt: a package-icon
            // fallback rendered as tofu because MnmlSymbols didn't
            // have F0487, and any letter fallback looked worse than
            // clean whitespace).
            let entry_glyph_span: Option<Span<'static>> = entry.glyph.as_ref().map(|g| {
                let fg = entry
                    .color
                    .as_deref()
                    .map(|c| crate::ui::theme::color_from_slot(c, &t))
                    .unwrap_or(t.fg);
                Span::styled(format!("  {g}  "), Style::default().fg(fg).bg(bg))
            });
            let mut name_spans: Vec<Span<'static>> = Vec::with_capacity(6);
            if let Some(g) = entry_glyph_span {
                name_spans.push(g);
                name_spans.push(Span::styled(
                    format!("{kind_tag} "),
                    Style::default().fg(kind_fg).bg(bg),
                ));
            } else {
                name_spans.push(Span::styled(
                    format!("  {kind_tag} "),
                    Style::default().fg(kind_fg).bg(bg),
                ));
            }
            name_spans.push(Span::styled(
                entry.label.clone(),
                Style::default().fg(row_fg).bg(bg).add_modifier(row_mod),
            ));
            // 2026-08-15 — CargoGit (private-repo) entries are neither
            // Official nor Community — they came in from a user-added
            // `github_monorepo_apps` source pointing at a private repo.
            // The `Private` chip below carries the "you added this
            // source" signal on its own; showing `~ Community` here too
            // would misleadingly imply third-party open-source origin.
            let is_private = matches!(
                entry.install,
                crate::marketplace::InstallSpec::CargoGit { .. }
            );
            if !is_private {
                name_spans.push(Span::styled(
                    format!("  {prov_glyph} {prov_label}"),
                    Style::default().fg(prov_fg).bg(bg),
                ));
            }
            // 2026-08-19 (user feedback) — Ready badge dropped. Since
            // the Ready gate above hides unready App entries entirely
            // (they show only on the InDev tab), every row on the
            // Marketplace tab is ready by construction. The badge was
            // just visual noise on every single row. If the app-manifest-
            // level `ready` bit ever lands (#1055 follow-up), community
            // authors' unready entries surface elsewhere, not here.
            // 2026-08-15 — `[Private]` chip for CargoGit installs
            // (github_monorepo_apps source). Tells the user "this
            // isn't on crates.io — cargo will shell to git; make
            // sure you have repo access." Distinct from Verified;
            // the two can coexist on the same row.
            if is_private {
                name_spans.push(Span::styled(
                    "  Private".to_string(),
                    Style::default().fg(t.yellow).bg(bg),
                ));
            }
            name_spans.push(Span::styled(
                format!("  ({})", entry.source_id),
                Style::default()
                    .fg(t.comment)
                    .bg(bg)
                    .add_modifier(Modifier::DIM),
            ));
            // 2026-08-16 — "↑ Update to <ver>" / "✓ Up to date" chip
            // rendered ONLY on rows that are already installed AND we
            // have a fresh update-check result from the background
            // worker. The chip is appended to the line's spans (right
            // of the existing chips); its rect is computed by
            // summing the prior spans' display widths so mouse hit-
            // testing lands precisely on the chip glyph + label.
            //
            // Held across the borrow because `app.rects.push` below
            // needs `&mut app`, but the map lookup needs `&app`. The
            // whole map is cloned per row — cheap for the ~dozens of
            // installed integrations we ever see; nothing else holds
            // this lock long enough to matter.
            let update_chip: Option<(String, ratatui::style::Color, bool)> = if is_installed {
                app.integration_updates
                    .lock()
                    .ok()
                    .and_then(|g| g.get(&entry.id).cloned())
                    .map(|c| {
                        if crate::app::integration_updates::is_update_available(&c) {
                            // #1086 — show `current → latest` when we have
                            // both, so the user knows how far behind they
                            // are without hovering. Falls back to the
                            // shorter form when current is missing (fresh
                            // cache).
                            let label = if !c.current.is_empty() {
                                format!("  \u{2191} {} \u{2192} {}", c.current, c.latest)
                            } else {
                                format!("  \u{2191} Update to {}", c.latest)
                            };
                            (label, t.green, true)
                        } else {
                            // Pin the version on "up to date" too so
                            // users see WHAT they're up to date at.
                            let label = if !c.current.is_empty() {
                                format!("  \u{2713} {}", c.current)
                            } else {
                                "  \u{2713} Up to date".to_string()
                            };
                            (label, t.comment, false)
                        }
                    })
            } else {
                None
            };
            if let Some((label, fg, clickable)) = &update_chip {
                let mut style = Style::default().fg(*fg).bg(bg);
                if *clickable {
                    style = style.add_modifier(Modifier::BOLD);
                } else {
                    style = style.add_modifier(Modifier::DIM);
                }
                // Sum the display widths of the spans painted so far
                // to derive the chip's origin. Saturating math keeps
                // a narrow terminal from underflowing.
                let prior_cols: usize = name_spans
                    .iter()
                    .map(|s| {
                        use unicode_width::UnicodeWidthStr;
                        UnicodeWidthStr::width(s.content.as_ref())
                    })
                    .sum();
                let chip_w = {
                    use unicode_width::UnicodeWidthStr;
                    UnicodeWidthStr::width(label.as_str()) as u16
                };
                let x0 = row1
                    .x
                    .saturating_add(prior_cols.min(u16::MAX as usize) as u16);
                let x_end = row1.x.saturating_add(row1.width);
                if x0 < x_end && clickable == &true {
                    // Only register a click rect on the actionable
                    // "↑ Update to <ver>" chip. "Up to date" is a
                    // passive indicator.
                    let chip_rect = Rect {
                        x: x0,
                        y: row1.y,
                        width: chip_w.min(x_end.saturating_sub(x0)),
                        height: 1,
                    };
                    app.rects
                        .update_chip_rects
                        .push((chip_rect, entry.id.clone()));
                }
                name_spans.push(Span::styled(label.clone(), style));
            }
            frame.render_widget(Paragraph::new(ratatui::text::Line::from(name_spans)), row1);
            app.rects.marketplace_row_rects.push((row1, idx));

            if y + 2 >= area.y + area.height {
                y = y.saturating_add(3);
                continue;
            }
            let row2 = Rect {
                x: area.x,
                y: y + 1,
                width: row_width,
                height: 1,
            };
            let desc = entry.description.as_deref().unwrap_or("(no description)");
            frame.render_widget(
                Paragraph::new(ratatui::text::Line::from(format!("    {}", desc))).style(
                    Style::default()
                        .fg(t.comment)
                        .bg(bg)
                        .add_modifier(Modifier::DIM),
                ),
                row2,
            );
            app.rects.marketplace_row_rects.push((row2, idx));
            y = y.saturating_add(3);
        }
    }

    // 2026-07-03 — scrollbar on the far-right column of the panel
    // body. Renders whenever the visible-tab row list is taller than
    // the body area.
    //
    // 2026-08-05 — count TAB-SPECIFIC rows so the Marketplace tab
    // (which paints both `icons` + `marketplace_entries` below the
    // icon list) doesn't undercount and hide the scrollbar.
    let body_h = body_area.height as usize;
    let visible_rows = (body_h / rows_per).max(1);
    let total_rows = total_row_count;
    if total_rows > visible_rows {
        let track_x = area.x + area.width.saturating_sub(1);
        let track_h = body_area.height;
        // Fill the track with a dim rail glyph.
        for row_y in 0..track_h {
            let cell = Rect {
                x: track_x,
                y: body_area.y + row_y,
                width: 1,
                height: 1,
            };
            frame.render_widget(
                Paragraph::new("").style(Style::default().fg(t.comment).bg(bg)),
                cell,
            );
        }
        // Thumb sizing: proportional to visible/total; min 1
        // cell so it's always visible.
        let thumb_h = ((visible_rows * track_h as usize) / total_rows).max(1) as u16;
        // Thumb offset: proportional to how far we've scrolled,
        // capped so thumb never overflows the track.
        let max_scroll_rows = total_rows.saturating_sub(visible_rows);
        let scrolled_rows = (app.integrations_panel_scroll / rows_per).min(max_scroll_rows);
        let track_movable = track_h.saturating_sub(thumb_h);
        let thumb_offset = if max_scroll_rows == 0 {
            0
        } else {
            (scrolled_rows as u32 * track_movable as u32 / max_scroll_rows as u32) as u16
        };
        for row_y in thumb_offset..(thumb_offset + thumb_h).min(track_h) {
            let cell = Rect {
                x: track_x,
                y: body_area.y + row_y,
                width: 1,
                height: 1,
            };
            frame.render_widget(
                Paragraph::new("").style(Style::default().fg(t.fg).bg(bg)),
                cell,
            );
        }
    }

    // 2026-07-19 — the `+ Add integration` chip that used to
    // paint here is retired. The panel now has an explicit
    // `Marketplace` tab at the top of the header that lists
    // everything installable — the chip was a duplicate entry
    // point. `integrations_add_chip` rect stays in `PaneRects`
    // as None so no click routes to it.
    let _ = area; // width no longer consumed here
}

/// Paint a multi-tab strip above an in-split leaf, one chip per
/// pane in the leaf's `tabs`. Post-2026-07-08 tab-refactor: chip
/// composition (glyph + name + diag + badge + verb split) goes
/// through the shared `ui::bufferline::paint_tab_chip` — active
/// chips get `t.bg` (not `t.bg2` as an earlier version had),
/// matching the top bufferline. Layout math (overflow, gap
/// between chips, right-cluster reservation) stays here.
/// Click chip → switch active. Click × → close that tab.
#[allow(clippy::too_many_arguments)]
fn paint_leaf_tab_strip_with_hidden(
    frame: &mut Frame,
    app: &mut App,
    active: crate::layout::PaneId,
    tabs: &[crate::layout::PaneId],
    hidden_tab_count: usize,
    strip: Rect,
    leaf_focused: bool,
) {
    use crate::pane::Pane;
    use ratatui::style::{Modifier, Style};
    use ratatui::text::{Line, Span};
    use ratatui::widgets::Paragraph;
    let t = theme::cur();
    let nerd = !app.config.ui.ascii_icons;

    // Paint the strip bg first so gaps between chips read as the
    // un-tabbed bar background, not random terminal fill.
    let strip_bg = t.bg_darker;
    frame.render_widget(
        Paragraph::new("").style(Style::default().bg(strip_bg)),
        strip,
    );

    // Per-chip layout: ` <icon> <name>[•] <× >`. Min name width 4
    // so chips with short names don't squish to nothing.
    let chip_max_name_w: usize = 18;

    // 2026-06-22 — VS Code-style split-editor buttons at the
    // far right of the strip. Reserve 6 cells (` ⊟ ` + ` ⊞ `,
    // 3 each) before laying tabs so chips don't overflow into
    // the buttons. Tabs that don't fit get clipped per the
    // existing chip_w logic.
    const SPLIT_BTN_W: u16 = 3;
    // Three base buttons (terminal + V-split + H-split) plus the
    // optional AI button(s). `"both"` mode shows 2 AI chips.
    // Graceful degradation: on narrow leaves the AI chips drop
    // out (Codex first, then Claude) so terminal + splits are
    // never sacrificed. design-critic 2026-07-09 SEV-2.
    // 2026-08-07 — was: `tab_bar_ai_icon` default of "claude_code"
    // meant the per-leaf strip auto-rendered a Claude chip even when
    // the integration was disabled. Result: opening a Pty pane
    // suddenly showed Claude Code in the split cluster when the user
    // hadn't enabled it. Now: derive purely from `enabled` state,
    // matching `paint_split_buttons` in bufferline. `tab_bar_ai_icon`
    // becomes an override — if user explicitly set it to "none" we
    // honor that; otherwise it's ignored.
    let ai_kind_cfg = app.config.ui.tab_bar_ai_icon.as_str();
    let ic_enabled = |id: &str| -> bool {
        app.config
            .ui
            .integration_icons
            .iter()
            .any(|ic| ic.id == id && ic.enabled)
    };
    let mut ai_button_count: u16 = if ai_kind_cfg == "none" {
        0
    } else {
        [ic_enabled("claude_code"), ic_enabled("codex")]
            .iter()
            .filter(|b| **b)
            .count() as u16
    };
    // Terminal + Vertical-split + Horizontal-split + Maximize/Restore.
    // Maximize joined this cluster 2026-08-18 (#1018) — a click-to-zoom
    // control matching the VS Code ⛶ affordance, wired to
    // `App::toggle_zoom_active_leaf`.
    let base_split_w: u16 = SPLIT_BTN_W * 4;
    while strip.width < base_split_w + ai_button_count * SPLIT_BTN_W && ai_button_count > 0 {
        ai_button_count -= 1;
    }
    let split_btns_total: u16 = base_split_w + ai_button_count * SPLIT_BTN_W;
    // #polish 2026-07-06 — per-leaf mode chip (Preview / Edit) for a
    // markdown editor / preview in this leaf. Sits between the tab
    // strip and the split buttons — same visual position as on the
    // top-level bufferline.
    let mode_chip = crate::ui::bufferline::mode_chip_for_pane(app, active);
    let mode_chip_w: u16 = mode_chip
        .as_ref()
        .map(|(label, _, _)| label.chars().count() as u16)
        .unwrap_or(0);
    let mut chip_x = strip.x;
    let strip_right = strip.x + strip.width;
    let tabs_right = strip_right.saturating_sub(split_btns_total + mode_chip_w);

    // 2026-07-08 stage-1 unification: per-chip painting now goes
    // through `bufferline::paint_tab_chip` — the same function the
    // top bufferline uses. Per-leaf chips gain diagnostics badges,
    // Request-pane verb splitting, and pin/dirty/preview semantics
    // identical to the top strip; the divergence that produced
    // "gremlins" is gone. Layout math (overflow break, gap between
    // chips) stays here; the caller still owns rect registration.
    //
    // Tester-round SEV-2 fix — track how many tabs we couldn't fit
    // so the "+N hidden" chip surfaces the overflow (previously only
    // the ActivitySection::Http filter path fed `hidden_tab_count`;
    // strip clipping was silent).
    let mut painted_count: usize = 0;
    for &id in tabs {
        if chip_x >= tabs_right {
            break;
        }
        let Some(pane) = app.panes.get(id) else {
            continue;
        };
        let (glyph, icon_color) = icon_for_pane(app, pane, nerd);
        let verb_split = if matches!(pane, Pane::Request(_)) {
            crate::ui::bufferline::split_http_verb(&pane.title())
        } else {
            None
        };
        let (diag_chip, diag_severity) =
            crate::ui::bufferline::diag_chip_for(pane, &app.config.ui.bufferline_diag_style);
        let inputs = crate::ui::bufferline::TabChipInputs {
            id,
            glyph,
            icon_color,
            name: pane.title(),
            is_active: id == active,
            is_dirty: pane.is_dirty(),
            is_pinned: matches!(pane, Pane::Editor(b) if b.is_pinned),
            is_preview: matches!(pane, Pane::Editor(b) if b.is_preview)
                || matches!(pane, Pane::Request(rp) if rp.is_preview),
            is_hovered: app.hovered_bufferline_tab == Some(id),
            diag_chip,
            diag_severity,
            verb_split,
            name_cap: chip_max_name_w,
        };
        let avail = tabs_right.saturating_sub(chip_x);
        let Some(rects) = crate::ui::bufferline::paint_tab_chip(
            frame,
            Rect {
                x: chip_x,
                y: strip.y,
                width: 0,
                height: 1,
            },
            &inputs,
            strip_bg,
            avail,
            nerd,
        ) else {
            break;
        };
        app.rects.split_tab_chips.push((rects.chip, active, id));
        if let Some(close) = rects.close {
            app.rects.split_tab_close.push((close, active, id));
        }
        chip_x = chip_x.saturating_add(rects.chip.width);
        // 1-cell gap between chips (strip bg shows through).
        chip_x = chip_x.saturating_add(1);
        painted_count += 1;
    }
    let _ = leaf_focused;
    // Roll silently-clipped tabs into the same `+N hidden` chip the
    // HTTP filter uses. Both paths converge here so a leaf that's
    // filtered AND overflowing reports the total (fix for SEV-2 in
    // tester-round-20260803-personas — `layout.merge_to_tabs` on
    // a 10-tab result strip rendered 5 chips + zero discoverability).
    let overflow_hidden = tabs.len().saturating_sub(painted_count);
    let hidden_tab_count = hidden_tab_count.saturating_add(overflow_hidden);

    // one-tab-type 2026-07-18 — a `+` chip immediately after the
    // last tab in this leaf's strip. Click → focus this leaf +
    // open the file picker so the user can add another buffer to
    // this leaf. Only render when there's room (before mode chip +
    // split buttons cluster).
    let plus_glyph = if nerd { "\u{F0415}" } else { "+" };
    let plus_w = 3u16; // ` + `
    let mode_chip_w = mode_chip
        .as_ref()
        .map(|(l, _, _)| l.chars().count() as u16)
        .unwrap_or(0);
    let reserved_right = split_btns_total + mode_chip_w;
    if chip_x + plus_w <= strip_right.saturating_sub(reserved_right) {
        let plus_rect = Rect {
            x: chip_x,
            y: strip.y,
            width: plus_w,
            height: 1,
        };
        // 2026-07-18 — paint the 3 cells with `t.bg` (same as an
        // active tab's chip bg) so `+` reads as its own little
        // mini-tab pill, not floating punctuation on the strip.
        let plus_bg = t.bg;
        frame.render_widget(
            Paragraph::new(Line::from(vec![
                Span::styled(" ", Style::default().bg(plus_bg)),
                Span::styled(
                    plus_glyph,
                    Style::default()
                        .fg(t.green)
                        .bg(plus_bg)
                        .add_modifier(Modifier::BOLD),
                ),
                Span::styled(" ", Style::default().bg(plus_bg)),
            ])),
            plus_rect,
        );
        app.rects.split_tab_plus_buttons.push((plus_rect, active));
    }
    // 2026-08-01 — "+N hidden" chip when the caller filtered tabs
    // out of the strip (currently only ActivitySection::Http does).
    // Signals that the missing tabs still exist, so switching back
    // to Explorer brings them back. Chip paints just past the last
    // tab / `+` chip, still bounded by mode chip + split buttons.
    if hidden_tab_count > 0 {
        // Recompute the leftmost x this chip could occupy — it's
        // the same slot `+` would go into, offset by the `+` width
        // when the `+` was drawn.
        let after_plus_x = if chip_x + plus_w <= strip_right.saturating_sub(reserved_right) {
            chip_x + plus_w
        } else {
            chip_x
        };
        let label = format!(" +{hidden_tab_count} hidden ");
        let label_w = label.chars().count() as u16;
        if after_plus_x + label_w <= strip_right.saturating_sub(reserved_right) {
            let chip_rect = Rect {
                x: after_plus_x,
                y: strip.y,
                width: label_w,
                height: 1,
            };
            frame.render_widget(
                Paragraph::new(Line::from(Span::styled(
                    label,
                    Style::default().fg(t.comment).bg(t.bg2),
                ))),
                chip_rect,
            );
        }
    }

    // #polish 2026-07-06 — mode chip (Preview / Edit) painted in the
    // strip between tabs and the split buttons.
    if let Some((label, kind, pid)) = mode_chip {
        let chip_w = label.chars().count() as u16;
        let chip_x = strip_right.saturating_sub(split_btns_total + chip_w);
        let chip_rect = Rect {
            x: chip_x,
            y: strip.y,
            width: chip_w,
            height: 1,
        };
        let (fg, bg) = match kind {
            crate::ui::bufferline::ModeChipKind::EditorMd => (t.bg_darker, t.purple),
            crate::ui::bufferline::ModeChipKind::PreviewMd => (t.bg_darker, t.blue),
        };
        frame.render_widget(
            Paragraph::new(Line::from(Span::styled(
                label.to_string(),
                Style::default().fg(fg).bg(bg).add_modifier(Modifier::BOLD),
            ))),
            chip_rect,
        );
        match kind {
            crate::ui::bufferline::ModeChipKind::EditorMd => {
                app.rects.editor_md_preview_buttons.push((chip_rect, pid))
            }
            crate::ui::bufferline::ModeChipKind::PreviewMd => {
                app.rects.md_preview_edit_buttons.push((chip_rect, pid))
            }
        }
    }

    // VS Code-style split-editor + terminal buttons on the far
    // right of the strip. Three glyphs (terminal, vertical-split,
    // horizontal-split), each in a 3-cell ` <glyph> ` button.
    // Terminal click → focus this leaf + open a shell. Split
    // clicks → focus this leaf + split_active(dir).
    // Glyph naming follows the *visual* layout, not the
    // SplitDir axis label. See `bufferline::paint_split_buttons`.
    // Route through the custom-glyph map so `[ui] terminal_glyph_svg`
    // (e.g. ghostty) shows here too — same as bufferline's H/V
    // split cluster. Was: hardcoded EA85 (nf-cod-terminal) which
    // reverted the ghostty glyph the moment a pane opened.
    let term_glyph_owned: String = if nerd {
        app.integration_glyph_codepoints
            .get("terminal")
            .and_then(|&cp| char::from_u32(cp))
            .map(|c| c.to_string())
            .unwrap_or_else(|| "\u{ea85}".to_string())
    } else {
        "$".to_string()
    };
    let term_glyph = term_glyph_owned.as_str();
    let side_by_side_glyph = if nerd { "\u{eb56}" } else { "|" };
    let stacked_glyph = if nerd { "\u{eb57}" } else { "-" };
    let dim_fg = t.comment;
    let mut bx = strip_right.saturating_sub(split_btns_total);

    // AI button(s), leftmost in cluster. `ai_button_count` was
    // downgraded above based on strip width, so a "both" config
    // on a 12-cell strip will paint 1 chip (Claude wins), and 9
    // cells will paint 0 chips. Terminal + splits are never
    // dropped.
    // 2026-08-07 — pure enabled-based (matches the top bufferline).
    // ai_button_count already accounts for width downgrade above; if
    // ai_button_count == 0 we render nothing.
    let mut ai_kinds: Vec<&'static str> = Vec::new();
    if ai_button_count > 0 && ic_enabled("claude_code") {
        ai_kinds.push("claude_code");
    }
    if ai_button_count > 0 && ic_enabled("codex") {
        ai_kinds.push("codex");
    }
    // Trim to ai_button_count in case width already downgraded.
    ai_kinds.truncate(ai_button_count as usize);
    for kind in &ai_kinds {
        let (ai_glyph, ai_fallback, ai_fg) =
            theme::ai_chip_parts_for(kind, &t, app.config.ui.ai_chip_use_mnml_glyphs);
        let glyph = if nerd { ai_glyph } else { ai_fallback };
        let ai_rect = Rect {
            x: bx,
            y: strip.y,
            width: SPLIT_BTN_W,
            height: 1,
        };
        let line = Line::from(vec![
            Span::styled(" ", Style::default().bg(strip_bg)),
            Span::styled(glyph, Style::default().fg(ai_fg).bg(strip_bg)),
            Span::styled(" ", Style::default().bg(strip_bg)),
        ]);
        frame.render_widget(Paragraph::new(line), ai_rect);
        let tag = if *kind == "codex" { 1u8 } else { 0u8 };
        app.rects
            .split_strip_ai_buttons
            .push((ai_rect, Some(active), tag));
        bx = bx.saturating_add(SPLIT_BTN_W);
    }

    // Terminal button.
    {
        let term_rect = Rect {
            x: bx,
            y: strip.y,
            width: SPLIT_BTN_W,
            height: 1,
        };
        let line = Line::from(vec![
            Span::styled(" ", Style::default().bg(strip_bg)),
            Span::styled(
                term_glyph,
                Style::default()
                    .fg(ratatui::style::Color::White)
                    .bg(strip_bg),
            ),
            Span::styled(" ", Style::default().bg(strip_bg)),
        ]);
        frame.render_widget(Paragraph::new(line), term_rect);
        app.rects
            .split_strip_term_buttons
            .push((term_rect, Some(active)));
        bx = bx.saturating_add(SPLIT_BTN_W);
    }

    for (glyph, dir) in [
        (side_by_side_glyph, crate::layout::SplitDir::Horizontal),
        (stacked_glyph, crate::layout::SplitDir::Vertical),
    ] {
        let btn_rect = Rect {
            x: bx,
            y: strip.y,
            width: SPLIT_BTN_W,
            height: 1,
        };
        let line = Line::from(vec![
            Span::styled(" ", Style::default().bg(strip_bg)),
            Span::styled(glyph, Style::default().fg(dim_fg).bg(strip_bg)),
            Span::styled(" ", Style::default().bg(strip_bg)),
        ]);
        frame.render_widget(Paragraph::new(line), btn_rect);
        app.rects
            .split_strip_buttons
            .push((btn_rect, Some(active), dir));
        bx = bx.saturating_add(SPLIT_BTN_W);
    }

    // Maximize / Restore button — #1018. Rightmost in the cluster so
    // it's the natural "grab and expand" affordance. Glyph flips
    // between expand and restore based on `App::zoomed_leaf` so the
    // button self-documents state. Cyan when zoom is live so it's
    // visibly different from the neutral splits — matches VS Code's
    // "you're in a zoomed editor" tint.
    //
    // #1096 (2026-08-20) — when in full-screen mode the leaf zoom is
    // moot (there's no chrome to zoom away from), so the button
    // repurposes as a "compress = exit full-screen" affordance. Same
    // inward-arrow glyph + cyan tint so mouse users have a click
    // target for exiting; the tab strip is the only visible chrome
    // left, so this is where it belongs. See click handler in
    // `tui/mouse/down_left.rs` — special-cases `fullscreen_mode`.
    let is_zoomed_here = app.zoomed_leaf == Some(active);
    let is_in_fullscreen = app.fullscreen_mode;
    let (max_glyph, max_color) = if nerd {
        if is_in_fullscreen || is_zoomed_here {
            // Compress = exit-fullscreen / exit-zoom.
            ("\u{f066}", t.cyan)
        } else {
            // Expand = enter-zoom.
            ("\u{f065}", dim_fg)
        }
    } else if is_in_fullscreen || is_zoomed_here {
        ("]", t.cyan)
    } else {
        ("[", dim_fg)
    };
    let max_rect = Rect {
        x: bx,
        y: strip.y,
        width: SPLIT_BTN_W,
        height: 1,
    };
    let line = Line::from(vec![
        Span::styled(" ", Style::default().bg(strip_bg)),
        Span::styled(max_glyph, Style::default().fg(max_color).bg(strip_bg)),
        Span::styled(" ", Style::default().bg(strip_bg)),
    ]);
    frame.render_widget(Paragraph::new(line), max_rect);
    app.rects
        .split_strip_maximize_buttons
        .push((max_rect, Some(active)));
}

/// Paint the `+ Add Claude Code` card into the BR quadrant of the
/// Claude 2×2 auto-tile layout. `App::ai_placeholder_slot` marks
/// this quadrant as live; click routing consults
/// `app.rects.ai_placeholder_card`.
fn paint_ai_placeholder_card(frame: &mut Frame, app: &mut App, area: Rect) {
    use ratatui::style::{Color, Modifier, Style};
    use ratatui::text::{Line, Span};
    use ratatui::widgets::Paragraph;
    if area.width < 8 || area.height < 3 {
        return;
    }
    let t = theme::cur();
    let nerd = !app.config.ui.ascii_icons;
    let plus_glyph = if nerd { "\u{F0415}" } else { "+" };
    // Faint frame: paint the whole area in the panel bg then a
    // dim border so the quadrant reads as a card, not blank space.
    for row in area.y..area.y.saturating_add(area.height) {
        let strip = Rect {
            x: area.x,
            y: row,
            width: area.width,
            height: 1,
        };
        frame.render_widget(
            Paragraph::new(Span::styled(
                " ".repeat(area.width as usize),
                Style::default().bg(t.bg),
            )),
            strip,
        );
    }
    // Center the chip. Label: `+ Add Claude Code` when there's
    // room, `+ Claude` when the quadrant is tight.
    let full_label = " Add Claude Code";
    let short_label = " Claude";
    let use_full =
        area.width >= (plus_glyph.chars().count() as u16 + full_label.chars().count() as u16 + 4);
    let label = if use_full { full_label } else { short_label };
    let chip_text_w = plus_glyph.chars().count() as u16 + label.chars().count() as u16;
    let chip_w = chip_text_w + 2; // 1-cell padding on each side
    if area.width < chip_w {
        return;
    }
    let cx = area.x + area.width.saturating_sub(chip_w) / 2;
    let cy = area.y + area.height / 2;
    let chip_rect = Rect {
        x: cx,
        y: cy,
        width: chip_w,
        height: 1,
    };
    let chip_bg = Color::Rgb(60, 60, 60); // subtle grey — reads as a button
    frame.render_widget(
        Paragraph::new(Line::from(vec![
            Span::styled(" ", Style::default().bg(chip_bg)),
            Span::styled(
                plus_glyph,
                Style::default()
                    .fg(t.green)
                    .bg(chip_bg)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(label, Style::default().fg(t.fg).bg(chip_bg)),
            Span::styled(" ", Style::default().bg(chip_bg)),
        ])),
        chip_rect,
    );
    app.rects.ai_placeholder_card = Some(chip_rect);
}

/// Pick a `(glyph, color)` for any pane kind — duplicates the
/// dispatch in `bufferline::draw` but kept inline here so the
/// per-leaf tab strip doesn't need a public API on bufferline.
/// Rich Pty icon: integration branded glyph when the pane's
/// profile.label matches a configured integration (Claude Code /
/// Codex / mnml-forge-bitbucket / …), animated Claude spinner when
/// Claude is thinking, breathing color when Codex is thinking. Falls
/// through to the generic ghost glyph for unmatched shells. Ported
/// from the retired top-bufferline Pty branch.
fn pty_icon(
    app: &crate::app::App,
    s: &crate::pty_pane::PtySession,
    nerd: bool,
) -> (String, ratatui::style::Color) {
    let tt = theme::cur();
    let profile_label = s.profile.label.as_str();
    let profile_label_lower = profile_label.to_ascii_lowercase();
    // 2026-07-19 — deterministic matching path. When a Pty was
    // launched from a rail chip, the dispatcher stamps that chip's
    // `IntegrationIcon.id` onto `profile.integration_id`. Look it
    // up by exact id — no substring guessing on labels or args.
    // Only falls through to the label heuristic (below) for panes
    // that weren't launched via a chip (raw `:term`, restored
    // sessions with no stamped id, etc.).
    let integration_glyph = if let Some(id) = &s.profile.integration_id {
        app.config
            .ui
            .integration_icons
            .iter()
            .find(|ic| &ic.id == id)
            .map(|ic| (ic.glyph.clone(), theme::color_from_slot(&ic.color, &tt)))
    } else {
        // Legacy heuristic — profile.label case-insensitive
        // against ic.id, then a couple of args-based fallbacks
        // for panes older than the integration_id stamping.
        let profile_label_normalized = profile_label_lower.replace(' ', "_");
        let profile_args = s.profile.args.join(" ").to_ascii_lowercase();
        app.config
            .ui
            .integration_icons
            .iter()
            .find(|ic| {
                if ic.id.eq_ignore_ascii_case(&profile_label_normalized) {
                    return true;
                }
                let cmd = ic.command.as_str();
                let Some(bin) = cmd.strip_prefix(":term ").map(str::trim) else {
                    return false;
                };
                if bin.split('-').next_back() == Some(profile_label) {
                    return true;
                }
                profile_args.contains(&bin.to_ascii_lowercase())
                    || profile_args.contains(&profile_label_lower)
            })
            .map(|ic| (ic.glyph.clone(), theme::color_from_slot(&ic.color, &tt)))
    };
    let spinner = s.current_spinner_glyph();
    let is_codex = profile_label_lower == "codex";
    let codex_thinking = is_codex && s.is_codex_thinking();
    // 2026-07-22 — plain shells + generic terminals get the same
    // codicon `` (U+EA85) that the split-strip terminal chip
    // uses in the CC/H/V cluster. 2026-07-25 — added "terminal"
    // (was falling through to the fallback because :term with no
    // explicit binary uses profile.label = "terminal"). Also
    // swapped the fallback from `\u{F001D}` (nf-md-airplane — a
    // literal airplane, matches user's "why is it a plane?"
    // report) to `\u{ea85}` (nf-cod-terminal) so ANY unmatched
    // Pty gets the standard terminal icon, not a random glyph.
    // Match the label OR its leading word (labels from
    // `BinaryProfile::shell` are `"<terminal_label> (<shell_name>)"`
    // — first word is the terminal brand, "terminal" by default but
    // e.g. "ghostty" when [ui] terminal_label overrides it).
    let leading_word = profile_label_lower
        .split_whitespace()
        .next()
        .unwrap_or(&profile_label_lower);
    let user_terminal_label_lower = app.config.ui.terminal_label.to_ascii_lowercase();
    let is_plain_shell = matches!(
        leading_word,
        "shell" | "zsh" | "bash" | "sh" | "fish" | "nu" | "nushell" | "terminal" | "term" | "tty"
    ) || leading_word == user_terminal_label_lower;
    // 2026-08-06 — the plain-shell fallback used a fixed U+EA85
    // (nf-cod-terminal). Now honors `[ui] terminal_glyph_svg`: if
    // the user baked a custom terminal SVG via
    // `integrations.bake_integration_glyphs`, resolve its
    // assigned codepoint from `integration_glyph_codepoints` and
    // render that instead. Falls back to EA85 on any miss so the
    // chip never renders as a tofu box.
    let terminal_glyph = app
        .integration_glyph_codepoints
        .get("terminal")
        .and_then(|cp| char::from_u32(*cp))
        .map(|c| c.to_string())
        .unwrap_or_else(|| "\u{ea85}".to_string());
    // 2026-08-08 — the "animated ✳ shows blue instead of Claude orange"
    // report. The `(None, Some(g), _)` arm falls to `tt.teal` (blue-ish)
    // when the integration lookup missed for a Claude Pty — happens when
    // the integration slot's `color` didn't parse. Same-shape backstop
    // for the resolved-integration path: force coral when the pane's
    // integration_id is claude_code, so the animation reads as Claude's
    // brand regardless of manifest state.
    // 2026-08-08 — single source of truth for the Claude brand color
    // (see `theme::brand_color_for_builtin`). Was a local `Rgb(…)`
    // constant hardcoded here, which the user rightly complained about
    // ("why aren't they controlled together").
    let claude_coral = theme::brand_color_for_builtin("claude_code")
        .unwrap_or(ratatui::style::Color::Rgb(0xD1, 0x6D, 0x51));
    let force_claude_color = s
        .profile
        .integration_id
        .as_deref()
        .is_some_and(|id| id == "claude_code");
    match (integration_glyph, spinner, codex_thinking) {
        (Some((g, _)), _, true) if nerd => (g, codex_breath_color()),
        // Spinner + integration → use integration color; but if this is a Claude
        // pane, override any stale/mis-parsed slot color with the brand
        // hex directly. Add a trailing space so the narrow dingbat char
        // (✳ ✢ ✶ ✻ ✽) doesn't sit tight against the label.
        // Spinner path — dingbat chars (✳ ✢ ✶ ✻ ✽) are narrow.
        // `tab_chip_spans` already wraps `" {g} "`, so keep the raw
        // spinner char here — otherwise the sum is 2 trailing spaces
        // (bufferline wrapper + this branch) and the tab label
        // visibly jiggles right by one cell every time thinking starts.
        // R5 keyboard SEV-3 + claude-power SEV-3, 2026-08-08.
        (Some((_, c)), Some(g), _) if nerd => (
            g.to_string(),
            if force_claude_color { claude_coral } else { c },
        ),
        (Some((g, c)), _, _) if nerd => (g, if force_claude_color { claude_coral } else { c }),
        (None, Some(g), _) if nerd => (
            g.to_string(),
            if force_claude_color {
                claude_coral
            } else {
                tt.teal
            },
        ),
        // 2026-08-07 — match the H/V cluster's pure-white terminal
        // glyph. Was `tt.comment` (dim gray), which made the tab
        // icon read as visibly darker than the cluster chip for the
        // same terminal.
        _ if is_plain_shell && nerd => (terminal_glyph.clone(), ratatui::style::Color::White),
        _ => (
            if nerd {
                terminal_glyph
            } else {
                "".to_string()
            },
            ratatui::style::Color::White,
        ),
    }
}

/// Codex uses a color-breath animation on `•`. Faithful port of
/// Codex's `shimmer_spans`: 2000ms cycle, period=21, band-half-
/// width=5, triangle-band interpolation between grey and white.
fn codex_breath_color() -> ratatui::style::Color {
    use ratatui::style::Color;
    static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
    let start = START.get_or_init(std::time::Instant::now);
    let ms = std::time::Instant::now().duration_since(*start).as_millis();
    const CYCLE_MS: u128 = 2000;
    const PERIOD: f32 = 21.0;
    const CHAR_POSITION: f32 = 10.0;
    const BAND_HALF_WIDTH: f32 = 5.0;
    let phase = (ms % CYCLE_MS) as f32 / CYCLE_MS as f32;
    let pos_f = phase * PERIOD;
    let raw = (pos_f - CHAR_POSITION).abs();
    let distance = raw.min(PERIOD - raw);
    let weight = if distance >= BAND_HALF_WIDTH {
        0.0
    } else {
        1.0 - (distance / BAND_HALF_WIDTH)
    };
    let base: u8 = 60;
    let peak: u8 = 255;
    let g = (base as f32 + (peak - base) as f32 * weight) as u8;
    Color::Rgb(g, g, g)
}

fn icon_for_pane(
    app: &crate::app::App,
    pane: &crate::pane::Pane,
    nerd: bool,
) -> (String, ratatui::style::Color) {
    use crate::pane::Pane;
    // Helper for the majority case: static glyph + static color.
    let s = |g: &'static str, c: ratatui::style::Color| (g.to_string(), c);
    match pane {
        Pane::Editor(b) => {
            let p = b
                .path
                .clone()
                .unwrap_or_else(|| std::path::PathBuf::from("untitled"));
            let icon = crate::ui::icons::for_path(&p, false, false, nerd);
            s(icon.0, icon.1)
        }
        Pane::MdPreview(p) => {
            let icon = crate::ui::icons::for_path(&p.path, false, false, nerd);
            s(icon.0, icon.1)
        }
        Pane::Diff(_) => s(if nerd { "\u{f0e7e}" } else { "±" }, theme::cur().orange),
        Pane::GitGraph(_) => s(if nerd { "\u{f1d3}" } else { "" }, theme::cur().orange),
        Pane::GitStatus(_) => s(if nerd { "\u{f1d2}" } else { "±" }, theme::cur().green),
        Pane::Request(r) => {
            let tt = theme::cur();
            let color = match r.request.method.to_uppercase().as_str() {
                "GET" => tt.green,
                "POST" => tt.orange,
                "PUT" => tt.blue,
                "PATCH" => tt.cyan,
                "DELETE" => tt.red,
                "HEAD" => tt.yellow,
                "OPTIONS" => tt.purple,
                _ => tt.blue,
            };
            s(if nerd { "\u{F1D8}" } else { "" }, color)
        }
        Pane::Pty(pty) => pty_icon(app, pty, nerd),
        Pane::Ai(_) => s(if nerd { "\u{f0e0a}" } else { "" }, theme::cur().purple),
        Pane::Tests(_) => s(if nerd { "\u{f0668}" } else { "" }, theme::cur().green),
        Pane::Browser(_) => s(if nerd { "\u{f059f}" } else { "" }, theme::cur().blue),
        Pane::Diagnostics(_) => s(if nerd { "\u{f0026}" } else { "" }, theme::cur().red),
        Pane::Grep(_) => s(if nerd { "\u{f0349}" } else { "" }, theme::cur().yellow),
        Pane::Flaky(_) => s(if nerd { "\u{f0668}" } else { "" }, theme::cur().purple),
        Pane::Outline(_) => s(if nerd { "\u{f01bd}" } else { "" }, theme::cur().purple),
        Pane::Quickfix(_) => s(if nerd { "\u{f0349}" } else { "" }, theme::cur().teal),
        Pane::CmdlineHistory(_) => s(if nerd { "\u{eb15}" } else { "" }, theme::cur().comment),
        Pane::Cheatsheet(_) => s(if nerd { "\u{f128}" } else { "?" }, theme::cur().yellow),
        Pane::Debug(_) => s(if nerd { "\u{f188}" } else { "🐛" }, theme::cur().red),
        Pane::DapRepl(_) => s(if nerd { "\u{F018D}" } else { ">" }, theme::cur().cyan),
        Pane::Image(_) => s(if nerd { "\u{F021F}" } else { "" }, theme::cur().purple),
        Pane::ClaudeAgents(_) => s(if nerd { "\u{F06A9}" } else { "" }, theme::cur().purple),
        Pane::Websocket(_) => s(if nerd { "\u{F0317}" } else { "" }, theme::cur().teal),
        Pane::SpendReport(_) => s(if nerd { "\u{F01C2}" } else { "$" }, theme::cur().orange),
        Pane::Mount(_) => s(if nerd { "\u{F0BD3}" } else { "M" }, theme::cur().cyan),
        Pane::CloudAgentRun(_) => s(if nerd { "\u{F0956}" } else { "" }, theme::cur().blue),
        Pane::NewCloudAgentWizard(_) => s(if nerd { "\u{F0FB1}" } else { "+" }, theme::cur().green),
        Pane::NewCloudRunWizard(_) => s(if nerd { "\u{F0FB1}" } else { "+" }, theme::cur().cyan),
        // nf-md-puzzle — matches the Integrations activity-bar chip
        // so the tab icon reads unambiguously as "integration detail"
        // (user 2026-08-06: was a lighthouse-looking glyph).
        Pane::IntegrationDetail(_) => s(if nerd { "\u{F0431}" } else { "" }, theme::cur().cyan),
        // 2026-08-16 — product-specific glyphs from mnml's baked
        // AI-tool range (F1E00-F1EFF, see `icon_catalog.rs`). Using
        // the same spark/logo pair the statusline chip renders keeps
        // the tab, the chip, and the right-click context menu visually
        // consistent — a user hovering "Claude" anywhere in the app
        // sees the same red spark. Was one shared `Pane::AiUsage`
        // rendered as a purple speedometer.
        Pane::ClaudeUsage(_) => s(if nerd { "\u{F1E00}" } else { "%" }, theme::cur().red),
        Pane::CodexUsage(_) => s(if nerd { "\u{F1E01}" } else { "%" }, theme::cur().green),
    }
}

/// Cell-width-aware clip with `…` suffix.
pub(crate) fn clip_to_cells(s: &str, max_cells: usize) -> String {
    if s.chars().count() <= max_cells {
        return s.to_string();
    }
    if max_cells == 0 {
        return String::new();
    }
    let mut out: String = s.chars().take(max_cells.saturating_sub(1)).collect();
    out.push('');
    out
}

fn draw_divider(frame: &mut Frame, rect: Rect, dir: SplitDir, hover: bool) {
    let t = theme::cur();
    // 2026-07-08 — grip glyphs removed. Hover state paints the WHOLE
    // divider in the accent color (was yellow, now cyan for parity
    // with the tree / right-panel edge hover); idle stays a subtle
    // `t.line`. The line itself IS the drag affordance — no `┃` /
    // `━` grip cue in the middle. Matches the tree / right-panel
    // edge treatment.
    let line_fg = if hover { t.cyan } else { t.line };
    let line_style = Style::default().fg(line_fg).bg(t.bg_dark);
    match dir {
        SplitDir::Horizontal => {
            // Vertical divider — one column of `│` glyphs.
            for dy in 0..rect.height {
                frame.render_widget(
                    Paragraph::new(Span::styled("", line_style)),
                    Rect::new(rect.x, rect.y + dy, 1, 1),
                );
            }
        }
        SplitDir::Vertical => {
            // Horizontal divider — one row of `─` glyphs across the
            // pane width.
            let line: String = "".repeat(rect.width as usize);
            frame.render_widget(Paragraph::new(Span::styled(line, line_style)), rect);
        }
    }
}

#[cfg(test)]
mod palette_bar_tests {
    use super::*;
    use crate::app::App;
    use crate::config::Config;
    use ratatui::Terminal;
    use ratatui::backend::TestBackend;

    /// Render the palette bar at `width` cells and return the row
    /// as a String. Drives the real `draw_palette_bar` (not just
    /// the math helper) so we catch behavior across the actual
    /// render path — including the bufferline cluster paint,
    /// which the unit tests in bufferline.rs can't verify.
    fn render_palette_bar_row(width: u16, n_tabs: usize) -> String {
        let d = tempfile::tempdir().unwrap();
        let ws = d.path().to_path_buf();
        let mut app = App::new(ws, Config::default()).unwrap();
        // Open extra tab pages to populate the TABS chip list.
        for _ in 1..n_tabs {
            app.tab_new(None);
        }
        let mut term = Terminal::new(TestBackend::new(width, 3)).unwrap();
        term.draw(|f| {
            let area = Rect {
                x: 0,
                y: 0,
                width,
                height: 1,
            };
            draw_palette_bar(f, &mut app, area);
        })
        .unwrap();
        let buf = term.backend().buffer();
        (0..buf.area.width).map(|x| buf[(x, 0)].symbol()).collect()
    }

    #[test]
    fn palette_bar_wide_shows_full_cluster_with_tabs() {
        let row = render_palette_bar_row(200, 3);
        // Wide enough — TABS label + numbered chips must be present.
        assert!(row.contains("TABS"), "expected 'TABS' in wide row: {row:?}");
        assert!(
            row.contains(" 1 "),
            "expected ' 1 ' tab chip in wide row: {row:?}"
        );
        assert!(
            row.contains(" 2 "),
            "expected ' 2 ' tab chip in wide row: {row:?}"
        );
    }

    #[test]
    fn palette_bar_narrow_hides_cluster_entirely() {
        // 90 cells: too narrow for the full cluster — and there's
        // no compact stage anymore. User preference (2026-06-22):
        // full-or-hidden, no intermediate. TABS / + / theme / × all
        // disappear in one drop.
        let row = render_palette_bar_row(90, 3);
        assert!(
            !row.contains("TABS"),
            "TABS label should be hidden at width 90: {row:?}"
        );
        assert!(
            !row.contains(" 1 "),
            "numbered tab chip ' 1 ' should be hidden at width 90: {row:?}"
        );
    }

    /// Regression: the bufferline used to clear `launcher_icon_rects`
    /// + the cluster chip rects every frame, but no longer paints
    /// them — the palette bar does. The clears wiped the click
    /// targets the palette bar just registered, so the chips
    /// rendered but were unclickable. This test runs the FULL
    /// `draw` (not just palette_bar) at a width wide enough for
    /// every chip and asserts the click rects survive afterward.
    #[test]
    fn full_draw_keeps_cluster_click_rects_registered() {
        let d = tempfile::tempdir().unwrap();
        let ws = d.path().to_path_buf();
        // 2026-08-01 (P2) — launcher_icon_rects assertion deleted
        // with the LauncherIcon retirement. Test still verifies the
        // rest of the cluster (new-tab, theme toggle, window close).
        let cfg = Config::default();
        let mut app = App::new(ws, cfg).unwrap();
        let mut term = Terminal::new(TestBackend::new(200, 30)).unwrap();
        term.draw(|f| draw(f, &mut app)).unwrap();
        assert!(
            app.rects.bufferline_new_tab_button.is_some(),
            "new tab button rect missing post-draw"
        );
        assert!(
            app.rects.bufferline_theme_toggle.is_some(),
            "theme toggle rect missing post-draw"
        );
        assert!(
            app.rects.bufferline_window_close.is_some(),
            "window close rect missing post-draw"
        );
    }

    #[test]
    fn palette_bar_extra_narrow_hides_cluster_entirely() {
        // 82 cells: even compact doesn't fit past the workspace
        // chip — cluster should vanish completely (still above
        // the 80-col palette-bar-visible cutoff).
        let row = render_palette_bar_row(82, 3);
        assert!(!row.contains("TABS"), "TABS must be hidden: {row:?}");
        // No tab chip
        assert!(!row.contains(" 1 "), "no tab chip allowed: {row:?}");
    }

    /// 2026-06-22 — full integration test: simulate the events
    /// crossterm would dispatch during a tree-file drag and
    /// verify the ghost + drop overlay paint at every stage.
    /// This covers what terminals (Apple Terminal, iTerm, Ghostty,
    /// kitty) should produce when the user drags a file from the
    /// tree to a pane. Catches regressions where:
    ///   - mouse-Moved without held-button is the only mid-drag
    ///     event (some terminals report it this way)
    ///   - tree_drag isn't being set on mouse-down on tree row
    ///   - ghost / overlay paint code paths regress
    #[test]
    fn full_drag_flow_paints_ghost_and_overlay() {
        use ratatui::crossterm::event::{KeyModifiers, MouseButton, MouseEvent, MouseEventKind};
        let d = tempfile::tempdir().unwrap();
        let ws = d.path().to_path_buf();
        std::fs::write(ws.join("a.txt"), "alpha").unwrap();
        std::fs::write(ws.join("b.txt"), "beta").unwrap();
        let mut app = App::new(ws.clone(), Config::default()).unwrap();
        // Open a.txt so there's a pane body to drop onto.
        app.open_path(&ws.join("a.txt"));
        let mut term = Terminal::new(TestBackend::new(120, 30)).unwrap();
        term.draw(|f| draw(f, &mut app)).unwrap();

        // Find a tree row for b.txt — pick the row + col that the
        // click handler would resolve. Compute the screen row for
        // a b.txt entry by walking the visible tree.
        let tree_rect = app
            .rects
            .tree
            .expect("tree should render with a workspace open");
        let visible_rows = app.tree.visible_rows();
        let b_idx = visible_rows
            .iter()
            .position(|r| r.path.file_name().is_some_and(|n| n == "b.txt"))
            .unwrap_or_else(|| {
                panic!(
                    "b.txt not in visible_rows; rows={:?}",
                    visible_rows
                        .iter()
                        .map(|r| r.path.file_name().map(|n| n.to_string_lossy().into_owned()))
                        .collect::<Vec<_>>()
                )
            });
        let click_x = tree_rect.x + tree_rect.width / 2;
        let click_y = tree_rect.y + (b_idx as u16);

        // === STAGE 1: mouse-down on tree row → begin_tree_drag ===
        crate::tui::dispatch_mouse(
            &mut app,
            MouseEvent {
                kind: MouseEventKind::Down(MouseButton::Left),
                column: click_x,
                row: click_y,
                modifiers: KeyModifiers::empty(),
            },
        );
        assert!(
            app.tree_drag.is_some(),
            "tree_drag should be Some after mouse-down on tree row (tree_rect={:?}, click=({},{}))",
            tree_rect,
            click_x,
            click_y
        );

        // === STAGE 2: cursor moves into a pane body ===
        // Terminals can deliver this as either Drag(Left) or
        // Moved depending on platform / capture mode. Test both.
        let body_rect = app
            .rects
            .pane_bodies
            .first()
            .map(|(r, _)| *r)
            .expect("expected at least one pane body");
        let move_x = body_rect.x + body_rect.width / 2;
        let move_y = body_rect.y + body_rect.height / 2;

        // First with Moved (the case other terminals sometimes
        // send during a drag).
        crate::tui::dispatch_mouse(
            &mut app,
            MouseEvent {
                kind: MouseEventKind::Moved,
                column: move_x,
                row: move_y,
                modifiers: KeyModifiers::empty(),
            },
        );
        assert!(
            app.tree_drag.as_ref().map(|d| d.armed).unwrap_or(false),
            "tree_drag should arm on cursor motion during drag (Moved event)"
        );
        assert!(
            app.rects.tab_drop_target.is_some(),
            "tab_drop_target should be set when cursor is over a pane body during a tree drag"
        );

        // === STAGE 3: render — ghost + overlay must be on screen ===
        term.draw(|f| draw(f, &mut app)).unwrap();
        let buf = term.backend().buffer();
        let screen: String = (0..buf.area.height)
            .map(|y| {
                let row: String = (0..buf.area.width).map(|x| buf[(x, y)].symbol()).collect();
                row + "\n"
            })
            .collect();
        assert!(
            screen.contains("b.txt"),
            "drag ghost chip should render 'b.txt' on screen.\n{}",
            screen
        );
        // 2026-06-22 — overlay redesigned to be label-less (a
        // translucent gray over the active zone). Verify the
        // drop target is registered instead.
        assert!(
            app.rects.tab_drop_target.is_some(),
            "drag flow should register a tab_drop_target.\n{}",
            screen
        );

        // === STAGE 4: mouse-up over pane → drop succeeds ===
        let initial_layouts: Vec<_> = app.layouts.to_vec();
        let _ = initial_layouts;
        crate::tui::dispatch_mouse(
            &mut app,
            MouseEvent {
                kind: MouseEventKind::Up(MouseButton::Left),
                column: move_x,
                row: move_y,
                modifiers: KeyModifiers::empty(),
            },
        );
        assert!(
            app.tree_drag.is_none(),
            "tree_drag should clear on mouse-up"
        );
        // The release dropped b.txt onto a.txt's pane → either a
        // split or center-move (depends on which zone the click
        // landed in). Either way, b.txt is now a buffer.
        let pane_paths: Vec<_> = app
            .panes
            .iter()
            .filter_map(|p| match p {
                crate::pane::Pane::Editor(b) => b.path.clone(),
                _ => None,
            })
            .collect();
        let b_open = pane_paths
            .iter()
            .any(|p| p.file_name().is_some_and(|n| n == "b.txt"));
        assert!(
            b_open,
            "after drop, b.txt should be open as a Pane::Editor. \
             panes: {:?}",
            pane_paths
        );
    }

    /// 2026-06-22 — verify the drop overlay paints when a tree
    /// drag is over a pane body.
    #[test]
    fn drop_overlay_paints_when_over_pane() {
        let d = tempfile::tempdir().unwrap();
        let ws = d.path().to_path_buf();
        std::fs::write(ws.join("a.txt"), "alpha").unwrap();
        std::fs::write(ws.join("b.txt"), "beta").unwrap();
        let mut app = App::new(ws.clone(), Config::default()).unwrap();
        // Open a file so there's a pane body to drop on.
        app.open_path(&ws.join("a.txt"));
        // Render once to populate pane_bodies.
        let mut term = Terminal::new(TestBackend::new(120, 30)).unwrap();
        term.draw(|f| draw(f, &mut app)).unwrap();
        // Now simulate: drag from tree (e.g. b.txt) over the pane.
        // Pick a coord that's inside the pane body.
        let body_rect = app
            .rects
            .pane_bodies
            .first()
            .map(|(r, _)| *r)
            .expect("expected at least one pane body");
        let center_x = body_rect.x + body_rect.width / 2;
        let center_y = body_rect.y + body_rect.height / 2;
        app.begin_tree_drag(ws.join("b.txt"), false, 10);
        app.set_tree_drag_cursor(center_x, center_y);
        app.update_tab_drop_target(center_x, center_y);
        assert!(
            app.rects.tab_drop_target.is_some(),
            "drop target should be set when cursor is over a pane body"
        );
        term.draw(|f| draw(f, &mut app)).unwrap();
        let buf = term.backend().buffer();
        let screen: String = (0..buf.area.height)
            .map(|y| {
                let row: String = (0..buf.area.width).map(|x| buf[(x, y)].symbol()).collect();
                row + "\n"
            })
            .collect();
        assert!(
            app.rects.tab_drop_target.is_some(),
            "drop overlay should register a tab_drop_target.\n\
             screen:\n{}",
            screen
        );
    }

    /// 2026-06-22 — verify the drag ghost actually paints during
    /// a tree drag. User-reported: no visible ghost during drag.
    /// This test simulates the drag (mouse-down on tree, then
    /// move) and asserts the ghost chip text appears on screen.
    #[test]
    fn drag_ghost_paints_during_armed_drag() {
        let d = tempfile::tempdir().unwrap();
        let ws = d.path().to_path_buf();
        std::fs::write(ws.join("dragme.txt"), "drag me").unwrap();
        let mut app = App::new(ws.clone(), Config::default()).unwrap();
        // Start a tree drag from row y=10 (simulating mouse-down on
        // the tree row), then move the cursor to (50, 20) — past
        // the tree, onto a pane area.
        app.begin_tree_drag(ws.join("dragme.txt"), false, 10);
        app.set_tree_drag_cursor(50, 20);
        assert!(
            app.tree_drag.as_ref().unwrap().armed,
            "drag should arm on cursor motion past origin"
        );
        let mut term = Terminal::new(TestBackend::new(120, 30)).unwrap();
        term.draw(|f| draw(f, &mut app)).unwrap();
        let buf = term.backend().buffer();
        // The ghost chip should contain the filename "dragme.txt"
        // somewhere on screen. Scan all rows.
        let screen: String = (0..buf.area.height)
            .map(|y| {
                let row: String = (0..buf.area.width).map(|x| buf[(x, y)].symbol()).collect();
                row + "\n"
            })
            .collect();
        assert!(
            screen.contains("dragme.txt"),
            "drag ghost chip should render 'dragme.txt' on screen but didn't.\n\
             Cursor: ({}, {}) armed: {} screen:\n{}",
            app.tree_drag.as_ref().unwrap().cursor_x,
            app.tree_drag.as_ref().unwrap().cursor_y,
            app.tree_drag.as_ref().unwrap().armed,
            screen
        );
    }
}