mnml-rs 0.2.14

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

use super::*;

/// Where to place a freshly-spawned AI pty pane relative to the
/// current active leaf. Surfaced by the tab-strip AI-chip right-
/// click menu (2026-07-09 — user request).
///
/// v1 is halves only. Quarters (top-left / top-right / bottom-left
/// / bottom-right) would need a second nested split; deferred until
/// there's a clear signal that users want them.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PanePlacement {
    LeftHalf,
    RightHalf,
    TopHalf,
    BottomHalf,
}

/// Strip wrappers Claude commonly emits around a single-line
/// response: markdown fences, leading "Branch:" / "Name:" labels,
/// surrounding quotes (single/double/backtick, nestable). Returns
/// the trimmed body. Used by the AI commands whose reply is a
/// short identifier (branch name, etc.) — was previously a
/// brittle `.trim_matches('`').trim_matches('"')` that failed on
/// `"` `feat/foo`"` and similar (power-user-ai SEV-3).
pub(crate) fn strip_reply_wrappers(s: &str) -> String {
    let mut t = s.trim().to_string();
    // Strip markdown fences (opening + closing).
    if t.starts_with("```") {
        if let Some(rest) = t.find('\n') {
            t = t[rest + 1..].to_string();
        }
        if let Some(idx) = t.rfind("```") {
            t = t[..idx].to_string();
        }
    }
    // Strip a prose preamble label like "Branch name: ".
    for label in ["branch name:", "branch:", "name:"] {
        if t.to_lowercase().starts_with(label) {
            t = t[label.len()..].trim_start().to_string();
        }
    }
    // Strip nested wrappers (quotes / backticks) up to 4 layers.
    let mut last = t.clone();
    for _ in 0..4 {
        let stripped = last
            .trim_matches(|c: char| c.is_whitespace())
            .trim_matches('`')
            .trim_matches('"')
            .trim_matches('\'')
            .to_string();
        if stripped == last {
            break;
        }
        last = stripped;
    }
    last.trim().to_string()
}

/// Slice the first `max_bytes` of `s` at a char boundary (so we
/// never bisect a multi-byte UTF-8 codepoint). Returns the empty
/// string when `s` is empty. 2026-06-21 — fixes the power-user-ai
/// `utf8-truncation-panic` SEV-2 across :ai.explain_diff /
/// :ai.write_pr_description / :ai.recompose_branch / commit-msg
/// generation (4 sites, all hit by a 4-byte emoji at the boundary).
fn truncate_at_char_boundary(s: &str, max_bytes: usize) -> &str {
    if s.len() <= max_bytes {
        return s;
    }
    // Walk backward from `max_bytes` until we find a byte that's a
    // char boundary. UTF-8 continuation bytes are 0b10xxxxxx; the
    // boundary is the first non-continuation byte at-or-before
    // `max_bytes`. std has `floor_char_boundary` on nightly only;
    // this 5-line impl works on stable.
    let mut i = max_bytes;
    while i > 0 && !s.is_char_boundary(i) {
        i -= 1;
    }
    &s[..i]
}

/// Tidy a raw AI completion into ghost-text-insertable form. The model
/// is told to output bare text but occasionally wraps it in a markdown
/// fence or adds a stray leading newline — strip those. Caps the length
/// so a runaway completion can't paint half the screen grey.
fn clean_suggestion(raw: &str) -> String {
    let mut s = raw;
    // Strip an opening ``` / ```lang fence + its closing fence.
    if let Some(rest) = s.strip_prefix("```") {
        // Drop the optional language tag on the fence's first line.
        let after_lang = rest.find('\n').map(|i| &rest[i + 1..]).unwrap_or("");
        s = after_lang.strip_suffix("```").unwrap_or(after_lang);
        s = s.strip_suffix("```\n").unwrap_or(s);
    }
    // A model sometimes leads with a newline; don't insert a blank line
    // at the cursor. Trailing whitespace-only tails are also unhelpful.
    let s = s.trim_end_matches([' ', '\t']);
    let s = s.strip_prefix('\n').unwrap_or(s);
    // Cap — 600 chars is plenty for a ghost completion.
    s.chars().take(600).collect()
}

/// Byte index after the first "word" of a ghost suggestion — leading
/// whitespace (incl. newlines) plus the first non-whitespace run. Used
/// by `Ctrl+Right` accept-word. Returns `s.len()` when `s` is all
/// whitespace, `0` when empty.
fn ghost_word_boundary(s: &str) -> usize {
    let mut idx = 0;
    let mut chars = s.char_indices().peekable();
    while let Some(&(i, c)) = chars.peek() {
        if c.is_whitespace() {
            idx = i + c.len_utf8();
            chars.next();
        } else {
            break;
        }
    }
    while let Some(&(i, c)) = chars.peek() {
        if c.is_whitespace() {
            break;
        }
        idx = i + c.len_utf8();
        chars.next();
    }
    idx
}

/// Byte index after the first line of a ghost suggestion — through and
/// including the first newline (the whole string when single-line).
/// Used by `Ctrl+Down` accept-line.
fn ghost_line_boundary(s: &str) -> usize {
    match s.find('\n') {
        Some(i) => i + 1,
        None => s.len(),
    }
}

/// Estimate the USD cost of a request from its model + token counts.
fn estimate_ai_cost(model: Option<&str>, input: u64, output: u64) -> Option<f64> {
    let (pin, pout) = ai_price_per_mtok(model)?;
    Some((input as f64 * pin + output as f64 * pout) / 1_000_000.0)
}

/// Compact token count — `840`, `2.1k`, `1.2M`.
fn fmt_tokens(n: u64) -> String {
    if n >= 1_000_000 {
        format!("{:.1}M", n as f64 / 1_000_000.0)
    } else if n >= 1_000 {
        format!("{:.1}k", n as f64 / 1_000.0)
    } else {
        n.to_string()
    }
}

impl App {
    /// Right-click on an AI pane — exposes re-ask / cancel / promote
    /// without remembering single-letter chords.
    pub fn open_ai_pane_context_menu(&mut self, anchor: (u16, u16)) {
        use crate::context_menu::{ContextMenu, MenuAction, MenuItem};
        let title = "AI".to_string();
        let items = vec![
            MenuItem::new("Re-ask (fresh session)", MenuAction::Command("ai.reask")),
            MenuItem::new("Cancel running job", MenuAction::Command("ai.cancel")),
            MenuItem::new(
                "Promote to interactive (claude --resume)",
                MenuAction::Command("ai.promote"),
            ),
            MenuItem::new("Apply suggested change", MenuAction::Command("ai.apply")),
            MenuItem::new(
                "View session transcript",
                MenuAction::Command("ai.session_view"),
            ),
        ];
        self.context_menu = Some(ContextMenu::new(Some(title), anchor, items));
    }

    /// Called after every editor edit. Keeps an open completion popup in sync
    /// with what's being typed (re-filtering it, or closing it once the prefix
    /// empties / stops matching), and auto-triggers a fresh request on a member
    /// access (`.` / `:`) or the first character of a new word.
    /// Called whenever the active editor changes — clears any visible
    /// ghost suggestion + (re)arms the debounce timer so a fresh
    /// completion fires once typing pauses. Also drops any in-flight
    /// request (its reply will be stale).
    pub fn note_edit_for_suggest(&mut self) {
        if !self.ai_inline_suggestions() {
            return;
        }
        if let Some(Pane::Editor(b)) = self.active.and_then(|i| self.panes.get_mut(i)) {
            b.editor.ghost_suggestion = None;
        }
        self.pending_suggest = None;
        self.suggest_dirty_at = Some(Instant::now());
    }

    /// True when the active editor is showing an AI ghost suggestion.
    pub fn has_ghost_suggestion(&self) -> bool {
        matches!(
            self.active.and_then(|i| self.panes.get(i)),
            Some(Pane::Editor(b)) if b.editor.ghost_suggestion.is_some()
        )
    }

    /// Drop any visible ghost suggestion on the active editor — used
    /// when the cursor moves (a stale completion for the old position
    /// would be wrong).
    pub fn clear_ghost_suggestion(&mut self) {
        if let Some(Pane::Editor(b)) = self.active.and_then(|i| self.panes.get_mut(i))
            && b.editor.ghost_suggestion.is_some()
        {
            b.editor.ghost_suggestion = None;
        }
    }

    /// True while an AI ghost-text request is in flight (sent to the
    /// backend, reply not yet drained). Drives the statusline `✦ AI`
    /// chip so the user knows a suggestion is coming.
    pub fn ai_suggestion_in_flight(&self) -> bool {
        self.pending_suggest.is_some()
    }

    /// Total count of background tasks currently in flight — LSP
    /// progress, AI suggestions, tracked progress items, SCM
    /// prefetches. Feeds the unified "mnml is busy" statusline chip
    /// (#6) so long-running work never runs silent.
    pub fn background_task_count(&self) -> usize {
        let mut n = 0;
        n += self.lsp_progress.len();
        if self.pending_suggest.is_some() {
            n += 1;
        }
        n += self.progress_items.len();
        if self.scm_pr_pending.is_some() {
            n += 1;
        }
        n
    }

    /// `tick` hook — fire an AI ghost-text request once the debounce
    /// window has elapsed since the last edit. No-op when the feature
    /// is off, a request is already in flight, or a suggestion is
    /// already showing.
    pub(super) fn maybe_fire_suggestion(&mut self) {
        if !self.ai_inline_suggestions() || self.pending_suggest.is_some() {
            return;
        }
        let Some(dirty_at) = self.suggest_dirty_at else {
            return;
        };
        if dirty_at.elapsed().as_millis() < SUGGEST_DEBOUNCE_MS as u128 {
            return;
        }
        let Some(pane_id) = self.active else { return };
        let Some(Pane::Editor(b)) = self.panes.get(pane_id) else {
            return;
        };
        if b.editor.ghost_suggestion.is_some() {
            return;
        }
        let text = b.editor.text();
        let cursor = b.editor.cursor();
        // Cap context: last ~2000 chars before the cursor, first ~1000
        // after. Sending a 100 KB file per keystroke-pause is wasteful.
        let pre_start = text[..cursor]
            .char_indices()
            .rev()
            .nth(2000)
            .map(|(i, _)| i)
            .unwrap_or(0);
        let suf_end = text[cursor..]
            .char_indices()
            .nth(1000)
            .map(|(i, _)| cursor + i)
            .unwrap_or(text.len());
        let prefix = text[pre_start..cursor].to_string();
        let suffix = text[cursor..suf_end].to_string();
        let language = b.language_ext.clone().unwrap_or_default();
        self.suggest_dirty_at = None;
        // Dedup — if the context is byte-identical to the last request
        // fired, don't re-spend an API call / inference cycle (cursor
        // jiggle, type-then-undo back to the same state, etc.).
        if self.last_suggest_context.as_ref() == Some(&(prefix.clone(), suffix.clone())) {
            return;
        }
        self.last_suggest_context = Some((prefix.clone(), suffix.clone()));
        let id = self.next_suggest_id;
        self.next_suggest_id += 1;
        self.pending_suggest = Some((id, pane_id, cursor));
        match self.ai_suggest_backend() {
            crate::ai::SuggestBackend::Local => {
                // Local FIM — hand the request to the engine worker
                // (it owns the model + replies through `suggest_chan`).
                let max_tokens = self.ai_fim_max_tokens();
                let fim_tx = self.ensure_fim_worker();
                let _ = fim_tx.send((id, prefix, suffix, max_tokens));
            }
            // ClaudeCode (sub OAuth), ClaudeApi (env key), Unset
            // (shouldn't reach here — setup picker gates first-enable,
            // but resolve_suggest_auth returns a clean Err either
            // way). Resolve auth up front so a missing token/key fails
            // this call fast with a targeted message instead of the
            // worker thread panicking or churning.
            backend => {
                let tx = self
                    .suggest_chan
                    .get_or_insert_with(std::sync::mpsc::channel)
                    .0
                    .clone();
                let suggest_model = self.ai_suggest_model();
                let auth = match crate::ai::api_client::resolve_suggest_auth(backend) {
                    Ok(a) => a,
                    Err(msg) => {
                        let _ = tx.send((id, Err(msg)));
                        return;
                    }
                };
                std::thread::Builder::new()
                    .name("mnml-suggest".into())
                    .spawn(move || {
                        let result = crate::ai::api_client::complete_code(
                            &prefix,
                            &suffix,
                            &language,
                            suggest_model.as_deref(),
                            auth,
                        );
                        let _ = tx.send((id, result));
                    })
                    .ok();
            }
        }
    }

    /// The configured local FIM model size — `[ai] fim_model` (`"1.5b"`
    /// default / `"3b"`). 3B is smarter at multi-line completion but
    /// ~2x slower with a bigger download.
    pub(super) fn ai_fim_model(&self) -> fim_engine::ModelChoice {
        self.config
            .ai
            .get("fim_model")
            .and_then(|v| v.as_str())
            .map(fim_engine::ModelChoice::parse)
            .unwrap_or(fim_engine::ModelChoice::Qwen1_5B)
    }

    /// The per-request token cap for local FIM completions — `[ai]
    /// fim_max_tokens` (default 64, clamped 8..=512). Bigger = longer
    /// multi-line completions but slower per keystroke-pause.
    fn ai_fim_max_tokens(&self) -> usize {
        self.config
            .ai
            .get("fim_max_tokens")
            .and_then(|v| v.as_integer())
            .map(|n| (n.clamp(8, 512)) as usize)
            .unwrap_or(64)
    }

    /// `tick` hook — apply a ghost-text reply if it's still relevant
    /// (request id matches + the cursor hasn't moved).
    pub(super) fn drain_suggestions(&mut self) {
        let replies: Vec<SuggestReply> = match &self.suggest_chan {
            Some((_, rx)) => rx.try_iter().collect(),
            None => return,
        };
        for (id, result) in replies {
            // `u64::MAX` — a local-FIM load-status message, not a
            // completion. Toast it so the user sees download / ready /
            // failure state.
            if id == u64::MAX {
                match result {
                    Ok(msg) => self.toast(format!("fim-engine: {msg}")),
                    Err(msg) => self.toast(format!("fim-engine: {msg}")),
                }
                continue;
            }
            let Some((pending_id, pane_id, cursor)) = self.pending_suggest else {
                continue;
            };
            if pending_id != id {
                continue; // a newer request superseded this one
            }
            self.pending_suggest = None;
            let text = match result {
                Ok(t) => t,
                Err(_) => continue, // silent — ghost-text is best-effort
            };
            let cleaned = clean_suggestion(&text);
            if cleaned.is_empty() {
                continue;
            }
            // Only land it if the cursor is still where we asked.
            if let Some(Pane::Editor(b)) = self.panes.get_mut(pane_id)
                && b.editor.cursor() == cursor
            {
                b.editor.ghost_suggestion = Some(cleaned);
                self.suggest_shown = self.suggest_shown.saturating_add(1);
                self.suggest_current_accepted = false;
            }
        }
    }

