croft-software 0.2.232

VSCode-style TUI written in Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
use crate::widgets::drawn_rows::follow;
use crate::widgets::surface::put_clipped;
use crate::widgets::view_cx::ViewCx;
use ratatui::{
    buffer::Buffer,
    layout::{Alignment, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Paragraph, Widget, Wrap},
};
use std::path::PathBuf;

const BODY_FG_RGB: (u8, u8, u8) = (0xb0, 0xb8, 0xc8);
const TITLE_FG_RGB: (u8, u8, u8) = (0xff, 0xff, 0xff);
const FOCUS_BORDER_RGB: (u8, u8, u8) = (0x4e, 0x9a, 0xff);

// --- Debug-panel (Variant A "Darcula") palette. Fixed darks chosen to read
// well on both the Black (#000) and Dark Blue (#1e222e) theme backgrounds. ---
const DBG_BAR_BG: Color = Color::Rgb(0x1c, 0x27, 0x33); // section-header bar fill
const DBG_BAR_FG: Color = Color::Rgb(0x8f, 0xd9, 0xcf); // section-header text
const DBG_FRAME_BG: Color = Color::Rgb(0x20, 0x2a, 0x37); // selected-frame fill
const DBG_ACCENT: Color = Color::Rgb(0x5c, 0xd6, 0xc8); // brand teal stripe / caret
const DBG_SCOPE: Color = Color::Rgb(0xc8, 0xa0, 0x6a); // Locals / Globals (gold)
const DBG_NAME: Color = Color::Rgb(0xbc, 0xbe, 0xc4); // identifiers / var names
const DBG_EQ: Color = Color::Rgb(0x6b, 0x72, 0x80); // "="
const DBG_TYPE: Color = Color::Rgb(0x78, 0x7c, 0x80); // ": type"
const DBG_STR: Color = Color::Rgb(0x6a, 0xab, 0x73); // strings / collections
const DBG_NUM: Color = Color::Rgb(0x2a, 0xac, 0xb8); // numbers
const DBG_KW: Color = Color::Rgb(0xcf, 0x8e, 0x6d); // None / bool
const DBG_CHEV: Color = Color::Rgb(0x5c, 0x66, 0x75); // expand chevrons
const DBG_LOC: Color = Color::Rgb(0x6b, 0x76, 0x89); // file:line / dim console
const DBG_PILL_BG: Color = Color::Rgb(0x0e, 0x7e, 0x76); // status pill
const DBG_PILL_FG: Color = Color::Rgb(0xdf, 0xfd, 0xf7);
const DBG_FRAME_SEL_FG: Color = Color::Rgb(0xff, 0xff, 0xff);
/// The keyboard's row (#2748): Source Control's list selection colour.
const DBG_CURSOR_BG: Color = Color::Rgb(0x26, 0x4f, 0x78);
const DBG_FIELD_BG: Color = Color::Rgb(0x0d, 0x11, 0x17); // REPL input field fill
const DBG_PLACEHOLDER: Color = Color::Rgb(0x4b, 0x55, 0x63); // ghost hint text

/// One button of the debug toolbar (#1545): VS Code's debug toolbar,
/// docked at the top of the Run and Debug panel while a session is live,
/// so a session can be driven by mouse when the F-keys never arrive.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DebugControl {
    Continue,
    Pause,
    StepOver,
    StepInto,
    StepOut,
    Restart,
    Stop,
}

impl DebugControl {
    /// The toolbar left to right: Continue while paused, Pause while
    /// running, then the steps, Restart and Stop.
    pub fn toolbar(paused: bool) -> [DebugControl; 6] {
        [
            if paused {
                DebugControl::Continue
            } else {
                DebugControl::Pause
            },
            DebugControl::StepOver,
            DebugControl::StepInto,
            DebugControl::StepOut,
            DebugControl::Restart,
            DebugControl::Stop,
        ]
    }

    /// The codicon VS Code draws for it (`debug-continue`, `debug-pause`,
    /// `debug-step-over`, `debug-step-into`, `debug-step-out`,
    /// `debug-restart`, `debug-stop`).
    pub fn glyph(self) -> char {
        match self {
            DebugControl::Continue => '\u{eacf}',
            DebugControl::Pause => '\u{ead1}',
            DebugControl::StepOver => '\u{ead6}',
            DebugControl::StepInto => '\u{ead4}',
            DebugControl::StepOut => '\u{ead5}',
            DebugControl::Restart => '\u{ead2}',
            DebugControl::Stop => '\u{ead7}',
        }
    }

    /// The button's name and key, shown while the pointer is over it.
    pub fn tooltip(self) -> &'static str {
        match self {
            DebugControl::Continue => "Continue (F5)",
            DebugControl::Pause => "Pause (F6)",
            DebugControl::StepOver => "Step Over (F10)",
            DebugControl::StepInto => "Step Into (F11)",
            DebugControl::StepOut => "Step Out (Shift+F11)",
            DebugControl::Restart => "Restart (Ctrl+Shift+F5)",
            DebugControl::Stop => "Stop (Shift+F5)",
        }
    }

    /// Whether it acts in this state: the steps need a paused thread.
    pub fn enabled(self, paused: bool) -> bool {
        paused
            || !matches!(
                self,
                DebugControl::StepOver | DebugControl::StepInto | DebugControl::StepOut
            )
    }
}

/// Add a background colour to `style` when `bg` is `Some` (so a selected frame's
/// segments share its highlight fill).
fn with_bg(style: Style, bg: Option<Color>) -> Style {
    match bg {
        Some(c) => style.bg(c),
        None => style,
    }
}

/// Word-wrap the panel's feedback line to rows at most `width` display
/// columns wide (#944): a launch error is the message most worth reading and
/// is usually far wider than the sidebar, so it gets as many rows as it
/// needs instead of running across the border into the editor. A word wider
/// than a row is split at the row's edge.
fn wrap_feedback(text: &str, width: usize) -> Vec<String> {
    use unicode_width::UnicodeWidthChar;
    let width = width.max(1);
    let mut rows = Vec::new();
    let mut row = String::new();
    let mut used = 0;
    for word in text.split_whitespace() {
        let w: usize = word.chars().map(|c| c.width().unwrap_or(0)).sum();
        if used > 0 && used + 1 + w > width {
            rows.push(std::mem::take(&mut row));
            used = 0;
        }
        if used > 0 {
            row.push(' ');
            used += 1;
        }
        for c in word.chars() {
            let cw = c.width().unwrap_or(0);
            if used + cw > width && used > 0 {
                rows.push(std::mem::take(&mut row));
                used = 0;
            }
            row.push(c);
            used += cw;
        }
    }
    if !row.is_empty() {
        rows.push(row);
    }
    rows
}

/// One wrapped console row: runs of text, each in the style its program
/// output set (#1501).
type ConsoleRow = Vec<(String, crate::ansi_text::AnsiStyle)>;

/// Soft-wrap one console line into rows at most `width` display columns
/// wide, the way a terminal wraps (#867): whitespace is kept, so a
/// traceback's indentation survives, a wide glyph never straddles two rows,
/// and a tab is four spaces. An empty line is one empty row. Each character
/// keeps the colour its span gives it, so a coloured word wrapped across two
/// rows is coloured on both (#1501).
///
/// Only the last `keep` rows are returned, oldest first, and only they are
/// built: a row that scrolls out of the kept tail lends its buffer to the
/// next, so a program printing one enormous line costs a scan of it per
/// frame but never a string per row (#867 review).
fn wrap_console_line_tail(
    line: &crate::ansi_text::AnsiLine,
    width: usize,
    keep: usize,
) -> Vec<ConsoleRow> {
    use unicode_width::UnicodeWidthChar;
    if keep == 0 {
        return Vec::new();
    }
    let width = width.max(1);
    let mut rows: std::collections::VecDeque<ConsoleRow> = std::collections::VecDeque::new();
    let mut row = ConsoleRow::new();
    let mut used = 0;
    let mut span = 0;
    for (at, c) in line.text.char_indices() {
        while line.spans.get(span).is_some_and(|s| s.end <= at) {
            span += 1;
        }
        let style = line
            .spans
            .get(span)
            .filter(|s| s.start <= at)
            .map(|s| s.style)
            .unwrap_or_default();
        // A tab is four spaces.
        let (c, n) = if c == '\t' { (' ', 4) } else { (c, 1) };
        let w = c.width().unwrap_or(0);
        for _ in 0..n {
            if used + w > width && !row.is_empty() {
                rows.push_back(std::mem::take(&mut row));
                // With the row in progress, `keep` rows are kept: once the
                // finished ones reach `keep`, the oldest one's buffer becomes
                // the next row instead of a fresh allocation.
                if rows.len() >= keep {
                    row = rows.pop_front().unwrap_or_default();
                    row.clear();
                }
                used = 0;
            }
            match row.last_mut() {
                Some((text, st)) if *st == style => text.push(c),
                _ => row.push((c.to_string(), style)),
            }
            used += w;
        }
    }
    rows.push_back(row);
    rows.into()
}

/// Paint one wrapped console row at (`x`, `y`), at most `width` columns,
/// each run in `base` overlaid with its own colours.
fn put_console_row(
    cx: &ViewCx,
    buf: &mut Buffer,
    x: u16,
    y: u16,
    row: &ConsoleRow,
    width: u16,
    base: Style,
) {
    let right = x.saturating_add(width);
    let mut at = x;
    for (text, st) in row {
        if at >= right {
            break;
        }
        let style = console_run_style(base, *st, cx.theme);
        let (end, _) = buf.set_stringn(at, y, text, (right - at) as usize, style);
        at = end;
    }
}

/// The style a console run paints in: `base` (the line's own colour), with
/// whatever the program's colour sequences set on top (#1501). Inverse is
/// left to the terminal, which knows the pair it swaps.
fn console_run_style(
    base: Style,
    st: crate::ansi_text::AnsiStyle,
    theme: crate::theme::Theme,
) -> Style {
    use crate::ansi_text::ansi_color_to_tui;
    let mut style = base;
    if let Some(c) = st.fg {
        style = style.fg(ansi_color_to_tui(c, theme));
    }
    if let Some(c) = st.bg {
        style = style.bg(ansi_color_to_tui(c, theme));
    }
    for (on, m) in [
        (st.bold, Modifier::BOLD),
        (st.dim, Modifier::DIM),
        (st.italic, Modifier::ITALIC),
        (st.underline, Modifier::UNDERLINED),
        (st.inverse, Modifier::REVERSED),
        (st.strikeout, Modifier::CROSSED_OUT),
    ] {
        if on {
            style = style.add_modifier(m);
        }
    }
    style
}

/// Colour a Python value by its `type_name` (PyCharm/Darcula-ish): strings and
/// collections green, numbers cyan, None/bool orange, everything else (objects)
/// the neutral name grey.
fn value_color(type_name: &str, theme: crate::theme::Theme) -> Color {
    match type_name {
        "str" => theme.ui(DBG_STR),
        "int" | "float" | "complex" => theme.ui(DBG_NUM),
        "bool" | "NoneType" => theme.ui(DBG_KW),
        "list" | "tuple" | "dict" | "set" | "frozenset" | "bytes" | "bytearray" => {
            theme.ui(DBG_STR)
        }
        _ => theme.ui(DBG_NAME),
    }
}

/// Cells reserved above the headline for the OSC-1337 debug-alt icon
/// overlay. Six cells wide × three cells tall lands a roughly 60×60-pixel
/// codicon at typical iTerm2 cell sizes (10×20 px), matching the VS Code
/// empty-state proportions the user supplied. The image is painted post-
/// frame by `App::flush_run_debug_icon_overlay`; on view change away from
/// Run-Debug the App's `terminal.clear()` evicts the cached image cells
/// (the same pipeline the welcome wordmark and editor preview use).
pub const RUN_DEBUG_ICON_CELLS_W: u16 = 6;
pub const RUN_DEBUG_ICON_CELLS_H: u16 = 3;

/// What a [`DebugRow`] represents, so a click can act on it (navigate to a
/// frame, expand a variable) and so the renderer can colour each part. Each
/// variant carries the structured pieces the renderer styles independently
/// (name vs value vs type), PyCharm-style.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DebugRowKind {
    /// A section header ("CALL STACK", "VARIABLES") drawn as a filled bar.
    Header { title: String },
    /// A call-stack frame; `name` is the function, `location` is `file:line`.
    Frame {
        id: i64,
        selected: bool,
        name: String,
        location: String,
    },
    /// A thread (a goroutine, under delve) in the CALL STACK when the
    /// debuggee has more than one (#264); `selected` is the one whose frames
    /// are listed and that stepping applies to.
    Thread {
        id: i64,
        name: String,
        selected: bool,
    },
    /// A scope container row ("Locals", "Globals"). `open` is `Some` for an
    /// expensive scope (#1421), which opens on click and shows a chevron;
    /// `None` for one that is always open. `index` is its position in the
    /// session's scopes.
    Scope {
        name: String,
        index: usize,
        open: Option<bool>,
    },
    /// A variable. `reference > 0` means expandable; `value`/`type_name` are
    /// coloured by type.
    Variable {
        reference: i64,
        expandable: bool,
        expanded: bool,
        name: String,
        value: String,
        type_name: String,
        /// The adapter's `evaluateName`, for Copy as Expression and Add to
        /// Watch (#1546).
        evaluate_name: Option<String>,
    },
    /// A watch expression (#112). `available` false renders `<not available>`
    /// (the adapter rejected it); `changed` highlights a value that differs
    /// from the previous stop; `pending` shows a placeholder until the
    /// evaluate response lands.
    Watch {
        /// Index into the App's expression list — carried IN the row so the
        /// remove `✕` maps to the right expression even when `debug_scroll`
        /// has skipped earlier Watch rows (a render-order counter restarted
        /// at the first VISIBLE row and removed the wrong one).
        index: usize,
        expression: String,
        value: String,
        available: bool,
        changed: bool,
        pending: bool,
    },
    /// The trailing "+ Add Expression" affordance row of the WATCH section.
    WatchAdd,
    /// A breakpoint (#250): `index` into [`RunDebugPanel::breakpoints`].
    /// Clicking the row jumps to it; the `✕` removes it. `path` and `line`
    /// (1-based) say which breakpoint it is, so the keyboard's row follows
    /// it when one above it goes (#2748).
    Breakpoint {
        index: usize,
        path: PathBuf,
        line: usize,
    },
}