    /// `Tab` accept of the active editor's ghost suggestion — inserts the
    /// whole suggestion at the cursor. Returns true if a suggestion was
    /// accepted (so the caller skips the normal Tab handling).
    pub fn accept_ghost_suggestion(&mut self) -> bool {
        self.accept_ghost_with(str::len)
    }

    /// Accept just the next word of the ghost suggestion (`Ctrl+Right` —
    /// Copilot convention). The rest stays as a ghost so the user can
    /// keep accepting word-by-word.
    pub fn accept_ghost_word(&mut self) -> bool {
        self.accept_ghost_with(ghost_word_boundary)
    }

    /// Accept the next line of the ghost suggestion (`Ctrl+Down`) —
    /// through the first newline; the whole thing when single-line.
    pub fn accept_ghost_line(&mut self) -> bool {
        self.accept_ghost_with(ghost_line_boundary)
    }

    /// Shared partial/full ghost-accept. `boundary(suggestion)` returns
    /// the byte count to accept now; the remainder (if any) stays as the
    /// ghost suggestion so accepts can chain.
    fn accept_ghost_with<F: Fn(&str) -> usize>(&mut self, boundary: F) -> bool {
        let Some(pane_id) = self.active else {
            return false;
        };
        let full = match self.panes.get(pane_id) {
            Some(Pane::Editor(b)) => b.editor.ghost_suggestion.clone(),
            _ => None,
        };
        let Some(full) = full.filter(|s| !s.is_empty()) else {
            return false;
        };
        let take = boundary(&full).min(full.len());
        if take == 0 {
            return false;
        }
        let accepted = full[..take].to_string();
        let remaining = full[take..].to_string();
        if let Some(Pane::Editor(b)) = self.panes.get_mut(pane_id) {
            let at = b.editor.cursor();
            let end = at + accepted.len();
            let clip = &mut self.clipboard;
            b.apply_edit_ops(
                vec![
                    crate::edit_op::EditOp::ReplaceRange {
                        start: at,
                        end: at,
                        text: accepted,
                    },
                    // Land the cursor past the accepted completion so the
                    // user keeps typing from there.
                    crate::edit_op::EditOp::SetCursorByte(end),
                ],
                clip,
                0,
            );
            b.editor.ghost_suggestion = (!remaining.is_empty()).then_some(remaining);
        }
        // Count the suggestion as accepted once — partial accepts of the
        // same suggestion chain, so only the first one bumps the tally.
        if !self.suggest_current_accepted {
            self.suggest_current_accepted = true;
            self.suggest_accepted = self.suggest_accepted.saturating_add(1);
        }
        true
    }

    /// `ai.suggestion_stats` — toast the inline-suggestion accept rate
    /// (accepted / shown, lifetime — persisted across launches). Helps
    /// gauge whether the chosen backend is pulling its weight.
    pub fn ai_suggestion_stats(&mut self) {
        if self.suggest_shown == 0 {
            self.toast("AI suggestions: none shown yet");
            return;
        }
        let pct = (self.suggest_accepted as u64 * 100) / self.suggest_shown as u64;
        self.toast(format!(
            "AI suggestions: {} accepted / {} shown ({}%)",
            self.suggest_accepted, self.suggest_shown, pct
        ));
    }

    /// Open an embedded terminal (`profile` = shell / `claude` / `codex`) as a
    /// stacked split below the focused leaf (a terminal "drawer"), and focus it.
    /// `Ctrl+F` while a Claude pty pane is focused — inject the most-
    /// recently-active editor's workspace-relative path into the pty's
    /// stdin (claude-chat.nvim's filename-inject gesture). Appends a
    /// trailing space, no Enter — the user keeps typing their prompt.
    pub fn inject_filename_to_claude(&mut self, pty_id: PaneId) {
        // The "current file" is the most-recent editor in the MRU list
        // (the Claude pane itself sits at the front; skip to the first
        // editor with a path).
        let rel = self
            .pane_mru
            .iter()
            .find_map(|&id| match self.panes.get(id) {
                Some(Pane::Editor(b)) => b.path.as_ref().map(|p| {
                    p.strip_prefix(&self.workspace)
                        .unwrap_or(p)
                        .to_string_lossy()
                        .into_owned()
                }),
                _ => None,
            });
        let Some(rel) = rel else {
            self.toast("no recent file to inject");
            return;
        };
        if let Some(Pane::Pty(s)) = self.panes.get_mut(pty_id) {
            s.write_bytes(format!("{rel} ").as_bytes());
        }
    }

    /// `ai.chat` — context-aware Claude dispatch (claude-chat.nvim-style
    /// wrapper). Opens a prompt; the title adapts to whether there's a
    /// selection. The accept routes to `dispatch_ai_chat`.
    pub fn open_ai_chat_prompt(&mut self) {
        let has_sel = self
            .active_editor()
            .map(|b| b.editor.has_selection())
            .unwrap_or(false);
        let title = if has_sel {
            "Ask Claude about the selection (empty = send selection only)"
        } else {
            "Ask Claude (empty = open plain Claude pane)"
        };
        let prompt = crate::prompt::Prompt::new(crate::prompt::PromptKind::AiChat, title);
        self.prompt = Some(prompt);
    }

    /// Build the file reference the `ai.chat` wrapper hands to Claude.
    /// Mirrors claude-chat.nvim's `context.format_*` exactly:
    /// `File: <rel> (lines N-M)` / `File: <rel> (line N)` / `File: <rel>`.
    /// A *reference*, not a paste — Claude reads fresh file state itself
    /// via its Read tool. `None` when there's no active editor with a path.
    fn ai_chat_context(&self) -> Option<String> {
        let b = self.active_editor()?;
        let path = b.path.as_ref()?;
        let rel = path
            .strip_prefix(&self.workspace)
            .unwrap_or(path)
            .to_string_lossy()
            .into_owned();
        // Live selection → include the 1-based inclusive line range.
        if let Some((lo, hi)) = b.editor.selection() {
            let (r1, _) = b.editor.row_col_at(lo);
            let (mut r2, c2) = b.editor.row_col_at(hi);
            // Roll back an exclusive end that sits at column 0 of the next
            // line so the range reflects the last content row.
            if r2 > r1 && c2 == 0 {
                r2 -= 1;
            }
            if r1 == r2 {
                Some(format!("File: {rel} (line {})", r1 + 1))
            } else {
                Some(format!("File: {rel} (lines {}-{})", r1 + 1, r2 + 1))
            }
        } else {
            Some(format!("File: {rel}"))
        }
    }

    /// Accept handler for `PromptKind::AiChat`. Composes the message in
    /// claude-chat.nvim's exact reference style:
    /// * query + selection ⇒ `File: <rel> (lines N-M).  Query: <prompt>`
    /// * query, no selection ⇒ `File: <rel>.  Query: <prompt>`
    /// * selection, no query ⇒ `File: <rel> (lines N-M). ` (bare ref)
    /// * neither ⇒ empty (plain Claude pane)
    ///
    /// Then: no Claude pane ⇒ spawn one seeded with the message; Claude
    /// pane already open + the user typed a query ⇒ bracketed-paste it
    /// into the live pty; Claude pane open + empty query ⇒ just focus it
    /// (claude-chat.nvim re-focuses an active session rather than
    /// re-seeding — we extend that with "but DO send if you asked
    /// something").
    pub fn dispatch_ai_chat(&mut self, typed: &str) {
        let typed = typed.trim();
        let context = self.ai_chat_context();
        let message = match (&context, typed.is_empty()) {
            // `format_prompt` joins `"File: x. "` + `"Query: q"` with a
            // space → the doubled space after the period is intentional.
            (Some(ctx), false) => format!("{ctx}.  Query: {typed}"),
            // `format_selection_prompt` — bare reference, no query part.
            (Some(ctx), true) => format!("{ctx}. "),
            (None, false) => typed.to_string(),
            (None, true) => String::new(),
        };
        if let Some(id) = self.find_claude_pty() {
            // Claude is already running. Only re-send when the user
            // actually typed a query — a bare focus / selection-only
            // gesture just reveals the pane (claude-chat.nvim's "active
            // session → focus" behavior).
            if !typed.is_empty()
                && let Some(Pane::Pty(s)) = self.panes.get_mut(id)
            {
                // Bracketed paste: `ESC[200~ … ESC[201~` keeps multi-line
                // text from submitting on each embedded newline; the
                // trailing `\r` then submits the whole message.
                let mut bytes = Vec::with_capacity(message.len() + 16);
                bytes.extend_from_slice(b"\x1b[200~");
                bytes.extend_from_slice(message.as_bytes());
                bytes.extend_from_slice(b"\x1b[201~\r");
                s.write_bytes(&bytes);
            }
            self.reveal_pane(id);
            return;
        }
        // No Claude pane yet — spawn one, seeded with the message if any.
        if message.is_empty() {
            self.open_pty_dir(
                crate::pty_pane::BinaryProfile::claude_code(self.workspace.clone()),
                crate::layout::SplitDir::Horizontal,
            );
        } else {
            self.open_pty_dir(
                crate::pty_pane::BinaryProfile::claude_code_with_prompt(
                    self.workspace.clone(),
                    message,
                ),
                crate::layout::SplitDir::Horizontal,
            );
        }
    }

    pub fn open_claude_code(&mut self) {
        // 2026-07-18 — also switch the activity bar to the Sessions
        // panel. AI panes live in Sessions, so having the user
        // context-shift to the panel that owns their new/revealed
        // pane matches expectations. Applies to both entry points
        // (sidebar Integrations chip + split-strip AI chip) since
        // both call this method.
        self.set_activity_section(crate::app::ActivitySection::Sessions);
        // If a Claude pane is already open, toggle focus / visibility-ish
        // by revealing it instead of spawning a duplicate. (Claude
        // sessions are expensive to bootstrap — same gesture as the
        // claude-chat.nvim "toggle if already active" behavior.)
        if let Some(id) = self.find_claude_pty() {
            self.reveal_pane(id);
            return;
        }
        // AI panes dock as a vertical split on the right of the active
        // leaf — the IDE-canonical "chat panel" placement.
        self.open_pty_dir(
            crate::pty_pane::BinaryProfile::claude_code(self.workspace.clone()),
            crate::layout::SplitDir::Horizontal,
        );
    }

    /// Always spawn a *new* Claude pane (no toggle / reuse) — the
    /// `ai.claude_code_new` palette command. Splits the active leaf;
    /// the pty tab strip's `+` uses `add_pty_tab` instead (tab, not
    /// split).
    ///
    /// Auto-tile — when N Claudes are already open:
    ///   - N == 2 in a clean H-split of leaves → rearrange to a 2×2
    ///     grid with the 3rd Claude on BL and an empty placeholder
    ///     on BR (`ai_placeholder_slot` marks it live).
    ///   - N == 3 with a live placeholder → fill the placeholder
    ///     with the new Claude → 2×2 fully populated.
    ///   - N == 4 in a recognisable 2×2 shape → grow to 3×2 with
    ///     placeholder → 5 Claudes + 1 placeholder in 6 slots.
    ///   - N == 5 with placeholder → fill → 3×2 fully populated.
    ///   - N == 6 in 3×2 shape → grow to 4×2 with placeholder.
    ///   - N == 7 with placeholder → fill → 4×2 fully populated.
    ///   - N >= 8 → default horizontal split (grid caps at 8).
    ///   - Otherwise → default horizontal split from the active pane.
    pub fn open_claude_code_new(&mut self) {
        if self.config.ui.auto_show_sessions_on_ai_activate {
            self.set_activity_section(crate::app::ActivitySection::Sessions);
        }
        // Tabs-only mode: new Claude becomes a tab in the active
        // leaf, not a split. Right-click the palette-bar AI chip
        // to switch back to grid.
        if self.config.ui.ai_layout_mode == "tabs" && self.open_claude_as_tab() {
            return;
        }
        // Guard against a stale slot marker — if the user closed a
        // Claude or dragged something into the Empty quadrant, the
        // tree no longer holds our placeholder even though the flag
        // may still say it does.
        if self.ai_placeholder_slot.is_some() && !self.layout().contains_empty() {
            self.ai_placeholder_slot = None;
        }
        let claudes = self.list_claude_pty_ids();
        match claudes.len() {
            2 if self.try_open_claude_2x2_third(claudes[0], claudes[1]) => {}
            3 | 5 | 7
                if self.ai_placeholder_slot.is_some()
                    && self.try_open_claude_fill_placeholder() => {}
            // 4 → grow 2×2 to 3×2 with slot 6 as placeholder.
            // 6 → grow 3×2 to 4×2 with slot 8 as placeholder.
            4 if self.try_open_claude_grid_grow(3) => {}
            6 if self.try_open_claude_grid_grow(4) => {}
            _ => self.open_pty_dir(
                crate::pty_pane::BinaryProfile::claude_code(self.workspace.clone()),
                crate::layout::SplitDir::Horizontal,
            ),
        }
    }

    fn list_claude_pty_ids(&self) -> Vec<crate::layout::PaneId> {
        self.panes
            .iter()
            .enumerate()
            .filter_map(|(i, p)| match p {
                Pane::Pty(s) if s.profile.label.starts_with("Claude") => Some(i),
                _ => None,
            })
            .collect()
    }

    /// Spawn a 3rd Claude, rearrange the {C1, C2} leaf-only split
    /// into a 2×2 grid, and set `ai_placeholder_slot`. Returns
    /// false (rolling back the spawn) if the layout doesn't have a
    /// clean leaf-only H-split of C1 and C2 to rearrange.
    fn try_open_claude_2x2_third(
        &mut self,
        c1: crate::layout::PaneId,
        c2: crate::layout::PaneId,
    ) -> bool {
        use crate::layout::{Layout, SplitDir};
        // Only rearrange when the two existing Claudes are in a
        // clean side-by-side (horizontal) split — that's the shape
        // the user is asking us to grow into a grid. Any other
        // topology (nested, multi-tab leaf, vertical split) falls
        // through to the default handler.
        if self
            .layout_mut()
            .find_leaf_pair_split_mut(c1, c2)
            .filter(|(_, dir)| *dir == SplitDir::Horizontal)
            .is_none()
        {
            return false;
        }
        // Spawn the 3rd Claude.
        let Some(new_id) = self.spawn_claude_pane() else {
            return false;
        };
        // Rearrange. `find_leaf_pair_split_mut` again since the
        // borrow above didn't survive across `spawn_claude_pane`.
        let Some((subtree, _)) = self.layout_mut().find_leaf_pair_split_mut(c1, c2) else {
            return false;
        };
        let old = std::mem::replace(subtree, Layout::Empty);
        *subtree = Layout::Split {
            dir: SplitDir::Vertical,
            ratio: 50,
            first: Box::new(old),
            second: Box::new(Layout::Split {
                dir: SplitDir::Horizontal,
                ratio: 50,
                first: Box::new(Layout::leaf(new_id)),
                second: Box::new(Layout::Empty),
            }),
        };
        self.ai_placeholder_slot = Some(crate::app::AiPlaceholderKind::ClaudeCode);
        self.active = Some(new_id);
        self.focus = crate::app::Focus::Pane;
        true
    }

    /// Grow the Claude grid from an existing N×2 shape to
    /// `target_cols × 2`, spawning one new Claude to occupy slot
    /// `target_cols*2 - 1` and marking slot `target_cols*2` as the
    /// `Empty` placeholder.
    ///
    /// For `target_cols == 3` this expands a 2×2 (4 Claudes) →
    /// 3×2 (5 real + 1 placeholder). For `target_cols == 4` it
    /// expands a 3×2 (6 Claudes) → 4×2 (7 real + 1 placeholder).
    ///
    /// Requires that the current layout contains a subtree whose
    /// leaves are exactly the existing Claudes (no other panes,
    /// possibly one already-filled Empty slot). Otherwise falls
    /// through to the default open path — the user has messed with
    /// the layout enough that auto-tile would surprise them.
    fn try_open_claude_grid_grow(&mut self, target_cols: usize) -> bool {
        use crate::layout::{Layout, SplitDir};
        let old_claudes = self.list_claude_pty_ids();
        if old_claudes.len() != target_cols * 2 - 2 {
            return false;
        }
        // Locate the existing Claude cluster (a subtree whose leaves
        // are exactly these `old_claudes`, with maybe one filled
        // Empty). Bail if the user's layout doesn't have a clean
        // cluster to rewrite.
        let old_set: std::collections::HashSet<crate::layout::PaneId> =
            old_claudes.iter().copied().collect();
        if self
            .layout_mut()
            .find_pure_pane_cluster_mut(&old_set)
            .is_none()
        {
            return false;
        }
        let Some(new_id) = self.spawn_claude_pane() else {
            return false;
        };
        // Slot layout: top row = the first `target_cols` old
        // Claudes; bottom row = remaining old Claudes + the newly
        // spawned Claude + one Empty placeholder in slot
        // `target_cols*2`.
        let top_row: Vec<crate::layout::PaneId> =
            old_claudes.iter().copied().take(target_cols).collect();
        let mut bottom_row: Vec<Option<crate::layout::PaneId>> = old_claudes
            .iter()
            .copied()
            .skip(target_cols)
            .map(Some)
            .collect();
        bottom_row.push(Some(new_id));
        bottom_row.push(None); // Empty → placeholder
        let new_cluster = Layout::Split {
            dir: SplitDir::Vertical,
            ratio: 50,
            first: Box::new(build_equal_row(
                top_row.into_iter().map(Layout::leaf).collect(),
            )),
            second: Box::new(build_equal_row(
                bottom_row
                    .into_iter()
                    .map(|opt| opt.map(Layout::leaf).unwrap_or(Layout::Empty))
                    .collect(),
            )),
        };
        let Some(cluster) = self.layout_mut().find_pure_pane_cluster_mut(&old_set) else {
            return false;
        };
        *cluster = new_cluster;
        self.ai_placeholder_slot = Some(crate::app::AiPlaceholderKind::ClaudeCode);
        self.active = Some(new_id);
        self.focus = crate::app::Focus::Pane;
        true
    }

    /// Spawn the 4th Claude and drop it into the `Empty` slot in
    /// the layout tree.
    fn try_open_claude_fill_placeholder(&mut self) -> bool {
        if !self.layout().contains_empty() {
            return false;
        }
        let Some(new_id) = self.spawn_claude_pane() else {
            return false;
        };
        if !self
            .layout_mut()
            .fill_first_empty(crate::layout::Layout::leaf(new_id))
        {
            return false;
        }
        self.ai_placeholder_slot = None;
        self.active = Some(new_id);
        self.focus = crate::app::Focus::Pane;
        true
    }

    /// Append a fresh Claude Code session as a TAB in the active
    /// leaf (no split). Used by the `tabs` layout mode. Returns
    /// false when there's no active leaf — caller falls through
    /// to the default open which creates the first pane.
    fn open_claude_as_tab(&mut self) -> bool {
        let Some(active) = self.active else {
            return false;
        };
        let Some(new_id) = self.spawn_claude_pane() else {
            return false;
        };
        // Append the new pane to the target leaf's tab list.
        let mut appended = false;
        if let Some((leaf_active, tabs)) = self.layout_mut().leaf_containing_mut(active) {
            tabs.push(new_id);
            *leaf_active = new_id;
            appended = true;
        }
        if !appended {
            return false;
        }
        self.active = Some(new_id);
        self.focus = crate::app::Focus::Pane;
        true
    }

    fn spawn_claude_pane(&mut self) -> Option<crate::layout::PaneId> {
        let mut profile = crate::pty_pane::BinaryProfile::claude_code(self.workspace.clone());
        // Match `open_pty_dir`'s Bridge-env injection so a
        // rearranged spawn behaves like the default path.
        let bridge = self.bridge_env();
        for (k, v) in bridge {
            if !profile.env.iter().any(|(pk, _)| pk == &k) {
                profile.env.push((k, v));
            }
        }
        match crate::pty_pane::PtySession::spawn(profile, 24, 80) {
            Ok(mut s) => {
                self.apply_saved_pty_name(&mut s);
                self.panes.push(Pane::Pty(s));
                Some(self.panes.len() - 1)
            }
            Err(e) => {
                self.toast(format!("can't open terminal: {e}"));
                None
            }
        }
    }

    /// Place a fresh Claude Code pane in a specific half of the
    /// active leaf's containing split. Routed from the right-click
    /// menu on the tab-strip `⚡ Claude` chip. `RightHalf` uses
    /// `open_claude_code_new` verbatim; `LeftHalf` / `TopHalf` /
    /// `BottomHalf` swap the newly-created split's sides so the new
    /// pane ends up where the user expected.
    pub fn open_claude_code_new_at(&mut self, placement: PanePlacement) {
        if self.config.ui.auto_show_sessions_on_ai_activate {
            self.set_activity_section(crate::app::ActivitySection::Sessions);
        }
        self.open_pty_at_placement(
            crate::pty_pane::BinaryProfile::claude_code(self.workspace.clone()),
            placement,
        );
    }

    /// Place a fresh Codex pane in a specific half. Mirror of
    /// `open_claude_code_new_at`.
    pub fn open_codex_new_at(&mut self, placement: PanePlacement) {
        if self.config.ui.auto_show_sessions_on_ai_activate {
            self.set_activity_section(crate::app::ActivitySection::Sessions);
        }
        self.open_pty_at_placement(
            crate::pty_pane::BinaryProfile::codex(self.workspace.clone()),
            placement,
        );
    }

    pub(crate) fn open_pty_at_placement(
        &mut self,
        profile: crate::pty_pane::BinaryProfile,
        placement: PanePlacement,
    ) {
        use crate::layout::SplitDir;
        let dir = match placement {
            PanePlacement::LeftHalf | PanePlacement::RightHalf => SplitDir::Horizontal,
            PanePlacement::TopHalf | PanePlacement::BottomHalf => SplitDir::Vertical,
        };
        self.open_pty_dir(profile, dir);
        // `open_pty_dir` puts the new pane on the `second` side
        // (right / bottom). Swap for LeftHalf / TopHalf so the new
        // pane lands in the requested position.
        if matches!(placement, PanePlacement::LeftHalf | PanePlacement::TopHalf)
            && let Some(new_id) = self.active
        {
            self.layout_mut().swap_siblings_containing(new_id);
        }
    }

    pub fn open_codex(&mut self) {
        // Parallel to `open_claude_code`: switch the activity bar
        // to Sessions since that's where AI panes are surfaced.
        self.set_activity_section(crate::app::ActivitySection::Sessions);
        if let Some(id) = self.find_codex_pty() {
            self.reveal_pane(id);
            return;
        }
        self.open_pty_dir(
            crate::pty_pane::BinaryProfile::codex(self.workspace.clone()),
            crate::layout::SplitDir::Horizontal,
        );
    }

    /// Always spawn a *new* Codex pane (no toggle / reuse). Parallel
    /// of `open_claude_code_new` — split-strip AI chip in `both` mode
    /// dispatches here.
    pub fn open_codex_new(&mut self) {
        if self.config.ui.auto_show_sessions_on_ai_activate {
            self.set_activity_section(crate::app::ActivitySection::Sessions);
        }
        // Tabs-only mode: new Codex becomes a tab in the active
        // leaf, not a split.
        if self.config.ui.ai_layout_mode == "tabs" && self.open_codex_as_tab() {
            return;
        }
        self.open_pty_dir(
            crate::pty_pane::BinaryProfile::codex(self.workspace.clone()),
            crate::layout::SplitDir::Horizontal,
        );
    }

    fn open_codex_as_tab(&mut self) -> bool {
        let Some(active) = self.active else {
            return false;
        };
        let mut profile = crate::pty_pane::BinaryProfile::codex(self.workspace.clone());
        let bridge = self.bridge_env();
        for (k, v) in bridge {
            if !profile.env.iter().any(|(pk, _)| pk == &k) {
                profile.env.push((k, v));
            }
        }
        let new_id = match crate::pty_pane::PtySession::spawn(profile, 24, 80) {
            Ok(mut s) => {
                self.apply_saved_pty_name(&mut s);
                self.panes.push(Pane::Pty(s));
                self.panes.len() - 1
            }
            Err(e) => {
                self.toast(format!("can't open terminal: {e}"));
                return false;
            }
        };
        if let Some((leaf_active, tabs)) = self.layout_mut().leaf_containing_mut(active) {
            tabs.push(new_id);
            *leaf_active = new_id;
            self.active = Some(new_id);
            self.focus = crate::app::Focus::Pane;
            return true;
        }
        false
    }

    /// Open the family DJ app `mixr` as a Pty pane. Reuses an
    /// existing mixr pty if one's already open; otherwise spawns a
    /// fresh one in a horizontal split (same shape as Codex).
    ///
    /// 2026-08-21 — source-aware startup: if Beatport is authed AND
    /// `~/.mixr/config.toml` has `favorite_genres` non-empty, spawn
    /// with `--play` (mixr queues a random chart from a random
    /// favorited genre). Otherwise spawn `--dashboard --panel browse`
    /// so the user lands on the minibrowser and can pick their own
    /// path. Local-library shuffle-by-genre isn't wired in mixr yet
    /// — once it is, we can add a third branch here without changing
    /// the chip surface.
    pub fn open_mixr(&mut self) {
        self.open_mixr_with_args(vec![
            "--dashboard".into(),
            "--panel".into(),
            "browse".into(),
        ]);
    }

    /// 2026-08-22 — one-tap "play a random chart from a random
    /// favorited genre" flow, fired by the play-glyph next to the
    /// music chip. When Beatport isn't authed OR favorites is empty,
    /// falls back to plain browser (mixr's --play already handles
    /// empty favorites by picking `default_genre`, but we still need
    /// an auth check so the user isn't confused by silent no-ops).
    pub fn open_mixr_and_play(&mut self) {
        let can_play = mixr_beatport_authed();
        let args = if can_play {
            vec!["--play".into(), "--panel".into(), "browse".into()]
        } else {
            self.toast("mixr: sign in to Beatport first — opening browser");
            vec!["--dashboard".into(), "--panel".into(), "browse".into()]
        };
        self.open_mixr_with_args(args);
    }

    fn open_mixr_with_args(&mut self, args: Vec<String>) {
        let existing = self.panes.iter().position(|p| match p {
            Pane::Pty(s) => s.profile.label.starts_with("mixr"),
            _ => false,
        });
        if let Some(id) = existing {
            self.reveal_pane(id);
            return;
        }
        self.open_pty_dir(
            crate::pty_pane::BinaryProfile::mixr(self.workspace.clone(), args),
            crate::layout::SplitDir::Horizontal,
        );
    }

    /// Return the pane id of any open Claude Code pty pane (matched by
    /// `BinaryProfile.label`), or `None`.
    fn find_claude_pty(&self) -> Option<PaneId> {
        self.panes.iter().position(|p| match p {
            Pane::Pty(s) => s.profile.label.starts_with("Claude"),
            _ => false,
        })
    }

    /// Return the pane id of any open Codex pty pane.
    fn find_codex_pty(&self) -> Option<PaneId> {
        self.panes.iter().position(|p| match p {
            Pane::Pty(s) => s.profile.label.starts_with("Codex"),
            _ => false,
        })
    }

    /// True while a `claude -p` run is in flight (so the event loop polls faster
    /// and streamed deltas render promptly).
    pub fn has_pending_ai(&self) -> bool {
        self.pending_commit_msg_job.is_some()
            || self.panes.iter().any(|p| {
                matches!(p, Pane::Ai(a)
                    if matches!(a.state, crate::ai::AiState::Asking | crate::ai::AiState::Streaming(_)))
            })
    }

    /// Allocate a job id + fresh session id and spawn `claude -p --session-id …`
    /// Precheck for the 4 new AI palette commands shipped this
    /// session. Toasts + returns false if `$ANTHROPIC_API_KEY`
    /// isn't set OR is empty. Was: each command fired a job, the
    /// API call inside the worker thread failed with a 401 /
    /// "key not set" message that took a few seconds to surface.
    /// Now: 0ms fail-fast at the palette layer. 2026-06-21
    /// power-user-ai SEV-3 fix.
    pub(crate) fn ai_api_key_ready(&mut self, label: &str) -> bool {
        match std::env::var("ANTHROPIC_API_KEY") {
            Ok(k) if !k.trim().is_empty() => true,
            _ => {
                self.toast(format!("{label}: $ANTHROPIC_API_KEY not set"));
                false
            }
        }
    }