/// One breakpoint as the BREAKPOINTS list shows it (#250), filled by the app
/// from the editor's breakpoints on every refresh, running or not.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BreakpointItem {
    pub path: PathBuf,
    /// 1-based, as the editor stores breakpoint lines.
    pub line: usize,
    /// `file.rs:12`.
    pub label: String,
    /// `if <condition>` or `log <message>` for a conditional breakpoint or a
    /// logpoint; `None` for a plain one.
    pub detail: Option<String>,
}

/// What names a breakpoint for a click: its file and 1-based line.
type BreakpointKey = (PathBuf, usize);

/// One rendered line of the paused-state debug tree. The app builds these from
/// the session; the panel renders them and maps clicks back to them.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DebugRow {
    pub indent: u8,
    pub kind: DebugRowKind,
}

/// What makes a row the same row across a rebuild (#2748): what it shows,
/// not where. A variable has no id of its own (every leaf's reference is
/// 0), so its name, expression and depth stand for it; its parents and its
/// place among same-keyed siblings ([`row_chain`]) tell apart the rest.
#[derive(Clone, Copy, PartialEq, Eq)]
enum RowKey<'a> {
    Header(&'a str),
    Frame(i64),
    Thread(i64),
    Scope(&'a str, usize),
    Variable(&'a str, Option<&'a str>, u8),
    Watch(&'a str),
    WatchAdd,
    Breakpoint(&'a std::path::Path, usize),
}

fn row_key(row: &DebugRow) -> RowKey<'_> {
    use DebugRowKind as K;
    match &row.kind {
        K::Header { title } => RowKey::Header(title),
        K::Frame { id, .. } => RowKey::Frame(*id),
        K::Thread { id, .. } => RowKey::Thread(*id),
        K::Scope { name, index, .. } => RowKey::Scope(name, *index),
        K::Variable {
            name,
            evaluate_name,
            ..
        } => RowKey::Variable(name, evaluate_name.as_deref(), row.indent),
        K::Watch { expression, .. } => RowKey::Watch(expression),
        K::WatchAdd => RowKey::WatchAdd,
        K::Breakpoint { path, line, .. } => RowKey::Breakpoint(path, *line),
    }
}

/// Each row's parent (#2748): the closest row above it with less indent,
/// `None` for a section header. One pass, so a rebuild of a long list of
/// variables stays linear.
fn row_parents(rows: &[DebugRow]) -> Vec<Option<usize>> {
    let mut open: Vec<usize> = Vec::new();
    rows.iter()
        .enumerate()
        .map(|(i, row)| {
            while open.last().is_some_and(|&j| rows[j].indent >= row.indent) {
                open.pop();
            }
            let parent = if row.indent == 0 {
                None
            } else {
                open.last().copied()
            };
            open.push(i);
            parent
        })
        .collect()
}

/// Row `at` as the steps down to it from its section header (#2748): each
/// step is a row's [`RowKey`] and how many earlier siblings share that
/// key. VS Code ids its variables the same way: the parent's id, the name,
/// and a count of same-named siblings before it. So two same-named fields
/// under different objects differ by their parents, and an adapter's two
/// same-named siblings by their count, at every depth.
fn row_chain<'a>(
    rows: &'a [DebugRow],
    parents: &[Option<usize>],
    at: usize,
) -> Vec<(RowKey<'a>, usize)> {
    let mut chain = Vec::new();
    let mut here = Some(at);
    while let Some(y) = here {
        let key = row_key(&rows[y]);
        let from = parents[y].map_or(0, |p| p + 1);
        let twin = (from..y)
            .filter(|&j| parents[j] == parents[y] && row_key(&rows[j]) == key)
            .count();
        chain.push((key, twin));
        here = parents[y];
    }
    chain.reverse();
    chain
}

/// The row `chain` names in `rows` (#2748), found top-down: each step looks
/// only among the children of the row the step before found, and stops at
/// its match, so a rebuild of a long variable list stays linear.
fn find_chain(
    rows: &[DebugRow],
    parents: &[Option<usize>],
    chain: &[(RowKey<'_>, usize)],
) -> Option<usize> {
    let mut found: Option<usize> = None;
    for &(key, twin) in chain {
        let parent = found;
        let from = parent.map_or(0, |p| p + 1);
        found = Some(
            (from..rows.len())
                .take_while(|&i| parent.is_none_or(|p| rows[i].indent > rows[p].indent))
                .filter(|&i| parents[i] == parent && row_key(&rows[i]) == key)
                .nth(twin)?,
        );
    }
    found
}

pub struct RunDebugPanel {
    pub active_file: Option<PathBuf>,
    /// Whether the active file is something croft can run or debug. When false
    /// (e.g. an extensionless `.git/config`) the empty state shows a "can't run
    /// this file" note instead of an actionable button. Set by the app.
    pub runnable: bool,
    /// Whether the button's action is debug (compiled source: build + lldb)
    /// rather than run-in-terminal (scripts / executables). Drives both the
    /// button verb ("Debug" vs "Run") and the click dispatch. Set by the app.
    pub run_is_debug: bool,
    pub last_area: Rect,
    pub last_button_area: Rect,
    /// How many launch.json configurations the workspace declares (#250) and
    /// which one F5 starts (`None` = zero-config active file). Set by the
    /// app's `refresh_run_debug` sync; drives the config row under the button.
    pub config_count: usize,
    pub selected_config: Option<String>,
    /// Hit area of the config row painted this frame; clicking it opens the
    /// Debug Configuration picker. Default when no row was painted.
    pub last_config_area: Rect,
    /// When a debug session is paused, the app fills these rows (call stack +
    /// variables) and sets `debug_active`; the panel then renders the tree
    /// instead of the empty-state Run button.
    pub debug_active: bool,
    /// Remove-`✕` hit cells for Watch rows painted this frame: `(y, x,
    /// index into the app's expressions, expression)`. Cleared at every tree
    /// render. A click follows the expression (#2753): a remove read before
    /// the next frame may have moved it up.
    watch_remove_rects: Vec<(u16, u16, usize, String)>,
    /// Every breakpoint, for the BREAKPOINTS list (#250).
    pub breakpoints: Vec<BreakpointItem>,
    /// Painted breakpoint rows this frame: `(y, index, file and line)`, and
    /// their remove `✕` cells `(y, x, index, file and line)`. Cleared at
    /// every render. A click follows the breakpoint it was drawn for
    /// (#2753), as it does the watch.
    breakpoint_row_rects: Vec<(u16, usize, BreakpointKey)>,
    breakpoint_remove_rects: Vec<(u16, u16, usize, BreakpointKey)>,
    pub debug_status: String,
    /// Whether the live session is paused (set by the app with the rows),
    /// which decides Continue vs Pause and whether the steps act (#1545).
    pub debug_paused: bool,
    /// The debug toolbar's buttons this frame: `(y, x, control)`, each
    /// button three cells wide from `x`. Cleared at every render.
    debug_control_rects: Vec<(u16, u16, DebugControl)>,
    pub debug_rows: Vec<DebugRow>,
    pub debug_scroll: usize,
    /// The row the keyboard is on (#2748), an index into `debug_rows`, or
    /// `None` while the expression prompt has the keys. Never a section
    /// header: [`Self::settle_row_cursor`] keeps it off them.
    pub row_cursor: Option<usize>,
    /// Screen y of the first rendered debug row and how many rows were drawn,
    /// recorded each frame so a click can be mapped to a row index.
    pub last_debug_row_y0: u16,
    pub last_debug_rows_shown: usize,
    /// The scroll those rows were drawn with (#2751). A click is matched
    /// against it: the screen shows it until the next frame, while a key or
    /// wheel step read in the same burst has already moved `debug_scroll`.
    pub last_debug_scroll: usize,
    /// The rows those were, when a rebuild has replaced them since (#2751):
    /// a click read before the next frame follows the row it was drawn on to
    /// where the rebuild put it, as the keyboard does, since a click on a
    /// scope or a watch's remove button in the same burst may have moved it.
    replaced_debug_rows: Option<Vec<DebugRow>>,
    /// Tail of the debug console (program output + REPL echoes/results), set by
    /// the app each refresh; rendered below the variables tree.
    pub console_tail: Vec<crate::ansi_text::AnsiLine>,
    /// Current REPL input line, rendered as a `❯` prompt at the panel bottom.
    pub repl_input: String,
    /// Caret inside `repl_input` as a char index; `None` follows the end (#2009).
    repl_caret: Option<usize>,
    /// The `❯` prompt's row painted this frame (#2748): a click there gives
    /// the prompt the keys back from the rows. Default when none was drawn.
    pub last_prompt_area: Rect,
    /// Top-left cell of the OSC-1337 icon overlay block. The post-draw
    /// flush in `App` reads this to emit the rasterised debug-alt PNG
    /// above the headline. `None` when the panel hasn't been laid out,
    /// or when the panel is too short for the icon to fit alongside
    /// the rest of the cluster.
    pub last_icon_cell: Option<(u16, u16)>,
    pub feedback: Option<String>,
    pub feedback_is_error: bool,
    /// True from when a debug session ends until the next one starts. While set
    /// (and `console_tail` is non-empty) the idle panel keeps the just-ended
    /// session's console output on screen instead of wiping straight back to the
    /// Run button, so a fast-exiting program's output/errors stay readable.
    pub session_ended: bool,
}

impl RunDebugPanel {
    pub fn new() -> Self {
        Self {
            active_file: None,
            runnable: false,
            run_is_debug: false,
            last_area: Rect::default(),
            last_button_area: Rect::default(),
            config_count: 0,
            selected_config: None,
            last_config_area: Rect::default(),
            debug_active: false,
            watch_remove_rects: Vec::new(),
            breakpoints: Vec::new(),
            breakpoint_row_rects: Vec::new(),
            breakpoint_remove_rects: Vec::new(),
            debug_status: String::new(),
            debug_paused: false,
            debug_control_rects: Vec::new(),
            debug_rows: Vec::new(),
            debug_scroll: 0,
            row_cursor: None,
            last_debug_row_y0: 0,
            last_debug_rows_shown: 0,
            last_debug_scroll: 0,
            replaced_debug_rows: None,
            console_tail: Vec::new(),
            repl_input: String::new(),
            repl_caret: None,
            last_prompt_area: Rect::default(),
            last_icon_cell: None,
            feedback: None,
            feedback_is_error: false,
            session_ended: false,
        }
    }

    /// Caret position in `repl_input`, as a char index.
    pub fn repl_caret(&self) -> usize {
        crate::widgets::line_edit::opt_caret(&self.repl_input, self.repl_caret)
    }

    /// Move the REPL caret with `step(input, caret)`.
    pub fn move_repl_caret(&mut self, step: impl FnOnce(&str, usize) -> usize) {
        crate::widgets::line_edit::walk_opt(&self.repl_input, &mut self.repl_caret, step);
    }

    /// Insert `c` at the REPL caret.
    pub fn push_repl_char(&mut self, c: char) {
        let mut buf = [0u8; 4];
        let s = c.encode_utf8(&mut buf);
        crate::widgets::line_edit::edit_opt(&mut self.repl_input, &mut self.repl_caret, |t, at| {
            crate::widgets::line_edit::insert_at(t, at, s)
        });
    }

    /// Delete one cluster (or word) before the REPL caret.
    pub fn backspace_repl(&mut self, word: bool) {
        crate::widgets::line_edit::edit_opt(&mut self.repl_input, &mut self.repl_caret, |t, at| {
            crate::widgets::line_edit::delete_before(t, at, word)
        });
    }

    /// Delete one cluster (or word) at the REPL caret.
    pub fn delete_repl(&mut self, word: bool) {
        crate::widgets::line_edit::edit_opt(&mut self.repl_input, &mut self.repl_caret, |t, at| {
            crate::widgets::line_edit::delete_at(t, at, word)
        });
    }

    /// Clear the REPL prompt and reset its caret.
    pub fn clear_repl(&mut self) {
        self.repl_input.clear();
        self.repl_caret = None;
    }

    /// Map a click to the watch whose remove `✕` the last frame drew at
    /// `(x, y)`: its index in `watches`, the app's expressions as they are
    /// now, or `None` once it is gone (#2753).
    pub fn watch_remove_at(&self, x: u16, y: u16, watches: &[String]) -> Option<usize> {
        let (_, _, at, expression) = self
            .watch_remove_rects
            .iter()
            .find(|&&(ry, rx, ..)| ry == y && (x == rx || x == rx + 1))?;
        follow(*at, expression, watches.len(), |i, e| watches[i] == *e)
    }

    /// The debug toolbar button painted at `(x, y)`, if it acts in the
    /// session's state; a greyed-out step button is not one (#1545).
    pub fn debug_control_at(&self, x: u16, y: u16) -> Option<DebugControl> {
        self.debug_control_painted_at(x, y)
            .filter(|c| c.enabled(self.debug_paused))
    }

    /// The debug toolbar button painted at `(x, y)`, greyed out or not: the
    /// one whose name and key the pointer's tooltip shows.
    pub fn debug_control_painted_at(&self, x: u16, y: u16) -> Option<DebugControl> {
        self.debug_control_rects
            .iter()
            .find(|&&(ry, rx, _)| ry == y && (rx..rx + 3).contains(&x))
            .map(|&(_, _, c)| c)
    }

    /// Map a click to a painted breakpoint (#250): the index into
    /// `breakpoints` of the one the last frame drew there, where it is now
    /// (#2753), and whether it landed on the remove `✕`. `None` once that
    /// breakpoint is gone.
    pub fn breakpoint_at(&self, x: u16, y: u16) -> Option<(usize, bool)> {
        let now = |at: usize, (path, line): &BreakpointKey| {
            follow(at, &(path, *line), self.breakpoints.len(), |i, &(p, l)| {
                self.breakpoints[i].path == *p && self.breakpoints[i].line == l
            })
        };
        if let Some((_, _, at, key)) = self
            .breakpoint_remove_rects
            .iter()
            .find(|&&(ry, rx, ..)| ry == y && (x == rx || x == rx + 1))
        {
            return now(*at, key).map(|i| (i, true));
        }
        let (_, at, key) = self
            .breakpoint_row_rects
            .iter()
            .find(|&&(ry, ..)| ry == y)?;
        now(*at, key).map(|i| (i, false))
    }

    /// Paint one breakpoint on row `y` between `x0` and `right`, recording
    /// its click cells.
    fn put_breakpoint(
        &mut self,
        cx: &ViewCx,
        buf: &mut Buffer,
        index: usize,
        x0: u16,
        y: u16,
        right: u16,
    ) {
        let Some(bp) = self.breakpoints.get(index).cloned() else {
            return;
        };
        let text_right = right.saturating_sub(3);
        let mut x = put_clipped(
            buf,
            x0,
            y,
            text_right,
            "\u{25cf} ",
            Style::default().fg(cx.theme.ui(Color::Rgb(0xe5, 0x14, 0x00))),
        );
        x = put_clipped(
            buf,
            x,
            y,
            text_right,
            &bp.label,
            Style::default().fg(cx.theme.ui(DBG_NAME)),
        );
        if let Some(detail) = &bp.detail {
            put_clipped(
                buf,
                x + 1,
                y,
                text_right,
                detail,
                Style::default()
                    .fg(cx.theme.ui(DBG_TYPE))
                    .add_modifier(Modifier::ITALIC),
            );
        }
        let key = (bp.path.clone(), bp.line);
        self.breakpoint_row_rects.push((y, index, key.clone()));
        if right > x0 + 2 {
            let rx = right - 2;
            put_clipped(
                buf,
                rx,
                y,
                right,
                "\u{2715}",
                Style::default().fg(cx.theme.ui(DBG_TYPE)),
            );
            self.breakpoint_remove_rects.push((y, rx, index, key));
        }
    }

    /// Map a click at screen row `y` to the index of the debug row drawn there,
    /// or `None` if the click missed the rendered rows.
    pub fn debug_row_at(&self, y: u16) -> Option<usize> {
        if !self.debug_active || self.last_debug_rows_shown == 0 || y < self.last_debug_row_y0 {
            return None;
        }
        let offset = (y - self.last_debug_row_y0) as usize;
        if offset >= self.last_debug_rows_shown {
            return None;
        }
        let at = self.last_debug_scroll + offset;
        let Some(drawn) = &self.replaced_debug_rows else {
            return (at < self.debug_rows.len()).then_some(at);
        };
        if at >= drawn.len() {
            return None;
        }
        let chain = row_chain(drawn, &row_parents(drawn), at);
        find_chain(&self.debug_rows, &row_parents(&self.debug_rows), &chain)
    }

    /// Whether the keyboard cursor can rest on row `idx`: any row but a
    /// section header (#2748).
    fn takes_cursor(&self, idx: usize) -> bool {
        self.debug_rows
            .get(idx)
            .is_some_and(|row| !matches!(row.kind, DebugRowKind::Header { .. }))
    }

    /// The nearest row the cursor can rest on from `from` on, looking down
    /// (or up), `from` itself included.
    fn cursor_row_from(&self, from: usize, down: bool) -> Option<usize> {
        if down {
            (from..self.debug_rows.len()).find(|&i| self.takes_cursor(i))
        } else {
            (0..=from.min(self.debug_rows.len().saturating_sub(1)))
                .rev()
                .find(|&i| self.takes_cursor(i))
        }
    }

    /// Give the rows the keys (#2748): the cursor on the first row, or the
    /// last with `last`. False, and the prompt keeps the keys, when no row
    /// can take the cursor.
    pub fn enter_rows(&mut self, last: bool) -> bool {
        let row = if last {
            self.debug_rows
                .len()
                .checked_sub(1)
                .and_then(|end| self.cursor_row_from(end, false))
        } else {
            self.cursor_row_from(0, true)
        };
        self.row_cursor = row;
        self.scroll_row_cursor_into_view();
        row.is_some()
    }

    /// Whether a click at `(x, y)` landed on the `❯` prompt (#2748).
    pub fn prompt_at(&self, x: u16, y: u16) -> bool {
        self.debug_active && crate::widgets::hover::contains(self.last_prompt_area, Some((x, y)))
    }

    /// Put the row cursor on row `idx`, a row a click landed on, when the
    /// cursor can rest there: mouse and keyboard agree on the row, as in VS
    /// Code's lists.
    pub fn put_row_cursor(&mut self, idx: usize) {
        if self.takes_cursor(idx) {
            self.row_cursor = Some(idx);
        }
    }

    /// Move the row cursor `by` rows, down for a positive count, past the
    /// headers, stopping at the first and last rows.
    pub fn move_row_cursor(&mut self, by: isize) {
        let Some(at) = self.row_cursor else {
            return;
        };
        let target = at
            .saturating_add_signed(by)
            .min(self.debug_rows.len().saturating_sub(1));
        let down = by > 0;
        self.row_cursor = self
            .cursor_row_from(target, down)
            .or_else(|| self.cursor_row_from(target, !down))
            .or(Some(at));
        self.scroll_row_cursor_into_view();
    }

    /// How many rows one PageUp / PageDown moves: the rows drawn last frame.
    pub fn row_page(&self) -> isize {
        self.last_debug_rows_shown.max(1) as isize
    }

    /// Scroll so the cursor row is among the rows drawn.
    pub fn scroll_row_cursor_into_view(&mut self) {
        let Some(at) = self.row_cursor else {
            return;
        };
        let shown = self.last_debug_rows_shown.max(1);
        if at < self.debug_scroll {
            self.debug_scroll = at;
        } else if at >= self.debug_scroll + shown {
            self.debug_scroll = at + 1 - shown;
        }
    }

    /// Swap in rebuilt rows (#2748), the keyboard staying on the row it was
    /// on: the same frame, thread, variable, watch or breakpoint, wherever
    /// the rebuild moved it ([`row_chain`]). Rows come and go above it
    /// (another thread's frames, a variable opened), so the index alone
    /// would land on an unrelated row for the next Enter or Delete. When
    /// its row is gone, the prompt has the keys again. A click read before
    /// the next frame follows the row it was drawn on the same way
    /// ([`Self::debug_row_at`]).
    pub fn replace_rows(&mut self, rows: Vec<DebugRow>) {
        let old = std::mem::replace(&mut self.debug_rows, rows);
        self.row_cursor = self.row_cursor.filter(|&at| at < old.len()).and_then(|at| {
            let chain = row_chain(&old, &row_parents(&old), at);
            find_chain(&self.debug_rows, &row_parents(&self.debug_rows), &chain)
        });
        self.settle_row_cursor();
        // The first rows replaced since the frame are the ones on screen.
        self.replaced_debug_rows.get_or_insert(old);
    }

    /// After the rows are rebuilt (#2748): a cursor past the end, or on a
    /// row that became a header, moves to the nearest row that takes it,
    /// and with no such row the prompt has the keys again.
    pub fn settle_row_cursor(&mut self) {
        if !self.debug_active {
            self.row_cursor = None;
            return;
        }
        let Some(at) = self.row_cursor else {
            return;
        };
        let at = at.min(self.debug_rows.len().saturating_sub(1));
        self.row_cursor = self
            .cursor_row_from(at, false)
            .or_else(|| self.cursor_row_from(at, true));
        self.scroll_row_cursor_into_view();
    }

    /// The screen row the cursor row was drawn on last frame, if it was.
    pub fn row_cursor_y(&self) -> Option<u16> {
        let at = self.row_cursor?;
        let offset = at.checked_sub(self.debug_scroll)?;
        (offset < self.last_debug_rows_shown).then(|| self.last_debug_row_y0 + offset as u16)
    }

    pub fn set_active_file(&mut self, path: Option<PathBuf>) {
        self.active_file = path;
    }

    pub fn click_button(&self, x: u16, y: u16) -> bool {
        let r = self.last_button_area;
        r.width > 0
            && r.height > 0
            && x >= r.x
            && x < r.x + r.width
            && y >= r.y
            && y < r.y + r.height
    }

    /// Whether a click lands on the config row under the button (#250).
    pub fn click_config(&self, x: u16, y: u16) -> bool {
        let r = self.last_config_area;
        r.width > 0
            && r.height > 0
            && x >= r.x
            && x < r.x + r.width
            && y >= r.y
            && y < r.y + r.height
    }

    /// The config row's text: the selected configuration's name, or an
    /// invitation when configs exist but none is selected.
    fn config_row_label(&self) -> Option<String> {
        match (&self.selected_config, self.config_count) {
            (Some(name), _) => Some(format!("⚙ {name} ▾")),
            (None, 0) => None,
            // "entries" rather than "configs": the count covers compounds too
            // since #250, and the singular case read "1 debug configs".
            (None, 1) => Some(String::from("⚙ 1 debug entry ▾")),
            (None, n) => Some(format!("⚙ {n} debug entries ▾")),
        }
    }

    /// The newest `max_rows` rows of the console tail, each line soft-wrapped
    /// to `width` columns (#867), oldest first so they paint top-down with
    /// the newest last. Each row says whether its line is a REPL echo
    /// (`❯ expr`), drawn in the accent colour down all its rows.
    fn console_rows(&self, width: usize, max_rows: usize) -> Vec<(ConsoleRow, bool)> {
        let mut rows = Vec::new();
        for line in self.console_tail.iter().rev() {
            let echo = line.text.starts_with('❯');
            let keep = max_rows.saturating_sub(rows.len());
            for row in wrap_console_line_tail(line, width, keep).into_iter().rev() {
                if rows.len() == max_rows {
                    rows.reverse();
                    return rows;
                }
                rows.push((row, echo));
            }
        }
        rows.reverse();
        rows
    }

    /// Render the paused-state tree (Variant A / Darcula): a status pill, the
    /// call-stack + variables tree with type-coloured values, then the console
    /// and a REPL bar pinned to the bottom. Records `last_debug_row_y0` /
    /// `last_debug_rows_shown` for click mapping.
    fn render_debug_tree(&mut self, cx: &ViewCx, inner: Rect, buf: &mut Buffer) {
        self.watch_remove_rects.clear();
        self.breakpoint_row_rects.clear();
        self.breakpoint_remove_rects.clear();
        self.debug_control_rects.clear();
        let right = inner.x + inner.width;
        let mut y = inner.y;

        // The debug toolbar (#1545): Continue / Pause, Step Over, Step Into,
        // Step Out, Restart, Stop, then the status pill, e.g.
        // " Paused (breakpoint) ". Each button's name and key is its tooltip.
        // A sidebar too narrow for all six wraps them onto further rows, so
        // Stop and the rest stay clickable at the minimum width.
        if !self.debug_status.is_empty() {
            let bottom = inner.y + inner.height;
            let mut x = inner.x + 1;
            for control in DebugControl::toolbar(self.debug_paused) {
                if x + 3 > right && x > inner.x + 1 {
                    x = inner.x + 1;
                    y += 1;
                }
                if x + 3 > right || y >= bottom {
                    break;
                }
                let fg = if control.enabled(self.debug_paused) {
                    cx.theme.ui(DBG_PILL_FG)
                } else {
                    cx.theme.ui(DBG_PLACEHOLDER)
                };
                let bg = cx.theme.ui(DBG_BAR_BG);
                buf.set_string(
                    x,
                    y,
                    format!(" {} ", control.glyph()),
                    Style::default().fg(fg).bg(bg),
                );
                self.debug_control_rects.push((y, x, control));
                x += 3;
            }
            let text = format!(" {} ", self.debug_status);
            put_clipped(
                buf,
                x + 1,
                y,
                right,
                &text,
                Style::default()
                    .fg(cx.theme.ui(DBG_PILL_FG))
                    .bg(cx.theme.ui(DBG_PILL_BG))
                    .add_modifier(Modifier::BOLD),
            );
            y += 2;
        }
        if y >= inner.y + inner.height {
            return;
        }

        // Reserve the bottom for the console + the REPL input area. The input
        // area is 2 rows: a "DEBUG CONSOLE" label and the filled input field.
        // The console is sized to its actual row count (capped at 6) so the
        // newest line sits directly above the label and output grows UPWARD,
        // like a terminal — never floating at the top of a fixed-height box.
        // Lines wrap to the panel's width rather than clip at its edge (#867).
        let bottom = inner.y + inner.height;
        let input_h: u16 = 2;
        let console_avail = bottom.saturating_sub(y).saturating_sub(input_h + 2);
        let console_w = inner.width.saturating_sub(2);
        let console_rows = self.console_rows(console_w as usize, console_avail.min(6) as usize);
        let console_h = console_rows.len() as u16;
        let rows_bottom = bottom.saturating_sub(input_h + console_h);
        let rows_area_h = rows_bottom.saturating_sub(y) as usize;
        self.last_debug_row_y0 = y;
        self.last_debug_scroll = self.debug_scroll;
        self.replaced_debug_rows = None;

        let mut shown = 0usize;
        // Breakpoint rows paint after the loop: `put_breakpoint` needs
        // `&mut self` while the loop holds `debug_rows`.
        let mut breakpoint_rows: Vec<(usize, u16, u16, u16)> = Vec::new();
        for row in self
            .debug_rows
            .iter()
            .skip(self.debug_scroll)
            .take(rows_area_h)
        {
            let row_y = y + shown as u16;
            match &row.kind {
                DebugRowKind::Header { title } => {
                    // Filled bar across the full width, title in teal.
                    buf.set_style(
                        Rect {
                            x: inner.x,
                            y: row_y,
                            width: inner.width,
                            height: 1,
                        },
                        Style::default().bg(cx.theme.ui(DBG_BAR_BG)),
                    );
                    let t: String = title
                        .chars()
                        .take(inner.width.saturating_sub(2) as usize)
                        .collect();
                    buf.set_string(
                        inner.x + 1,
                        row_y,
                        &t,
                        Style::default()
                            .fg(cx.theme.ui(DBG_BAR_FG))
                            .bg(cx.theme.ui(DBG_BAR_BG))
                            .add_modifier(Modifier::BOLD),
                    );
                }
                DebugRowKind::Frame {
                    selected,
                    name,
                    location,
                    ..
                } => {
                    if *selected {
                        buf.set_style(
                            Rect {
                                x: inner.x,
                                y: row_y,
                                width: inner.width,
                                height: 1,
                            },
                            Style::default().bg(cx.theme.ui(DBG_FRAME_BG)),
                        );
                        buf.set_string(
                            inner.x,
                            row_y,
                            "▌",
                            Style::default()
                                .fg(cx.theme.ui(DBG_ACCENT))
                                .bg(cx.theme.ui(DBG_FRAME_BG)),
                        );
                    }
                    let bg = if *selected {
                        Some(cx.theme.ui(DBG_FRAME_BG))
                    } else {
                        None
                    };
                    let mut x = inner.x + 2;
                    let name_style = if *selected {
                        Style::default()
                            .fg(cx.theme.ui(DBG_FRAME_SEL_FG))
                            .add_modifier(Modifier::BOLD)
                    } else {
                        Style::default().fg(cx.theme.ui(DBG_NAME))
                    };
                    x = put_clipped(buf, x, row_y, right, name, with_bg(name_style, bg));
                    x = put_clipped(buf, x, row_y, right, " ", with_bg(Style::default(), bg));
                    put_clipped(
                        buf,
                        x,
                        row_y,
                        right,
                        location,
                        with_bg(Style::default().fg(cx.theme.ui(DBG_LOC)), bg),
                    );
                }
                DebugRowKind::Thread { name, selected, .. } => {
                    // Open chevron on the thread whose frames follow.
                    let text = format!("{} {name}", if *selected { "▾" } else { "▸" });
                    let style = if *selected {
                        Style::default()
                            .fg(cx.theme.ui(DBG_FRAME_SEL_FG))
                            .add_modifier(Modifier::BOLD)
                    } else {
                        Style::default().fg(cx.theme.ui(DBG_SCOPE))
                    };
                    put_clipped(buf, inner.x + 1, row_y, right, &text, style);
                }
                DebugRowKind::Scope { name, open, .. } => {
                    let text = match open {
                        Some(true) => format!("\u{25be} {name}"),
                        Some(false) => format!("\u{25b8} {name}"),
                        None => name.clone(),
                    };
                    put_clipped(
                        buf,
                        inner.x + 1,
                        row_y,
                        right,
                        &text,
                        Style::default()
                            .fg(cx.theme.ui(DBG_SCOPE))
                            .add_modifier(Modifier::BOLD),
                    );
                }
                DebugRowKind::Variable {
                    expandable,
                    expanded,
                    name,
                    value,
                    type_name,
                    ..
                } => {
                    let indent = (row.indent as u16) * 2;
                    let mut x = inner.x + indent;
                    let chev = if *expandable {
                        if *expanded { "▾ " } else { "▸ " }
                    } else {
                        "  "
                    };
                    x = put_clipped(
                        buf,
                        x,
                        row_y,
                        right,
                        chev,
                        Style::default().fg(cx.theme.ui(DBG_CHEV)),
                    );
                    x = put_clipped(
                        buf,
                        x,
                        row_y,
                        right,
                        name,
                        Style::default().fg(cx.theme.ui(DBG_NAME)),
                    );
                    x = put_clipped(
                        buf,
                        x,
                        row_y,
                        right,
                        " = ",
                        Style::default().fg(cx.theme.ui(DBG_EQ)),
                    );
                    x = put_clipped(
                        buf,
                        x,
                        row_y,
                        right,
                        value,
                        Style::default().fg(value_color(type_name, cx.theme)),
                    );
                    if !type_name.is_empty() {
                        put_clipped(
                            buf,
                            x,
                            row_y,
                            right,
                            &format!(" : {type_name}"),
                            Style::default()
                                .fg(cx.theme.ui(DBG_TYPE))
                                .add_modifier(Modifier::ITALIC),
                        );
                    }
                }
                DebugRowKind::Watch {
                    index,
                    expression,
                    value,
                    available,
                    changed,
                    pending,
                } => {
                    let indent = (row.indent as u16) * 2;
                    let mut x = inner.x + indent;
                    // Text clips three cells early: the remove `\u{2715}` owns
                    // the right edge, and a long value ran under it.
                    let right = right.saturating_sub(3);
                    x = put_clipped(
                        buf,
                        x,
                        row_y,
                        right,
                        expression,
                        Style::default().fg(cx.theme.ui(DBG_NAME)),
                    );
                    x = put_clipped(
                        buf,
                        x,
                        row_y,
                        right,
                        " = ",
                        Style::default().fg(cx.theme.ui(DBG_EQ)),
                    );
                    let (text, style) = if *pending {
                        ("\u{2026}", Style::default().fg(cx.theme.ui(DBG_TYPE)))
                    } else if !*available {
                        (
                            "<not available>",
                            Style::default()
                                .fg(cx.theme.ui(DBG_TYPE))
                                .add_modifier(Modifier::ITALIC),
                        )
                    } else if *changed {
                        (
                            value.as_str(),
                            Style::default()
                                .fg(cx.theme.ui(Color::Rgb(0xb6, 0xee, 0xc4)))
                                .add_modifier(Modifier::BOLD),
                        )
                    } else {
                        (
                            value.as_str(),
                            Style::default().fg(value_color("", cx.theme)),
                        )
                    };
                    put_clipped(buf, x, row_y, right, text, style);
                    // Per-row remove ✕ pinned at the right edge, recorded for
                    // the click map (cleared at render start — hit rects
                    // always describe the painted frame).
                    let right = right + 3;
                    if right > inner.x + 2 {
                        let rx = right - 2;
                        put_clipped(
                            buf,
                            rx,
                            row_y,
                            right,
                            "\u{2715}",
                            Style::default().fg(cx.theme.ui(DBG_TYPE)),
                        );
                        self.watch_remove_rects
                            .push((row_y, rx, *index, expression.clone()));
                    }
                }
                DebugRowKind::Breakpoint { index, .. } => {
                    let indent = (row.indent as u16) * 2;
                    breakpoint_rows.push((*index, inner.x + indent, row_y, right));
                }
                DebugRowKind::WatchAdd => {
                    let indent = (row.indent as u16) * 2;
                    put_clipped(
                        buf,
                        inner.x + indent,
                        row_y,
                        right,
                        "+ Add Expression",
                        Style::default()
                            .fg(cx.theme.ui(DBG_TYPE))
                            .add_modifier(Modifier::ITALIC),
                    );
                }
            }
            shown += 1;
        }
        for (index, x, row_y, right) in breakpoint_rows {
            self.put_breakpoint(cx, buf, index, x, row_y, right);
        }
        self.last_debug_rows_shown = shown;
        // The keyboard's row (#2748), lit as Source Control lights its list's
        // while the panel has focus.
        if cx.focused
            && let Some(cursor_y) = self.row_cursor_y()
        {
            buf.set_style(
                Rect {
                    x: inner.x,
                    y: cursor_y,
                    width: inner.width,
                    height: 1,
                },
                Style::default().bg(cx.theme.ui(DBG_CURSOR_BG)),
            );
        }

        // Bottom-up: the input field is the last row, the "DEBUG CONSOLE" label
        // the row above it, and any console output sits above that.
        let field_y = bottom - 1;
        self.last_prompt_area = Rect {
            x: inner.x,
            y: field_y,
            width: inner.width,
            height: 1,
        };
        let label_y = bottom - 2;

        // Console: program output + REPL echoes, above the label.
        let console_y0 = label_y.saturating_sub(console_h);
        for (i, (row, echo)) in console_rows.iter().enumerate() {
            let style = if *echo {
                Style::default().fg(cx.theme.ui(DBG_ACCENT))
            } else {
                Style::default().fg(cx.theme.ui(DBG_LOC))
            };
            put_console_row(
                cx,
                buf,
                inner.x + 1,
                console_y0 + i as u16,
                row,
                console_w,
                style,
            );
        }

        // "DEBUG CONSOLE" label above the field.
        put_clipped(
            buf,
            inner.x + 1,
            label_y,
            right,
            "DEBUG CONSOLE",
            Style::default()
                .fg(cx.theme.ui(DBG_LOC))
                .add_modifier(Modifier::BOLD),
        );

        // The input field: a subtle full-width fill makes it read as a text box.
        // A teal caret, then the input (or a dim-italic placeholder when empty),
        // with a teal block cursor marking the insertion point.
        buf.set_style(
            Rect {
                x: inner.x,
                y: field_y,
                width: inner.width,
                height: 1,
            },
            Style::default().bg(cx.theme.ui(DBG_FIELD_BG)),
        );
        let bg = Some(cx.theme.ui(DBG_FIELD_BG));
        let caret_end = put_clipped(
            buf,
            inner.x + 1,
            field_y,
            right,
            "❯ ",
            with_bg(
                Style::default()
                    .fg(cx.theme.ui(DBG_ACCENT))
                    .add_modifier(Modifier::BOLD),
                bg,
            ),
        );
        // The block cursor marks the insertion point while the prompt has
        // the keys; while a row has them (#2748) the field shows none.
        let caret = if self.row_cursor.is_none() {
            Style::default().bg(cx.theme.ui(DBG_ACCENT))
        } else {
            with_bg(Style::default(), bg)
        };
        if self.repl_input.is_empty() {
            // Block cursor at the insertion point, then the ghost placeholder.
            let after_cursor = put_clipped(buf, caret_end, field_y, right, " ", caret);
            put_clipped(
                buf,
                after_cursor,
                field_y,
                right,
                "Evaluate expression",
                with_bg(
                    Style::default()
                        .fg(cx.theme.ui(DBG_PLACEHOLDER))
                        .add_modifier(Modifier::ITALIC),
                    bg,
                ),
            );
        } else {
            let avail = usize::from(right.saturating_sub(caret_end));
            if avail > 0 {
                let caret_idx = self.repl_caret();
                let win = crate::widgets::line_edit::window(&self.repl_input, caret_idx, avail);
                let shown = crate::widgets::line_edit::visible_slice(&self.repl_input, win);
                put_clipped(
                    buf,
                    caret_end,
                    field_y,
                    right,
                    shown,
                    with_bg(Style::default().fg(cx.theme.ui(DBG_NAME)), bg),
                );
                let cx_col = caret_end.saturating_add(win.caret_cell as u16);
                if cx_col < right {
                    if caret_idx >= crate::widgets::line_edit::char_len(&self.repl_input) {
                        put_clipped(buf, cx_col, field_y, right, " ", caret);
                    } else if self.row_cursor.is_none() {
                        buf[(cx_col, field_y)].set_style(
                            Style::default()
                                .fg(cx.theme.ui(Color::Black))
                                .bg(cx.theme.ui(DBG_ACCENT)),
                        );
                    }
                }
            }
        }
    }

    pub fn button_label(&self) -> String {
        match self.active_file.as_ref().and_then(|p| p.file_name()) {
            Some(name) => {
                // Compiled source builds + launches the debugger; scripts and
                // executables run in a terminal.
                let verb = if self.run_is_debug { "Debug" } else { "Run" };
                format!("{verb} {}", name.to_string_lossy())
            }
            None => String::from("Run and Debug"),
        }
    }
}

impl Default for RunDebugPanel {
    fn default() -> Self {
        Self::new()
    }
}

impl RunDebugPanel {
    /// Draw the view into `area` with this frame's [`ViewCx`].
    pub fn draw(&mut self, cx: &ViewCx, area: Rect, buf: &mut Buffer) {
        let border_style = if cx.focused {
            Style::default().fg(Color::Rgb(
                FOCUS_BORDER_RGB.0,
                FOCUS_BORDER_RGB.1,
                FOCUS_BORDER_RGB.2,
            ))
        } else {
            Style::default().fg(Color::DarkGray)
        };
        let block = crate::widgets::surface::view_block(cx.theme, true, border_style);
        let inner = block.inner(area);
        block.render(area, buf);
        // Black theme: replace the solid focus border with the brand gradient.
        // This panel has no border title, so nothing needs re-stamping.
        crate::widgets::surface::paint_view_focus(
            buf,
            area,
            cx.theme,
            cx.focused,
            cx.theme.gradient(),
        );
        self.last_area = area;
        self.last_button_area = Rect::default();
        self.last_config_area = Rect::default();
        self.last_icon_cell = None;
        self.last_debug_rows_shown = 0;
        if inner.height == 0 || inner.width == 0 {
            return;
        }

        // Paused at a breakpoint: render the call-stack + variables tree instead
        // of the empty-state Run button.
        if self.debug_active {
            self.render_debug_tree(cx, inner, buf);
            return;
        }

        // Vertical cluster, top-to-bottom: icon, gap, headline, gap, body, gap, button.
        // Centre the cluster vertically so the panel feels balanced like the mockup.
        const GAP_AFTER_ICON: u16 = 2;
        const TITLE_H: u16 = 1;
        const GAP_AFTER_TITLE: u16 = 1;
        const BODY_MAX_H: u16 = 3;
        const GAP_AFTER_BODY: u16 = 2;
        const BUTTON_H: u16 = 3;

        let show_button = self.active_file.is_none() || self.runnable;
        let action_h = if show_button {
            BUTTON_H
        } else {
            u16::from(self.config_row_label().is_some())
        };
        let icon_w = RUN_DEBUG_ICON_CELLS_W.min(inner.width);
        let icon_h_full = RUN_DEBUG_ICON_CELLS_H;
        let cluster_full = icon_h_full
            + GAP_AFTER_ICON
            + TITLE_H
            + GAP_AFTER_TITLE
            + BODY_MAX_H
            + GAP_AFTER_BODY
            + action_h;

        // If the panel is too short for the full cluster, drop the icon
        // first (it's decorative) before sacrificing the body or button.
        let (icon_h, gap_after_icon, cluster) = if inner.height >= cluster_full {
            (icon_h_full, GAP_AFTER_ICON, cluster_full)
        } else {
            (
                0,
                0,
                TITLE_H + GAP_AFTER_TITLE + BODY_MAX_H + GAP_AFTER_BODY + action_h,
            )
        };

        // After a session ends with output, anchor the cluster to the top so the
        // retained console (rendered below the button) gets the lower region;
        // otherwise centre it like the resting state.
        let show_ended_console = self.session_ended && !self.console_tail.is_empty();
        self.breakpoint_row_rects.clear();
        self.breakpoint_remove_rects.clear();
        self.debug_control_rects.clear();
        let top_pad = if show_ended_console || !self.breakpoints.is_empty() {
            0
        } else if inner.height > cluster {
            (inner.height - cluster) / 2
        } else {
            0
        };
        let mut y = inner.y + top_pad;

        if icon_h > 0 && y + icon_h <= inner.y + inner.height {
            let icon_x = inner.x + (inner.width.saturating_sub(icon_w)) / 2;
            self.last_icon_cell = Some((icon_x, y));
            // Glyph fallback: paint the cod-debug-alt codicon centred
            // inside the reserved icon block so terminals without
            // OSC-1337 image support still see a recognisable shape.
            // On iTerm2 the post-draw `flush_run_debug_icon_overlay`
            // overwrites these cells with the proper rasterised PNG.
            let glyph_style = Style::default()
                .fg(Color::Rgb(BODY_FG_RGB.0, BODY_FG_RGB.1, BODY_FG_RGB.2))
                .add_modifier(Modifier::BOLD);
            let glyph_x = icon_x + icon_w / 2;
            let glyph_y = y + icon_h / 2;
            buf.set_span(
                glyph_x,
                glyph_y,
                &Span::styled(crate::icons::ACTIVITY_RUN_DEBUG.to_string(), glyph_style),
                1,
            );
            y += icon_h + gap_after_icon;
        }

        if y + TITLE_H > inner.y + inner.height {
            return;
        }
        let title = Paragraph::new(Line::from("RUN AND DEBUG"))
            .alignment(Alignment::Center)
            .style(
                Style::default()
                    .fg(Color::Rgb(TITLE_FG_RGB.0, TITLE_FG_RGB.1, TITLE_FG_RGB.2))
                    .add_modifier(Modifier::BOLD),
            );
        title.render(
            Rect {
                x: inner.x,
                y,
                width: inner.width,
                height: TITLE_H,
            },
            buf,
        );
        y += TITLE_H + GAP_AFTER_TITLE;

        if y >= inner.y + inner.height {
            return;
        }
        let body_text = match self.active_file.as_ref() {
            Some(_) if self.runnable => {
                "Press the button below to run the active file in a new terminal."
            }
            Some(_) => {
                "This file can't be run or debugged. Open a Python, Rust, C/C++, or script file."
            }
            None => "Open a file that can be run or debugged, then press the button below.",
        };
        let body_h = BODY_MAX_H.min(inner.y + inner.height - y);
        let body_x_pad = (inner.width / 12).clamp(1, 4);
        let body_area = Rect {
            x: inner.x + body_x_pad,
            y,
            width: inner.width.saturating_sub(body_x_pad * 2).max(1),
            height: body_h,
        };
        let body = Paragraph::new(body_text)
            .style(Style::default().fg(Color::Rgb(BODY_FG_RGB.0, BODY_FG_RGB.1, BODY_FG_RGB.2)))
            .alignment(Alignment::Center)
            .wrap(Wrap { trim: true });
        body.render(body_area, buf);
        y += BODY_MAX_H + GAP_AFTER_BODY;

        // A file is open but croft can't run/debug it directly: omit the
        // primary Run/Debug button (`last_button_area` stays default), while
        // still rendering the workspace's launch.json config row, feedback,
        // breakpoints, and any retained session console below (#2943).
        let mut next_y = y;
        if show_button {
            if y + BUTTON_H > inner.y + inner.height {
                return;
            }
            let label = self.button_label();
            let label_chars = label.chars().count() as u16;
            // Pin the button to the panel's interior so it can never be wider
            // than the available space; without this clamp `inner.width -
            // button_w` underflowed at narrow sidebar widths and ratatui
            // panicked indexing the buffer at a wrapped-u16 column.
            let button_w = (label_chars + 8).min(inner.width.saturating_sub(2));
            if button_w < 4 {
                return;
            }
            let button_x = inner.x + inner.width.saturating_sub(button_w) / 2;
            let button_area = Rect {
                x: button_x,
                y,
                width: button_w,
                height: BUTTON_H,
            };
            self.last_button_area = button_area;
            // Black theme: brand-teal button fill; Croft Dark keeps VS Code blue;
            // Croft Loch draws the shared pill, lifted under the pointer.
            let (button_bg, button_fg) = crate::widgets::source_control::primary_button_colors(
                cx.theme,
                cx.theme.gradient(),
            );
            crate::widgets::source_control::render_button(
                buf,
                button_area,
                label.as_str(),
                button_bg,
                button_fg,
                cx.theme,
                crate::widgets::hover::contains(button_area, cx.pointer),
            );
            next_y = button_area.y + button_area.height + 1;
        }
        // The launch.json config row (#250): which configuration F5 starts,
        // clickable to open the Debug Configuration picker.
        if let Some(label) = self.config_row_label()
            && next_y < inner.y + inner.height
        {
            let shown: String = label
                .chars()
                .take(inner.width.saturating_sub(2) as usize)
                .collect();
            let w = shown.chars().count() as u16;
            let x = inner.x + inner.width.saturating_sub(w) / 2;
            let style = Style::default().fg(cx.theme.ui(Color::Rgb(0x8f, 0xd9, 0xcf)));
            buf.set_string(x, next_y, &shown, style);
            self.last_config_area = Rect {
                x,
                y: next_y,
                width: w,
                height: 1,
            };
            next_y = next_y.saturating_add(1);
        }
        if let Some(msg) = self.feedback.as_ref()
            && next_y < inner.y + inner.height
        {
            let style = if self.feedback_is_error {
                Style::default().fg(cx.theme.ui(Color::Rgb(0xe7, 0x70, 0x70)))
            } else {
                Style::default().fg(cx.theme.ui(Color::Rgb(0xa3, 0xbe, 0x8c)))
            };
            let room = inner.width.saturating_sub(2) as usize;
            for row in wrap_feedback(msg, room) {
                if next_y >= inner.y + inner.height {
                    break;
                }
                buf.set_stringn(inner.x + 1, next_y, &row, room, style);
                next_y = next_y.saturating_add(1);
            }
        }
        // BREAKPOINTS (#250): listed at rest too, so they can be found and
        // cleared without starting a session.
        if !self.breakpoints.is_empty() && next_y + 1 < inner.y + inner.height {
            next_y = next_y.saturating_add(1);
            buf.set_string(
                inner.x + 1,
                next_y,
                "BREAKPOINTS",
                Style::default()
                    .fg(Color::Rgb(TITLE_FG_RGB.0, TITLE_FG_RGB.1, TITLE_FG_RGB.2))
                    .add_modifier(Modifier::BOLD),
            );
            next_y = next_y.saturating_add(1);
            let right = inner.x + inner.width;
            for i in 0..self.breakpoints.len() {
                if next_y >= inner.y + inner.height {
                    break;
                }
                self.put_breakpoint(cx, buf, i, inner.x + 2, next_y, right);
                next_y = next_y.saturating_add(1);
            }
        }
        // Retained console from the just-ended session: program output / errors
        // stay readable after the run instead of being wiped to the Run button.
        if show_ended_console && next_y + 1 < inner.y + inner.height {
            next_y = next_y.saturating_add(1);
            buf.set_string(
                inner.x + 1,
                next_y,
                "DEBUG CONSOLE",
                Style::default()
                    .fg(Color::Rgb(TITLE_FG_RGB.0, TITLE_FG_RGB.1, TITLE_FG_RGB.2))
                    .add_modifier(Modifier::BOLD),
            );
            next_y = next_y.saturating_add(1);
            let bottom = inner.y + inner.height;
            let avail = bottom.saturating_sub(next_y) as usize;
            let max_w = inner.width.saturating_sub(2) as usize;
            let line_style = Style::default().fg(cx.theme.ui(Color::Rgb(0x9d, 0xa5, 0xb4)));
            for (row, _) in self.console_rows(max_w, avail) {
                put_console_row(cx, buf, inner.x + 1, next_y, &row, max_w as u16, line_style);
                next_y = next_y.saturating_add(1);
            }
        }
        let _ = next_y;
    }
}

#[cfg(test)]
mod tests {

    use super::*;
    use crate::ansi_text::AnsiLine;

    /// #2748: a rebuild that adds or drops rows above the keyboard's row
    /// keeps the keyboard on that row, and one that drops the row itself
    /// hands the keys back to the prompt, so the next Enter or Delete never
    /// lands on an unrelated row.
    #[test]
    fn the_row_cursor_follows_its_row_across_a_rebuild() {
        let row = |indent, kind| DebugRow { indent, kind };
        let thread = |id, selected| DebugRowKind::Thread {
            id,
            name: format!("t{id}"),
            selected,
        };
        let frame = |id| DebugRowKind::Frame {
            id,
            selected: false,
            name: format!("f{id}"),
            location: String::from("s.py:1"),
        };
        let header = || DebugRowKind::Header {
            title: String::from("CALL STACK"),
        };
        let mut panel = RunDebugPanel::new();
        panel.debug_active = true;
        panel.debug_rows = vec![
            row(0, header()),
            row(1, thread(1, true)),
            row(2, frame(11)),
            row(2, frame(12)),
            row(2, frame(13)),
            row(1, thread(2, false)),
            row(1, DebugRowKind::WatchAdd),
        ];
        panel.row_cursor = Some(5);
        // Thread 2 picked: thread 1's frames go, thread 2's come.
        panel.replace_rows(vec![
            row(0, header()),
            row(1, thread(1, false)),
            row(1, thread(2, true)),
            row(2, frame(21)),
            row(1, DebugRowKind::WatchAdd),
        ]);
        assert_eq!(panel.row_cursor, Some(2), "still on thread 2");
        // A stop with new frames: the cursor's frame is gone.
        panel.row_cursor = Some(3);
        panel.replace_rows(vec![
            row(0, header()),
            row(1, thread(2, true)),
            row(2, frame(31)),
            row(1, DebugRowKind::WatchAdd),
        ]);
        assert_eq!(
            panel.row_cursor, None,
            "its frame is gone: the prompt has the keys"
        );
    }

    /// #2748: two fields named alike under different objects are different
    /// rows. A rebuild (the panel rebuilds on every poll) keeps the
    /// keyboard on the second, not the first that shares its name.
    #[test]
    fn same_named_fields_under_different_parents_stay_apart() {
        let variable = |indent, name: &str, reference| DebugRow {
            indent,
            kind: DebugRowKind::Variable {
                reference,
                expandable: reference != 0,
                expanded: reference != 0,
                name: name.into(),
                value: String::from("1"),
                type_name: String::from("int"),
                evaluate_name: None,
            },
        };
        let rows = || {
            vec![
                DebugRow {
                    indent: 0,
                    kind: DebugRowKind::Header {
                        title: String::from("VARIABLES"),
                    },
                },
                variable(2, "first", 7),
                variable(3, "value", 0),
                variable(2, "second", 8),
                variable(3, "value", 0),
            ]
        };
        let mut panel = RunDebugPanel::new();
        panel.debug_active = true;
        panel.debug_rows = rows();
        panel.row_cursor = Some(4);
        panel.replace_rows(rows());
        assert_eq!(panel.row_cursor, Some(4), "still second's `value`");
    }

    /// #2748: a breakpoint row is its breakpoint, not its place in the list.
    /// One removed above it leaves the keyboard on the same breakpoint, and
    /// when its own breakpoint goes the prompt has the keys again.
    #[test]
    fn the_row_cursor_follows_its_breakpoint() {
        let header = DebugRow {
            indent: 0,
            kind: DebugRowKind::Header {
                title: String::from("BREAKPOINTS"),
            },
        };
        let breakpoints = |lines: &[usize]| {
            let mut rows = vec![header.clone()];
            rows.extend(lines.iter().enumerate().map(|(index, &line)| DebugRow {
                indent: 1,
                kind: DebugRowKind::Breakpoint {
                    index,
                    path: PathBuf::from("/w/s.py"),
                    line,
                },
            }));
            rows
        };
        let mut panel = RunDebugPanel::new();
        panel.debug_active = true;
        panel.debug_rows = breakpoints(&[3, 7, 9]);
        panel.row_cursor = Some(2);
        panel.replace_rows(breakpoints(&[7, 9]));
        assert_eq!(panel.row_cursor, Some(1), "still line 7, now first");
        panel.replace_rows(breakpoints(&[9]));
        assert_eq!(
            panel.row_cursor, None,
            "line 7 is gone: the prompt has the keys"
        );
    }

    /// #2748: an adapter can list two siblings with the same name and no
    /// expression of their own. The keyboard on the second stays on the
    /// second, told apart by order as VS Code's variable ids are.
    #[test]
    fn the_row_cursor_stays_on_the_second_of_two_twins() {
        let rows = || {
            let variable = |name: &str| DebugRow {
                indent: 2,
                kind: DebugRowKind::Variable {
                    reference: 0,
                    expandable: false,
                    expanded: false,
                    name: name.into(),
                    value: String::from("1"),
                    type_name: String::from("int"),
                    evaluate_name: None,
                },
            };
            vec![
                DebugRow {
                    indent: 0,
                    kind: DebugRowKind::Header {
                        title: String::from("VARIABLES"),
                    },
                },
                DebugRow {
                    indent: 1,
                    kind: DebugRowKind::Scope {
                        name: String::from("Locals"),
                        index: 0,
                        open: None,
                    },
                },
                variable("x"),
                variable("x"),
                variable("y"),
            ]
        };
        let mut panel = RunDebugPanel::new();
        panel.debug_active = true;
        panel.debug_rows = rows();
        panel.row_cursor = Some(3);
        panel.replace_rows(rows());
        assert_eq!(panel.row_cursor, Some(3), "still the second `x`");
    }

    /// #2748: twins are counted at every depth. Two same-named parents each
    /// hold an `x`; the keyboard is on the second parent's `x` while the
    /// first parent's children are still loading. When they arrive, the
    /// keyboard stays under the second parent.
    #[test]
    fn the_row_cursor_stays_under_the_second_of_two_twin_parents() {
        let variable = |indent: u8, name: &str| DebugRow {
            indent,
            kind: DebugRowKind::Variable {
                reference: if indent == 2 { 7 } else { 0 },
                expandable: indent == 2,
                expanded: indent == 2,
                name: name.into(),
                value: String::new(),
                type_name: String::new(),
                evaluate_name: None,
            },
        };
        let top = || {
            vec![
                DebugRow {
                    indent: 0,
                    kind: DebugRowKind::Header {
                        title: String::from("VARIABLES"),
                    },
                },
                DebugRow {
                    indent: 1,
                    kind: DebugRowKind::Scope {
                        name: String::from("Locals"),
                        index: 0,
                        open: None,
                    },
                },
            ]
        };
        let mut loading = top();
        loading.extend([variable(2, "p"), variable(2, "p"), variable(3, "x")]);
        let mut loaded = top();
        loaded.extend([
            variable(2, "p"),
            variable(3, "x"),
            variable(2, "p"),
            variable(3, "x"),
        ]);
        let mut panel = RunDebugPanel::new();
        panel.debug_active = true;
        panel.debug_rows = loading;
        panel.row_cursor = Some(4);
        panel.replace_rows(loaded);
        assert_eq!(panel.row_cursor, Some(5), "still the second `p`'s `x`");
    }

    /// #2748: a cursor past the old rows' end (a list shortened behind its
    /// back) gives the keys to the prompt instead of crashing.
    #[test]
    fn a_cursor_past_the_old_rows_hands_the_keys_back() {
        let header = DebugRow {
            indent: 0,
            kind: DebugRowKind::Header {
                title: String::from("WATCH"),
            },
        };
        let mut panel = RunDebugPanel::new();
        panel.debug_active = true;
        panel.debug_rows = vec![header.clone()];
        panel.row_cursor = Some(4);
        panel.replace_rows(vec![
            header,
            DebugRow {
                indent: 1,
                kind: DebugRowKind::WatchAdd,
            },
        ]);
        assert_eq!(panel.row_cursor, None);
    }

    /// Every row of `line` wrapped to `width`.
    fn wrap_console_line(line: &str, width: usize) -> Vec<String> {
        wrap_console_line_tail(&AnsiLine::plain(line), width, usize::MAX)
            .iter()
            .map(row_text)
            .collect()
    }

    /// A wrapped row's text, its runs joined.
    fn row_text(row: &ConsoleRow) -> String {
        row.iter().map(|(t, _)| t.as_str()).collect()
    }

    /// Console lines with no colour in them.
    fn plain_lines<S: Into<String>>(lines: impl IntoIterator<Item = S>) -> Vec<AnsiLine> {
        lines.into_iter().map(AnsiLine::plain).collect()
    }

    #[test]
    fn paused_state_renders_call_stack_and_variables_and_maps_clicks() {
        let mut panel = RunDebugPanel::new();
        panel.debug_active = true;
        panel.debug_status = String::from("Paused (breakpoint)");
        panel.debug_rows = vec![
            DebugRow {
                indent: 0,
                kind: DebugRowKind::Header {
                    title: "CALL STACK".into(),
                },
            },
            DebugRow {
                indent: 1,
                kind: DebugRowKind::Frame {
                    id: 1000,
                    selected: true,
                    name: "isValid".into(),
                    location: "app.py:12".into(),
                },
            },
            DebugRow {
                indent: 0,
                kind: DebugRowKind::Header {
                    title: "VARIABLES".into(),
                },
            },
            DebugRow {
                indent: 1,
                kind: DebugRowKind::Scope {
                    name: "Locals".into(),
                    index: 0,
                    open: None,
                },
            },
            DebugRow {
                indent: 2,
                kind: DebugRowKind::Variable {
                    reference: 0,
                    expandable: false,
                    expanded: false,
                    name: "x".into(),
                    value: "1".into(),
                    type_name: "int".into(),
                    evaluate_name: None,
                },
            },
            DebugRow {
                indent: 2,
                kind: DebugRowKind::Variable {
                    reference: 9,
                    expandable: true,
                    expanded: false,
                    name: "obj".into(),
                    value: "<Foo>".into(),
                    type_name: "Foo".into(),
                    evaluate_name: None,
                },
            },
        ];
        let area = Rect {
            x: 0,
            y: 0,
            width: 40,
            height: 24,
        };
        let mut buf = Buffer::empty(area);
        panel.draw(&ViewCx::default(), area, &mut buf);
        let dump = buffer_to_string(&buf);
        assert!(dump.contains("CALL STACK"), "call stack header:\n{dump}");
        assert!(dump.contains("VARIABLES"), "variables header:\n{dump}");
        assert!(dump.contains("isValid"), "frame name:\n{dump}");
        assert!(dump.contains("app.py:12"), "frame location:\n{dump}");
        assert!(dump.contains("x = 1"), "variable row:\n{dump}");
        assert!(
            dump.contains("▸ obj = <Foo>"),
            "expandable chevron:\n{dump}"
        );
        // The empty-state Run button must NOT be laid out while debugging.
        assert_eq!(panel.last_button_area, Rect::default());
        // Click mapping: first row sits at last_debug_row_y0.
        let y0 = panel.last_debug_row_y0;
        assert_eq!(panel.debug_row_at(y0), Some(0));
        assert_eq!(panel.debug_row_at(y0 + 1), Some(1));
        assert_eq!(panel.debug_row_at(y0.saturating_sub(1)), None);
    }

    /// #867 review: only the rows the console shows are built. Wrapping
    /// just a line's last `keep` rows gives exactly the tail of wrapping the
    /// whole line, for tabs, wide glyphs, an empty line and any `keep`.
    #[test]
    fn wrapping_a_lines_tail_matches_the_tail_of_wrapping_it_whole() {
        let wide = "界".repeat(9) + "x";
        let lines = [
            String::new(),
            String::from("short"),
            String::from("\tif x:\n"),
            "y".repeat(30) + "END",
            wide,
            format!("\t{}\t{}", "a".repeat(17), "界b".repeat(7)),
        ];
        for line in &lines {
            for width in [0, 1, 3, 8, 25] {
                let whole = wrap_console_line(line, width);
                for keep in 0..=whole.len() + 2 {
                    let tail = &whole[whole.len().saturating_sub(keep)..];
                    assert_eq!(
                        wrap_console_line_tail(&AnsiLine::plain(line.as_str()), width, keep)
                            .iter()
                            .map(row_text)
                            .collect::<Vec<_>>(),
                        tail,
                        "{line:?} at {width} keeping {keep}"
                    );
                }
            }
        }
    }

    /// #867 review guard: a single enormous line still shows its last rows,
    /// and only those are built, however long the line is.
    #[test]
    fn a_huge_console_line_shows_its_last_rows() {
        let mut panel = RunDebugPanel::default();
        let huge = "a".repeat(2_000_000) + "THE END";
        panel.console_tail = plain_lines([String::from("before"), huge]);
        let rows = panel.console_rows(10, 3);
        assert_eq!(rows.len(), 3);
        assert_eq!(row_text(&rows[2].0), "THE END");
        assert_eq!(row_text(&rows[1].0), "a".repeat(10));
    }

    #[test]
    fn paused_state_renders_console_tail_and_repl_prompt() {
        let mut panel = RunDebugPanel::new();
        panel.debug_active = true;
        panel.debug_status = String::from("Paused (breakpoint)");
        panel.debug_rows = vec![DebugRow {
            indent: 0,
            kind: DebugRowKind::Header {
                title: "CALL STACK".into(),
            },
        }];
        panel.console_tail = plain_lines(["hello from program", "42"]);
        panel.repl_input = String::from("x + 1");
        let area = Rect {
            x: 0,
            y: 0,
            width: 40,
            height: 24,
        };
        let mut buf = Buffer::empty(area);
        panel.draw(&ViewCx::default(), area, &mut buf);
        let dump = buffer_to_string(&buf);
        assert!(
            dump.contains("hello from program"),
            "console output:\n{dump}"
        );
        assert!(dump.contains("❯ x + 1"), "repl prompt with input:\n{dump}");
        assert!(
            dump.contains("DEBUG CONSOLE"),
            "input field must carry a label:\n{dump}"
        );
        // Bottom-anchored: the newest console line ("42") must sit on the row
        // directly above the DEBUG CONSOLE label, with no gap floating it up.
        let row_text = |y: u16| -> String {
            (0..area.width)
                .map(|x| buf[(x, y)].symbol())
                .collect::<String>()
        };
        let label_y = (0..area.height)
            .find(|&y| row_text(y).contains("DEBUG CONSOLE"))
            .expect("label present");
        assert!(
            row_text(label_y - 1).contains("42"),
            "newest console line must hug the label (row above it):\nlabel-1: {:?}",
            row_text(label_y - 1)
        );
    }

    /// #1501: the console paints the colours a program's SGR sequences set,
    /// over the console's own colour, and a wrapped run keeps its colour on
    /// both rows.
    #[test]
    fn console_rows_paint_program_colours() {
        let mut panel = RunDebugPanel::new();
        panel.debug_active = true;
        panel.debug_status = String::from("Paused");
        let mut style = crate::ansi_text::AnsiStyle::default();
        panel.console_tail = vec![crate::ansi_text::parse_line(
            "\x1b[31mFAILED\x1b[0m ok \x1b[32mgreen-run-that-is-too-long-for-the-panel-TAIL\x1b[0m",
            &mut style,
        )];
        let area = Rect {
            x: 0,
            y: 0,
            width: 40,
            height: 24,
        };
        let mut buf = Buffer::empty(area);
        panel.draw(&ViewCx::default(), area, &mut buf);
        let find = |text: &str| {
            (0..area.height)
                .find_map(|y| {
                    let row: String = (0..area.width).map(|x| buf[(x, y)].symbol()).collect();
                    row.find(text).map(|i| (row[..i].chars().count() as u16, y))
                })
                .unwrap_or_else(|| panic!("{text:?} on screen:\n{}", buffer_to_string(&buf)))
        };
        let ansi = |i: usize| {
            let (r, g, b) = crate::theme::Theme::default().ansi()[i];
            Color::Rgb(r, g, b)
        };
        let (x, y) = find("FAILED");
        assert_eq!(buf[(x, y)].fg, ansi(1), "red");
        assert_eq!(
            buf[(x + 7, y)].fg,
            crate::theme::Theme::default().ui(DBG_LOC),
            "back to the console's own"
        );
        let (x, y) = find("green");
        assert_eq!(buf[(x, y)].fg, ansi(2));
        let (x2, y2) = find("TAIL");
        assert!(y2 > y, "the green run wrapped");
        assert_eq!(
            buf[(x2, y2)].fg,
            ansi(2),
            "and is green on its next row too"
        );
    }

    /// #867: program output wider than the sidebar was cut at its edge, with
    /// no wrap and no scroll. A long line now wraps onto the rows above the
    /// label, every character of it on screen, still anchored to the label.
    #[test]
    fn a_long_console_line_wraps_with_all_its_text_visible() {
        let long = "ValueError: 12345 is not one of the permitted choices \
                    (alpha, beta, gamma, delta) - END";
        let mut panel = RunDebugPanel::new();
        panel.debug_active = true;
        panel.debug_status = String::from("Paused (exception)");
        panel.debug_rows = vec![DebugRow {
            indent: 0,
            kind: DebugRowKind::Header {
                title: "CALL STACK".into(),
            },
        }];
        panel.console_tail = plain_lines(["short", long]);
        let area = Rect {
            x: 0,
            y: 0,
            width: 30,
            height: 24,
        };
        let mut buf = Buffer::empty(area);
        panel.draw(&ViewCx::default(), area, &mut buf);
        let cells = |y: u16, from: u16, to: u16| -> String {
            (from..to).map(|x| buf[(x, y)].symbol()).collect::<String>()
        };
        let label_y = (0..area.height)
            .find(|&y| cells(y, 0, area.width).contains("DEBUG CONSOLE"))
            .expect("label present");
        // Text runs from one cell inside the border for the inner width
        // less a margin: columns 2..28 of a 30-wide panel.
        let width = 26usize;
        let rows = long.chars().count().div_ceil(width) as u16;
        let wrapped: String = (label_y - rows..label_y).map(|y| cells(y, 2, 28)).collect();
        assert_eq!(wrapped.trim_end(), long, "every character is on screen");
        assert!(
            cells(label_y - rows - 1, 0, area.width).contains("short"),
            "the line before it sits above its first row"
        );
    }

    /// #867: the idle panel's retained console wraps the same way.
    #[test]
    fn the_retained_console_wraps_too() {
        let long = "x".repeat(60) + "END";
        let mut panel = RunDebugPanel::new();
        panel.session_ended = true;
        panel.console_tail = plain_lines([long.clone()]);
        let area = Rect {
            x: 0,
            y: 0,
            width: 30,
            height: 30,
        };
        let mut buf = Buffer::empty(area);
        panel.draw(&ViewCx::default(), area, &mut buf);
        let dump = buffer_to_string(&buf);
        assert!(
            dump.contains("END"),
            "the line's tail is on screen:\n{dump}"
        );
        assert_eq!(dump.matches('x').count(), 60, "{dump}");
    }

    /// Wrapping counts display columns: a double-width glyph fills two, and
    /// never straddles the edge.
    #[test]
    fn console_wrapping_measures_display_width() {
        let wide = "界".repeat(20);
        let rows = wrap_console_line(&wide, 25);
        assert_eq!(
            rows.iter().map(|r| r.chars().count()).collect::<Vec<_>>(),
            vec![12, 8]
        );
        assert_eq!(rows.concat(), wide);
        assert_eq!(
            wrap_console_line("\tif x:", 8),
            vec![String::from("    if x"), String::from(":")],
            "a tab is four columns and indentation is kept"
        );
        assert_eq!(wrap_console_line("", 8), vec![String::new()]);
    }

    /// #867 guard: a line that fits is left alone. One exactly as wide as
    /// the console is a single row, not a row and an empty one, and a
    /// zero-width console still ends (a character per row) instead of
    /// looping.
    #[test]
    fn a_console_line_that_fits_is_not_wrapped() {
        assert_eq!(wrap_console_line("short", 26), vec![String::from("short")]);
        assert_eq!(
            wrap_console_line("12345678", 8),
            vec![String::from("12345678")]
        );
        assert_eq!(
            wrap_console_line("ab", 0),
            vec![String::from("a"), String::from("b")]
        );
    }

    /// #867 guard: wrapping does not grow the paused console past its cap.
    /// The newest rows are the ones kept, the long line's tail among them,
    /// and older lines give way first.
    #[test]
    fn wrapped_console_rows_keep_the_newest_within_the_cap() {
        let mut panel = RunDebugPanel::new();
        panel.console_tail = plain_lines([String::from("older"), "y".repeat(30) + "END"]);
        let rows = panel.console_rows(10, 3);
        assert_eq!(rows.len(), 3, "{rows:?}");
        // 33 columns at width 10: three full rows of `y`, then `END`.
        assert_eq!(
            rows.last().map(|(r, _)| row_text(r)),
            Some(String::from("END"))
        );
        assert!(
            !rows.iter().any(|(r, _)| row_text(r).contains("older")),
            "{rows:?}"
        );
        // A REPL echo keeps its accent on every one of its rows.
        panel.console_tail = plain_lines([format!("❯ {}", "e".repeat(20))]);
        let rows = panel.console_rows(10, 6);
        assert!(
            rows.len() > 1 && rows.iter().all(|(_, echo)| *echo),
            "{rows:?}"
        );
    }

    #[test]
    fn empty_repl_shows_a_ghost_placeholder() {
        let mut panel = RunDebugPanel::new();
        panel.debug_active = true;
        panel.debug_status = String::from("Paused");
        panel.debug_rows = vec![DebugRow {
            indent: 0,
            kind: DebugRowKind::Header {
                title: "VARIABLES".into(),
            },
        }];
        // repl_input left empty
        let area = Rect {
            x: 0,
            y: 0,
            width: 40,
            height: 24,
        };
        let mut buf = Buffer::empty(area);
        panel.draw(&ViewCx::default(), area, &mut buf);
        let dump = buffer_to_string(&buf);
        assert!(
            dump.contains("Evaluate expression"),
            "empty REPL must show a placeholder hint:\n{dump}"
        );
    }

    #[test]
    fn button_label_says_run_and_debug_when_no_file_is_active() {
        let panel = RunDebugPanel::new();
        assert_eq!(panel.button_label(), "Run and Debug");
    }

    #[test]
    fn button_label_includes_filename_when_a_file_is_active() {
        let mut panel = RunDebugPanel::new();
        panel.set_active_file(Some(PathBuf::from("/work/script.py")));
        assert_eq!(panel.button_label(), "Run script.py");
    }

    #[test]
    fn button_label_says_debug_for_compiled_source() {
        let mut panel = RunDebugPanel::new();
        panel.set_active_file(Some(PathBuf::from("/work/main.rs")));
        panel.run_is_debug = true;
        assert_eq!(panel.button_label(), "Debug main.rs");
    }

    #[test]
    fn config_row_label_names_the_selection_or_counts_the_configs() {
        let mut panel = RunDebugPanel::new();
        assert_eq!(panel.config_row_label(), None, "no configs, no row");
        panel.config_count = 2;
        assert_eq!(
            panel.config_row_label().as_deref(),
            Some("⚙ 2 debug entries ▾")
        );
        panel.config_count = 1;
        assert_eq!(
            panel.config_row_label().as_deref(),
            Some("⚙ 1 debug entry ▾"),
            "singular reads correctly rather than \"1 debug configs\""
        );
        panel.config_count = 2;
        panel.selected_config = Some(String::from("Run API"));
        assert_eq!(panel.config_row_label().as_deref(), Some("⚙ Run API ▾"));
    }

    #[test]
    fn click_button_is_inside_recorded_button_area() {
        let mut panel = RunDebugPanel::new();
        panel.last_button_area = Rect {
            x: 10,
            y: 5,
            width: 12,
            height: 3,
        };
        assert!(panel.click_button(10, 5));
        assert!(panel.click_button(21, 7));
        assert!(!panel.click_button(22, 5));
        assert!(!panel.click_button(15, 8));
    }

    #[test]
    fn rendering_lays_out_button_area_inside_panel() {
        let mut panel = RunDebugPanel::new();
        panel.set_active_file(Some(PathBuf::from("/work/run_me.rs")));
        panel.runnable = true;
        let area = Rect {
            x: 0,
            y: 0,
            width: 40,
            height: 24,
        };
        let mut buf = Buffer::empty(area);
        panel.draw(&ViewCx::default(), area, &mut buf);
        let b = panel.last_button_area;
        assert!(b.width > 0 && b.height > 0, "button area must be laid out");
        assert!(b.x >= area.x && b.x + b.width <= area.x + area.width);
        assert!(b.y >= area.y && b.y < area.y + area.height);
    }

    #[test]
    fn non_runnable_file_shows_a_note_and_no_button() {
        // An open file croft can't run/debug (e.g. .git/config) must not offer a
        // Run button that would just fail.
        let mut panel = RunDebugPanel::new();
        panel.set_active_file(Some(PathBuf::from("/repo/.git/config")));
        panel.runnable = false;
        let area = Rect {
            x: 0,
            y: 0,
            width: 40,
            height: 24,
        };
        let mut buf = Buffer::empty(area);
        panel.draw(&ViewCx::default(), area, &mut buf);
        assert_eq!(
            panel.last_button_area,
            Rect::default(),
            "no Run button for a non-runnable file"
        );
        let mut dump = String::new();
        for y in 0..area.height {
            for x in 0..area.width {
                dump.push_str(buf[(x, y)].symbol());
            }
        }
        // The note wraps across rows in the narrow panel, so assert an
        // intra-line fragment rather than the whole phrase.
        assert!(
            dump.contains("can't be run") && dump.contains("debugged"),
            "must explain why there's no button: {dump:?}"
        );
    }

    #[test]
    fn non_runnable_file_still_renders_launch_config_row_and_hit_rect() {
        let mut panel = RunDebugPanel::new();
        panel.set_active_file(Some(PathBuf::from("/repo/README.md")));
        panel.runnable = false;
        panel.config_count = 2;
        let area = Rect {
            x: 0,
            y: 0,
            width: 40,
            height: 24,
        };
        let mut buf = Buffer::empty(area);
        panel.draw(&ViewCx::default(), area, &mut buf);
        assert_eq!(
            panel.last_button_area,
            Rect::default(),
            "primary Run button stays hidden for a non-runnable file"
        );
        assert!(
            panel.last_config_area.width > 0 && panel.last_config_area.height == 1,
            "launch.json config row must still lay out a clickable area"
        );
        let mut dump = String::new();
        for y in 0..area.height {
            for x in 0..area.width {
                dump.push_str(buf[(x, y)].symbol());
            }
        }
        assert!(
            dump.contains("2 debug entries"),
            "config count row must stay visible on non-runnable files: {dump:?}"
        );
    }

    /// #2751: a click read after a key that scrolled the rows, in the same
    /// burst and so before the next frame, meets the rows the last frame
    /// drew: the screen still shows them, and the key has already moved the
    /// scroll by one.
    #[test]
    fn a_click_before_the_next_frame_meets_the_drawn_rows() {
        let mut panel = RunDebugPanel::new();
        panel.debug_active = true;
        panel.debug_rows = std::iter::once(DebugRow {
            indent: 0,
            kind: DebugRowKind::Header {
                title: String::from("VARIABLES"),
            },
        })
        .chain((0..30).map(|i| DebugRow {
            indent: 1,
            kind: DebugRowKind::Variable {
                reference: 0,
                expandable: false,
                expanded: false,
                name: format!("v{i}"),
                value: String::from("1"),
                type_name: String::from("int"),
                evaluate_name: Some(format!("v{i}")),
            },
        }))
        .collect();
        let area = Rect {
            x: 0,
            y: 0,
            width: 40,
            height: 16,
        };
        let mut buf = Buffer::empty(area);
        panel.draw(&ViewCx::default(), area, &mut buf);
        let shown = panel.last_debug_rows_shown;
        assert!(
            shown > 1 && shown < panel.debug_rows.len(),
            "rows to scroll"
        );
        let y0 = panel.last_debug_row_y0;
        let top = panel.debug_row_at(y0).expect("a row is drawn at the top");
        panel.row_cursor = Some(top + shown - 1);
        let before = panel.debug_scroll;
        panel.move_row_cursor(1);
        assert!(panel.debug_scroll > before, "the key scrolled the rows");
        assert_eq!(
            panel.debug_row_at(y0),
            Some(top),
            "the row drawn at the top, not the one scrolled there"
        );
    }

    /// #2751: a click that rebuilds the rows (a scope opened, a watch
    /// removed) and a second click read in the same burst: the second meets
    /// the row drawn on its line where the rebuild put it, and nothing once
    /// it is gone, however many rebuilds came between.
    #[test]
    fn a_click_after_a_rebuild_meets_the_drawn_row() {
        let header = DebugRow {
            indent: 0,
            kind: DebugRowKind::Header {
                title: String::from("VARIABLES"),
            },
        };
        let var = |name: &str| DebugRow {
            indent: 1,
            kind: DebugRowKind::Variable {
                reference: 0,
                expandable: false,
                expanded: false,
                name: name.to_string(),
                value: String::from("1"),
                type_name: String::from("int"),
                evaluate_name: Some(name.to_string()),
            },
        };
        let rows = |names: &[&str]| -> Vec<DebugRow> {
            std::iter::once(header.clone())
                .chain(names.iter().map(|n| var(n)))
                .collect()
        };
        let name_at = |panel: &RunDebugPanel, y| {
            panel
                .debug_row_at(y)
                .map(|i| match &panel.debug_rows[i].kind {
                    DebugRowKind::Variable { name, .. } => name.clone(),
                    _ => String::from("not a variable"),
                })
        };
        let mut panel = RunDebugPanel::new();
        panel.debug_active = true;
        panel.replace_rows(rows(&["v0", "v1", "v2", "v3"]));
        let area = Rect {
            x: 0,
            y: 0,
            width: 40,
            height: 16,
        };
        panel.draw(&ViewCx::default(), area, &mut Buffer::empty(area));
        let y = (panel.last_debug_row_y0..area.height)
            .find(|&y| name_at(&panel, y).as_deref() == Some("v2"))
            .expect("v2 is drawn");

        panel.replace_rows(rows(&["w", "v0", "v1", "v2", "v3"]));
        assert_eq!(
            name_at(&panel, y).as_deref(),
            Some("v2"),
            "the row drawn there, a row down now, not v1"
        );
        panel.replace_rows(rows(&["w", "v0", "v1", "v3"]));
        assert_eq!(
            name_at(&panel, y),
            None,
            "v2 is gone, so the click meets none"
        );
    }

    fn buffer_to_string(buf: &Buffer) -> String {
        let mut out = String::new();
        for y in 0..buf.area.height {
            for x in 0..buf.area.width {
                out.push_str(buf[(buf.area.x + x, buf.area.y + y)].symbol());
            }
            out.push('\n');
        }
        out
    }

    #[test]
    fn empty_state_renders_centred_title_and_description_and_chunky_button() {
        let mut panel = RunDebugPanel::new();
        let area = Rect {
            x: 0,
            y: 0,
            width: 36,
            height: 24,
        };
        let mut buf = Buffer::empty(area);
        panel.draw(&ViewCx::default(), area, &mut buf);
        let dump = buffer_to_string(&buf);
        assert!(
            dump.contains("RUN AND DEBUG"),
            "headline must be present: \n{dump}"
        );
        assert!(
            dump.contains("Open a file"),
            "body copy must be present: \n{dump}"
        );
        assert!(
            !dump.lines().next().unwrap().contains("RUN AND DEBUG"),
            "title bar must NOT sit on the top border row (mockup has no title bar): \n{dump}"
        );
        let button = panel.last_button_area;
        assert!(
            button.height >= 3,
            "button must be at least 3 rows tall to feel chunky like the mockup; got height={}",
            button.height
        );
        // The OSC-1337 icon block must be reserved ABOVE the button.
        let icon = panel.last_icon_cell.expect("icon block must be reserved");
        assert!(
            button.y > icon.1,
            "button must sit below the icon (icon top y={}, button.y={})",
            icon.1,
            button.y
        );
    }

    #[test]
    fn icon_block_reserves_an_osc_1337_overlay_cell_with_a_glyph_fallback() {
        // The headline icon is a 6x3-cell OSC-1337 image overlay (the
        // codicon `debug-alt` PNG, same one the activity-bar slot uses),
        // emitted post-frame by App::flush_run_debug_icon_overlay. The
        // widget's job is to (1) reserve the icon block via
        // last_icon_cell and (2) paint the codicon glyph as a text
        // fallback for terminals without OSC-1337 support; iTerm2
        // overwrites those cells with the rasterised image.
        let mut panel = RunDebugPanel::new();
        let area = Rect {
            x: 0,
            y: 0,
            width: 36,
            height: 24,
        };
        let mut buf = Buffer::empty(area);
        panel.draw(&ViewCx::default(), area, &mut buf);
        let (ix, iy) = panel
            .last_icon_cell
            .expect("icon overlay cell must be reserved on a tall enough panel");
        let icon_w = RUN_DEBUG_ICON_CELLS_W;
        let icon_h = RUN_DEBUG_ICON_CELLS_H;
        let glyph_x = ix + icon_w / 2;
        let glyph_y = iy + icon_h / 2;
        let cell = buf[(glyph_x, glyph_y)].symbol().to_string();
        assert_eq!(
            cell,
            crate::icons::ACTIVITY_RUN_DEBUG.to_string(),
            "glyph fallback must be the cod-debug-alt codicon at the centre of the icon block"
        );
    }

    #[test]
    fn run_and_debug_button_uses_rounded_border_corners() {
        let mut cx = ViewCx::default();
        // The line-art corners are the boxed themes'; Croft Loch's soft
        // slab is checked below.
        let mut panel = RunDebugPanel::new();
        cx.theme = crate::theme::Theme::BLACK;
        let area = Rect {
            x: 0,
            y: 0,
            width: 36,
            height: 24,
        };
        let mut buf = Buffer::empty(area);
        panel.draw(&cx, area, &mut buf);
        let b = panel.last_button_area;
        assert!(b.height >= 3 && b.width >= 4, "button must be laid out");
        let tl = buf[(b.x, b.y)].symbol().to_string();
        let tr = buf[(b.x + b.width - 1, b.y)].symbol().to_string();
        let bl = buf[(b.x, b.y + b.height - 1)].symbol().to_string();
        let br = buf[(b.x + b.width - 1, b.y + b.height - 1)]
            .symbol()
            .to_string();
        assert_eq!(
            tl, "╭",
            "top-left button corner must be rounded; got {tl:?}"
        );
        assert_eq!(
            tr, "╮",
            "top-right button corner must be rounded; got {tr:?}"
        );
        assert_eq!(
            bl, "╰",
            "bottom-left button corner must be rounded; got {bl:?}"
        );
        assert_eq!(
            br, "╯",
            "bottom-right button corner must be rounded; got {br:?}"
        );
    }

    /// Croft Loch: the Run and Debug button is the shared one-row pill, the
    /// brand teal face on its middle row between half-block caps, the rows
    /// above and below left as the panel's surface, rather than `╭╮╰╯` arcs
    /// on the chrome; the pointer anywhere on its three-row target lifts it.
    #[test]
    fn croft_loch_run_and_debug_button_is_a_one_row_pill() {
        let mut cx = ViewCx::default();
        let mut panel = RunDebugPanel::new();
        cx.theme = crate::theme::Theme::LOCH;
        let area = Rect::new(0, 0, 36, 24);
        let mut buf = Buffer::empty(area);
        panel.draw(&cx, area, &mut buf);
        let b = panel.last_button_area;
        assert!(b.height == 3 && b.width >= 4, "button must be laid out");
        let teal = crate::gradient::rgb_color(crate::gradient::PRIMARY_BTN_BG);
        let face_y = b.y + 1;
        assert_eq!(buf[(b.x, face_y)].symbol(), "\u{2590}");
        assert_eq!(buf[(b.x, face_y)].fg, teal);
        assert_eq!(buf[(b.right() - 1, face_y)].symbol(), "\u{258c}");
        assert_eq!(buf[(b.x + b.width / 2, face_y)].bg, teal);
        for y in [b.y, b.bottom() - 1] {
            for x in b.x..b.right() {
                assert_eq!(buf[(x, y)].symbol(), " ", "no band at ({x}, {y})");
                assert_ne!(buf[(x, y)].bg, teal, "no slab at ({x}, {y})");
            }
        }
        cx.pointer = Some((b.x + 1, b.y));
        let mut buf = Buffer::empty(area);
        panel.draw(&cx, area, &mut buf);
        assert_ne!(buf[(b.x + b.width / 2, face_y)].bg, teal, "the face lifts");
    }

    #[test]
    fn rendering_at_narrow_widths_does_not_panic() {
        // Repro for the user-reported crash: dragging the sidebar
        // splitter all the way to the left squeezed Run-and-Debug to a
        // few cells wide and ratatui panicked with `index outside of
        // buffer`. The cause was `inner.width - button_w` wrapping to a
        // huge u16 when the "Run and Debug" label (13 chars) was wider
        // than `inner.width`. Render the panel at every width from 0 up
        // to a reasonable maximum and assert nothing crashes.
        for width in 0u16..40 {
            for height in 0u16..30 {
                let mut panel = RunDebugPanel::new();
                panel.set_active_file(Some(PathBuf::from("/work/run_me.rs")));
                let area = Rect {
                    x: 0,
                    y: 0,
                    width,
                    height,
                };
                if area.width == 0 || area.height == 0 {
                    continue;
                }
                let mut buf = Buffer::empty(area);
                panel.draw(&ViewCx::default(), area, &mut buf);
            }
        }
    }

    /// #944: a feedback message wider than the panel wraps onto as many
    /// rows as it needs, and nothing is painted past the panel's right edge
    /// into the editor beside it.
    #[test]
    fn long_feedback_wraps_inside_the_panel() {
        let msg =
            "config \"Run server\": a go launch needs a \"program\" (a package directory or file)";
        let mut panel = RunDebugPanel::new();
        panel.set_active_file(Some(PathBuf::from("/work/run_me.py")));
        panel.runnable = true;
        panel.feedback = Some(String::from(msg));
        panel.feedback_is_error = true;
        let panel_area = Rect {
            x: 0,
            y: 0,
            width: 28,
            height: 40,
        };
        // A wider buffer stands in for the editor to the panel's right.
        let mut buf = Buffer::empty(Rect {
            width: 60,
            ..panel_area
        });
        panel.draw(&ViewCx::default(), panel_area, &mut buf);
        let row_text = |y: u16, xs: std::ops::Range<u16>| -> String {
            xs.map(|x| buf[(x, y)].symbol().to_string()).collect()
        };
        for y in 0..40 {
            assert_eq!(
                row_text(y, 28..60).trim(),
                "",
                "row {y} painted past the panel"
            );
        }
        let shown: Vec<String> = (0..40)
            .map(|y| row_text(y, 0..28))
            .filter(|r| r.contains("config") || r.contains("launch") || r.contains("file)"))
            .collect();
        assert!(shown.len() >= 2, "the message wraps: {shown:?}");
        let words: String = (0..40)
            .map(|y| row_text(y, 1..27).trim().to_string())
            .collect::<Vec<_>>()
            .join(" ");
        assert!(
            words.contains("directory or file)"),
            "the end is shown: {words}"
        );
    }

    #[test]
    fn feedback_wraps_on_words_and_splits_a_word_wider_than_a_row() {
        assert_eq!(wrap_feedback("aa bb cc", 5), vec!["aa bb", "cc"]);
        assert_eq!(wrap_feedback("abcdefgh", 3), vec!["abc", "def", "gh"]);
        assert_eq!(wrap_feedback("", 10), Vec::<String>::new());
    }

    #[test]
    fn small_panel_skips_icon_block_to_keep_button_visible() {
        let mut panel = RunDebugPanel::new();
        let area = Rect {
            x: 0,
            y: 0,
            width: 30,
            height: 12,
        };
        let mut buf = Buffer::empty(area);
        panel.draw(&ViewCx::default(), area, &mut buf);
        assert!(
            panel.last_button_area.height >= 3,
            "button must remain laid out when the panel collapses the icon block"
        );
    }
    /// #250: the BREAKPOINTS list shows at rest (no session) under the
    /// button, and a click maps to the row or to its remove `✕`.
    #[test]
    fn idle_panel_lists_breakpoints_and_maps_row_and_remove_clicks() {
        let mut panel = RunDebugPanel::new();
        panel.breakpoints = vec![
            BreakpointItem {
                path: PathBuf::from("/w/a.rs"),
                line: 3,
                label: "a.rs:3".into(),
                detail: None,
            },
            BreakpointItem {
                path: PathBuf::from("/w/b.rs"),
                line: 9,
                label: "b.rs:9".into(),
                detail: Some("if x > 1".into()),
            },
        ];
        let area = Rect {
            x: 0,
            y: 0,
            width: 44,
            height: 30,
        };
        let mut buf = Buffer::empty(area);
        panel.draw(&ViewCx::default(), area, &mut buf);
        let dump = buffer_to_string(&buf);
        assert!(dump.contains("BREAKPOINTS"), "header:\n{dump}");
        assert!(dump.contains("a.rs:3"), "first row:\n{dump}");
        assert!(dump.contains("b.rs:9 if x > 1"), "detail shown:\n{dump}");
        assert_eq!(panel.breakpoint_row_rects.len(), 2);
        let (y, idx, _) = panel.breakpoint_row_rects[1].clone();
        assert_eq!(idx, 1);
        assert_eq!(panel.breakpoint_at(3, y), Some((1, false)), "a row click");
        let (ry, rx, ridx, _) = panel.breakpoint_remove_rects[0].clone();
        assert_eq!(panel.breakpoint_at(rx, ry), Some((ridx, true)), "the ✕");
        assert_eq!(panel.breakpoint_at(3, y + 10), None);
    }

    #[test]
    fn watch_section_renders_states_and_maps_remove_clicks() {
        let mut panel = RunDebugPanel::new();
        panel.debug_active = true;
        panel.debug_status = String::from("Paused (breakpoint)");
        panel.debug_rows = vec![
            DebugRow {
                indent: 0,
                kind: DebugRowKind::Header {
                    title: "WATCH".into(),
                },
            },
            DebugRow {
                indent: 1,
                kind: DebugRowKind::Watch {
                    index: 0,
                    expression: "t".into(),
                    value: "9.99".into(),
                    available: true,
                    changed: true,
                    pending: false,
                },
            },
            DebugRow {
                indent: 1,
                kind: DebugRowKind::Watch {
                    index: 1,
                    expression: "self.missing".into(),
                    value: "NameError".into(),
                    available: false,
                    changed: false,
                    pending: false,
                },
            },
            DebugRow {
                indent: 1,
                kind: DebugRowKind::Watch {
                    index: 2,
                    expression: "len(cart)".into(),
                    value: String::new(),
                    available: true,
                    changed: false,
                    pending: true,
                },
            },
            DebugRow {
                indent: 1,
                kind: DebugRowKind::WatchAdd,
            },
        ];
        let area = Rect {
            x: 0,
            y: 0,
            width: 44,
            height: 20,
        };
        let mut buf = Buffer::empty(area);
        panel.draw(&ViewCx::default(), area, &mut buf);
        let dump = buffer_to_string(&buf);
        assert!(dump.contains("WATCH"), "watch header:\n{dump}");
        assert!(dump.contains("t = 9.99"), "watched value:\n{dump}");
        assert!(
            dump.contains("self.missing = <not available>"),
            "a rejected expression must degrade, not show the adapter error:\n{dump}"
        );
        assert!(
            !dump.contains("NameError"),
            "the raw adapter error must not leak into the row:\n{dump}"
        );
        assert!(dump.contains("+ Add Expression"), "add affordance:\n{dump}");
        // Every watch row recorded a remove ✕ at the right edge, mapped by
        // render order.
        assert_eq!(panel.watch_remove_rects.len(), 3);
        let watches = ["t", "self.missing", "len(cart)"].map(String::from);
        let (y, x, idx, _) = panel.watch_remove_rects[1].clone();
        assert_eq!(idx, 1, "the second watch row maps to index 1");
        assert_eq!(panel.watch_remove_at(x, y, &watches), Some(1));
        assert_eq!(panel.watch_remove_at(x, y + 5, &watches), None);

        // Scrolled: the header and the first watch row are skipped. The
        // first VISIBLE watch row must still map to expression index 1 —
        // a render-order counter restarted at 0 here and the ✕ removed
        // the wrong expression (#113 review).
        panel.debug_scroll = 2;
        let mut buf = Buffer::empty(area);
        panel.draw(&ViewCx::default(), area, &mut buf);
        let (y, x, idx, _) = panel.watch_remove_rects[0].clone();
        assert_eq!(
            idx, 1,
            "after scrolling past the first watch row, the first visible one keeps its true index"
        );
        assert_eq!(panel.watch_remove_at(x, y, &watches), Some(1));
    }

    /// #2753: two remove clicks read in one burst: once the first watch is
    /// gone, the second `✕` still removes the watch it was drawn for, now
    /// one place up, and the first `✕` meets nothing.
    #[test]
    fn a_remove_click_after_another_meets_the_drawn_watch() {
        let watch = |index: usize, expression: &str| DebugRow {
            indent: 1,
            kind: DebugRowKind::Watch {
                index,
                expression: expression.into(),
                value: "1".into(),
                available: true,
                changed: false,
                pending: false,
            },
        };
        let mut panel = RunDebugPanel::new();
        panel.debug_active = true;
        panel.debug_rows = vec![watch(0, "a"), watch(1, "b"), watch(2, "c")];
        let area = Rect {
            x: 0,
            y: 0,
            width: 44,
            height: 20,
        };
        panel.draw(&ViewCx::default(), area, &mut Buffer::empty(area));
        let cell = |i: usize| {
            let (y, x, ..) = panel.watch_remove_rects[i];
            (x, y)
        };
        let ((ax, ay), (bx, by)) = (cell(0), cell(1));
        let after_a = ["b", "c"].map(String::from);
        assert_eq!(
            panel.watch_remove_at(bx, by, &after_a),
            Some(0),
            "b, now first, not c"
        );
        assert_eq!(panel.watch_remove_at(ax, ay, &after_a), None, "a is gone");
    }
}