    /// on a worker thread. Returns `(job_id, session_id, cancel_flag)` — set the
    /// flag to ask the worker to kill its child and bail.
    fn spawn_ai_job(
        &mut self,
        prompt: String,
    ) -> (u64, String, std::sync::Arc<std::sync::atomic::AtomicBool>) {
        let job_id = self.next_job_id;
        self.next_job_id += 1;
        let session_id = crate::ai::gen_session_id();
        let tx = self
            .ai_chan
            .get_or_insert_with(std::sync::mpsc::channel)
            .0
            .clone();
        let sid = session_id.clone();
        let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let worker_cancel = cancel.clone();
        let backend = self.ai_backend();
        let model = self.ai_model();
        let system = self.ai_system_prompt();
        let max_tokens = self.ai_max_tokens();
        let api_tools = self.ai_api_tools();
        let api_write_tools = self.ai_api_write_tools();
        let api_shell_tools = self.ai_api_shell_tools();
        // Confirm before a write/shell: on unless the user opted out.
        let write_confirm = api_write_tools && self.ai_api_write_confirm();
        let shell_confirm = api_shell_tools && self.ai_api_shell_confirm();
        let (confirm_tx, confirm_rx) = std::sync::mpsc::channel::<bool>();
        self.ai_confirm_senders.insert(job_id, confirm_tx);
        let workspace = self.workspace.clone();
        std::thread::spawn(move || match backend {
            crate::ai::AiBackend::Api => {
                if api_tools {
                    // Agentic loop — read-only workspace tools (read_file
                    // / list_directory / grep), plus write_file when the
                    // user opted in via `[ai] api_write_tools`.
                    crate::ai::api_client::agent_to_channel(
                        &prompt,
                        &workspace,
                        model.as_deref(),
                        system.as_deref(),
                        max_tokens,
                        api_write_tools,
                        write_confirm,
                        api_shell_tools,
                        shell_confirm,
                        &confirm_rx,
                        &worker_cancel,
                        tx,
                        job_id,
                    );
                } else {
                    crate::ai::api_client::stream_to_channel(
                        &prompt,
                        &workspace,
                        model.as_deref(),
                        system.as_deref(),
                        max_tokens,
                        &worker_cancel,
                        tx,
                        job_id,
                    );
                }
            }
            crate::ai::AiBackend::Cli => {
                crate::ai::stream_to_channel(&prompt, &sid, &worker_cancel, tx, job_id);
            }
        });
        (job_id, session_id, cancel)
    }

    /// Optional `[ai] max_tokens = N` from the config — overrides the API
    /// backend's default output cap (4096). CLI backend ignores this.
    pub fn ai_max_tokens(&self) -> Option<u32> {
        self.config
            .ai
            .get("max_tokens")
            .and_then(|v| v.as_integer())
            .and_then(|n| u32::try_from(n).ok())
    }

    /// Optional `[ai] model = "..."` from the config — overrides the API
    /// backend's default model when set. CLI backend ignores this (the
    /// `claude` binary picks its own default).
    pub fn ai_model(&self) -> Option<String> {
        self.config
            .ai
            .get("model")
            .and_then(|v| v.as_str())
            .filter(|s| !s.trim().is_empty())
            .map(str::to_string)
    }

    /// Optional `[ai] suggest_model = "..."` from the config — overrides
    /// the model used for inline ghost-text completion (the ClaudeApi
    /// suggestion backend). Defaults to the fast `claude-haiku-4-5`
    /// since latency matters more than depth for inline completion;
    /// distinct from `[ai] model` (the chat/explain default).
    pub fn ai_suggest_model(&self) -> Option<String> {
        self.config
            .ai
            .get("suggest_model")
            .and_then(|v| v.as_str())
            .filter(|s| !s.trim().is_empty())
            .map(str::to_string)
    }

    /// `[ai] api_tools` — whether the direct-API backend runs the
    /// agentic loop with read-only workspace tools (`read_file` /
    /// `list_directory` / `grep`) vs plain text-in/text-out streaming.
    /// Default on — that's the point of the API backend being useful
    /// for more than short asks. CLI backend is unaffected (it always
    /// runs the full `claude` agent).
    pub fn ai_api_tools(&self) -> bool {
        self.config
            .ai
            .get("api_tools")
            .and_then(|v| v.as_bool())
            .unwrap_or(true)
    }

    /// `[ai] api_write_tools` — whether the direct-API agent loop also
    /// gets the `write_file` tool (it can create/overwrite workspace
    /// files autonomously). Default **off** — read-only keeps the API
    /// backend strictly safer than the CLI backend. Opt in deliberately.
    pub fn ai_api_write_tools(&self) -> bool {
        self.config
            .ai
            .get("api_write_tools")
            .and_then(|v| v.as_bool())
            .unwrap_or(false)
    }

    /// `[ai] api_write_confirm` — whether each agent `write_file` blocks
    /// for the user's approval before it runs. Default **on** — the
    /// human-in-the-loop safety net for `api_write_tools`. Set false for
    /// unattended writes.
    pub fn ai_api_write_confirm(&self) -> bool {
        self.config
            .ai
            .get("api_write_confirm")
            .and_then(|v| v.as_bool())
            .unwrap_or(true)
    }

    /// `[ai] api_shell_tools` — whether the direct-API agent loop gets
    /// the `shell_exec` tool (it can run arbitrary `sh -c` commands in
    /// the workspace). Default **off** — strictly opt-in. Combine with
    /// `api_shell_confirm` (default on) for the per-call safety net.
    pub fn ai_api_shell_tools(&self) -> bool {
        self.config
            .ai
            .get("api_shell_tools")
            .and_then(|v| v.as_bool())
            .unwrap_or(false)
    }

    /// `[ai] api_shell_confirm` — whether each agent `shell_exec` call
    /// blocks for the user's approval before it runs. Default **on**.
    pub fn ai_api_shell_confirm(&self) -> bool {
        self.config
            .ai
            .get("api_shell_confirm")
            .and_then(|v| v.as_bool())
            .unwrap_or(true)
    }

    /// `ai.show_config` — toast the live AI backend + model + tool
    /// state. A reliable "what am I running" readout (asking the model
    /// itself doesn't work — LLMs don't know their own version).
    pub fn ai_show_config(&mut self) {
        match self.ai_backend() {
            crate::ai::AiBackend::Cli => {
                self.toast("AI: backend=cli (claude binary · your subscription)");
            }
            crate::ai::AiBackend::Api => {
                let model = self
                    .ai_model()
                    .unwrap_or_else(|| "claude-opus-4-7 (default)".to_string());
                let tools = if !self.ai_api_tools() {
                    "off"
                } else if self.ai_api_write_tools() {
                    "read+write"
                } else {
                    "read-only"
                };
                self.toast(format!("AI: backend=api · model={model} · tools={tools}"));
            }
        }
    }

    /// `ai.token_usage` — toast the direct-API token tally (summed
    /// across every job, lifetime — persisted across launches) + a
    /// rough cost estimate.
    pub fn ai_token_usage(&mut self) {
        if self.ai_tokens_in == 0 && self.ai_tokens_out == 0 {
            self.toast("AI usage: no direct-API calls recorded yet");
            return;
        }
        let model = self.ai_model();
        let base = format!(
            "AI usage: {} in · {} out",
            fmt_tokens(self.ai_tokens_in),
            fmt_tokens(self.ai_tokens_out)
        );
        let msg = match estimate_ai_cost(model.as_deref(), self.ai_tokens_in, self.ai_tokens_out) {
            Some(c) => format!("{base} (~${c:.2})"),
            None => base,
        };
        self.toast(msg);
    }

    /// Optional `[ai] system_prompt = "..."` from the config — prepended
    /// to every API-backend request as the `system` field. CLI backend
    /// ignores this (it has its own conversation system prompt).
    pub fn ai_system_prompt(&self) -> Option<String> {
        self.config
            .ai
            .get("system_prompt")
            .and_then(|v| v.as_str())
            .filter(|s| !s.trim().is_empty())
            .map(str::to_string)
    }

    /// Read the user's `[ai] backend = "cli" | "api"` setting. Default
    /// `Cli` (no surprises for users without an API key set).
    /// `[ai] inline_suggestions` — whether Cursor-style AI ghost-text
    /// fires as you type. Defaults to **on** (task #974, 2026-08-17)
    /// now that the default AI backend is `cli` / `claude-code` (sub-
    /// backed via the Keychain OAuth token — no per-keystroke API
    /// billing). Existing users with an explicit `inline_suggestions =
    /// false` in their config keep it off (defaults only kick in when
    /// the key is absent). Also automatically disabled when the Claude
    /// product is routed `off` (task #975).
    pub fn ai_inline_suggestions(&self) -> bool {
        // Product-off short-circuits the config default. A user who
        // set `[ai.routing.claude] backend = "off"` clearly doesn't
        // want any Claude calls, ghost-text included, so we never
        // fire them regardless of `inline_suggestions`.
        if crate::ai::resolve_backend(&self.config.ai, crate::ai::AiProduct::Claude)
            == crate::ai::ResolvedBackend::Off
        {
            return false;
        }
        self.config
            .ai
            .get("inline_suggestions")
            .and_then(|v| v.as_bool())
            .unwrap_or(true)
    }

    /// Flip `[ai] inline_suggestions` at runtime. Doesn't persist —
    /// restart re-reads the config file. Turning it ON for the first
    /// time (no backend chosen yet) opens the setup picker instead.
    pub fn toggle_inline_suggestions(&mut self) {
        let next = !self.ai_inline_suggestions();
        if next && self.ai_suggest_backend() == crate::ai::SuggestBackend::Unset {
            // First enable — let the user pick a backend. The picker's
            // accept turns the feature on once a choice is made.
            self.open_suggest_backend_picker();
            return;
        }
        if !self.config.ai.is_table() {
            self.config.ai = toml::Value::Table(toml::value::Table::new());
        }
        if let Some(t) = self.config.ai.as_table_mut() {
            t.insert("inline_suggestions".to_string(), toml::Value::Boolean(next));
        }
        if next {
            self.toast("AI ghost-text: on");
        } else {
            self.clear_ghost_suggestion();
            self.pending_suggest = None;
            self.suggest_dirty_at = None;
            self.last_suggest_context = None;
            self.toast("AI ghost-text: off");
        }
    }

    /// `ai.setup_suggestions` — open the inline-suggestion backend
    /// picker. Reachable any time, so the user can switch backends
    /// later (the answer to "pick + change later").
    pub fn open_suggest_backend_picker(&mut self) {
        use crate::picker::{Picker, PickerItem, PickerKind};
        let cur = self.ai_suggest_backend();
        let mark = |b: crate::ai::SuggestBackend| {
            if cur == b { "" } else { "  " }
        };
        let items = vec![
            PickerItem::new(
                "claude-code",
                format!(
                    "{}Claude Code sub",
                    mark(crate::ai::SuggestBackend::ClaudeCode)
                ),
                "reuses your Max/Pro plan · no separate API key · ~1s",
            ),
            PickerItem::new(
                "claude-api",
                format!("{}Claude API", mark(crate::ai::SuggestBackend::ClaudeApi)),
                "needs $ANTHROPIC_API_KEY · ~1s · works now",
            ),
            PickerItem::new(
                "local",
                format!(
                    "{}Local model (embedded)",
                    mark(crate::ai::SuggestBackend::Local)
                ),
                "private · free · offline · one-time ~1GB download",
            ),
            PickerItem::new(
                "off",
                "  Turn off inline suggestions".to_string(),
                "disable AI ghost-text",
            ),
        ];
        self.open_picker(Picker::new(
            PickerKind::SuggestBackend,
            "AI inline suggestions — pick a backend",
            items,
        ));
    }

    /// Picker-accept for `PickerKind::SuggestBackend`.
    pub fn accept_suggest_backend(&mut self, id: &str) {
        match id {
            "off" => {
                if self.config.ai.is_table()
                    && let Some(t) = self.config.ai.as_table_mut()
                {
                    t.insert(
                        "inline_suggestions".to_string(),
                        toml::Value::Boolean(false),
                    );
                }
                self.clear_ghost_suggestion();
                self.toast("AI ghost-text: off");
            }
            other => {
                let backend = crate::ai::SuggestBackend::parse(other);
                self.set_ai_suggest_backend(backend);
                if !self.config.ai.is_table() {
                    self.config.ai = toml::Value::Table(toml::value::Table::new());
                }
                if let Some(t) = self.config.ai.as_table_mut() {
                    t.insert("inline_suggestions".to_string(), toml::Value::Boolean(true));
                }
                match backend {
                    crate::ai::SuggestBackend::ClaudeCode => {
                        self.toast("AI ghost-text: on · Claude Code sub");
                    }
                    crate::ai::SuggestBackend::ClaudeApi => {
                        self.toast("AI ghost-text: on · Claude API");
                    }
                    crate::ai::SuggestBackend::Local => {
                        self.toast("AI ghost-text: on · local model");
                        // Warm up now — spawn the worker so the one-time
                        // download/load starts immediately (the worker
                        // loads eagerly on spawn) rather than stalling
                        // the user's first keystroke-pause.
                        self.ensure_fim_worker();
                    }
                    crate::ai::SuggestBackend::Unset => {}
                }
            }
        }
    }

    /// `[ai] suggest_backend` — which engine powers inline ghost-text.
    /// Defaults to `ClaudeCode` (sub-backed OAuth) as of task #974
    /// (2026-08-17); was `Unset` (forcing a setup picker on first
    /// enable) back when ghost-text billed API tokens per keystroke.
    /// The setup picker is still reachable via `ai.setup_suggestions`
    /// for anyone who wants Local or ClaudeApi instead.
    pub fn ai_suggest_backend(&self) -> crate::ai::SuggestBackend {
        let s = self
            .config
            .ai
            .get("suggest_backend")
            .and_then(|v| v.as_str())
            .unwrap_or("claude-code");
        crate::ai::SuggestBackend::parse(s)
    }

    /// Resolve which billing/routing lane THIS product's calls take
    /// on the current machine. Reads `[ai.routing.<product>] backend`
    /// (new key, task #975), falling back to the legacy `[ai] backend`
    /// key for Claude. `Auto` resolves to `Sub` or `Api` via a `PATH`
    /// probe + the vendor's API-key env var (`$ANTHROPIC_API_KEY` for
    /// Claude, `$OPENAI_API_KEY` for Codex).
    pub fn ai_resolved_backend(&self, product: crate::ai::AiProduct) -> crate::ai::ResolvedBackend {
        crate::ai::resolve_backend(&self.config.ai, product)
    }

    /// `[ai.routing.claude] backend` resolved. Sub / Api / Off.
    pub fn ai_route_claude(&self) -> crate::ai::ResolvedBackend {
        self.ai_resolved_backend(crate::ai::AiProduct::Claude)
    }

    /// `[ai.routing.codex] backend` resolved. Sub / Api / Off — same
    /// three lanes as Claude (Codex CLI supports both ChatGPT Plus/Team
    /// sub auth and the OpenAI API key).
    pub fn ai_route_codex(&self) -> crate::ai::ResolvedBackend {
        self.ai_resolved_backend(crate::ai::AiProduct::Codex)
    }

    /// Persist the inline-suggestion backend choice into the runtime
    /// config (`[ai] suggest_backend`). Not written to disk — restart
    /// re-reads the config file; the user pins it there for permanence.
    pub fn set_ai_suggest_backend(&mut self, backend: crate::ai::SuggestBackend) {
        if !self.config.ai.is_table() {
            self.config.ai = toml::Value::Table(toml::value::Table::new());
        }
        if let Some(t) = self.config.ai.as_table_mut() {
            t.insert(
                "suggest_backend".to_string(),
                toml::Value::String(backend.as_str().to_string()),
            );
        }
    }

    pub fn ai_backend(&self) -> crate::ai::AiBackend {
        // Task #975 (2026-08-17) — route through the resolved product
        // backend so `[ai.routing.claude] backend = "api"` etc. take
        // effect for the ask/explain/fix Claude job path too. `Off`
        // maps to `Cli` (a safer default than surprise-hitting the
        // API); ask/explain call sites can further gate on
        // `ai_route_claude() == Off` if they want to hide the action.
        match self.ai_route_claude() {
            crate::ai::ResolvedBackend::Api => crate::ai::AiBackend::Api,
            _ => crate::ai::AiBackend::Cli,
        }
    }

    /// Flip `[ai] backend` at runtime (`cli` ↔ `api`). Affects every
    /// AI job spawned after the toggle. Doesn't persist to the config
    /// file — restart re-reads from disk.
    pub fn toggle_ai_backend(&mut self) {
        let next = match self.ai_backend() {
            crate::ai::AiBackend::Cli => "api",
            crate::ai::AiBackend::Api => "cli",
        };
        // The raw `Value` may be Table or empty; we need a Table to set keys.
        if !self.config.ai.is_table() {
            self.config.ai = toml::Value::Table(toml::value::Table::new());
        }
        if let Some(t) = self.config.ai.as_table_mut() {
            t.insert("backend".to_string(), toml::Value::String(next.to_string()));
        }
        self.toast(format!("ai.backend: {next}"));
    }

    /// Open a `Pane::Ai` showing `title` and the answer to `prompt`, and kick off
    /// `claude -p <prompt>` on a background thread (`tick` delivers the answer).
    /// Right-panel v4 (2026-06-28): when the right panel is visible, hosts the
    /// AI chat there as a new tab instead of splitting the editor body. AI chat
    /// is content-rich and benefits from the dedicated column; the panel
    /// auto-widens via the user's drag handle if 32 cells reads too tight.
    pub fn ask_ai(&mut self, title: impl Into<String>, prompt: String) {
        let (job_id, session_id, cancel) = self.spawn_ai_job(prompt.clone());
        let pane = Pane::Ai(crate::ai::AiPane::new(
            title, prompt, session_id, job_id, cancel,
        ));
        if self.right_panel_visible {
            self.panes.push(pane);
            let new_id = self.panes.len() - 1;
            self.right_panel_push(new_id);
            return;
        }
        match self.active {
            Some(cur) => {
                let new_id = self.split_leaf_with(cur, crate::layout::SplitDir::Horizontal, pane);
                self.active = Some(new_id);
            }
            None => {
                self.panes.push(pane);
                let id = self.panes.len() - 1;
                *self.layout_mut() = Layout::leaf(id);
                self.active = Some(id);
            }
        }
        self.focus = Focus::Pane;
    }

    /// Re-send the prompt an existing `Pane::Ai` holds (with a fresh session id).
    /// No-op for a live transcript mirror (it has no `-p` prompt). Signals any
    /// still-running worker for this pane to bail first.
    fn reask_ai(&mut self, pane_id: PaneId) {
        let prompt = match self.panes.get(pane_id) {
            Some(Pane::Ai(a)) if !a.is_live() => {
                a.cancel.store(true, std::sync::atomic::Ordering::Relaxed);
                a.prompt.clone()
            }
            _ => return,
        };
        let (job_id, session_id, cancel) = self.spawn_ai_job(prompt);
        if let Some(Pane::Ai(a)) = self.panes.get_mut(pane_id) {
            a.job_id = job_id;
            a.session_id = session_id;
            a.state = crate::ai::AiState::Asking;
            a.scroll = 0;
            a.cancel = cancel;
            a.pending_apply = None;
        }
    }

    /// `x` in an `Asking` `Pane::Ai` — ask the worker to kill `claude -p` and bail
    /// (the reply lands as `Failed("cancelled")`).
    pub fn cancel_active_ai(&mut self) {
        let Some(cur) = self.active else { return };
        if let Some(Pane::Ai(a)) = self.panes.get(cur)
            && matches!(
                a.state,
                crate::ai::AiState::Asking | crate::ai::AiState::Streaming(_)
            )
        {
            a.cancel.store(true, std::sync::atomic::Ordering::Relaxed);
            self.toast("cancelling…");
        }
    }

    /// `y` in a `Pane::Ai` — copy the rendered answer text to the clipboard.
    /// No-op for `Asking` (nothing typed yet) and `Live` mirrors (those are
    /// transcripts, not a single answer body).
    pub fn copy_active_ai_answer(&mut self) {
        let Some(cur) = self.active else { return };
        let text = match self.panes.get(cur) {
            Some(Pane::Ai(a)) => a.answer_text().map(str::to_string),
            _ => return,
        };
        match text {
            Some(t) if !t.is_empty() => {
                let chars = t.chars().count();
                self.clipboard.set(t, false);
                self.toast(format!("copied AI answer ({chars} chars)"));
            }
            _ => self.toast("no AI answer to copy yet"),
        }
    }

    /// `c` in a `Pane::Ai`: open `claude --resume <session>` interactively (a split
    /// below) so you can carry the conversation further — and flip this pane into
    /// a live transcript mirror of that session.
    pub fn continue_active_ai(&mut self) {
        let Some(cur) = self.active else { return };
        let sid = match self.panes.get(cur) {
            Some(Pane::Ai(a))
                if matches!(
                    a.state,
                    crate::ai::AiState::Asking | crate::ai::AiState::Streaming(_)
                ) =>
            {
                self.toast("wait for the answer first");
                return;
            }
            Some(Pane::Ai(a)) => a.session_id.clone(),
            _ => return,
        };
        // Flip the source pane to a live mirror (unless it already is one).
        if let Some(path) = crate::ai::transcript::session_path(&self.workspace, &sid)
            && let Some(Pane::Ai(a)) = self.panes.get_mut(cur)
            && !a.is_live()
        {
            let turns = crate::ai::transcript::read(&path);
            let last_len = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0);
            a.state = crate::ai::AiState::Live {
                path,
                last_len,
                turns,
            };
            a.scroll = usize::MAX;
        }
        self.open_pty(crate::pty_pane::BinaryProfile::claude_code_resume(
            self.workspace.clone(),
            sid,
        ));
    }

    /// `ai.session_picker` — pick from past Claude sessions in this
    /// workspace (`~/.claude/projects/<dashed-cwd>/*.jsonl`, newest
    /// first). Accept opens a live mirror — read-only follow. Useful
    /// for revisiting prior conversations without spinning up a new
    /// pty.
    pub fn open_ai_session_picker(&mut self) {
        // #25 v2 — try the background prefetch cache first; fall
        // back to sync if the worker hasn't landed yet or the
        // cache was consumed.
        let sessions = self
            .sessions_prefetch
            .lock()
            .ok()
            .and_then(|mut g| g.take())
            .unwrap_or_else(|| crate::ai::transcript::list_sessions(&self.workspace));
        if sessions.is_empty() {
            self.toast("no Claude sessions found for this workspace");
            return;
        }
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs() as i64)
            .unwrap_or(0);
        let items: Vec<crate::picker::PickerItem> = sessions
            .into_iter()
            .map(|s| {
                let age = crate::ui::git_graph_view::humanize_age(now.saturating_sub(s.mtime));
                let preview = if s.preview.is_empty() {
                    "(no user message)".to_string()
                } else {
                    s.preview
                };
                let short_id: String = s.session_id.chars().take(8).collect();
                crate::picker::PickerItem::new(s.session_id, format!("{short_id}  {preview}"), age)
            })
            .collect();
        self.open_picker(crate::picker::Picker::new(
            crate::picker::PickerKind::AiSessions,
            "Claude sessions",
            items,
        ));
    }

    /// Accept handler for `PickerKind::AiSessions` — open a live mirror
    /// for the chosen session id.
    pub fn open_ai_session_mirror(&mut self, session_id: &str) {
        let Some(path) = crate::ai::transcript::session_path(&self.workspace, session_id) else {
            self.toast("can't locate session transcript ($HOME unset?)");
            return;
        };
        // Focus an existing mirror if one is open.
        if let Some(i) = self
            .panes
            .iter()
            .position(|p| matches!(p, Pane::Ai(a) if a.is_live() && a.session_id == session_id))
        {
            self.reveal_pane(i);
            return;
        }
        let pane = Pane::Ai(crate::ai::AiPane::live(session_id.to_string(), path));
        match self.active {
            Some(cur) => {
                let new_id = self.split_leaf_with(cur, crate::layout::SplitDir::Horizontal, pane);
                self.active = Some(new_id);
            }
            None => {
                self.panes.push(pane);
                let id = self.panes.len() - 1;
                *self.layout_mut() = Layout::leaf(id);
                self.active = Some(id);
            }
        }
        self.focus = Focus::Pane;
    }

    /// Re-read any live transcript mirrors whose `.jsonl` has grown — incrementally:
    /// only the bytes past `last_len` are read and parsed (up to the last complete
    /// line) and their turns appended. A shrunk file (rotation / rewrite) triggers a
    /// full re-read.
    pub(super) fn refresh_live_ai_panes(&mut self) {
        use std::io::{Read, Seek, SeekFrom};
        for pane in &mut self.panes {
            let Pane::Ai(a) = pane else { continue };
            let crate::ai::AiState::Live {
                path,
                last_len,
                turns,
            } = &mut a.state
            else {
                continue;
            };
            let len = std::fs::metadata(&*path).map(|m| m.len()).unwrap_or(0);
            if len < *last_len {
                // file shrank / rotated — re-read from scratch.
                *turns = crate::ai::transcript::read(path);
                *last_len = std::fs::metadata(&*path).map(|m| m.len()).unwrap_or(0);
                continue;
            }
            if len == *last_len {
                continue;
            }
            // Append-only growth: read just the new tail, parse complete lines.
            let mut chunk = String::new();
            let ok = std::fs::File::open(&*path)
                .and_then(|mut f| {
                    f.seek(SeekFrom::Start(*last_len))?;
                    f.read_to_string(&mut chunk)
                })
                .is_ok();
            if !ok {
                continue;
            }
            let Some(cut) = chunk.rfind('\n').map(|i| i + 1) else {
                continue; // a partial line is still being written — wait for the rest
            };
            turns.extend(crate::ai::transcript::parse(&chunk[..cut]));
            *last_len += cut as u64;
        }
    }

    /// `ai.explain` / `ai.fix` / `ai.refactor` / `ai.write_tests` — feed the active
    /// editor's selection (or the whole buffer) + a task prompt to `claude -p`.
    /// For `fix`/`refactor` the source range is remembered as the answer pane's
    /// [`ApplyTarget`](crate::ai::ApplyTarget) so `a` can apply the suggested code.
    pub fn ai_action(&mut self, what: &str) {
        let (code, lang, target) = match self.active.and_then(|i| self.panes.get(i)) {
            Some(Pane::Editor(b)) => {
                let sel = b.editor.selected_text();
                let (code, range) = if sel.trim().is_empty() {
                    let t = b.editor.text();
                    (t.to_string(), (0usize, t.len()))
                } else {
                    let r = b.editor.selection().unwrap_or((0, 0));
                    (sel, r)
                };
                let target = if matches!(what, "fix" | "refactor") {
                    b.path.clone().map(|path| crate::ai::ApplyTarget {
                        path,
                        start: range.0.min(range.1),
                        end: range.0.max(range.1),
                    })
                } else {
                    None
                };
                (code, b.language_ext.clone().unwrap_or_default(), target)
            }
            // Re-fire from an existing AI pane.
            Some(Pane::Ai(_)) => {
                if let Some(cur) = self.active {
                    self.reask_ai(cur);
                }
                return;
            }
            _ => {
                self.toast("AI actions need an editor (select code, or use the whole file)");
                return;
            }
        };
        if code.trim().is_empty() {
            self.toast("nothing to send");
            return;
        }
        let title = format!("AI: {}", what.replace('_', " "));
        self.ask_ai(title, crate::ai::action_prompt(what, &code, &lang));
        if target.is_some()
            && let Some(Pane::Ai(a)) = self.active.and_then(|i| self.panes.get_mut(i))
        {
            a.target = target;
        }
    }

    /// `a` in a Done `Pane::Ai`: first press *stages* the first fenced code block
    /// from the answer against the range the AI was asked about — building a diff
    /// preview the pane renders. A second `a` applies it (a `ReplaceRange`, left
    /// dirty: review, undo to revert). `r` (re-ask) discards a staged suggestion.
    /// No-op without a recorded target / a code block in the answer.
    pub fn apply_ai_suggestion(&mut self) {
        let Some(cur) = self.active else { return };
        // If a suggestion is already staged, this press applies it.
        if let Some(Pane::Ai(a)) = self.panes.get_mut(cur)
            && let Some(p) = a.pending_apply.take()
        {
            self.do_apply_suggestion(p.target, p.code);
            return;
        }
        // Otherwise stage it: parse target + code, diff against the live range.
        let parsed: Result<(crate::ai::ApplyTarget, String), &'static str> =
            match self.panes.get(cur) {
                Some(Pane::Ai(a)) => match (&a.target, &a.state) {
                    (None, _) => Err("nothing to apply here (use AI `fix`/`refactor` on a buffer)"),
                    (Some(_), crate::ai::AiState::Asking | crate::ai::AiState::Streaming(_)) => {
                        Err("wait for the answer first")
                    }
                    (Some(t), crate::ai::AiState::Done(text)) => {
                        match crate::ai::first_code_block(text) {
                            Some(code) => Ok((t.clone(), code)),
                            None => Err("no code block in the answer to apply"),
                        }
                    }
                    (Some(_), _) => Err("nothing to apply (the run didn't finish ok)"),
                },
                _ => return,
            };
        let (target, code) = match parsed {
            Ok(v) => v,
            Err(msg) => {
                self.toast(msg);
                return;
            }
        };
        // The current text of the target range (from the open editor, or disk).
        let old = self
            .panes
            .iter()
            .find_map(|p| match p {
                Pane::Editor(b) if b.is_at(&target.path) => Some(b.editor.text().to_string()),
                _ => None,
            })
            .or_else(|| std::fs::read_to_string(&target.path).ok())
            .unwrap_or_default();
        let old_range = {
            let s = target.start.min(old.len());
            let e = target.end.min(old.len()).max(s);
            old[s..e].to_string()
        };
        if old_range == code {
            self.toast("the suggestion matches what's already there");
            return;
        }
        let diff = crate::ai::line_diff(&old_range, &code);
        if let Some(Pane::Ai(a)) = self.panes.get_mut(cur) {
            a.pending_apply = Some(crate::ai::PendingApply { target, code, diff });
            a.scroll = usize::MAX; // show the preview at the bottom
        }
        self.toast("review the diff below — press a again to apply (r re-asks)");
    }

    /// Actually splice the AI suggestion's `code` over `target` in the editor
    /// (opening the file if needed), left dirty.
    fn do_apply_suggestion(&mut self, target: crate::ai::ApplyTarget, code: String) {
        if !self
            .panes
            .iter()
            .any(|p| matches!(p, Pane::Editor(b) if b.is_at(&target.path)))
        {
            self.open_path(&target.path);
        }
        let Some(idx) = self
            .panes
            .iter()
            .position(|p| matches!(p, Pane::Editor(b) if b.is_at(&target.path)))
        else {
            self.toast("couldn't open the source file");
            return;
        };
        let clip = &mut self.clipboard;
        if let Some(Pane::Editor(b)) = self.panes.get_mut(idx) {
            let len = b.editor.text().len();
            let start = target.start.min(len);
            let end = target.end.min(len).max(start);
            b.apply_edit_ops(
                vec![crate::edit_op::EditOp::ReplaceRange {
                    start,
                    end,
                    text: code,
                }],
                clip,
                0,
            );
        }
        if let Some(Pane::Editor(b)) = self.panes.get(idx)
            && let Some(p) = b.path.clone()
        {
            let t = b.editor.text().to_string();
            self.lsp.did_change(&p, &t);
        }
        self.reveal_pane(idx);
        self.toast("applied — review it; undo to revert");
    }

    /// `http.ai_debug` (`.` in a request pane) — hand the request + its response
    /// (or transport error) to `claude -p` and ask why it's failing / how to fix.
    /// Opens a prompt asking what the user wants to know about
    /// the active Request pane's request + response. On Enter,
    /// calls `ai_ask_about_request_with_question`. Used by the
    /// clickable AI section header in the Request pane.
    pub fn ai_ask_about_request_prompt(&mut self) {
        let has_request = matches!(
            self.active.and_then(|i| self.panes.get(i)),
            Some(Pane::Request(_))
        );
        if !has_request {
            self.toast("open a request pane first (http.send)");
            return;
        }
        self.prompt = Some(crate::prompt::Prompt::new(
            crate::prompt::PromptKind::AiAskAboutRequest,
            "Ask Claude about this request/response:".to_string(),
        ));
    }

    /// Accept handler for `PromptKind::AiAskAboutRequest`. Builds
    /// an AI prompt with the user's question + the active
    /// request/response context and dispatches to `ask_ai`.
    pub fn ai_ask_about_request_with_question(&mut self, question: &str) {
        use crate::request_pane::RunState;
        let question = question.trim();
        if question.is_empty() {
            self.toast("ai: question can't be empty");
            return;
        }
        let context = match self.active.and_then(|i| self.panes.get(i)) {
            Some(Pane::Request(rp)) => {
                let req = &rp.request;
                let mut req_text = format!("{} {}\n", req.method, req.url);
                for (k, v) in &req.headers {
                    req_text.push_str(&format!("{k}: {v}\n"));
                }
                if let Some(b) = &req.body {
                    req_text.push_str(&format!("\n{b}\n"));
                }
                let resp_text = match &rp.state {
                    RunState::Sending => "(still in flight — wait for it)".to_string(),
                    RunState::Streaming(r) => {
                        format!("(streaming · {} bytes so far)\n{}", r.body.len(), r.body)
                    }
                    RunState::Failed(e) => format!("transport error: {e}"),
                    RunState::Done(r) => {
                        let mut s = format!("{} {}\n", r.status, r.status_text);
                        for (k, v) in &r.headers {
                            s.push_str(&format!("{k}: {v}\n"));
                        }
                        let body: String = r.body.chars().take(4000).collect();
                        s.push_str(&format!("\n{body}\n"));
                        s
                    }
                };
                if matches!(rp.state, RunState::Sending) {
                    self.toast("wait for the response first");
                    return;
                }
                format!(
                    "{question}\n\n## Request\n```http\n{req_text}```\n\n## Response\n```\n{resp_text}```"
                )
            }
            _ => {
                self.toast("open a request pane first (http.send)");
                return;
            }
        };
        self.ask_ai("AI: ask about request", context);
    }

    pub fn ai_debug_request(&mut self) {
        use crate::request_pane::RunState;
        let prompt = match self.active.and_then(|i| self.panes.get(i)) {
            Some(Pane::Request(rp)) => {
                let req = &rp.request;
                let mut req_text = format!("{} {}\n", req.method, req.url);
                for (k, v) in &req.headers {
                    req_text.push_str(&format!("{k}: {v}\n"));
                }
                if let Some(b) = &req.body {
                    req_text.push_str(&format!("\n{b}\n"));
                }
                let resp_text = match &rp.state {
                    RunState::Sending => "(still in flight — wait for it)".to_string(),
                    RunState::Streaming(r) => {
                        format!("(streaming · {} bytes so far)\n{}", r.body.len(), r.body)
                    }
                    RunState::Failed(e) => format!("transport error: {e}"),
                    RunState::Done(r) => {
                        let mut s = format!("{} {}\n", r.status, r.status_text);
                        for (k, v) in &r.headers {
                            s.push_str(&format!("{k}: {v}\n"));
                        }
                        let body: String = r.body.chars().take(4000).collect();
                        s.push_str(&format!("\n{body}\n"));
                        s
                    }
                };
                if matches!(rp.state, RunState::Sending) {
                    self.toast("wait for the response first");
                    return;
                }
                format!(
                    "This HTTP request isn't behaving. What's likely wrong and how do I fix it? \
                     Be concise.\n\n## Request\n```http\n{req_text}```\n\n## Response\n```\n{resp_text}```"
                )
            }
            _ => {
                self.toast("open a request pane first (http.send)");
                return;
            }
        };
        self.ask_ai("AI: debug request", prompt);
    }

    /// Re-fire the active `Pane::Ai`'s prompt (its `r` key).
    pub fn resend_active_ai(&mut self) {
        if let Some(cur) = self
            .active
            .filter(|&i| matches!(self.panes.get(i), Some(Pane::Ai(_))))
        {
            self.reask_ai(cur);
        }
    }

    /// `ai.ask` — accepted from the text-input prompt: a free-text question to `claude -p`.
    pub fn open_ai_ask_prompt(&mut self) {
        self.prompt = Some(crate::prompt::Prompt::new(
            crate::prompt::PromptKind::AiAsk,
            "Ask Claude",
        ));
    }

    /// Drain the streamed `claude -p` messages into their `Pane::Ai` (deltas
    /// accumulate; a final Done/Failed settles the pane). The commit-message job
    /// shares this channel — it ignores deltas and acts on the final text.
    pub(super) fn drain_ai_jobs(&mut self) {
        use crate::ai::{AiMsg, AiState};
        let Some((_, rx)) = &self.ai_chan else {
            return;
        };
        let msgs: Vec<AiJobMsg> = rx.try_iter().collect();
        let mut toasts: Vec<String> = Vec::new();
        for (job_id, msg) in msgs {
            // Token-usage report — accumulate the session tally + toast
            // this call's cost. Independent of which job kind it was.
            if let AiMsg::Usage {
                input_tokens,
                output_tokens,
            } = msg
            {
                self.ai_tokens_in = self.ai_tokens_in.saturating_add(input_tokens);
                self.ai_tokens_out = self.ai_tokens_out.saturating_add(output_tokens);
                let model = self.ai_model();
                let base = format!(
                    "AI: {} in · {} out",
                    fmt_tokens(input_tokens),
                    fmt_tokens(output_tokens)
                );
                toasts.push(
                    match estimate_ai_cost(model.as_deref(), input_tokens, output_tokens) {
                        Some(c) => format!("{base} (~${c:.4})"),
                        None => base,
                    },
                );
                continue;
            }
            // Tool-confirmation request — the agent worker is blocked
            // waiting for the user to approve a write. Open the prompt.
            if let AiMsg::ConfirmTool { summary } = &msg {
                self.pending_tool_confirm = Some(job_id);
                let mut p = crate::prompt::Prompt::new(
                    crate::prompt::PromptKind::AiToolConfirm,
                    format!("AI wants to {summary}"),
                );
                // Default to Deny — safety-first for arbitrary AI tool
                // invocation. User must explicitly Allow.
                p.cursor = 1;
                self.prompt = Some(p);
                continue;
            }
            // Job finished — drop its confirm channel.
            if matches!(msg, AiMsg::Done(_) | AiMsg::Failed(_)) {
                self.ai_confirm_senders.remove(&job_id);
            }
            // An "AI: rewrite HEAD's message" job? Route the final text to a
            // GitCommitAmend prompt (same shape as the GitCommit case below).
            if self.pending_amend_msg_job == Some(job_id) {
                let result = match msg {
                    AiMsg::Delta(_) => continue,
                    AiMsg::Usage { .. } | AiMsg::ConfirmTool { .. } => continue, // handled above
                    AiMsg::Done(text) => Ok(text),
                    AiMsg::Failed(e) => Err(e),
                };
                self.pending_amend_msg_job = None;
                match result {
                    Ok(text) => {
                        let summary = text
                            .lines()
                            .map(str::trim)
                            .find(|l| !l.is_empty())
                            .unwrap_or("")
                            .trim_matches('`')
                            .trim()
                            .to_string();
                        if summary.is_empty() {
                            toasts.push("AI returned an empty commit message".to_string());
                        } else {
                            self.prompt = Some(crate::prompt::Prompt::seeded(
                                crate::prompt::PromptKind::GitCommitAmend,
                                "Rewrite HEAD's message (AI draft — edit & Enter)",
                                summary,
                            ));
                        }
                    }
                    Err(e) => toasts.push(format!("AI recompose: {e}")),
                }
                continue;
            }
            // An "AI: suggest a branch name" job? Open a BranchName
            // prompt seeded with the reply.
            if self.pending_branch_name_job == Some(job_id) {
                let result = match msg {
                    AiMsg::Delta(_) => continue,
                    AiMsg::Usage { .. } | AiMsg::ConfirmTool { .. } => continue,
                    AiMsg::Done(text) => Ok(text),
                    AiMsg::Failed(e) => Err(e),
                };
                self.pending_branch_name_job = None;
                match result {
                    Ok(text) => {
                        let suggestion = strip_reply_wrappers(text.lines().next().unwrap_or(""));
                        if suggestion.is_empty() {
                            toasts.push("ai.write_branch_name: empty reply".to_string());
                        } else {
                            self.prompt = Some(crate::prompt::Prompt::seeded(
                                crate::prompt::PromptKind::BranchName,
                                "Branch name (Enter to create):".to_string(),
                                suggestion,
                            ));
                        }
                    }
                    Err(e) => toasts.push(format!("ai.write_branch_name: {e}")),
                }
                continue;
            }
            // An "AI: recompose branch commit messages" job?
            // Route to [recompose-suggestions] scratch.
            if self.pending_recompose_branch_job == Some(job_id) {
                let result = match msg {
                    AiMsg::Delta(_) => continue,
                    AiMsg::Usage { .. } | AiMsg::ConfirmTool { .. } => continue,
                    AiMsg::Done(text) => Ok(text),
                    AiMsg::Failed(e) => Err(e),
                };
                self.pending_recompose_branch_job = None;
                match result {
                    Ok(text) => {
                        let clean = text
                            .trim()
                            .trim_start_matches("```")
                            .trim_end_matches("```")
                            .trim()
                            .to_string();
                        let mut body = String::new();
                        body.push_str("# Recompose suggestions\n\n");
                        body.push_str(
                            "_Claude's drafts — review before applying. \
                             Apply via `git rebase -i <base>`, swapping \
                             `pick → reword` for each line, then paste in \
                             the new message when the editor opens._\n\n",
                        );
                        body.push_str("```\n");
                        body.push_str(&clean);
                        if !clean.ends_with('\n') {
                            body.push('\n');
                        }
                        body.push_str("```\n");
                        self.open_scratch_with_text("[recompose-suggestions]".to_string(), body);
                        toasts.push(
                            "ai.recompose_branch: ready → [recompose-suggestions]".to_string(),
                        );
                    }
                    Err(e) => toasts.push(format!("ai.recompose_branch: {e}")),
                }
                continue;
            }
            // An "AI: explain this diff" job? Route the final text
            // into a [diff-explanation] scratch buffer.
            if self.pending_explain_diff_job == Some(job_id) {
                let result = match msg {
                    AiMsg::Delta(_) => continue,
                    AiMsg::Usage { .. } | AiMsg::ConfirmTool { .. } => continue,
                    AiMsg::Done(text) => Ok(text),
                    AiMsg::Failed(e) => Err(e),
                };
                self.pending_explain_diff_job = None;
                match result {
                    Ok(text) => {
                        let clean = text
                            .trim()
                            .trim_start_matches("```markdown")
                            .trim_start_matches("```md")
                            .trim_start_matches("```")
                            .trim_end_matches("```")
                            .trim()
                            .to_string();
                        self.open_scratch_with_text("[diff-explanation]".to_string(), clean);
                        toasts.push("ai.explain_diff: ready → [diff-explanation]".to_string());
                    }
                    Err(e) => toasts.push(format!("ai.explain_diff: {e}")),
                }
                continue;
            }
            // An "AI: write me a PR description" job? Route the final
            // text into a [pr-description] scratch buffer.
            if self.pending_pr_desc_job == Some(job_id) {
                let result = match msg {
                    AiMsg::Delta(_) => continue,
                    AiMsg::Usage { .. } | AiMsg::ConfirmTool { .. } => continue,
                    AiMsg::Done(text) => Ok(text),
                    AiMsg::Failed(e) => Err(e),
                };
                self.pending_pr_desc_job = None;
                match result {
                    Ok(text) => {
                        let clean = text
                            .trim()
                            .trim_start_matches("```markdown")
                            .trim_start_matches("```md")
                            .trim_start_matches("```")
                            .trim_end_matches("```")
                            .trim()
                            .to_string();
                        self.open_scratch_with_text("[pr-description]".to_string(), clean);
                        toasts.push("ai.pr_desc: ready → [pr-description]".to_string());
                    }
                    Err(e) => toasts.push(format!("ai.pr_desc: {e}")),
                }
                continue;
            }
            // An "AI: write me a commit message" job? Route the final text to the
            // commit prompt; deltas are noise here.
            if self.pending_commit_msg_job == Some(job_id) {
                let result = match msg {
                    AiMsg::Delta(_) => continue,
                    AiMsg::Usage { .. } | AiMsg::ConfirmTool { .. } => continue, // handled above
                    AiMsg::Done(text) => Ok(text),
                    AiMsg::Failed(e) => Err(e),
                };
                self.pending_commit_msg_job = None;
                for pane in &mut self.panes {
                    if let Pane::GitStatus(g) = pane
                        && g.ai_msg_job == Some(job_id)
                    {
                        g.ai_msg_job = None;
                    }
                }
                // Inline-textarea path — fill the GitGraph pane's
                // WIP commit textarea instead of opening the modal.
                let wip_target = self
                    .pending_wip_commit_msg_pane
                    .take_if(|(jid, _)| *jid == job_id);
                if let Some((_, pane_id)) = wip_target {
                    match result {
                        Ok(text) => {
                            let clean = text
                                .trim()
                                .trim_start_matches("```")
                                .trim_end_matches("```")
                                .trim()
                                .to_string();
                            if let Some(Pane::GitGraph(g)) = self.panes.get_mut(pane_id) {
                                g.wip_commit.ai_streaming = false;
                                if clean.is_empty() {
                                    toasts.push("AI returned an empty commit message".to_string());
                                } else {
                                    g.wip_commit.set_text(clean);
                                    g.wip_commit.focused = true;
                                }
                            }
                        }
                        Err(e) => {
                            if let Some(Pane::GitGraph(g)) = self.panes.get_mut(pane_id) {
                                g.wip_commit.ai_streaming = false;
                            }
                            toasts.push(format!("AI commit message: {e}"));
                        }
                    }
                    continue;
                }
                match result {
                    Ok(text) => {
                        let summary = text
                            .lines()
                            .map(str::trim)
                            .find(|l| !l.is_empty())
                            .unwrap_or("")
                            .trim_matches('`')
                            .trim()
                            .to_string();
                        if summary.is_empty() {
                            toasts.push("AI returned an empty commit message".to_string());
                        } else {
                            self.prompt = Some(crate::prompt::Prompt::seeded(
                                crate::prompt::PromptKind::GitCommit,
                                "Commit message (AI draft — edit & Enter)",
                                summary,
                            ));
                        }
                    }
                    Err(e) => toasts.push(format!("AI commit message: {e}")),
                }
                continue;
            }
            let Some(Pane::Ai(a)) = self.panes.iter_mut().find(|p| {
                matches!(p, Pane::Ai(a)
                    if a.job_id == job_id
                    && matches!(a.state, AiState::Asking | AiState::Streaming(_)))
            }) else {
                continue;
            };
            match msg {
                AiMsg::Delta(s) => match &mut a.state {
                    AiState::Streaming(buf) => buf.push_str(&s),
                    _ => a.state = AiState::Streaming(s),
                },
                AiMsg::Done(text) => {
                    toasts.push(format!("{} — done", a.title));
                    a.state = AiState::Done(text);
                }
                AiMsg::Failed(e) => {
                    toasts.push(format!("AI: {e}"));
                    a.state = AiState::Failed(e);
                }
                AiMsg::Usage { .. } | AiMsg::ConfirmTool { .. } => {} // handled at the top
            }
        }
        for t in toasts {
            self.toast(t);
        }
    }

    /// `C` in the status pane — ask `claude -p` to write a commit message from the
    /// staged diff; when it lands, the commit prompt opens pre-seeded with the
    /// first line (`drain_ai_jobs` routes it via `pending_commit_msg_job`).
    ///
    /// When the active pane is a `Pane::GitGraph` with its WIP detail
    /// visible, the result fills that pane's inline textarea instead
    /// of opening the modal prompt. The textarea's `ai_streaming`
    /// flag is set so the buttons row shows the "AI writing…" state.
    pub fn request_ai_commit_message(&mut self) {
        if self.git.snapshot().staged == 0 {
            self.toast("nothing staged — stage some changes first");
            return;
        }
        let diff = crate::git::stage::staged_diff(self.active_repo_path());
        if diff.trim().is_empty() {
            self.toast("no staged diff to summarise");
            return;
        }
        // Keep the prompt from getting silly-long on huge diffs.
        let diff = if diff.len() > 24_000 {
            format!(
                "{}\n…(diff truncated)…",
                truncate_at_char_boundary(&diff, 24_000)
            )
        } else {
            diff
        };
        let prompt = format!(
            "Write a git commit message for the staged changes below. \
             First line: imperative mood, ≤72 chars, no trailing period. \
             Then a blank line and a short body ONLY if it adds something. \
             Output ONLY the commit message — no preamble, no code fences.\n\n\
             ```diff\n{diff}\n```"
        );
        let (job_id, _sid, _cancel) = self.spawn_ai_job(prompt);
        self.pending_commit_msg_job = Some(job_id);
        // Route the result to a GitGraph WIP textarea when one is
        // currently active — otherwise fall through to the existing
        // modal prompt flow.
        let active_id = self.active;
        if let Some(id) = active_id
            && let Some(Pane::GitGraph(g)) = self.panes.get_mut(id)
            && g.is_wip_selected()
        {
            g.wip_commit.ai_streaming = true;
            self.pending_wip_commit_msg_pane = Some((job_id, id));
        }
        if let Some(Pane::GitStatus(g)) = self.active.and_then(|i| self.panes.get_mut(i)) {
            g.ai_msg_job = Some(job_id);
        }
        self.toast("asking Claude for a commit message…");
    }

    /// `:ai.write_branch_name` — open a prompt for a NL
    /// description of what the branch is for; Claude returns a
    /// kebab-case branch name suggestion (e.g.
    /// "add Apple Pay support" → `feat/apple-pay-support`). The
    /// suggestion is seeded into a `BranchName` prompt where the
    /// user accepts or edits.
    pub fn request_ai_write_branch_name(&mut self) {
        if !self.ai_api_key_ready("ai.write_branch_name") {
            return;
        }
        // 2026-06-21 power-user-ai SEV-3: unconditional
        // `self.prompt = Some(...)` clobbered an open
        // `AiToolConfirm` prompt, leaving an agent worker
        // silently wedged with no UI path to deny it. Refuse to
        // open if a confirm is up; user must answer that first.
        if matches!(
            self.prompt.as_ref().map(|p| p.kind),
            Some(crate::prompt::PromptKind::AiToolConfirm)
        ) {
            self.toast("ai.write_branch_name: resolve the tool-confirm prompt first");
            return;
        }
        self.prompt = Some(crate::prompt::Prompt::new(
            crate::prompt::PromptKind::AiBranchNameDescription,
            "describe the branch (NL → branch name):".to_string(),
        ));
    }

    /// Accept handler for `AiBranchNameDescription` — spawns the
    /// Claude job.
    pub fn ai_write_branch_name_accept(&mut self, description: String) {
        if description.trim().is_empty() {
            self.toast("ai.write_branch_name: empty description");
            return;
        }
        // 2026-06-21 power-user-ai SEV-2 no-in-flight-guard: a rapid
        // double-fire silently dropped the first reply (the job_id
        // got overwritten) while still billing tokens.
        if self.pending_branch_name_job.is_some() {
            self.toast("ai.write_branch_name: already in flight");
            return;
        }
        let prompt = format!(
            "Suggest ONE git branch name for the following work. \
             Rules:\n\
             - Format: `<type>/<kebab-case-slug>` where type is one of \
             feat, fix, chore, docs, test, refactor.\n\
             - Slug ≤ 30 chars, lowercase, hyphens between words.\n\
             - No trailing punctuation.\n\
             - Output ONLY the branch name on a single line — no \
             explanation, no quotes, no fences.\n\n\
             Description:\n{description}\n\n\
             Branch name:"
        );
        let (job_id, _sid, _cancel) = self.spawn_ai_job(prompt);
        self.pending_branch_name_job = Some(job_id);
        self.toast("ai.write_branch_name: asking Claude…");
    }

    /// `:ai.recompose_branch` — draft rewritten commit messages
    /// for every commit on the current branch (vs origin/main /
    /// main / master). Output lands in a `[recompose-suggestions]`
    /// scratch with the original SHA + old message + suggested new
    /// message per commit, PLUS a copy-pasteable
    /// `git rebase -i` plan at the end. The user applies the
    /// rebase themselves — we deliberately don't mutate history
    /// from inside mnml since one wrong tweak loses commits.
    pub fn request_ai_recompose_branch(&mut self) {
        if !self.ai_api_key_ready("ai.recompose_branch") {
            return;
        }
        if self.pending_recompose_branch_job.is_some() {
            self.toast("ai.recompose_branch: already in flight");
            return;
        }
        // 2026-06-21 power-user-ai SEV-3 base-ref-chain-misses-trunk-develop:
        // also try `trunk` and `develop` for repos that use those.
        let candidates = [
            "origin/main",
            "origin/master",
            "origin/trunk",
            "origin/develop",
            "main",
            "master",
            "trunk",
            "develop",
        ];
        let base = candidates.iter().find(|r| {
            std::process::Command::new("git")
                .args(["rev-parse", "--verify", "--quiet", r])
                .current_dir(self.active_repo_path())
                .output()
                .map(|o| o.status.success())
                .unwrap_or(false)
        });
        let Some(base) = base else {
            self.toast("ai.recompose_branch: no main/master ref found");
            return;
        };
        let mb_out = std::process::Command::new("git")
            .args(["merge-base", "HEAD", base])
            .current_dir(self.active_repo_path())
            .output();
        let merge_base = match mb_out {
            Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
            _ => {
                self.toast(format!(
                    "ai.recompose_branch: merge-base HEAD..{base} failed"
                ));
                return;
            }
        };
        // Format: `<sha>\x00<subject>\x00<body>\x00\x00` per commit.
        // Using NUL separators so newlines in bodies don't confuse parsing.
        let log_out = std::process::Command::new("git")
            .args([
                "log",
                "--reverse",
                "--format=%H%x00%s%x00%b%x00%x00",
                &format!("{merge_base}..HEAD"),
            ])
            .current_dir(self.active_repo_path())
            .output();
        let raw = match log_out {
            Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).to_string(),
            _ => {
                self.toast("ai.recompose_branch: git log failed");
                return;
            }
        };
        if raw.trim().is_empty() {
            self.toast(format!(
                "ai.recompose_branch: HEAD has no commits past {base}"
            ));
            return;
        }
        let prompt = format!(
            "Rewrite each commit message below to be cleaner. For each:\n\
             - First line: imperative mood, ≤72 chars, no trailing period.\n\
             - Body (if useful): explain WHY, not just WHAT. Reference \
             tickets/PRs if mentioned in the original.\n\
             - Preserve EVERY trailer line at the end of the body verbatim. \
             A trailer is any `<Key>: <value>` line at the message tail. \
             Common ones to NOT strip: `Co-Authored-By:`, `Claude-Session:`, \
             `Signed-off-by:`, `Reviewed-by:`, `Fixes:`, `Closes:`, ticket-key \
             footers (e.g. `TE-1234`), and any `🤖 Generated with …` markers.\n\
             - Drop redundant boilerplate (\"fix typo\" → maybe drop entirely \
             if trivial, but still emit something so the SHA mapping stays \
             1:1).\n\n\
             Output format (machine-parseable):\n\n\
             ```\n\
             <sha>\n\
             <new subject>\n\
             <blank line>\n\
             <new body or nothing>\n\
             ===\n\
             ```\n\
             (the `===` line separates commits. Repeat for every commit.)\n\n\
             Below are the commits, NUL-separated as \
             <sha>\\x00<subject>\\x00<body>\\x00\\x00:\n\n{raw}"
        );
        let (job_id, _sid, _cancel) = self.spawn_ai_job(prompt);
        self.pending_recompose_branch_job = Some(job_id);
        self.toast(format!("ai.recompose_branch: asking Claude (vs {base})…"));
    }

    /// `:ai.explain_diff` — ask Claude to walk through the staged
    /// diff (or the working diff if nothing is staged) and explain
    /// what it changes + why. Output lands in a `[diff-explanation]`
    /// scratch. Useful before pushing a chunk you want a second
    /// reading of.
    pub fn request_ai_explain_diff(&mut self) {
        if !self.ai_api_key_ready("ai.explain_diff") {
            return;
        }
        if self.pending_explain_diff_job.is_some() {
            self.toast("ai.explain_diff: already in flight");
            return;
        }
        // Prefer staged diff; fall back to working-tree diff.
        let staged = crate::git::stage::staged_diff(self.active_repo_path());
        let (diff, label) = if !staged.trim().is_empty() {
            (staged, "staged")
        } else {
            let out = std::process::Command::new("git")
                .args(["diff"])
                .current_dir(self.active_repo_path())
                .output();
            let working = out
                .ok()
                .map(|o| String::from_utf8_lossy(&o.stdout).to_string())
                .unwrap_or_default();
            if working.trim().is_empty() {
                self.toast("ai.explain_diff: no diff (nothing staged or modified)");
                return;
            }
            (working, "working tree")
        };
        let diff = if diff.len() > 32_000 {
            format!(
                "{}\n…(diff truncated)…",
                truncate_at_char_boundary(&diff, 32_000)
            )
        } else {
            diff
        };
        let prompt = format!(
            "Walk through the following git diff and explain what it changes \
             and why. Structure:\n\n## Summary\n<1-3 sentence overview>\n\n\
             ## Per-file walkthrough\n<for each file: what changed + why \
             you think the author did it>\n\n## Risks / questions\n<anything \
             you'd flag in a code review>\n\nNo preamble, no code fences \
             around the whole output. Be specific — quote actual lines from \
             the diff to ground each claim.\n\n```diff\n{diff}\n```"
        );
        let (job_id, _sid, _cancel) = self.spawn_ai_job(prompt);
        self.pending_explain_diff_job = Some(job_id);
        self.toast(format!("ai.explain_diff: asking Claude ({label})…"));
    }

    /// `:ai.write_pr_description` — diff the current branch against
    /// its merge-base with origin/main (falling back to main /
    /// master / origin/master), collect the commits on this branch,
    /// ask Claude to draft a PR description, and drop the result
    /// into a `[pr-description]` scratch. Useful for the "I've got
    /// 5 commits, give me something I can paste into the PR body"
    /// workflow.
    pub fn request_ai_pr_description(&mut self) {
        if !self.ai_api_key_ready("ai.pr_desc") {
            return;
        }
        if self.pending_pr_desc_job.is_some() {
            self.toast("ai.pr_desc: already in flight");
            return;
        }
        // Resolve a base ref. Try origin/{main,master,trunk,develop}
        // then unqualified. Repos using trunk/develop don't fall
        // through anymore (SEV-3 base-ref-chain-misses-trunk-develop).
        let candidates = [
            "origin/main",
            "origin/master",
            "origin/trunk",
            "origin/develop",
            "main",
            "master",
            "trunk",
            "develop",
        ];
        let base_ref = candidates.iter().find(|r| {
            std::process::Command::new("git")
                .args(["rev-parse", "--verify", "--quiet", r])
                .current_dir(self.active_repo_path())
                .output()
                .map(|o| o.status.success())
                .unwrap_or(false)
        });
        let Some(base_ref) = base_ref else {
            self.toast("ai.pr_desc: no main/master ref found");
            return;
        };
        // Find merge-base so the diff covers only this branch's work,
        // not main's recent commits.
        let mb_out = std::process::Command::new("git")
            .args(["merge-base", "HEAD", base_ref])
            .current_dir(self.active_repo_path())
            .output();
        let merge_base = match mb_out {
            Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
            _ => {
                self.toast(format!("ai.pr_desc: merge-base HEAD..{base_ref} failed"));
                return;
            }
        };
        let diff = std::process::Command::new("git")
            .args(["diff", &format!("{merge_base}..HEAD")])
            .current_dir(self.active_repo_path())
            .output();
        let Ok(d) = diff else {
            self.toast("ai.pr_desc: git diff failed");
            return;
        };
        let diff_text = String::from_utf8_lossy(&d.stdout).to_string();
        if diff_text.trim().is_empty() {
            // 2026-06-21 power-user-ai SEV-3: clearer wording.
            // "Forgot to commit?" was misleading for mnml's
            // documented small-commits-to-main workflow (the user
            // IS on the base ref).
            self.toast(format!(
                "ai.pr_desc: HEAD is identical to {base_ref} — nothing to summarize"
            ));
            return;
        }
        // Commit list (subjects) on this branch.
        let log_out = std::process::Command::new("git")
            .args(["log", "--format=%h %s", &format!("{merge_base}..HEAD")])
            .current_dir(self.active_repo_path())
            .output();
        let commits = match log_out {
            Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).to_string(),
            _ => String::new(),
        };
        let diff = if diff_text.len() > 32_000 {
            format!("{}\n…(diff truncated)…", &diff_text[..32_000])
        } else {
            diff_text
        };
        let prompt = format!(
            "Write a GitHub Pull Request description for the changes below. \
             Structure: a 1-sentence summary line, then a `## Summary` section \
             with 2-4 bullet points covering what changed and why, then a \
             `## Test plan` section with a markdown checklist of TODOs for a \
             reviewer to verify. No preamble, no code fences around the whole \
             output, no '🤖 Generated by …' footer.\n\n\
             Commits on this branch:\n{commits}\n\
             Diff (vs {base_ref}):\n```diff\n{diff}\n```"
        );
        let (job_id, _sid, _cancel) = self.spawn_ai_job(prompt);
        self.pending_pr_desc_job = Some(job_id);
        self.toast(format!("ai.pr_desc: asking Claude (vs {base_ref})…"));
    }

    /// `git.codex_commit` — same shape as `request_ai_commit_message` but
    /// invokes the Codex CLI (`codex exec <prompt>`) instead of Claude.
    /// Useful when the user prefers OpenAI's model for commit messages.
    /// Routes the reply through the same `pending_commit_msg_job` channel,
    /// so the commit prompt opens pre-seeded just like the Claude flow.
    pub fn request_codex_commit_message(&mut self) {
        if self.git.snapshot().staged == 0 {
            self.toast("nothing staged — stage some changes first");
            return;
        }
        let diff = crate::git::stage::staged_diff(self.active_repo_path());
        if diff.trim().is_empty() {
            self.toast("no staged diff to summarise");
            return;
        }
        let diff = if diff.len() > 24_000 {
            format!(
                "{}\n…(diff truncated)…",
                truncate_at_char_boundary(&diff, 24_000)
            )
        } else {
            diff
        };
        let prompt = format!(
            "Write a git commit message for the staged changes below. \
             First line: imperative mood, ≤72 chars, no trailing period. \
             Then a blank line and a short body ONLY if it adds something. \
             Output ONLY the commit message — no preamble, no code fences.\n\n\
             ```diff\n{diff}\n```"
        );
        let job_id = self.spawn_codex_job(prompt);
        self.pending_commit_msg_job = Some(job_id);
        if let Some(Pane::GitStatus(g)) = self.active.and_then(|i| self.panes.get_mut(i)) {
            g.ai_msg_job = Some(job_id);
        }
        self.toast("asking Codex for a commit message…");
    }

    /// Mirror of [`Self::spawn_ai_job`] for `codex exec` — codex is
    /// stateless per call so no session id; we still use the
    /// `App.ai_chan` for delivery (the messages share `AiMsg` shape).
    fn spawn_codex_job(&mut self, prompt: String) -> u64 {
        let job_id = self.next_job_id;
        self.next_job_id += 1;
        let tx = self
            .ai_chan
            .get_or_insert_with(std::sync::mpsc::channel)
            .0
            .clone();
        let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let worker_cancel = cancel.clone();
        std::thread::spawn(move || {
            crate::ai::stream_codex_to_channel(&prompt, &worker_cancel, tx, job_id);
        });
        job_id
    }

    /// `git.ai_recompose` — ask Claude to rewrite HEAD's commit message based
    /// on its diff. The reply lands as a `PromptKind::GitCommitAmend` prompt;
    /// accept ⇒ `git commit --amend -m <new>`. Limited to HEAD for now —
    /// rewriting older commits would require interactive rebase machinery.
    pub fn request_ai_recompose_message(&mut self) {
        let diff = match crate::git::commit::show_head(self.active_repo_path()) {
            Ok(d) if d.trim().is_empty() => {
                self.toast("HEAD has no patch to summarise");
                return;
            }
            Ok(d) => d,
            Err(e) => {
                self.toast(format!("AI recompose: {e}"));
                return;
            }
        };
        let diff = if diff.len() > 24_000 {
            format!(
                "{}\n…(diff truncated)…",
                truncate_at_char_boundary(&diff, 24_000)
            )
        } else {
            diff
        };
        let existing = crate::git::commit::head_message(self.active_repo_path());
        let existing_block = if existing.is_empty() {
            String::new()
        } else {
            format!("Current message:\n```\n{existing}\n```\n\n")
        };
        let prompt = format!(
            "Rewrite this commit's message based on what actually changed. \
             First line: imperative mood, ≤72 chars, no trailing period. \
             Then a blank line and a short body ONLY if it adds something the \
             subject doesn't. Output ONLY the new message — no preamble, no \
             code fences.\n\n\
             {existing_block}\
             ```diff\n{diff}\n```"
        );
        let (job_id, _sid, _cancel) = self.spawn_ai_job(prompt);
        self.pending_amend_msg_job = Some(job_id);
        self.toast("asking Claude to rewrite HEAD's message…");
    }
}

/// Build a horizontal row of `n` equal-width columns from the
/// given leaves. Uses left-associative binary splits so the
/// resulting per-column width converges to `1/n` of the row:
///
///   n=1 → the single leaf
///   n=2 → HSplit{ratio=50, first, second}
///   n=3 → HSplit{ratio=33, first, HSplit{ratio=50, second, third}}
///   n=4 → HSplit{ratio=25, first, HSplit{ratio=33, second,
///                          HSplit{ratio=50, third, fourth}}}
///
/// Every leaf ends up with ~`100/n` % of the row's width.
fn build_equal_row(items: Vec<crate::layout::Layout>) -> crate::layout::Layout {
    use crate::layout::{Layout, SplitDir};
    match items.len() {
        0 => Layout::Empty,
        1 => items.into_iter().next().unwrap(),
        n => {
            let ratio = (100 / n as u16).max(1);
            let mut iter = items.into_iter();
            let first = iter.next().unwrap();
            let rest: Vec<Layout> = iter.collect();
            Layout::Split {
                dir: SplitDir::Horizontal,
                ratio,
                first: Box::new(first),
                second: Box::new(build_equal_row(rest)),
            }
        }
    }
}

/// Pick the argv mixr should launch with. See `App::open_mixr` for
/// the design rationale (Beatport-authed + favorites → one-click
/// play a chart; otherwise open on minibrowser).
///
/// Read heuristically — we don't parse the whole TOML/JSON, just
/// substring-check. Cheap and safe when the files are absent or
/// malformed (both branches return the fallback args).
/// True when Beatport is authed AND `favoriteGenres` in mixr's config
/// is non-empty — the precondition for `--play` to actually queue
/// something. Both files live under `~/.mixr/`; missing/malformed
/// treated as false (fall through to plain --dashboard).
pub(crate) fn mixr_beatport_authed() -> bool {
    let Some(home) = std::env::var_os("HOME").map(std::path::PathBuf::from) else {
        return false;
    };
    std::fs::read_to_string(home.join(".mixr").join("auth.json"))
        .map(|s| {
            // Match the presence AND non-empty non-null value of the token,
            // not just the key — mirrors the empty-list guard in
            // `mixr_has_favorite_genres` below. Skips the `--play` path
            // if mixr wrote `"access_token":""` or `"access_token":null`
            // after a logout that left the key in place.
            let compact: String = s.chars().filter(|c| !c.is_whitespace()).collect();
            compact.contains("\"access_token\":\"")
                && !compact.contains("\"access_token\":\"\"")
                && !compact.contains("\"access_token\":null")
        })
        .unwrap_or(false)
}

pub(crate) fn mixr_has_favorite_genres() -> bool {
    let Some(home) = std::env::var_os("HOME").map(std::path::PathBuf::from) else {
        return false;
    };
    std::fs::read_to_string(home.join(".mixr").join("config.json"))
        .map(|s| {
            let compact: String = s.chars().filter(|c| !c.is_whitespace()).collect();
            compact.contains("\"favoriteGenres\":[") && !compact.contains("\"favoriteGenres\":[]")
        })
        .unwrap_or(false)
}

#[cfg(test)]
mod ai_tests {
    use super::*;

    #[test]
    fn ghost_word_boundary_takes_leading_ws_plus_one_word() {
        // Leading whitespace + first non-ws run.
        assert_eq!(ghost_word_boundary(" + b\n}"), 2); // " +"
        assert_eq!(ghost_word_boundary("foo bar"), 3); // "foo"
        // Crosses a newline when the suggestion starts with one.
        assert_eq!(ghost_word_boundary("\n    foo bar"), 8); // "\n    foo"
        // All whitespace ⇒ take everything.
        assert_eq!(ghost_word_boundary("   "), 3);
        // Empty ⇒ 0 (caller treats as "nothing to accept").
        assert_eq!(ghost_word_boundary(""), 0);
    }

    #[test]
    fn ghost_line_boundary_takes_through_first_newline() {
        // Through and including the first newline.
        assert_eq!(ghost_line_boundary("a + b\n}\n"), 6);
        // Single-line ⇒ the whole string.
        assert_eq!(ghost_line_boundary("a + b"), 5);
        assert_eq!(ghost_line_boundary(""), 0);
    }

    #[test]
    fn estimate_ai_cost_uses_per_model_rates() {
        // Sonnet: $3/M in, $15/M out → 1M in + 1M out = $18.
        let c = estimate_ai_cost(Some("claude-sonnet-4-6"), 1_000_000, 1_000_000).unwrap();
        assert!((c - 18.0).abs() < 1e-9, "got {c}");
        // Haiku is cheaper than Sonnet for the same tokens.
        let haiku = estimate_ai_cost(Some("claude-haiku-4-5"), 100_000, 50_000).unwrap();
        let sonnet = estimate_ai_cost(Some("claude-sonnet-4-6"), 100_000, 50_000).unwrap();
        assert!(haiku < sonnet);
        // None model ⇒ defaults to Opus pricing (recognized).
        assert!(estimate_ai_cost(None, 1000, 1000).is_some());
        // Unrecognized model ⇒ no estimate.
        assert_eq!(estimate_ai_cost(Some("some-other-llm"), 1000, 1000), None);
    }

    #[test]
    fn fmt_tokens_is_compact() {
        assert_eq!(fmt_tokens(840), "840");
        assert_eq!(fmt_tokens(2_100), "2.1k");
        assert_eq!(fmt_tokens(1_200_000), "1.2M");
    }
}