opencrabs 0.3.37

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

use super::events::{AppMode, TuiEvent};
use super::onboarding::{OnboardingStep, WELCOME_MESSAGE, WizardAction};
use super::*;
use crate::brain::provider::{ContentBlock, LLMRequest};
use crate::tui::provider_selector::{CUSTOM_INSTANCES_START, CUSTOM_PROVIDER_IDX};
use anyhow::Result;
use std::path::PathBuf;
use uuid::Uuid;

impl App {
    /// Detect existing API key for the currently selected provider in model selector.
    /// Delegates to `ProviderSelectorState::detect_existing_key()`.
    pub(crate) fn detect_model_selector_key_for_provider(&mut self) {
        tracing::debug!(
            "[detect_key] provider_idx={}, custom_names={:?}",
            self.ps.selected_provider,
            self.ps.custom_names,
        );
        self.ps.detect_existing_key();
    }

    /// Refresh the model-selector's per-provider input fields
    /// (`custom_name`, `base_url`, `custom_model`, `context_window`,
    /// `editing_custom_key`) to match whatever `self.ps.selected_provider`
    /// currently points at. Called from both navigation (Up/Down) and
    /// the post-save reposition; without the latter call the dialog
    /// kept showing the values the user just typed for a newly-saved
    /// provider while the cursor was already on a different row.
    pub(crate) fn reload_model_selector_custom_fields(&mut self) {
        let provider_idx = self.ps.selected_provider;
        if provider_idx == CUSTOM_PROVIDER_IDX {
            self.ps.custom_name.clear();
            self.ps.custom_model.clear();
            self.ps.base_url.clear();
            self.ps.context_window.clear();
            self.ps.api_key_input.clear();
            self.ps.editing_custom_key = None;
        } else if provider_idx >= CUSTOM_INSTANCES_START {
            let custom_idx = provider_idx - CUSTOM_INSTANCES_START;
            if let Some(name) = self.ps.custom_names.get(custom_idx).cloned()
                && let Ok(c) = crate::config::Config::load()
                && let Some(cfg) = c.providers.custom_by_name(&name)
            {
                self.ps.custom_name = name.clone();
                self.ps.base_url = cfg.base_url.clone().unwrap_or_default();
                self.ps.custom_model = cfg.default_model.clone().unwrap_or_default();
                self.ps.context_window = cfg
                    .context_window
                    .map(|cw| cw.to_string())
                    .unwrap_or_default();
                self.ps.editing_custom_key = Some(name);
            }
        } else {
            self.ps.custom_name.clear();
            self.ps.custom_model.clear();
            self.ps.base_url.clear();
            self.ps.context_window.clear();
            self.ps.editing_custom_key = None;
        }
    }

    /// Open the model selector dialog - load from config and fetch models
    pub(crate) async fn open_model_selector(&mut self) {
        tracing::debug!("[open_model_selector] Opening model selector");

        // Load config to get enabled provider
        let config = match crate::config::Config::load() {
            Ok(c) => c,
            Err(e) => {
                tracing::error!("Failed to load config for model selector: {}", e);
                self.push_system_message(format!(
                    "⚠️ Could not load config.toml: {}. Model selector unavailable.",
                    e
                ));
                return;
            }
        };

        // Cache existing custom provider names early (needed for index mapping)
        self.ps.custom_names = config
            .providers
            .custom
            .as_ref()
            .map(|m| m.keys().cloned().collect())
            .unwrap_or_default();

        // Try session's provider first, then fall back to config
        let session_provider = self
            .current_session
            .as_ref()
            .and_then(|s| s.provider_name.as_deref());

        // Resolve provider index + API key from session provider name.
        //
        // CRITICAL: custom entries win over built-in aliases. A user who
        // created a custom provider literally named "anthropic" or
        // "opencode" means their custom entry, not the built-in — the
        // config section `providers.custom.<name>` is the unambiguous
        // source of truth. Built-in alias resolution only runs when no
        // custom entry by that exact name exists. This prevents
        // collisions like the 2026-04-18 "opencode" case where a custom
        // provider silently displayed as opencode-cli in /models.
        let from_session: Option<(usize, Option<String>)> = session_provider.map(|name| {
            use crate::utils::providers;

            // 1. Custom provider by exact name (takes precedence)
            if let Some(c) = config.providers.custom_by_name(name) {
                let api_key = c.api_key.clone();
                self.ps.base_url = c.base_url.clone().unwrap_or_default();
                self.ps.custom_model = c.default_model.clone().unwrap_or_default();
                self.ps.context_window = c
                    .context_window
                    .map(|cw| cw.to_string())
                    .unwrap_or_default();
                self.ps.custom_name = name.to_string();
                self.ps.editing_custom_key = Some(name.to_string());
                let idx = self
                    .ps
                    .custom_names
                    .iter()
                    .position(|n| n == name)
                    .map(|pos| CUSTOM_INSTANCES_START + pos)
                    .unwrap_or(CUSTOM_PROVIDER_IDX);
                return (idx, api_key);
            }

            // 2. Built-in provider id/alias
            if let Some(idx) = providers::tui_index_for_id(name) {
                let api_key =
                    providers::config_for(&config.providers, name).and_then(|p| p.api_key.clone());
                return (idx, api_key);
            }

            // 3. Unknown — default to new-custom flow
            (CUSTOM_PROVIDER_IDX, None)
        });

        // Determine which provider is enabled — iterate PROVIDERS using shared utility
        let (provider_idx, api_key) = if let Some(resolved) = from_session {
            tracing::debug!("[open_model_selector] From session: {:?}", session_provider);
            resolved
        } else {
            use crate::tui::onboarding::PROVIDERS;
            use crate::utils::providers as prov;

            let mut found: Option<(usize, Option<String>)> = None;

            // Check known providers by iterating PROVIDERS (skip custom sentinel)
            for (idx, info) in PROVIDERS.iter().enumerate().take(CUSTOM_PROVIDER_IDX) {
                if let Some(cfg) = prov::config_for(&config.providers, info.id)
                    && cfg.enabled
                {
                    // Special case: OpenAI with custom base_url may actually be another provider
                    if info.id == "openai"
                        && let Some(base_url) = &cfg.base_url
                    {
                        if base_url.contains("openrouter") {
                            if let Some(oi) = prov::tui_index_for_id("openrouter") {
                                found = Some((oi, cfg.api_key.clone()));
                            }
                        } else if base_url.contains("minimax") {
                            if let Some(mi) = prov::tui_index_for_id("minimax") {
                                found = Some((mi, cfg.api_key.clone()));
                            }
                        } else {
                            found = Some((CUSTOM_PROVIDER_IDX, cfg.api_key.clone())); // custom-like
                        }
                        break;
                    }
                    tracing::debug!("[open_model_selector] {} enabled", info.name);
                    found = Some((idx, cfg.api_key.clone()));
                    break;
                }
            }

            // Check custom providers if no known provider is enabled
            if found.is_none()
                && let Some((name, custom_cfg)) = config.providers.active_custom()
            {
                tracing::debug!("[open_model_selector] Custom provider '{}' enabled", name);
                if let Some(base_url) = &custom_cfg.base_url {
                    self.ps.base_url = base_url.clone();
                }
                self.ps.custom_model = custom_cfg.default_model.clone().unwrap_or_default();
                self.ps.context_window = custom_cfg
                    .context_window
                    .map(|cw| cw.to_string())
                    .unwrap_or_default();
                self.ps.custom_name = name.to_string();
                self.ps.editing_custom_key = Some(name.to_string());
                let idx = self
                    .ps
                    .custom_names
                    .iter()
                    .position(|n| n == name)
                    .map(|pos| CUSTOM_INSTANCES_START + pos)
                    .unwrap_or(CUSTOM_PROVIDER_IDX);
                found = Some((idx, custom_cfg.api_key.clone()));
            }

            found.unwrap_or_else(|| {
                tracing::debug!(
                    "[open_model_selector] No provider enabled, defaulting to Anthropic"
                );
                (0, None)
            })
        };

        tracing::debug!(
            "[open_model_selector] provider_idx={}, has_api_key={}",
            provider_idx,
            api_key.is_some()
        );

        self.ps.selected_provider = provider_idx;

        tracing::info!(
            "[open_model_selector] resolved: provider_idx={}, has_key={}, custom_names={:?}",
            provider_idx,
            api_key.is_some(),
            self.ps.custom_names,
        );

        // Load zhipu endpoint type from config
        self.ps.zhipu_endpoint_type = config
            .providers
            .zhipu
            .as_ref()
            .and_then(|p| p.endpoint_type.as_deref())
            .map(|et| if et == "coding" { 1 } else { 0 })
            .unwrap_or(0);

        // Track whether key exists — never load the actual key into UI state
        self.ps.has_existing_key = api_key.is_some();
        self.ps.api_key_input.clear();

        // Spawn async model fetch — dialog opens immediately, models arrive via event.
        // Custom providers default to PASTE mode: skip the auto-fetch and let
        // the user explicitly request the live /v1/models list by pressing
        // Enter on an empty model field. This avoids overwriting a typed
        // model with a stale list mid-input.
        let is_custom_provider = provider_idx >= CUSTOM_PROVIDER_IDX;
        if !is_custom_provider {
            let sender = self.event_sender();
            tokio::spawn(async move {
                let models = super::onboarding::fetch_provider_models(
                    provider_idx,
                    api_key.as_deref(),
                    None,
                    None,
                )
                .await;
                let _ = sender.send(TuiEvent::ModelSelectorModelsFetched(provider_idx, models));
            });
        }

        // Clear models until fetch completes (or stays empty for custom)
        self.ps.models.clear();

        // Reset view state
        self.ps.showing_providers = false;
        self.ps.model_filter.clear();
        self.ps.focused_field = 0;
        self.ps.selected_model = 0;

        self.mode = AppMode::ModelSelector;
    }

    /// Handle keys in model selector mode
    pub(crate) async fn handle_model_selector_key(
        &mut self,
        event: crossterm::event::KeyEvent,
    ) -> Result<()> {
        use super::events::keys;
        use super::onboarding::PROVIDERS;

        let is_zhipu = self.ps.provider_id() == "zhipu";
        let is_custom_field_3 =
            self.ps.focused_field == 3 && self.ps.selected_provider >= CUSTOM_PROVIDER_IDX;

        if keys::is_cancel(&event) {
            // Custom field 3 in LIST mode: Esc drops back to PASTE mode
            // (clears the fetched models so the renderer shows the
            // free-text input) instead of closing the whole dialog. The
            // user keeps their progress and can type/paste a model name.
            if is_custom_field_3 && !self.ps.models.is_empty() {
                self.ps.models.clear();
                self.ps.model_filter.clear();
                self.ps.selected_model = 0;
            } else {
                self.switch_mode(AppMode::Chat).await?;
            }
        } else if event.code == crossterm::event::KeyCode::Tab {
            // Tab cycles through fields:
            // - Normal providers: provider(0) -> api_key(1) -> model(2) -> provider(0)
            // - Zhipu: provider(0) -> endpoint_type(1) -> api_key(2) -> model(3) -> provider(0)
            // - Custom provider: provider(0) -> base_url(1) -> api_key(2) -> model(3) -> provider(0)
            let is_custom = self.ps.selected_provider >= CUSTOM_PROVIDER_IDX; // Custom provider index
            let is_oauth = self.ps.is_oauth();
            let is_codex_oauth = is_oauth && self.ps.provider_id() == "codex";
            let max_field = if is_custom {
                5
            } else if is_zhipu {
                4
            } else if is_codex_oauth && !self.ps.has_existing_key {
                3 // Codex OAuth not yet authenticated: provider(0) -> oauth(1) -> model(2)
            } else if is_oauth {
                2 // Other OAuth or already authenticated: provider(0) -> model(2), skip key field
            } else {
                3
            };
            self.ps.focused_field = (self.ps.focused_field + 1) % max_field;
            // If moving to provider, enable provider list; otherwise show model list
            self.ps.showing_providers = self.ps.focused_field == 0;
        } else if self.ps.focused_field == 0 {
            // Provider selection (focused)
            // Navigate using display order: static providers sorted alphabetically, then customs, then "+New"
            let num_customs = self.ps.custom_names.len();
            let mut static_indices: Vec<usize> = (0..CUSTOM_PROVIDER_IDX).collect();
            static_indices.sort_by_key(|&i| PROVIDERS[i].name.to_ascii_lowercase());
            let display_order: Vec<usize> = static_indices
                .into_iter()
                .chain(CUSTOM_INSTANCES_START..CUSTOM_INSTANCES_START + num_customs)
                .chain(std::iter::once(CUSTOM_PROVIDER_IDX))
                .collect();
            let provider_changed = match event.code {
                crossterm::event::KeyCode::Up => {
                    let pos = display_order
                        .iter()
                        .position(|&i| i == self.ps.selected_provider)
                        .unwrap_or(0);
                    if pos > 0 {
                        self.ps.selected_provider = display_order[pos - 1];
                    }
                    true
                }
                crossterm::event::KeyCode::Down => {
                    let pos = display_order
                        .iter()
                        .position(|&i| i == self.ps.selected_provider)
                        .unwrap_or(0);
                    if pos + 1 < display_order.len() {
                        self.ps.selected_provider = display_order[pos + 1];
                    }
                    true
                }
                _ => false,
            };

            // If provider changed, detect existing key and refresh models
            if provider_changed {
                tracing::debug!(
                    "[model_selector] provider navigated to idx={}, custom_names_len={}",
                    self.ps.selected_provider,
                    self.ps.custom_names.len(),
                );
                self.detect_model_selector_key_for_provider();

                // Clear/populate per-provider input fields. Both the
                // navigation path here and the post-save reposition
                // below now share this helper so the dialog never
                // shows the previous entry's fields on the wrong row.
                self.reload_model_selector_custom_fields();

                // Re-fetch models for the new provider — load API key from config
                let provider_idx = self.ps.selected_provider;
                let provider_id = self.ps.provider_id();
                let custom_idx = provider_idx
                    .checked_sub(CUSTOM_INSTANCES_START)
                    .and_then(|i| self.ps.custom_names.get(i).cloned());
                let api_key = crate::config::Config::load().ok().and_then(|c| {
                    if provider_id.is_empty() {
                        custom_idx.as_ref().and_then(|name| {
                            c.providers
                                .custom_by_name(name)
                                .and_then(|p| p.api_key.clone())
                        })
                    } else {
                        crate::utils::providers::config_for(&c.providers, provider_id)
                            .and_then(|p| p.api_key.clone())
                    }
                    .filter(|k| !k.is_empty())
                });
                let zhipu_et = if provider_id == "zhipu" {
                    Some(
                        if self.ps.zhipu_endpoint_type == 1 {
                            "coding"
                        } else {
                            "api"
                        }
                        .to_string(),
                    )
                } else {
                    None
                };
                // Custom providers default to PASTE mode: skip auto-fetch.
                // The user requests /v1/models by pressing Enter on field 3
                // with an empty input.
                let is_custom_dest = provider_idx >= CUSTOM_PROVIDER_IDX;
                if !is_custom_dest {
                    let sender = self.event_sender();
                    tokio::spawn(async move {
                        let models = super::onboarding::fetch_provider_models(
                            provider_idx,
                            api_key.as_deref(),
                            zhipu_et.as_deref(),
                            None,
                        )
                        .await;
                        let _ =
                            sender.send(TuiEvent::ModelSelectorModelsFetched(provider_idx, models));
                    });
                }
                self.ps.models.clear();
                self.ps.selected_model = 0;
                self.ps.model_filter.clear();
            }
        } else if self.ps.focused_field == 1 && is_zhipu {
            // z.ai GLM endpoint type toggle (field 1)
            match event.code {
                crossterm::event::KeyCode::Up | crossterm::event::KeyCode::Down => {
                    self.ps.zhipu_endpoint_type = 1 - self.ps.zhipu_endpoint_type;
                }
                _ => {}
            }
        } else if self.ps.focused_field == 1 && self.ps.selected_provider >= CUSTOM_PROVIDER_IDX {
            // Base URL input for Custom provider (field 1)
            match event.code {
                crossterm::event::KeyCode::Char(c) => {
                    self.ps.base_url.push(c);
                }
                crossterm::event::KeyCode::Backspace => {
                    self.ps.base_url.pop();
                }
                _ => {}
            }
        } else if (self.ps.focused_field == 1 && self.ps.selected_provider < 7 && !is_zhipu)
            || (self.ps.focused_field == 2 && is_zhipu)
            || (self.ps.focused_field == 2 && self.ps.selected_provider >= CUSTOM_PROVIDER_IDX)
        {
            // API key input (field 1 for non-Custom non-zhipu, field 2 for zhipu/Custom)
            match event.code {
                crossterm::event::KeyCode::Char(c) => {
                    // Clear sentinel on first keystroke so user replaces it
                    if self.ps.has_existing_key_sentinel() {
                        self.ps.api_key_input.clear();
                    }
                    self.ps.api_key_input.push(c);
                }
                crossterm::event::KeyCode::Backspace => {
                    // Clear sentinel entirely on backspace (can't partially edit masked key)
                    if self.ps.has_existing_key_sentinel() {
                        self.ps.api_key_input.clear();
                    } else {
                        self.ps.api_key_input.pop();
                    }
                }
                _ => {}
            }
        } else if self.ps.focused_field == 3 && self.ps.selected_provider >= CUSTOM_PROVIDER_IDX {
            // Custom provider field 3: model selection
            // If models were fetched, treat as list picker; otherwise free-text
            if self.ps.models.is_empty() {
                // No models fetched — free-text input
                match event.code {
                    crossterm::event::KeyCode::Char(c) => {
                        self.ps.custom_model.push(c);
                    }
                    crossterm::event::KeyCode::Backspace => {
                        self.ps.custom_model.pop();
                    }
                    _ => {}
                }
            } else {
                // Models fetched — list picker with filter + up/down
                match event.code {
                    crossterm::event::KeyCode::Char(c) => {
                        self.ps.model_filter.push(c);
                        self.ps.selected_model = 0;
                    }
                    crossterm::event::KeyCode::Backspace => {
                        self.ps.model_filter.pop();
                        let filter = self.ps.model_filter.to_lowercase();
                        let count = self
                            .ps
                            .models
                            .iter()
                            .filter(|m| m.to_lowercase().contains(&filter))
                            .count();
                        if self.ps.selected_model >= count && count > 0 {
                            self.ps.selected_model = count - 1;
                        }
                    }
                    crossterm::event::KeyCode::Esc => {
                        // Unreachable: the cancel branch at the top of
                        // `handle_model_selector_key` intercepts Esc.
                        // Kept as a no-op for clarity.
                        self.ps.model_filter.clear();
                        self.ps.selected_model = 0;
                    }
                    _ => {
                        let filter = self.ps.model_filter.to_lowercase();
                        let filtered: Vec<&String> = self
                            .ps
                            .models
                            .iter()
                            .filter(|m| m.to_lowercase().contains(&filter))
                            .collect();
                        if keys::is_up(&event) {
                            self.ps.selected_model = self.ps.selected_model.saturating_sub(1);
                        } else if keys::is_down(&event) && !filtered.is_empty() {
                            self.ps.selected_model =
                                (self.ps.selected_model + 1).min(filtered.len() - 1);
                        }
                    }
                }
            }
        } else if self.ps.focused_field == 4 && self.ps.selected_provider >= CUSTOM_PROVIDER_IDX {
            // Custom provider: name identifier input (field 4)
            match event.code {
                crossterm::event::KeyCode::Char(c) => {
                    self.ps.custom_name.push(c);
                    self.error_message = None;
                    self.error_message_shown_at = None;
                }
                crossterm::event::KeyCode::Backspace => {
                    self.ps.custom_name.pop();
                }
                _ => {}
            }
        } else if self.ps.focused_field == 5 && self.ps.selected_provider >= CUSTOM_PROVIDER_IDX {
            // Custom provider: context window input (field 5 — last before save)
            match event.code {
                crossterm::event::KeyCode::Char(c) if c.is_ascii_digit() => {
                    self.ps.context_window.push(c);
                }
                crossterm::event::KeyCode::Backspace => {
                    self.ps.context_window.pop();
                }
                _ => {}
            }
        } else if (self.ps.focused_field == 2
            && self.ps.selected_provider < CUSTOM_PROVIDER_IDX
            && !is_zhipu)
            || (self.ps.focused_field == 3 && is_zhipu)
        {
            // Non-custom: filter/search model list (field 2, or field 3 for zhipu)
            match event.code {
                crossterm::event::KeyCode::Char(c) => {
                    // Type to filter models
                    self.ps.model_filter.push(c);
                    self.ps.selected_model = 0;
                }
                crossterm::event::KeyCode::Backspace => {
                    self.ps.model_filter.pop();
                    // Keep selection valid after filter change
                    let filter = self.ps.model_filter.to_lowercase();
                    let count = if self.ps.models.is_empty() {
                        self.ps.current_provider().models.len()
                    } else {
                        self.ps
                            .models
                            .iter()
                            .filter(|m| m.to_lowercase().contains(&filter))
                            .count()
                    };
                    if self.ps.selected_model >= count && count > 0 {
                        self.ps.selected_model = count - 1;
                    }
                }
                crossterm::event::KeyCode::Esc => {
                    // Clear filter on Escape
                    self.ps.model_filter.clear();
                    self.ps.selected_model = 0;
                }
                _ => {
                    if keys::is_up(&event) {
                        self.ps.selected_model = self.ps.selected_model.saturating_sub(1);
                    } else if keys::is_down(&event) {
                        // Get filtered count
                        let filter = self.ps.model_filter.to_lowercase();
                        let max_models = if self.ps.models.is_empty() {
                            self.ps.current_provider().models.len()
                        } else {
                            self.ps
                                .models
                                .iter()
                                .filter(|m| m.to_lowercase().contains(&filter))
                                .count()
                        };
                        if max_models > 0 {
                            self.ps.selected_model =
                                (self.ps.selected_model + 1).min(max_models - 1);
                        }
                    }
                }
            }
        }

        // Enter to confirm - move to next field
        if keys::is_enter(&event) {
            let is_custom = self.ps.selected_provider >= CUSTOM_PROVIDER_IDX;

            tracing::debug!(
                "[model_selector] Enter pressed: field={}, provider_idx={}, is_custom={}, custom_name='{}', base_url='{}'",
                self.ps.focused_field,
                self.ps.selected_provider,
                is_custom,
                self.ps.custom_name,
                self.ps.base_url,
            );

            let is_oauth_provider = self.ps.is_oauth();

            if self.ps.focused_field == 0 {
                // On provider field - save config, DON'T close dialog.
                // Existing-custom indices (>= CUSTOM_INSTANCES_START) collapse
                // back onto the single "Custom" sentinel for persistence.
                let save_idx = self.ps.selected_provider.min(CUSTOM_PROVIDER_IDX);
                if let Err(e) = self
                    .save_provider_selection_internal(save_idx, false, false)
                    .await
                {
                    self.push_system_message(format!("Error: {}", e));
                } else {
                    // Keyless providers have no API key — skip straight to the
                    // model field. CLI subprocesses, OAuth, AND key-less API
                    // providers like Xiaomi (empty key_label).
                    // Exception: Codex OAuth uses field 1 for device flow.
                    self.ps.focused_field = if self.ps.is_keyless() {
                        2
                    } else if is_oauth_provider
                        && self.ps.provider_id() == "codex"
                        && !self.ps.has_existing_key
                    {
                        1 // Go to device flow field
                    } else if is_oauth_provider {
                        2 // Already authenticated or non-codex OAuth
                    } else {
                        1
                    };
                }
            } else if self.ps.focused_field == 1 && is_zhipu {
                // z.ai GLM: field 1 is endpoint type, move to field 2 (api_key)
                self.ps.focused_field = 2;
            } else if self.ps.focused_field == 1 && is_custom {
                // Custom provider: field 1 is base_url, move to field 2 (api_key).
                // No auto-fetch — the user requests /v1/models explicitly
                // on field 3 by pressing Enter on an empty input.
                self.ps.focused_field = 2;
            } else if self.ps.focused_field == 1
                && is_oauth_provider
                && self.ps.provider_id() == "codex"
            {
                // Codex OAuth: field 1 is the device flow trigger
                use crate::tui::onboarding::CodexDeviceFlowStatus;
                match &self.ps.codex_device_flow_status {
                    CodexDeviceFlowStatus::Complete => {
                        // Already done — move to model field
                        self.ps.focused_field = 2;
                    }
                    CodexDeviceFlowStatus::WaitingForUser => {
                        // Still waiting — ignore
                    }
                    _ => {
                        // Idle or Failed — start the device flow
                        self.ps.codex_device_flow_status = CodexDeviceFlowStatus::WaitingForUser;
                        let sender = self.event_sender();
                        tokio::spawn(async move {
                            // Step 1: Request device code
                            let device =
                                match crate::brain::provider::codex_oauth::start_device_flow().await
                                {
                                    Ok(d) => d,
                                    Err(e) => {
                                        let _ =
                                            sender.send(TuiEvent::CodexOAuthError(e.to_string()));
                                        return;
                                    }
                                };

                            // Send user code for display
                            let _ =
                                sender.send(TuiEvent::CodexDeviceCode(device.user_code.clone()));

                            // Step 2: Poll until user authorizes (returns intermediate PKCE code)
                            let device_code =
                                match crate::brain::provider::codex_oauth::poll_for_device_code(
                                    &device.device_auth_id,
                                    &device.user_code,
                                    device.interval,
                                )
                                .await
                                {
                                    Ok(dc) => dc,
                                    Err(e) => {
                                        let _ =
                                            sender.send(TuiEvent::CodexOAuthError(e.to_string()));
                                        return;
                                    }
                                };

                            // Step 3: Exchange PKCE code for final tokens
                            match crate::brain::provider::codex_oauth::exchange_device_code_for_tokens(
                                &device_code,
                            )
                            .await
                            {
                                Ok(token_resp) => {
                                    let expires_at = std::time::SystemTime::now()
                                        .duration_since(std::time::UNIX_EPOCH)
                                        .unwrap()
                                        .as_secs()
                                        + token_resp.expires_in;
                                    let tokens =
                                        crate::brain::provider::codex_oauth::CodexTokens {
                                            access_token: token_resp.access_token,
                                            refresh_token: token_resp.refresh_token,
                                            id_token: token_resp.id_token,
                                            account_id: token_resp.account_id,
                                            expires_at,
                                        };
                                    if let Err(e) = tokens.save() {
                                        let _ = sender.send(TuiEvent::CodexOAuthError(format!(
                                            "Failed to save tokens: {}",
                                            e
                                        )));
                                        return;
                                    }
                                    let _ = sender.send(TuiEvent::CodexOAuthComplete);
                                }
                                Err(e) => {
                                    let _ =
                                        sender.send(TuiEvent::CodexOAuthError(e.to_string()));
                                }
                            }
                        });
                    }
                }
            } else if (self.ps.focused_field == 1 && !is_custom && !is_zhipu && !is_oauth_provider)
                || (self.ps.focused_field == 2 && (is_custom || is_zhipu))
            {
                // On API key field (field 1 for non-Custom non-zhipu, field 2 for zhipu/Custom)
                let provider_idx = self.ps.selected_provider.min(CUSTOM_PROVIDER_IDX);

                // User typed a new key — sentinel means key was pre-populated and not changed
                let key_changed =
                    !self.ps.api_key_input.is_empty() && !self.ps.has_existing_key_sentinel();
                let provider_id = self.ps.provider_id();
                let api_key = if key_changed {
                    Some(self.ps.api_key_input.clone())
                } else if provider_id.is_empty() {
                    // Custom provider — read from the active custom entry
                    crate::config::Config::load()
                        .ok()
                        .and_then(|c| {
                            c.providers
                                .active_custom()
                                .and_then(|(_, p)| p.api_key.clone())
                        })
                        .filter(|k| !k.is_empty())
                } else {
                    // Existing key untouched — load from config (merged with keys.toml)
                    crate::config::Config::load()
                        .ok()
                        .and_then(|c| {
                            crate::utils::providers::config_for(&c.providers, provider_id)
                                .and_then(|p| p.api_key.clone())
                        })
                        .filter(|k| !k.is_empty())
                };

                // Save provider config - DON'T close
                if let Err(e) = self
                    .save_provider_selection_internal(provider_idx, false, key_changed)
                    .await
                {
                    self.push_system_message(format!("Error: {}", e));
                } else {
                    self.ps.selected_model = 0;
                    self.ps.model_filter.clear();
                    if is_custom {
                        // Custom: stay in PASTE mode. User requests
                        // /v1/models explicitly on field 3.
                        self.ps.models.clear();
                    } else {
                        // Non-custom (and zhipu): auto-fetch the live list.
                        self.ps.models.clear();
                        let zhipu_et = if is_zhipu {
                            Some(if self.ps.zhipu_endpoint_type == 1 {
                                "coding"
                            } else {
                                "api"
                            })
                        } else {
                            None
                        };
                        self.ps.models = super::onboarding::fetch_provider_models(
                            provider_idx,
                            api_key.as_deref(),
                            zhipu_et,
                            None,
                        )
                        .await;
                        self.ps.merge_config_models_into_fetched();
                    }

                    // Move to model field (field 2 for non-Custom, field 3 for Custom/zhipu)
                    self.ps.focused_field = if is_custom || is_zhipu { 3 } else { 2 };
                }
            } else if is_custom && self.ps.focused_field == 3 {
                // Custom: model field has two modes selected by whether
                // `self.ps.models` is empty:
                //
                //   PASTE MODE (models empty): the input is free-text,
                //   the user types or pastes a model name straight
                //   into `custom_model`. Enter on an empty input
                //   triggers a live /v1/models fetch and switches
                //   into LIST mode. Enter on a non-empty input
                //   accepts the typed value and advances.
                //
                //   LIST MODE (models non-empty): the user filters
                //   the fetched list and Up/Down navigates. Enter
                //   takes filtered[selected_model] — or, if the
                //   filter matches none, treats the filter text as
                //   a manual entry and appends it to the models
                //   list so the save persists it.
                if self.ps.models.is_empty() {
                    if self.ps.custom_model.trim().is_empty() {
                        // Trigger live fetch — switches into LIST mode.
                        let provider_idx = self.ps.selected_provider.min(CUSTOM_PROVIDER_IDX);
                        let api_key = crate::config::Config::load().ok().and_then(|c| {
                            c.providers
                                .active_custom()
                                .and_then(|(_, p)| p.api_key.clone())
                                .filter(|k| !k.is_empty())
                        });
                        let base_url = self.ps.base_url.clone();
                        self.ps.models = super::onboarding::fetch_provider_models(
                            provider_idx,
                            api_key.as_deref(),
                            None,
                            Some(&base_url),
                        )
                        .await;
                        self.ps.merge_config_models_into_fetched();
                        self.ps.selected_model = 0;
                        self.ps.model_filter.clear();
                        // Stay on field 3 — user picks from the list.
                    } else {
                        // Typed/pasted model: accept and advance.
                        let typed = self.ps.custom_model.trim().to_string();
                        self.ps.custom_model = typed;
                        self.ps.model_filter.clear();
                        self.ps.selected_model = 0;
                        self.ps.focused_field = 4;
                    }
                } else {
                    let filter = self.ps.model_filter.to_lowercase();
                    let filtered: Vec<&String> = self
                        .ps
                        .models
                        .iter()
                        .filter(|m| m.to_lowercase().contains(&filter))
                        .collect();
                    if let Some(m) = filtered.get(self.ps.selected_model) {
                        self.ps.custom_model = (*m).clone();
                    } else if !self.ps.model_filter.trim().is_empty() {
                        let typed = self.ps.model_filter.trim().to_string();
                        self.ps.custom_model = typed.clone();
                        if !self.ps.models.iter().any(|m| m == &typed) {
                            self.ps.models.push(typed);
                        }
                    }
                    self.ps.model_filter.clear();
                    self.ps.selected_model = 0;
                    self.ps.focused_field = 4;
                }
            } else if is_custom && self.ps.focused_field == 4 {
                // Custom: on name field — validate, normalize, then go to context window
                if self.ps.custom_name.is_empty() {
                    self.error_message =
                        Some("Enter a name identifier for this provider".to_string());
                    self.error_message_shown_at = Some(std::time::Instant::now());
                } else {
                    self.ps.custom_name = crate::config::normalize_toml_key(&self.ps.custom_name);
                    self.error_message = None;
                    self.error_message_shown_at = None;
                    self.ps.focused_field = 5;
                }
            } else if is_custom && self.ps.focused_field == 5 {
                // Custom: on context window field — save
                let key_changed =
                    !self.ps.api_key_input.is_empty() && !self.ps.has_existing_key_sentinel();
                self.save_provider_selection(
                    self.ps.selected_provider.min(CUSTOM_PROVIDER_IDX),
                    key_changed,
                )
                .await?;
            } else {
                // Non-custom: on model field — save and close
                let key_changed =
                    !self.ps.api_key_input.is_empty() && !self.ps.has_existing_key_sentinel();
                self.save_provider_selection(
                    self.ps.selected_provider.min(CUSTOM_PROVIDER_IDX),
                    key_changed,
                )
                .await?;
            }
        }

        Ok(())
    }

    /// Save provider selection to config and reload agent service
    /// If `close_dialog` is false, stays in model selector (for step 1 and 2)
    async fn save_provider_selection(
        &mut self,
        provider_idx: usize,
        key_changed: bool,
    ) -> Result<()> {
        self.save_provider_selection_internal(provider_idx, true, key_changed)
            .await
    }

    /// Internal: save provider with option to close dialog
    /// `key_changed` - true if user typed a new key (needs to be saved)
    async fn save_provider_selection_internal(
        &mut self,
        provider_idx: usize,
        close_dialog: bool,
        key_changed: bool,
    ) -> Result<()> {
        use super::onboarding::PROVIDERS;
        use crate::config::ProviderConfig;

        // Defensive clamp: callers already map existing-custom indices back
        // to CUSTOM_PROVIDER_IDX, but guard in case a future caller forgets.
        let clamped_idx = provider_idx.min(CUSTOM_PROVIDER_IDX);
        let provider = &PROVIDERS[clamped_idx];

        // Load existing config to merge — CRITICAL: empty defaults would wipe all settings
        let mut config = crate::config::Config::load().map_err(|e| {
            anyhow::anyhow!(
                "Cannot save provider: config.toml failed to load ({}). Fix config first.",
                e
            )
        })?;

        // Disable all providers first - we'll enable only the selected one
        if let Some(ref mut p) = config.providers.anthropic {
            p.enabled = false;
        }
        if let Some(ref mut p) = config.providers.openai {
            p.enabled = false;
        }
        if let Some(ref mut p) = config.providers.github {
            p.enabled = false;
        }
        if let Some(ref mut p) = config.providers.gemini {
            p.enabled = false;
        }
        if let Some(ref mut p) = config.providers.openrouter {
            p.enabled = false;
        }
        if let Some(ref mut p) = config.providers.minimax {
            p.enabled = false;
        }
        if let Some(ref mut p) = config.providers.zhipu {
            p.enabled = false;
        }
        if let Some(ref mut p) = config.providers.claude_cli {
            p.enabled = false;
        }
        if let Some(ref mut p) = config.providers.opencode_cli {
            p.enabled = false;
        }
        if let Some(ref mut p) = config.providers.codex_cli {
            p.enabled = false;
        }
        if let Some(ref mut p) = config.providers.codex {
            p.enabled = false;
        }
        if let Some(ref mut p) = config.providers.opencode {
            p.enabled = false;
        }
        if let Some(ref mut p) = config.providers.qwen {
            p.enabled = false;
        }
        if let Some(ref mut p) = config.providers.ollama {
            p.enabled = false;
        }
        if let Some(ref mut p) = config.providers.xiaomi {
            p.enabled = false;
        }

        // Get existing key from config if not changing. Routes by provider
        // id so reordering PROVIDERS doesn't break the match.
        let existing_key = if provider.id.is_empty() {
            // Custom — pull key from the currently active custom entry
            config
                .providers
                .active_custom()
                .and_then(|(_, p)| p.api_key.as_ref())
                .filter(|k| !k.is_empty())
                .cloned()
        } else {
            crate::utils::providers::config_for(&config.providers, provider.id)
                .and_then(|p| p.api_key.as_ref())
                .filter(|k| !k.is_empty())
                .cloned()
        };

        // Only use a key if the user actually typed one — never pull from config
        let api_key = if key_changed && !self.ps.api_key_input.is_empty() {
            Some(self.ps.api_key_input.clone())
        } else {
            existing_key
        };

        // Log what's being saved (hide key)
        tracing::info!(
            "Saving provider config: idx={}, has_api_key={}",
            provider_idx,
            api_key.is_some()
        );

        // Resolve default_model:
        // - On final confirm (close_dialog=true): use the user's selected model
        // - On provider switch (close_dialog=false): preserve existing config model
        // Empty string = "no real model yet" → skip the config.toml write below.
        // Writing the literal "default" (2026-04-22 bug) produced
        // `default_model = "default"` entries that then failed every
        // request with "Model default not supported".
        let default_model = if !close_dialog {
            // Preserve whatever is already saved in config for this provider
            let provider_id = self.ps.provider_id();
            crate::config::Config::load()
                .ok()
                .and_then(|c| {
                    crate::utils::providers::config_for(&c.providers, provider_id)
                        .and_then(|p| p.default_model.clone())
                })
                .unwrap_or_else(|| {
                    provider
                        .models
                        .first()
                        .map(|s| s.to_string())
                        .unwrap_or_default()
                })
        } else if provider_idx >= CUSTOM_PROVIDER_IDX {
            // Custom provider: trust `self.ps.custom_model`. The field-3
            // Enter handler always writes the user's pick into it (either
            // `filtered[selected_model]` in LIST mode, the typed text in
            // PASTE mode, or a typed-not-in-list value), then clears the
            // filter and resets `selected_model = 0` before advancing to
            // field 4. By the time save fires the user has walked past
            // field 4 and field 5, so `selected_model` is stale (0) and
            // `filter` is empty — deriving from `filtered[selected_model]`
            // here returns the FIRST item in the live list, not the pick.
            // Repro (2026-05-21 02:58): user picked
            // `qwen-3.7-max-preview-thinking`, hit Enter, status bar
            // saved `qwen-3.7-max-preview` because that was filtered[0].
            // Fall back to the live list only when custom_model is empty
            // (e.g. existing-provider re-save with no model edit).
            if !self.ps.custom_model.trim().is_empty() {
                self.ps.custom_model.clone()
            } else if !self.ps.models.is_empty() {
                let filter = self.ps.model_filter.to_lowercase();
                let filtered: Vec<_> = self
                    .ps
                    .models
                    .iter()
                    .filter(|m| m.to_lowercase().contains(&filter))
                    .collect();
                filtered
                    .get(self.ps.selected_model)
                    .map(|m| m.to_string())
                    .unwrap_or_default()
            } else {
                String::new()
            }
        } else if !self.ps.models.is_empty() {
            let filter = self.ps.model_filter.to_lowercase();
            let filtered: Vec<_> = self
                .ps
                .models
                .iter()
                .filter(|m| m.to_lowercase().contains(&filter))
                .collect();
            filtered
                .get(self.ps.selected_model)
                .map(|m| m.to_string())
                .or_else(|| self.ps.models.first().cloned())
                .unwrap_or_else(|| self.default_model_name.clone())
        } else if let Some(model) = provider.models.get(self.ps.selected_model) {
            model.to_string()
        } else {
            // Empty string → write below is skipped. Do NOT write "default"
            // as a placeholder — it gets persisted to config.toml and then
            // every request fails with "Model default not supported".
            provider
                .models
                .first()
                .map(|s| s.to_string())
                .unwrap_or_default()
        };
        // Route by provider.id so reordering PROVIDERS or adding new
        // built-ins never breaks the save logic again.
        match provider.id {
            "anthropic" => {
                config.providers.anthropic = Some(ProviderConfig {
                    enabled: true,
                    api_key: api_key.clone(),
                    base_url: None,
                    default_model: Some(default_model.to_string()),
                    models: vec![],
                    vision_model: None,
                    ..Default::default()
                });
            }
            "openai" => {
                config.providers.openai = Some(ProviderConfig {
                    enabled: true,
                    api_key: api_key.clone(),
                    base_url: None,
                    default_model: Some(default_model.to_string()),
                    models: vec![],
                    vision_model: None,
                    ..Default::default()
                });
            }
            "github" => {
                config.providers.github = Some(ProviderConfig {
                    enabled: true,
                    api_key: api_key.clone(),
                    base_url: Some("https://api.githubcopilot.com/chat/completions".to_string()),
                    default_model: Some(default_model.to_string()),
                    models: vec![],
                    vision_model: None,
                    ..Default::default()
                });
            }
            "gemini" => {
                config.providers.gemini = Some(ProviderConfig {
                    enabled: true,
                    api_key: api_key.clone(),
                    base_url: None,
                    default_model: Some(default_model.to_string()),
                    models: vec![],
                    vision_model: None,
                    ..Default::default()
                });
            }
            "openrouter" => {
                config.providers.openrouter = Some(ProviderConfig {
                    enabled: true,
                    api_key: api_key.clone(),
                    base_url: Some("https://openrouter.ai/api/v1/chat/completions".to_string()),
                    default_model: Some(default_model.to_string()),
                    models: vec![],
                    vision_model: None,
                    ..Default::default()
                });
            }
            "minimax" => {
                config.providers.minimax = Some(ProviderConfig {
                    enabled: true,
                    api_key: api_key.clone(),
                    base_url: Some("https://api.minimax.io/v1".to_string()),
                    default_model: Some(default_model.to_string()),
                    models: vec![],
                    vision_model: None,
                    ..Default::default()
                });
            }
            "zhipu" => {
                let endpoint_type = Some(
                    if self.ps.zhipu_endpoint_type == 1 {
                        "coding"
                    } else {
                        "api"
                    }
                    .to_string(),
                );
                config.providers.zhipu = Some(ProviderConfig {
                    enabled: true,
                    api_key: api_key.clone(),
                    base_url: None,
                    default_model: Some(default_model.to_string()),
                    models: vec![],
                    vision_model: None,
                    endpoint_type,
                    ..Default::default()
                });
            }
            "claude-cli" => {
                config.providers.claude_cli = Some(ProviderConfig {
                    enabled: true,
                    api_key: None,
                    base_url: None,
                    default_model: Some(default_model.to_string()),
                    models: vec![],
                    vision_model: None,
                    ..Default::default()
                });
            }
            "opencode-cli" => {
                config.providers.opencode_cli = Some(ProviderConfig {
                    enabled: true,
                    api_key: None,
                    base_url: None,
                    default_model: Some(default_model.to_string()),
                    models: vec![],
                    vision_model: None,
                    ..Default::default()
                });
            }
            "codex-cli" => {
                config.providers.codex_cli = Some(ProviderConfig {
                    enabled: true,
                    api_key: None,
                    base_url: None,
                    default_model: Some(default_model.to_string()),
                    models: vec![],
                    vision_model: None,
                    ..Default::default()
                });
            }
            "codex" => {
                config.providers.codex = Some(ProviderConfig {
                    enabled: true,
                    api_key: None,
                    base_url: None,
                    default_model: Some(default_model.to_string()),
                    models: vec![],
                    vision_model: None,
                    ..Default::default()
                });
            }
            "opencode" => {
                // OpenCode native API provider
                config.providers.opencode = Some(ProviderConfig {
                    enabled: true,
                    api_key: api_key.clone(),
                    base_url: None,
                    default_model: Some(default_model.to_string()),
                    models: vec![],
                    vision_model: None,
                    ..Default::default()
                });
            }
            "qwen" => {
                let merged = config.providers.qwen.clone().unwrap_or_default();
                config.providers.qwen = Some(ProviderConfig {
                    enabled: true,
                    default_model: Some(default_model.to_string()),
                    ..merged
                });
            }
            "ollama" => {
                let merged = config.providers.ollama.clone().unwrap_or_default();
                config.providers.ollama = Some(ProviderConfig {
                    enabled: true,
                    api_key: api_key.clone(),
                    default_model: Some(default_model.to_string()),
                    ..merged
                });
            }
            "xiaomi" => {
                // Keyless collab provider — preserve base_url / models /
                // context_window from config; just enable it and record the
                // chosen model. The api_key stays whatever config has (none
                // during the keyless window).
                let merged = config.providers.xiaomi.clone().unwrap_or_default();
                config.providers.xiaomi = Some(ProviderConfig {
                    enabled: true,
                    api_key: api_key.clone().or(merged.api_key.clone()),
                    default_model: Some(default_model.to_string()),
                    ..merged
                });
            }
            "" if !self.ps.custom_name.is_empty() => {
                // Custom provider: edit-in-place semantics. If editing an
                // existing entry, write back to that key (even on rename).
                let custom_model = self.ps.custom_model.clone();
                let new_name = self.ps.custom_name.clone();
                let editing = self.ps.editing_custom_key.clone();
                let mut customs = config.providers.custom.unwrap_or_default();
                let context_window = self.ps.context_window.parse::<u32>().ok();

                let existing = editing
                    .as_ref()
                    .and_then(|k| customs.get(k).cloned())
                    .unwrap_or_default();

                // Sync `models` with the live-fetched list when one is
                // available — the dialog populates `self.ps.models` from
                // the provider's `/models` endpoint when the user opens
                // `/models`, so a save is the right moment to record what
                // the endpoint actually has today. Without this, new
                // models (e.g. qwen-3.7-max-preview-thinking appearing on
                // dialagram 2026-05-18) showed in the list but never
                // persisted, and old retired models stayed forever.
                // Falls back to the existing list when the live fetch was
                // empty (offline, endpoint down, free-text custom).
                let models = if !self.ps.models.is_empty() {
                    self.ps.models.clone()
                } else {
                    existing.models.clone()
                };
                let merged = ProviderConfig {
                    enabled: true,
                    api_key: api_key.clone().or(existing.api_key.clone()),
                    base_url: Some(self.ps.base_url.clone()),
                    default_model: Some(custom_model),
                    models,
                    vision_model: existing.vision_model.clone(),
                    context_window: context_window.or(existing.context_window),
                    ..existing
                };

                if let Some(old_key) = editing.as_ref()
                    && old_key != &new_name
                {
                    customs.remove(old_key);
                }
                customs.insert(new_name, merged);
                config.providers.custom = Some(customs);
            }
            _ => {}
        }

        // Resolve the TOML section to write. Routes by provider.id so
        // adding or reordering built-ins never corrupts config again.
        let custom_section;
        let section = match provider.id {
            "anthropic" => "providers.anthropic",
            "openai" => "providers.openai",
            "github" => "providers.github",
            "gemini" => "providers.gemini",
            "openrouter" => "providers.openrouter",
            "minimax" => "providers.minimax",
            "zhipu" => "providers.zhipu",
            "claude-cli" => "providers.claude_cli",
            "opencode-cli" => "providers.opencode_cli",
            "codex-cli" => "providers.codex_cli",
            "codex" => "providers.codex",
            "opencode" => "providers.opencode",
            "qwen" => "providers.qwen",
            "ollama" => "providers.ollama",
            "xiaomi" => "providers.xiaomi",
            "" => {
                // Custom provider: resolve name from UI field. NEVER fall
                // back to `active_custom()` — the previous code did, and
                // that's how the 2026-06-04 dialagram section got its
                // base_url silently overwritten with modelscope-qwen's
                // URL. Flow that triggers it: cursor on dialagram row
                // (active custom) → user navigates to "+ Add new custom"
                // → `reload_model_selector_custom_fields` clears
                // `custom_name` (correct) → user types base_url for the
                // new entry → per-field save fires with `custom_name=""`
                // → the fallback rescues with `active_custom()` =
                // "dialagram" → `try_write("providers.custom.dialagram",
                // "base_url", "<new-entry-url>")` corrupts dialagram's
                // section, leaving its `default_model` intact because
                // `write_key` is a per-key merge. Empty `custom_name` in
                // the "" provider arm now means exactly one thing: the
                // user hasn't typed a name for the draft yet — nothing
                // legitimate to save.
                if self.ps.custom_name.is_empty() {
                    tracing::debug!(
                        "save_provider: empty custom_name (drafting new custom?) — skipping write \
                         to avoid corrupting whichever section active_custom() would have resolved to"
                    );
                    return Ok(());
                }
                custom_section = format!("providers.custom.{}", self.ps.custom_name);
                &custom_section
            }
            _ => {
                // Unknown provider — don't corrupt a random section
                tracing::warn!(
                    "save_provider: unknown provider.id '{}', skipping config write",
                    provider.id
                );
                return Ok(());
            }
        };

        // Disable ALL other providers on disk before enabling the selected one.
        // rebuild_agent_service() reloads from disk, so this is the only source of truth.
        let mut write_errors: Vec<String> = Vec::new();
        let mut try_write = |s: &str, k: &str, v: &str| {
            if let Err(e) = crate::config::Config::write_key(s, k, v) {
                tracing::warn!("Failed to write {}.{}: {}", s, k, e);
                write_errors.push(format!("{}.{}", s, k));
            }
        };

        for s in [
            "providers.anthropic",
            "providers.openai",
            "providers.github",
            "providers.gemini",
            "providers.openrouter",
            "providers.minimax",
            "providers.zhipu",
            "providers.claude_cli",
            "providers.opencode_cli",
            "providers.codex_cli",
            "providers.codex",
            "providers.opencode",
            "providers.qwen",
            "providers.ollama",
        ] {
            if s != section {
                try_write(s, "enabled", "false");
            }
        }
        if let Some(ref customs) = config.providers.custom {
            for name in customs.keys() {
                let cs = format!("providers.custom.{}", name);
                if cs != section {
                    try_write(&cs, "enabled", "false");
                }
            }
        }

        // On custom-provider rename, delete the old `[providers.custom.<old>]`
        // block and port its api_key to the new section in keys.toml.
        // Without this, editing the name field in /models leaves a
        // duplicate entry behind (old name still present with the key,
        // new name empty and unusable) — the exact bug behind the
        // 2026-04-18 13:52 401 where `opencodeiolo` had no key because
        // it was a rename-duplicate. `api_key` here already comes from
        // the merged config (Config::load merges keys.toml into
        // api_key), so we just re-write it under the new section.
        if provider.id.is_empty()
            && let Some(ref old_key) = self.ps.editing_custom_key
            && old_key != &self.ps.custom_name
            && !old_key.is_empty()
        {
            let old_section = format!("providers.custom.{}", old_key);
            if let Err(e) = crate::config::Config::remove_section(&old_section) {
                tracing::warn!(
                    "Failed to remove old custom section '{}': {}",
                    old_section,
                    e
                );
            } else {
                tracing::info!(
                    "Renamed custom provider: '{}' -> '{}' (old section removed)",
                    old_key,
                    self.ps.custom_name
                );
            }
            // Port the api_key to the new keys.toml section. This must
            // happen unconditionally on rename (the key_changed gate
            // below only fires when the user typed in the key field).
            if let Some(ref key_val) = api_key
                && !key_val.is_empty()
                && let Err(e) = crate::config::write_secret_key(section, "api_key", key_val)
            {
                tracing::warn!("Failed to migrate api_key on rename: {}", e);
            }
            // Remove the OLD keys.toml section. Without this, the rename
            // ports the api_key to the new section but leaves the old
            // section behind in keys.toml — and `merge_provider_keys`
            // on next `Config::load()` resurrects the old name as a
            // phantom entry (it creates a minimal config entry for any
            // keys.toml provider that lacks a config counterpart). The
            // user then sees BOTH names in /models even though config.toml
            // only has one. 2026-06-05: `modelscope-qwen` → `modelscope`
            // rename surfaced this exact path.
            if let Err(e) = crate::config::Config::remove_secret_section(&old_section) {
                tracing::warn!(
                    "Failed to remove old keys.toml section '{}' on rename: {} \
                     (next load may resurrect the old name as a phantom entry via merge_provider_keys)",
                    old_section,
                    e
                );
            }
        }

        // Enable the chosen provider on disk. User reported 2026-04-19
        // that after picking opencode2 in /models, config.toml still had
        // `providers.custom.opencode2.enabled = false`. Add loud tracing
        // around this single write + a reload-and-verify guard so any
        // future drift (section mismatch, toml_edit corruption,
        // concurrent writer) is caught in the log and re-written instead
        // of being swallowed silently by try_write's warn-and-continue.
        tracing::info!(
            "[save_provider] writing enabled=true to section '{}' (provider_idx={}, custom_name='{}')",
            section,
            provider_idx,
            self.ps.custom_name,
        );
        try_write(section, "enabled", "true");

        // Verify the write actually landed. Re-read config and confirm.
        // On mismatch, try again via the raw write_key (bypasses try_write's
        // borrow on write_errors so we can act on the true/false outcome).
        let verified_enabled = crate::config::Config::load()
            .ok()
            .and_then(|cfg| match section {
                "providers.anthropic" => cfg.providers.anthropic.map(|p| p.enabled),
                "providers.openai" => cfg.providers.openai.map(|p| p.enabled),
                "providers.github" => cfg.providers.github.map(|p| p.enabled),
                "providers.gemini" => cfg.providers.gemini.map(|p| p.enabled),
                "providers.openrouter" => cfg.providers.openrouter.map(|p| p.enabled),
                "providers.minimax" => cfg.providers.minimax.map(|p| p.enabled),
                "providers.zhipu" => cfg.providers.zhipu.map(|p| p.enabled),
                "providers.claude_cli" => cfg.providers.claude_cli.map(|p| p.enabled),
                "providers.opencode_cli" => cfg.providers.opencode_cli.map(|p| p.enabled),
                "providers.codex_cli" => cfg.providers.codex_cli.map(|p| p.enabled),
                "providers.codex" => cfg.providers.codex.map(|p| p.enabled),
                "providers.opencode" => cfg.providers.opencode.map(|p| p.enabled),
                "providers.qwen" => cfg.providers.qwen.map(|p| p.enabled),
                "providers.ollama" => cfg.providers.ollama.map(|p| p.enabled),
                s if s.starts_with("providers.custom.") => {
                    let name = s.trim_start_matches("providers.custom.");
                    cfg.providers
                        .custom
                        .as_ref()
                        .and_then(|m| m.get(name))
                        .map(|p| p.enabled)
                }
                _ => None,
            })
            .unwrap_or(false);
        if !verified_enabled {
            tracing::warn!(
                "[save_provider] enabled=true did NOT land on disk for '{}' — retrying via try_write",
                section
            );
            // try_write logs + pushes to write_errors itself on failure,
            // so we don't touch write_errors directly (which would conflict
            // with the closure's active &mut borrow).
            try_write(section, "enabled", "true");
        } else {
            tracing::info!(
                "[save_provider] verified enabled=true on disk for '{}'",
                section
            );
        }

        // Write base_url if applicable. Routes by provider.id so indices
        // never matter.
        match provider.id {
            "github" => {
                try_write(
                    section,
                    "base_url",
                    "https://api.githubcopilot.com/chat/completions",
                );
            }
            "openrouter" => {
                try_write(
                    section,
                    "base_url",
                    "https://openrouter.ai/api/v1/chat/completions",
                );
            }
            "minimax" => {
                try_write(section, "base_url", "https://api.minimax.io/v1");
            }
            "zhipu" => {
                let endpoint_type = if self.ps.zhipu_endpoint_type == 1 {
                    "coding"
                } else {
                    "api"
                };
                try_write(section, "endpoint_type", endpoint_type);
            }
            "" if !self.ps.base_url.is_empty() => {
                // Custom provider
                try_write(section, "base_url", &self.ps.base_url);
                if !self.ps.context_window.is_empty() {
                    try_write(section, "context_window", &self.ps.context_window);
                }
            }
            _ => {}
        }

        // Clean up ghost custom provider entries (empty name/url/model)
        crate::config::Config::cleanup_empty_custom_providers();

        // Write API key to keys.toml BEFORE any Config::load() calls.
        // Otherwise merge_provider_keys() won't find the key during rebuild.
        // This was the root cause of custom provider keys not persisting on first try.
        if key_changed
            && !self.ps.has_existing_key_sentinel()
            && let Some(ref key) = api_key
            && !key.is_empty()
            && let Err(e) = crate::config::write_secret_key(section, "api_key", key)
        {
            tracing::warn!("Failed to save API key to keys.toml: {}", e);
        }

        // Refresh custom provider names list after saving (so new entries appear immediately)
        if provider.id.is_empty()
            && let Ok(fresh) = crate::config::Config::load()
        {
            self.ps.custom_names = fresh
                .providers
                .custom
                .as_ref()
                .map(|m| m.keys().cloned().collect())
                .unwrap_or_default();
            tracing::debug!(
                "[save_provider] refreshed custom_names after save: {:?}",
                self.ps.custom_names,
            );
            // Point selection to the newly saved custom provider, and
            // re-read its fields from disk. Without the explicit
            // reload, the dialog kept the values the user just typed
            // visible even after the cursor moved off the new entry —
            // and any subsequent save would re-write to whichever
            // section `self.ps.custom_name` still pointed at, not the
            // visually-selected row.
            if !self.ps.custom_name.is_empty()
                && let Some(pos) = self
                    .ps
                    .custom_names
                    .iter()
                    .position(|n| n == &self.ps.custom_name)
            {
                self.ps.selected_provider = CUSTOM_INSTANCES_START + pos;
                self.reload_model_selector_custom_fields();
                tracing::debug!(
                    "[save_provider] mapped custom '{}' to idx={}",
                    self.ps.custom_name,
                    CUSTOM_INSTANCES_START + pos,
                );
            }
        }

        // Write default_model to config BEFORE rebuild so the provider picks it up.
        // Skip when we don't have a real model id — writing the literal "default"
        // or an empty string pollutes config.toml and every subsequent request
        // fails with "Model <garbage> not supported".
        if default_model.is_empty() || default_model == "default" {
            tracing::info!(
                "Not writing default_model for section '{}' — no valid model selected yet (value was {:?})",
                section,
                default_model,
            );
        } else if let Err(e) =
            crate::config::Config::write_key(section, "default_model", &default_model)
        {
            tracing::warn!("Failed to persist model to config: {}", e);
            write_errors.push(format!("{}.default_model", section));
        }

        // Persist the live-fetched models list onto the provider section so
        // `supported_models()` returns the real catalog at next load. Without
        // this, picking qwen on dialagram (or any non-default model on a
        // custom router) makes helpers.rs:95 either log a no-op remap or
        // route to default_model. Skip when the list is empty (e.g. provider
        // has no /v1/models endpoint) to avoid wiping a legitimate manually
        // curated `models = [...]` entry.
        if !self.ps.models.is_empty()
            && let Err(e) = crate::config::Config::write_array(section, "models", &self.ps.models)
        {
            tracing::warn!("Failed to persist models list to config: {}", e);
            write_errors.push(format!("{}.models", section));
        }

        // Warn user if any config writes failed
        if !write_errors.is_empty() {
            self.push_system_message(format!(
                "⚠️ Failed to save some config keys: {}. Check file permissions on config.toml.",
                write_errors.join(", ")
            ));
        }

        // Fast path for mid-navigation in /models: the user is still
        // moving between fields (provider → api_key → model → ...), so
        // we've written the enabled flag + base_url + default_model to
        // disk but we don't need to rebuild the full provider chain yet
        // — that call can take 5-10s because it re-creates every
        // fallback (HTTP health checks, subprocess spawns). Defer
        // rebuild until the final Enter (close_dialog=true). Navigation
        // now returns ~immediately; the old flow made users think the
        // dialog had hung and they'd mash Enter multiple times.
        if !close_dialog {
            return Ok(());
        }

        // Rebuild agent service with new provider (now sees the correct model)
        if let Err(e) = self.rebuild_agent_service().await {
            if api_key.is_none() && provider_idx == CUSTOM_PROVIDER_IDX {
                self.push_system_message(format!(
                    "API key required for {}. Type it and press Enter.",
                    provider
                        .name
                        .split('(')
                        .next()
                        .unwrap_or(provider.name)
                        .trim()
                ));
                return Ok(());
            }
            return Err(e);
        }

        // Persist provider + model to current session DB record AND pin the
        // newly built provider to THIS session's entry in the agent service.
        // Without the per-session pin a second pane's turn using a different
        // provider would fall through to the new global default on its next
        // iteration (2026-04-17 17:01 logs — background qwen-plus turn
        // silently rerouted to localhost:8891 when the other pane swapped).
        //
        // CRITICAL: for custom providers, construct the session's instance
        // BY NAME via create_provider_by_name(&config, chosen). Using
        // `self.agent_service.provider()` was the root cause of the
        // 2026-04-19 "session says opencode2 but routes to opencode" bug —
        // agent_service.provider() returns the global default, which lags
        // /models save by one rebuild cycle on a busy TUI. When the user
        // switched from opencode to opencode2 the session would record
        // "opencode2" as the name but pin the global's opencode-arc
        // underneath, routing every request to the rate-limited account.
        // Building from config by name is pure and always hits the
        // correct section.
        let (agent_provider_name, provider_arc) = if provider_idx == CUSTOM_PROVIDER_IDX
            && !self.ps.custom_name.is_empty()
        {
            let chosen = self.ps.custom_name.clone();
            match crate::config::Config::load() {
                Ok(cfg) => {
                    match crate::brain::provider::factory::create_provider_by_name(&cfg, &chosen)
                        .await
                    {
                        Ok(p) => (chosen, p),
                        Err(e) => {
                            tracing::warn!(
                                "[save_provider] create_provider_by_name('{}') failed: {} — falling back to agent_service global",
                                chosen,
                                e
                            );
                            (
                                self.agent_service.provider_name(),
                                self.agent_service.provider(),
                            )
                        }
                    }
                }
                Err(e) => {
                    tracing::warn!(
                        "[save_provider] Config::load() failed while resolving session provider: {}",
                        e
                    );
                    (
                        self.agent_service.provider_name(),
                        self.agent_service.provider(),
                    )
                }
            }
        } else {
            (
                self.agent_service.provider_name(),
                self.agent_service.provider(),
            )
        };

        // Read the model from the SESSION's provider, never from
        // `agent_service.provider_model()`. The global agent service can be
        // sitting on a sticky-fallback target whose model belongs to a
        // different provider's catalogue (e.g. global is zhipu/glm-5.1 after
        // a fallback while the user just picked dialagram). Sourcing
        // `actual_model` from the global there persists `dialagram/glm-5.1`
        // to the session, then every following turn ships glm-5.1 to
        // dialagram (which serves only qwen-* models), 3-retries, falls
        // back to zhipu, and the user sees the cross-provider mash-up the
        // last fix was supposed to prevent. `provider_arc` was built fresh
        // from config-by-name above with the user's selected default_model
        // already written to disk, so its `.default_model()` is the right
        // model for THIS session.
        let actual_model = provider_arc.default_model().to_string();
        self.default_model_name = actual_model.clone();

        // Flush ONLY the current session's stale entry so runtime picks up
        // the fresh config immediately. Other sessions keep their pins —
        // per-session isolation must never be broken by a /models save in
        // a different pane.
        // Without this, a session that cached an instance built before
        // the save (e.g. stale no-key opencodeiolo) keeps failing until
        // the user manually forces a new provider creation. The 2026-04-18
        // 13:52 401 cascade was exactly this — config had the key,
        // session_providers cache had the keyless instance.
        if let Some(ref current) = self.current_session {
            let current_sid = current.id;
            if let Some(cached) = self
                .agent_service
                .session_provider_snapshot()
                .into_iter()
                .find(|(sid, _)| *sid == current_sid)
                .map(|(_, p)| p)
            {
                let cached_name = cached.name().to_string();
                let mut invalidate_names: Vec<String> = vec![agent_provider_name.clone()];
                if let Some(ref old_key) = self.ps.editing_custom_key
                    && old_key != &self.ps.custom_name
                {
                    invalidate_names.push(old_key.clone());
                }
                if invalidate_names.iter().any(|n| n == &cached_name) {
                    self.agent_service.remove_session_provider(current_sid);
                    tracing::info!(
                        "[save_provider] flushed stale session_providers entry for current session={} (was '{}')",
                        current_sid,
                        cached_name
                    );
                }
            }
        }

        // Resolve the session id the user just configured this provider for.
        // Prefer `current_session` (the foreground chat), then fall back to
        // the focused pane's session_id. Without the fallback, a save that
        // fires while `current_session` is momentarily None (e.g. mid-pane-
        // switch, between load_session calls) silently skipped the DB
        // persist while the cosmetic "[Model changed to ...]" banner still
        // ran — and the next turn shipped the stale prior-provider model
        // because session.model in DB was never updated (2026-06-04 17:38
        // incident: modelscope-qwen newly configured but request went out
        // with qwen-3.7-max-thinking from a dialagram-era sticky pin).
        let target_session_id = self
            .current_session
            .as_ref()
            .map(|s| s.id)
            .or_else(|| self.pane_manager.focused_pane().and_then(|p| p.session_id));
        if let Some(session_id) = target_session_id {
            // Update in-memory copy if it's the same session (keeps footer
            // and any subsequent reads in this turn aligned).
            if let Some(ref mut session) = self.current_session
                && session.id == session_id
            {
                session.provider_name = Some(agent_provider_name.clone());
                session.model = Some(actual_model.clone());
            }
            // Always re-fetch from DB, mutate, and write back — covers the
            // current_session=None case AND keeps the write authoritative
            // when other fields on the row were touched between read and
            // write upstream.
            match self.session_service.get_session(session_id).await {
                Ok(Some(mut row)) => {
                    row.provider_name = Some(agent_provider_name.clone());
                    row.model = Some(actual_model.clone());
                    if let Err(e) = self.session_service.update_session(&row).await {
                        tracing::warn!(
                            "save_provider_settings: persist to session {} failed: {}",
                            session_id,
                            e
                        );
                    } else {
                        tracing::info!(
                            "save_provider_settings: persisted provider={} model={} to session {}",
                            agent_provider_name,
                            actual_model,
                            session_id
                        );
                    }
                }
                Ok(None) => {
                    tracing::warn!(
                        "save_provider_settings: target session {} not found in DB — provider/model not persisted",
                        session_id
                    );
                }
                Err(e) => {
                    tracing::warn!(
                        "save_provider_settings: get_session({}) failed: {} — provider/model not persisted",
                        session_id,
                        e
                    );
                }
            }
            // Provider+model are a pair: set both atomically to the user's
            // explicit pick. provider_arc is a cached object whose
            // default_model can be stale, so the model MUST come from
            // actual_model (what the user just selected), not the provider.
            self.agent_service.swap_provider_for_session(
                session_id,
                provider_arc.clone(),
                actual_model.clone(),
            );
            // Pin this as a USER switch so an in-flight turn's fallback can't
            // permanently overwrite it — the pick is restored after that turn
            // completes (never on the completion path, so it can't drop it).
            self.agent_service
                .mark_manual_switch(session_id, actual_model.clone());

            // Update context_max_tokens to reflect the new provider's context window.
            // Without this, the footer shows stale values (e.g., 128k) after switching
            // to a model with a different limit (e.g., 200k).
            self.context_max_tokens = self.agent_service.context_limit_for_session(session_id);
        } else {
            tracing::warn!(
                "save_provider_settings: no current_session and no focused-pane session — \
                 provider/model written to config.toml but not pinned to any session"
            );
        }
        // Cache the provider instance for fast session switching
        self.provider_cache
            .insert(agent_provider_name.clone(), provider_arc);
        // Anchor moves to the new key for the next save in this dialog
        // session (if the user saves again without reopening).
        self.ps.editing_custom_key = Some(self.ps.custom_name.clone());

        // Only close dialog if explicitly requested
        if close_dialog {
            // Use user-configured name for custom providers (e.g. "nvidia"), fall back to generic
            let provider_name =
                if provider_idx == CUSTOM_PROVIDER_IDX && !self.ps.custom_name.is_empty() {
                    self.ps.custom_name.clone()
                } else {
                    provider
                        .name
                        .split('(')
                        .next()
                        .unwrap_or(provider.name)
                        .trim()
                        .to_string()
                };

            let change_msg = format!("[Model changed to {}/{}]", provider_name, default_model);
            self.push_system_message(change_msg.clone());
            self.pending_context.push(change_msg);

            self.mode = AppMode::Chat;
        }

        Ok(())
    }

    /// Handle keys in onboarding wizard mode
    pub(crate) async fn handle_onboarding_key(
        &mut self,
        event: crossterm::event::KeyEvent,
    ) -> Result<()> {
        if let Some(ref mut wizard) = self.onboarding {
            let action = wizard.handle_key(event);
            match action {
                WizardAction::Cancel => {
                    // Persist whatever the user entered before dropping the wizard.
                    // Without this, going back from channel setup loses all typed values.
                    if let Some(ref wizard) = self.onboarding
                        && let Err(e) = wizard.apply_config()
                    {
                        tracing::warn!("Wizard cancel: partial save failed: {}", e);
                    }
                    self.onboarding = None;
                    self.switch_mode(AppMode::Chat).await?;
                }
                WizardAction::QuickJumpDone => {
                    // Quick-jump completed a step — save config then close
                    let mut needs_rebuild = false;
                    if let Some(ref wizard) = self.onboarding {
                        if let Err(e) = wizard.apply_config() {
                            self.push_system_message(format!(
                                "Settings saved with warnings: {}",
                                e
                            ));
                        } else {
                            // Show what changed based on the step
                            let msg = match wizard.step {
                                OnboardingStep::ProviderAuth => {
                                    needs_rebuild = true;
                                    let (pname, mname) = if wizard.ps.is_custom() {
                                        (
                                            format!("Custom ({})", wizard.ps.custom_name),
                                            wizard.ps.custom_model.clone(),
                                        )
                                    } else {
                                        (
                                            super::onboarding::PROVIDERS
                                                [wizard.ps.selected_provider]
                                                .name
                                                .to_string(),
                                            wizard.ps.selected_model_name().to_string(),
                                        )
                                    };
                                    format!("[Model changed to {}/{}]", pname, mname)
                                }
                                OnboardingStep::VoiceSetup => {
                                    let stt_name = match wizard.stt_provider {
                                        super::onboarding::SttProvider::Off => "Off",
                                        super::onboarding::SttProvider::Groq => "Groq",
                                        super::onboarding::SttProvider::Local => "Local Whisper",
                                        super::onboarding::SttProvider::OpenAiCompatible => {
                                            "OpenAI-compatible"
                                        }
                                        super::onboarding::SttProvider::Voicebox => "Voicebox",
                                    };
                                    let tts_name = match wizard.tts_provider {
                                        super::onboarding::TtsProvider::Off => "Off",
                                        super::onboarding::TtsProvider::OpenAi => "OpenAI",
                                        super::onboarding::TtsProvider::Local => "Local Piper",
                                        super::onboarding::TtsProvider::OpenAiCompatible => {
                                            "OpenAI-compatible"
                                        }
                                        super::onboarding::TtsProvider::Voicebox => "Voicebox",
                                    };
                                    let mut parts = vec![
                                        format!("STT: {}", stt_name),
                                        format!("TTS: {}", tts_name),
                                    ];
                                    if wizard.tts_provider
                                        == super::onboarding::TtsProvider::Voicebox
                                        && !wizard.tts_voicebox_profile_id.is_empty()
                                    {
                                        parts.push(format!(
                                            "Profile: {}",
                                            &wizard.tts_voicebox_profile_id
                                                [..8.min(wizard.tts_voicebox_profile_id.len())]
                                        ));
                                    }
                                    if wizard.tts_provider
                                        == super::onboarding::TtsProvider::Voicebox
                                        && !wizard.tts_voicebox_engine.is_empty()
                                    {
                                        parts.push(format!(
                                            "Engine: {}",
                                            wizard.tts_voicebox_engine
                                        ));
                                    }
                                    format!("Voice settings saved — {}", parts.join(" | "))
                                }
                                OnboardingStep::ImageSetup => {
                                    let mut parts = vec![];
                                    if wizard.image_vision_enabled {
                                        parts.push("Vision: ON".to_string());
                                    }
                                    if wizard.image_generation_enabled {
                                        parts.push("Generation: ON".to_string());
                                    }
                                    if parts.is_empty() {
                                        parts.push("Image: OFF".to_string());
                                    }
                                    format!("Image settings saved — {}", parts.join(" | "))
                                }
                                OnboardingStep::Channels => {
                                    let mut parts = vec![];
                                    if wizard.is_telegram_enabled() {
                                        parts.push("Telegram".to_string());
                                    }
                                    if wizard.is_discord_enabled() {
                                        parts.push("Discord".to_string());
                                    }
                                    if wizard.channel_toggles.get(2).is_some_and(|t| t.1) {
                                        parts.push("WhatsApp".to_string());
                                    }
                                    if wizard.is_slack_enabled() {
                                        parts.push("Slack".to_string());
                                    }
                                    if wizard.is_trello_enabled() {
                                        parts.push("Trello".to_string());
                                    }
                                    if parts.is_empty() {
                                        parts.push("All channels OFF".to_string());
                                    }
                                    format!("Channels saved — {}", parts.join(", "))
                                }
                                _ => "Settings saved.".to_string(),
                            };
                            self.push_system_message(msg);
                        }
                    }
                    self.onboarding = None;
                    if needs_rebuild && let Err(e) = self.rebuild_agent_service().await {
                        tracing::warn!("Failed to rebuild agent service: {}", e);
                        self.push_system_message(format!(
                            "Warning: Failed to reload provider: {}",
                            e
                        ));
                    }
                    if needs_rebuild {
                        // Swap the CURRENT session's per-session provider to
                        // the newly-rebuilt global. Without this, the agent
                        // service still serves the old per-session pin (set
                        // by an earlier swap_provider_for_session, e.g. from
                        // a previous /models switch), so the footer keeps
                        // showing the OLD provider while the banner reads
                        // the new GLOBAL provider — half-changed state.
                        // 2026-05-28 user report: "[Model changed to
                        // OpenRouter/qwen]" banner appeared, footer still
                        // said dialagram. Both now reflect the same change.
                        if let Some(ref session) = self.current_session {
                            let session_id = session.id;
                            let new_provider = self.agent_service.provider();
                            // Pair with the newly-configured global model.
                            let model = self.agent_service.provider_model();
                            self.agent_service.swap_provider_for_session(
                                session_id,
                                new_provider,
                                model,
                            );
                        }
                        self.sync_session_to_provider().await;
                    }
                    self.switch_mode(AppMode::Chat).await?;
                }
                WizardAction::Complete => {
                    // Apply wizard config before transitioning
                    if let Some(ref wizard) = self.onboarding {
                        match wizard.apply_config() {
                            Ok(()) => {
                                let (provider_name, model_name) = if wizard.ps.is_custom() {
                                    (
                                        format!("Custom ({})", wizard.ps.custom_name),
                                        wizard.ps.custom_model.clone(),
                                    )
                                } else {
                                    (
                                        super::onboarding::PROVIDERS[wizard.ps.selected_provider]
                                            .name
                                            .to_string(),
                                        wizard.ps.selected_model_name().to_string(),
                                    )
                                };
                                self.push_system_message(format!(
                                    "Setup complete! Provider: {} | Model: {}",
                                    provider_name, model_name
                                ));
                                // Rebuild agent service with new provider
                                if let Err(e) = self.rebuild_agent_service().await {
                                    tracing::warn!("Failed to rebuild agent service: {}", e);
                                    self.push_system_message(format!(
                                        "Warning: Failed to reload provider: {}",
                                        e
                                    ));
                                }
                            }
                            Err(e) => {
                                self.push_system_message(format!(
                                    "Setup finished with warnings: {}",
                                    e
                                ));
                            }
                        }
                    }
                    let is_first_time = self
                        .onboarding
                        .as_ref()
                        .map(|w| w.is_first_time)
                        .unwrap_or(false);
                    self.onboarding = None;
                    self.sync_session_to_provider().await;
                    self.switch_mode(AppMode::Chat).await?;

                    // First-time onboard welcome message — only on genuine fresh installs
                    if is_first_time {
                        let msg_id = Uuid::new_v4();
                        let display_msg = DisplayMessage {
                            id: msg_id,
                            role: "assistant".to_string(),
                            content: WELCOME_MESSAGE.to_string(),
                            timestamp: chrono::Utc::now(),
                            token_count: None,
                            cost: None,
                            approval: None,
                            approve_menu: None,
                            details: None,
                            expanded: false,
                            tool_group: None,
                        };
                        self.messages.push(display_msg.clone());
                        if let Some(ref session) = self.current_session {
                            let _ = self
                                .message_service
                                .create_message(
                                    session.id,
                                    "assistant".to_string(),
                                    WELCOME_MESSAGE.to_string(),
                                )
                                .await;
                        }
                    }
                }
                WizardAction::FetchModels => {
                    let provider_idx = wizard.ps.selected_provider;
                    // Resolve API key from config (keys.toml) or raw input
                    let api_key = if wizard.ps.has_existing_key_sentinel() {
                        let provider_name = super::onboarding::PROVIDERS
                            [provider_idx.min(super::onboarding::PROVIDERS.len() - 1)]
                        .name;
                        let loaded = crate::config::Config::load().ok();
                        match provider_name {
                            "Anthropic Claude" => loaded
                                .as_ref()
                                .and_then(|c| c.providers.anthropic.as_ref())
                                .and_then(|p| p.api_key.clone()),
                            "OpenAI" => loaded
                                .as_ref()
                                .and_then(|c| c.providers.openai.as_ref())
                                .and_then(|p| p.api_key.clone()),
                            "Google Gemini" => loaded
                                .as_ref()
                                .and_then(|c| c.providers.gemini.as_ref())
                                .and_then(|p| p.api_key.clone()),
                            "OpenRouter" => loaded
                                .as_ref()
                                .and_then(|c| c.providers.openrouter.as_ref())
                                .and_then(|p| p.api_key.clone()),
                            "Minimax" => loaded
                                .as_ref()
                                .and_then(|c| c.providers.minimax.as_ref())
                                .and_then(|p| p.api_key.clone()),
                            "z.ai GLM" => loaded
                                .as_ref()
                                .and_then(|c| c.providers.zhipu.as_ref())
                                .and_then(|p| p.api_key.clone()),
                            "GitHub Copilot" => loaded
                                .as_ref()
                                .and_then(|c| c.providers.github.as_ref())
                                .and_then(|p| p.api_key.clone()),
                            _ => None,
                        }
                    } else if !wizard.ps.api_key_input.is_empty() {
                        Some(wizard.ps.api_key_input.clone())
                    } else {
                        None
                    };
                    wizard.ps.models_fetching = true;

                    // Capture zhipu endpoint type from wizard state (not yet saved to config)
                    let zhipu_et = if wizard.ps.provider_id() == "zhipu" {
                        Some(if wizard.ps.zhipu_endpoint_type == 1 {
                            "coding".to_string()
                        } else {
                            "api".to_string()
                        })
                    } else {
                        None
                    };

                    let sender = self.event_sender();
                    tokio::spawn(async move {
                        let models = super::onboarding::fetch_provider_models(
                            provider_idx,
                            api_key.as_deref(),
                            zhipu_et.as_deref(),
                            None,
                        )
                        .await;
                        let _ = sender.send(TuiEvent::OnboardingModelsFetched(models));
                    });
                }
                WizardAction::GitHubDeviceFlow => {
                    wizard.github_device_flow_status =
                        super::onboarding::GitHubDeviceFlowStatus::WaitingForUser;
                    let sender = self.event_sender();
                    tokio::spawn(async move {
                        // Step 1: Request device code
                        let device =
                            match crate::brain::provider::copilot::start_device_flow().await {
                                Ok(d) => d,
                                Err(e) => {
                                    let _ = sender.send(TuiEvent::GitHubOAuthError(e.to_string()));
                                    return;
                                }
                            };

                        // Send the user code for display
                        let _ = sender.send(TuiEvent::GitHubDeviceCode(device.user_code.clone()));

                        // Step 2-3: Poll until user authorizes
                        match crate::brain::provider::copilot::poll_for_oauth_token(
                            &device.device_code,
                            device.interval,
                        )
                        .await
                        {
                            Ok(token) => {
                                let _ = sender.send(TuiEvent::GitHubOAuthComplete(token));
                            }
                            Err(e) => {
                                let _ = sender.send(TuiEvent::GitHubOAuthError(e.to_string()));
                            }
                        }
                    });
                }
                WizardAction::CodexDeviceFlow => {
                    wizard.ps.codex_device_flow_status =
                        super::onboarding::CodexDeviceFlowStatus::WaitingForUser;
                    let sender = self.event_sender();
                    tokio::spawn(async move {
                        // Step 1: Request device code
                        let device =
                            match crate::brain::provider::codex_oauth::start_device_flow().await {
                                Ok(d) => d,
                                Err(e) => {
                                    let _ = sender.send(TuiEvent::CodexOAuthError(e.to_string()));
                                    return;
                                }
                            };

                        // Send the user code for display
                        let _ = sender.send(TuiEvent::CodexDeviceCode(device.user_code.clone()));

                        // Step 2: Poll until user authorizes (returns intermediate PKCE code)
                        let device_code =
                            match crate::brain::provider::codex_oauth::poll_for_device_code(
                                &device.device_auth_id,
                                &device.user_code,
                                device.interval,
                            )
                            .await
                            {
                                Ok(dc) => dc,
                                Err(e) => {
                                    let _ = sender.send(TuiEvent::CodexOAuthError(e.to_string()));
                                    return;
                                }
                            };

                        // Step 3: Exchange PKCE code for final tokens at /oauth/token
                        match crate::brain::provider::codex_oauth::exchange_device_code_for_tokens(
                            &device_code,
                        )
                        .await
                        {
                            Ok(token_resp) => {
                                // Save tokens to disk
                                let expires_at = std::time::SystemTime::now()
                                    .duration_since(std::time::UNIX_EPOCH)
                                    .unwrap()
                                    .as_secs()
                                    + token_resp.expires_in;
                                let tokens = crate::brain::provider::codex_oauth::CodexTokens {
                                    access_token: token_resp.access_token,
                                    refresh_token: token_resp.refresh_token,
                                    id_token: token_resp.id_token,
                                    account_id: token_resp.account_id,
                                    expires_at,
                                };
                                if let Err(e) = tokens.save() {
                                    let _ = sender.send(TuiEvent::CodexOAuthError(format!(
                                        "Failed to save tokens: {}",
                                        e
                                    )));
                                    return;
                                }
                                let _ = sender.send(TuiEvent::CodexOAuthComplete);
                            }
                            Err(e) => {
                                let _ = sender.send(TuiEvent::CodexOAuthError(e.to_string()));
                            }
                        }
                    });
                }
                WizardAction::WhatsAppConnect => {
                    // Wipe session so agent shows fresh QR, then enable so
                    // ChannelManager (re)starts the single agent bot.
                    #[cfg(feature = "whatsapp")]
                    {
                        let wa_dir = crate::config::opencrabs_home().join("whatsapp");
                        let _ = std::fs::remove_file(wa_dir.join("session.db"));
                        let _ = std::fs::remove_file(wa_dir.join("session.db-wal"));
                        let _ = std::fs::remove_file(wa_dir.join("session.db-shm"));
                        let _ = crate::config::Config::write_key(
                            "channels.whatsapp",
                            "enabled",
                            "true",
                        );
                    }

                    // Subscribe to QR/connected events from the agent bot
                    #[cfg(feature = "whatsapp")]
                    let wa_state = self.whatsapp_state.clone();
                    let sender = self.event_sender();
                    tokio::spawn(async move {
                        #[cfg(feature = "whatsapp")]
                        {
                            let handle =
                                crate::brain::tools::whatsapp_connect::subscribe_whatsapp_pairing(
                                    &wa_state, false,
                                );
                            // Forward QR codes to the TUI
                            let qr_sender = sender.clone();
                            let mut qr_rx = handle.qr_rx;
                            tokio::spawn(async move {
                                while let Ok(qr) = qr_rx.recv().await {
                                    let _ = qr_sender.send(TuiEvent::WhatsAppQrCode(qr));
                                }
                            });
                            // Forward agent errors to the TUI
                            let err_sender = sender.clone();
                            let mut error_rx = handle.error_rx;
                            tokio::spawn(async move {
                                if let Ok(err) = error_rx.recv().await {
                                    let _ = err_sender.send(TuiEvent::WhatsAppError(err));
                                }
                            });
                            // Wait for connection (2 minute timeout)
                            let mut connected_rx = handle.connected_rx;
                            match tokio::time::timeout(
                                std::time::Duration::from_secs(120),
                                connected_rx.recv(),
                            )
                            .await
                            {
                                Ok(Ok(())) => {
                                    let _ = sender.send(TuiEvent::WhatsAppConnected);
                                }
                                Ok(Err(e)) => {
                                    // Broadcast channel closed — agent crashed or failed to start
                                    let msg = format!(
                                        "WhatsApp agent stopped unexpectedly: {}. Check logs at ~/.opencrabs/logs/",
                                        e
                                    );
                                    tracing::error!("{}", msg);
                                    let _ = sender.send(TuiEvent::WhatsAppError(msg));
                                }
                                Err(_) => {
                                    let _ = sender.send(TuiEvent::WhatsAppError(
                                        "QR scan timed out (2 minutes). Press R to retry.".into(),
                                    ));
                                }
                            }
                        }
                    });
                }
                WizardAction::TestWhatsApp => {
                    wizard.channel_test_status = super::onboarding::ChannelTestStatus::Testing;
                    let phone = if wizard.has_existing_whatsapp_phone() {
                        crate::config::Config::load()
                            .ok()
                            .and_then(|c| c.channels.whatsapp.allowed_phones.first().cloned())
                            .unwrap_or_default()
                    } else {
                        wizard.whatsapp_phone_input.clone()
                    };
                    #[cfg(feature = "whatsapp")]
                    let wa_state = self.whatsapp_state.clone();
                    let sender = self.event_sender();
                    let agent = self.agent_service.clone();
                    tokio::spawn(async move {
                        #[cfg(feature = "whatsapp")]
                        let result = test_whatsapp_connection(wa_state, &phone, agent).await;
                        #[cfg(not(feature = "whatsapp"))]
                        let result: Result<(), String> =
                            Err("WhatsApp feature not enabled".to_string());
                        let _ = sender.send(TuiEvent::ChannelTestResult {
                            channel: "whatsapp".to_string(),
                            success: result.is_ok(),
                            error: result.err(),
                            detected_telegram_user_id: None,
                        });
                    });
                }
                WizardAction::TestTelegram => {
                    wizard.channel_test_status = super::onboarding::ChannelTestStatus::Testing;
                    let token = if wizard.has_existing_telegram_token() {
                        crate::config::Config::load()
                            .ok()
                            .and_then(|c| c.channels.telegram.token.clone())
                            .unwrap_or_default()
                    } else {
                        wizard.telegram_token_input.clone()
                    };
                    // telegram_user_id_input is never a sentinel — always the real value.
                    let user_id_str = wizard.telegram_user_id_input.clone();
                    let sender = self.event_sender();
                    let agent = self.agent_service.clone();
                    tokio::spawn(async move {
                        let result = test_telegram_connection(&token, &user_id_str, agent).await;
                        let detected_uid = result
                            .as_ref()
                            .ok()
                            .and_then(|r| r.detected_user_id.clone());
                        let _ = sender.send(TuiEvent::ChannelTestResult {
                            channel: "telegram".to_string(),
                            success: result.is_ok(),
                            error: result.err(),
                            detected_telegram_user_id: detected_uid,
                        });
                    });
                }
                WizardAction::TestDiscord => {
                    wizard.channel_test_status = super::onboarding::ChannelTestStatus::Testing;
                    let token = if wizard.has_existing_discord_token() {
                        crate::config::Config::load()
                            .ok()
                            .and_then(|c| c.channels.discord.token.clone())
                            .unwrap_or_default()
                    } else {
                        wizard.discord_token_input.clone()
                    };
                    let channel_id = if wizard.has_existing_discord_channel_id() {
                        crate::config::Config::load()
                            .ok()
                            .and_then(|c| c.channels.discord.allowed_channels.first().cloned())
                            .unwrap_or_default()
                    } else {
                        wizard.discord_channel_id_input.clone()
                    };
                    let sender = self.event_sender();
                    let agent = self.agent_service.clone();
                    tokio::spawn(async move {
                        let result = test_discord_connection(&token, &channel_id, agent).await;
                        let _ = sender.send(TuiEvent::ChannelTestResult {
                            channel: "discord".to_string(),
                            success: result.is_ok(),
                            error: result.err(),
                            detected_telegram_user_id: None,
                        });
                    });
                }
                WizardAction::TestSlack => {
                    wizard.channel_test_status = super::onboarding::ChannelTestStatus::Testing;
                    let token = if wizard.has_existing_slack_bot_token() {
                        crate::config::Config::load()
                            .ok()
                            .and_then(|c| c.channels.slack.token.clone())
                            .unwrap_or_default()
                    } else {
                        wizard.slack_bot_token_input.clone()
                    };
                    let channel_id = if wizard.has_existing_slack_channel_id() {
                        crate::config::Config::load()
                            .ok()
                            .and_then(|c| c.channels.slack.allowed_channels.first().cloned())
                            .unwrap_or_default()
                    } else {
                        wizard.slack_channel_id_input.clone()
                    };
                    let sender = self.event_sender();
                    let agent = self.agent_service.clone();
                    tokio::spawn(async move {
                        let result = test_slack_connection(&token, &channel_id, agent).await;
                        let _ = sender.send(TuiEvent::ChannelTestResult {
                            channel: "slack".to_string(),
                            success: result.is_ok(),
                            error: result.err(),
                            detected_telegram_user_id: None,
                        });
                    });
                }
                WizardAction::TestTrello => {
                    wizard.channel_test_status = super::onboarding::ChannelTestStatus::Testing;
                    let api_key = if wizard.has_existing_trello_api_key() {
                        crate::config::Config::load()
                            .ok()
                            .and_then(|c| c.channels.trello.app_token.clone())
                            .unwrap_or_default()
                    } else {
                        wizard.trello_api_key_input.clone()
                    };
                    let api_token = if wizard.has_existing_trello_api_token() {
                        crate::config::Config::load()
                            .ok()
                            .and_then(|c| c.channels.trello.token.clone())
                            .unwrap_or_default()
                    } else {
                        wizard.trello_api_token_input.clone()
                    };
                    let sender = self.event_sender();
                    tokio::spawn(async move {
                        let result = test_trello_connection(&api_key, &api_token).await;
                        let _ = sender.send(TuiEvent::ChannelTestResult {
                            channel: "trello".to_string(),
                            success: result.is_ok(),
                            error: result.err(),
                            detected_telegram_user_id: None,
                        });
                    });
                }
                WizardAction::GenerateBrain => {
                    // Extract prompt and workspace path before dropping wizard.
                    // Brain generation runs in the background after entering chat.
                    let brain_context = self.onboarding.as_mut().map(|wizard| {
                        wizard.normalize_brain_inputs();
                        let prompt = wizard.build_brain_prompt();
                        let workspace = wizard.workspace_path.clone();
                        (prompt, workspace)
                    });

                    // Ensure provider is available (fresh install may still
                    // have PlaceholderProvider at this point).
                    if self.agent_service.provider_name() == "none" {
                        if let Some(ref wizard) = self.onboarding
                            && let Err(e) = wizard.apply_config()
                        {
                            tracing::warn!("Brain gen: apply_config before generation: {}", e);
                        }
                        if let Err(e) = self.rebuild_agent_service().await {
                            tracing::warn!("Brain gen: rebuild_agent_service failed: {}", e);
                        }
                    }

                    // Complete onboarding — go straight to chat
                    if let Some(ref wizard) = self.onboarding {
                        match wizard.apply_config() {
                            Ok(()) => {
                                let (provider_name, model_name) = if wizard.ps.is_custom() {
                                    (
                                        format!("Custom ({})", wizard.ps.custom_name),
                                        wizard.ps.custom_model.clone(),
                                    )
                                } else {
                                    (
                                        super::onboarding::PROVIDERS[wizard.ps.selected_provider]
                                            .name
                                            .to_string(),
                                        wizard.ps.selected_model_name().to_string(),
                                    )
                                };
                                self.push_system_message(format!(
                                    "Setup complete! Provider: {} | Model: {}",
                                    provider_name, model_name
                                ));
                                if let Err(e) = self.rebuild_agent_service().await {
                                    tracing::warn!("Failed to rebuild agent service: {}", e);
                                }
                            }
                            Err(e) => {
                                self.push_system_message(format!(
                                    "Setup finished with warnings: {}",
                                    e
                                ));
                            }
                        }
                    }
                    let is_first_time = self
                        .onboarding
                        .as_ref()
                        .map(|w| w.is_first_time)
                        .unwrap_or(false);
                    self.onboarding = None;
                    self.sync_session_to_provider().await;
                    self.switch_mode(AppMode::Chat).await?;

                    // First-time onboard welcome message — only on genuine fresh installs
                    if is_first_time {
                        let msg_id = Uuid::new_v4();
                        let display_msg = DisplayMessage {
                            id: msg_id,
                            role: "assistant".to_string(),
                            content: WELCOME_MESSAGE.to_string(),
                            timestamp: chrono::Utc::now(),
                            token_count: None,
                            cost: None,
                            approval: None,
                            approve_menu: None,
                            details: None,
                            expanded: false,
                            tool_group: None,
                        };
                        self.messages.push(display_msg.clone());
                        if let Some(ref session) = self.current_session {
                            let _ = self
                                .message_service
                                .create_message(
                                    session.id,
                                    "assistant".to_string(),
                                    WELCOME_MESSAGE.to_string(),
                                )
                                .await;
                        }
                    }

                    // Fire brain generation in the background
                    if let Some((prompt, workspace)) = brain_context {
                        self.push_system_message(
                            "Generating personalized brain files in the background...".to_string(),
                        );
                        self.generate_brain_files_background(prompt, workspace);
                    }
                }
                WizardAction::DownloadWhisperModel => {
                    #[cfg(feature = "local-stt")]
                    {
                        use crate::channels::voice::local_whisper::{
                            DownloadProgress, LOCAL_MODEL_PRESETS,
                        };
                        let tui_sender = self.event_sender();
                        if let Some(ref mut wizard) = self.onboarding {
                            let idx = wizard.selected_local_stt_model;
                            if idx < LOCAL_MODEL_PRESETS.len() {
                                let preset = &LOCAL_MODEL_PRESETS[idx];
                                wizard.stt_model_download_progress = Some(0.0);
                                let (progress_tx, mut progress_rx) =
                                    tokio::sync::mpsc::unbounded_channel::<DownloadProgress>();
                                let fwd_sender = tui_sender.clone();
                                tokio::spawn(async move {
                                    while let Some(p) = progress_rx.recv().await {
                                        let frac = match p.total {
                                            Some(t) if t > 0 => p.downloaded as f64 / t as f64,
                                            _ => 0.0,
                                        };
                                        let _ = fwd_sender
                                            .send(TuiEvent::WhisperDownloadProgress(frac));
                                    }
                                });
                                tokio::spawn(async move {
                                    let result =
                                        crate::channels::voice::local_whisper::download_model(
                                            preset,
                                            progress_tx,
                                        )
                                        .await;
                                    let _ = tui_sender.send(TuiEvent::WhisperDownloadComplete(
                                        result.map(|_| ()).map_err(|e| e.to_string()),
                                    ));
                                });
                            }
                        }
                    }
                }
                WizardAction::DownloadPiperVoice => {
                    #[cfg(feature = "local-tts")]
                    {
                        use crate::channels::voice::local_tts::{
                            DownloadProgress, PIPER_VOICES, delete_other_voices,
                        };
                        let tui_sender = self.event_sender();
                        if let Some(ref mut wizard) = self.onboarding {
                            let idx = wizard.selected_tts_voice;
                            if idx < PIPER_VOICES.len() {
                                let voice_id = PIPER_VOICES[idx].id.to_string();
                                delete_other_voices(&voice_id);
                                wizard.tts_voice_download_progress = Some(0.0);
                                let (progress_tx, mut progress_rx) =
                                    tokio::sync::mpsc::unbounded_channel::<DownloadProgress>();
                                let fwd_sender = tui_sender.clone();
                                tokio::spawn(async move {
                                    while let Some(p) = progress_rx.recv().await {
                                        let frac = match p.total {
                                            Some(t) if t > 0 => p.downloaded as f64 / t as f64,
                                            _ => 0.0,
                                        };
                                        let _ =
                                            fwd_sender.send(TuiEvent::PiperDownloadProgress(frac));
                                    }
                                });
                                tokio::spawn(async move {
                                    // Install Piper venv if not present
                                    if !crate::channels::voice::local_tts::piper_venv_exists() {
                                        let (setup_tx, mut setup_rx) =
                                            tokio::sync::mpsc::unbounded_channel::<
                                                crate::channels::voice::local_tts::SetupProgress,
                                            >();
                                        let setup_fwd = tui_sender.clone();
                                        tokio::spawn(async move {
                                            while let Some(p) = setup_rx.recv().await {
                                                tracing::info!("Piper setup: {}", p.stage);
                                                let _ = setup_fwd
                                                    .send(TuiEvent::PiperDownloadProgress(0.0));
                                            }
                                        });
                                        if let Err(e) =
                                            crate::channels::voice::local_tts::setup_piper_venv(
                                                setup_tx,
                                            )
                                            .await
                                        {
                                            let _ = tui_sender.send(
                                                TuiEvent::PiperDownloadComplete(Err(e.to_string())),
                                            );
                                            return;
                                        }
                                    }
                                    // Download voice model
                                    let result = crate::channels::voice::local_tts::download_voice(
                                        &voice_id,
                                        progress_tx,
                                    )
                                    .await;
                                    let _ = tui_sender.send(TuiEvent::PiperDownloadComplete(
                                        result.map(|_| voice_id.clone()).map_err(|e| e.to_string()),
                                    ));
                                });
                            }
                        }
                    }
                }
                WizardAction::None => {
                    // Stay in onboarding
                }
            }
        }
        Ok(())
    }

    /// Fire brain generation in the background. Onboarding is already done —
    /// the user is in chat. On success, writes brain files directly to workspace
    /// and notifies via `TuiEvent::BrainGenerationResult`.
    fn generate_brain_files_background(&self, prompt: String, workspace: String) {
        let provider = self.agent_service.provider().clone();
        let model = self.agent_service.provider_model().to_string();
        let sender = self.event_sender();

        let request = LLMRequest::new(model, vec![crate::brain::provider::Message::user(prompt)])
            .with_max_tokens(65536);

        tokio::spawn(async move {
            let result: Result<String, String> = match tokio::time::timeout(
                std::time::Duration::from_secs(120),
                provider.complete(request),
            )
            .await
            {
                Ok(Ok(response)) => {
                    let text: String = response
                        .content
                        .iter()
                        .filter_map(|block| {
                            if let ContentBlock::Text { text } = block {
                                Some(text.as_str())
                            } else {
                                None
                            }
                        })
                        .collect();

                    // Parse and write directly to workspace
                    let parsed = crate::tui::onboarding::parse_brain_sections(&text);

                    let names = ["SOUL", "USER", "AGENTS", "TOOLS", "MEMORY"];
                    let found: Vec<&str> = names
                        .iter()
                        .zip(parsed.iter())
                        .filter_map(|(n, p)| p.as_ref().map(|_| *n))
                        .collect();
                    let missing: Vec<&str> = names
                        .iter()
                        .zip(parsed.iter())
                        .filter_map(|(n, p)| if p.is_none() { Some(*n) } else { None })
                        .collect();
                    tracing::info!(
                        "Brain gen parsed: found=[{}], missing=[{}]",
                        found.join(", "),
                        missing.join(", ")
                    );

                    // Need at least SOUL + USER
                    if parsed[0].is_none() || parsed[0].is_none() || parsed[1].is_none() {
                        tracing::warn!(
                            "Brain gen: couldn't parse response (first 500 chars): {}",
                            &text[..text.len().min(500)]
                        );
                        Err(
                            "Couldn't parse brain files from AI response — using defaults"
                                .to_string(),
                        )
                    } else {
                        let ws = std::path::Path::new(&workspace);
                        let file_map = [
                            ("SOUL.md", &parsed[0]),
                            ("USER.md", &parsed[1]),
                            ("AGENTS.md", &parsed[2]),
                            ("TOOLS.md", &parsed[3]),
                            ("MEMORY.md", &parsed[4]),
                        ];
                        let mut written = 0;
                        for (filename, content) in &file_map {
                            if let Some(text) = content {
                                if let Err(e) = std::fs::write(ws.join(filename), text) {
                                    tracing::warn!(
                                        "Brain gen: failed to write {}: {}",
                                        filename,
                                        e
                                    );
                                } else {
                                    written += 1;
                                }
                            }
                        }
                        Ok(format!("{written} brain files personalized"))
                    }
                }
                Ok(Err(e)) => {
                    tracing::warn!("Brain generation failed: {}", e);
                    Err(format!("Brain generation failed: {}", e))
                }
                Err(_) => {
                    tracing::warn!("Brain generation timed out after 120s");
                    Err("Brain generation timed out — using defaults".to_string())
                }
            };
            let _ = sender.send(TuiEvent::BrainGenerationResult { result });
        });
    }

    /// Open file picker and populate file list.
    ///
    /// Starts at the session's working directory (not the app startup cwd).
    /// Call `refresh_file_picker()` to reload entries without resetting the dir.
    pub(crate) async fn open_file_picker(&mut self) -> Result<()> {
        // Start at the session's working directory
        self.file_picker_current_dir = self.working_directory.clone();
        self.file_picker_search.clear();
        self.file_picker_recursive = false;
        self.refresh_file_picker().await
    }

    /// Reload file list for the current directory and apply search filter.
    pub(crate) async fn refresh_file_picker(&mut self) -> Result<()> {
        self.load_flat_picker_files();
        self.file_picker_recursive = false;
        self.apply_file_picker_filter();
        self.switch_mode(AppMode::FilePicker).await?;
        Ok(())
    }

    /// Populate `file_picker_files` with a flat listing of
    /// `file_picker_current_dir` (plus a `..` entry when applicable).
    fn load_flat_picker_files(&mut self) {
        let mut files = Vec::new();

        if self.file_picker_current_dir.parent().is_some() {
            files.push(self.file_picker_current_dir.join(".."));
        }

        if let Ok(entries) = std::fs::read_dir(&self.file_picker_current_dir) {
            for entry in entries.flatten() {
                files.push(entry.path());
            }
        }

        files.sort_by(|a, b| {
            let a_is_dir = a.is_dir();
            let b_is_dir = b.is_dir();
            match (a_is_dir, b_is_dir) {
                (true, false) => std::cmp::Ordering::Less,
                (false, true) => std::cmp::Ordering::Greater,
                _ => a.file_name().cmp(&b.file_name()),
            }
        });

        self.file_picker_files = files;
    }

    /// Recursively walk the session working directory using ripgrep's
    /// `ignore` walker (respects `.gitignore`, `.ignore`, hidden file rules).
    /// Caps the result at `MAX_RECURSIVE_RESULTS` to keep huge repos snappy.
    fn load_recursive_picker_files(&mut self) {
        const MAX_RECURSIVE_RESULTS: usize = 20_000;

        let mut files = Vec::with_capacity(256);
        let walker = ignore::WalkBuilder::new(&self.working_directory)
            .standard_filters(true)
            .hidden(false)
            .git_ignore(true)
            .git_exclude(true)
            .max_depth(Some(20))
            // `.hidden(false)` keeps dotfiles like `.env` visible, but without
            // this filter we also descend into VCS metadata trees — `.git/`
            // alone can hold thousands of pack/ref files and silently eat the
            // result cap before legitimate source dirs are reached.
            .filter_entry(|e| !matches!(e.file_name().to_str(), Some(".git" | ".hg" | ".svn")))
            .build();

        for entry in walker.flatten() {
            if entry.depth() == 0 {
                continue;
            }
            if entry.file_type().is_some_and(|ft| ft.is_dir()) {
                continue;
            }
            files.push(entry.into_path());
            if files.len() >= MAX_RECURSIVE_RESULTS {
                break;
            }
        }

        files.sort();
        self.file_picker_files = files;
    }

    /// Switch the underlying file source based on the current search length:
    /// flat dir listing for `< 2` chars, recursive walk for `>= 2`. Only
    /// rebuilds when the source actually needs to change so per-keystroke
    /// filtering stays cheap.
    fn sync_file_picker_source(&mut self) {
        let wants_recursive = self.file_picker_search.chars().count() >= 2;
        if wants_recursive && !self.file_picker_recursive {
            self.load_recursive_picker_files();
            self.file_picker_recursive = true;
        } else if !wants_recursive && self.file_picker_recursive {
            self.load_flat_picker_files();
            self.file_picker_recursive = false;
        }
    }

    /// Filter the file list based on the current search query.
    /// `".."` shows when the query is empty so the user can still navigate
    /// up a directory, but drops OUT of the filtered list as soon as the
    /// user starts typing — otherwise `file_picker_selected = 0` lands on
    /// `..` instead of the first real match, and hitting Enter navigates
    /// up instead of picking the file the user was filtering for.
    ///
    /// In recursive mode the query is matched against the path **relative to
    /// the working directory** so users can filter by directory segments
    /// (e.g. `tui/render` matches `src/tui/render/dialogs.rs`).
    fn apply_file_picker_filter(&mut self) {
        let query = self.file_picker_search.to_lowercase();
        let recursive = self.file_picker_recursive;
        let working_dir = self.working_directory.clone();
        self.file_picker_filtered = if query.is_empty() {
            (0..self.file_picker_files.len()).collect()
        } else {
            self.file_picker_files
                .iter()
                .enumerate()
                .filter(|(_, path)| {
                    if path.ends_with("..") {
                        return false;
                    }
                    let haystack = if recursive {
                        path.strip_prefix(&working_dir)
                            .unwrap_or(path)
                            .to_string_lossy()
                            .to_lowercase()
                    } else {
                        path.file_name()
                            .and_then(|n| n.to_str())
                            .map(|s| s.to_lowercase())
                            .unwrap_or_default()
                    };
                    haystack.contains(&query)
                })
                .map(|(i, _)| i)
                .collect()
        };
        self.file_picker_selected = 0;
        self.file_picker_scroll_offset = 0;
    }

    /// Handle keys in file picker mode
    pub(crate) async fn handle_file_picker_key(
        &mut self,
        event: crossterm::event::KeyEvent,
    ) -> Result<()> {
        use super::events::keys;
        use crossterm::event::KeyCode;

        let filtered_len = self.file_picker_filtered.len();

        if keys::is_cancel(&event) {
            self.file_picker_search.clear();
            self.switch_mode(AppMode::Chat).await?;
        } else if keys::is_up(&event) {
            self.file_picker_selected = self.file_picker_selected.saturating_sub(1);
            if self.file_picker_selected < self.file_picker_scroll_offset {
                self.file_picker_scroll_offset = self.file_picker_selected;
            }
        } else if keys::is_down(&event) {
            if self.file_picker_selected + 1 < filtered_len {
                self.file_picker_selected += 1;
                let visible_items = 20;
                if self.file_picker_selected >= self.file_picker_scroll_offset + visible_items {
                    self.file_picker_scroll_offset = self.file_picker_selected - visible_items + 1;
                }
            }
        } else if keys::is_enter(&event) || keys::is_tab(&event) {
            // Resolve filtered index to actual file index
            if let Some(&file_idx) = self.file_picker_filtered.get(self.file_picker_selected)
                && let Some(selected_path) = self.file_picker_files.get(file_idx).cloned()
            {
                if selected_path.is_dir() {
                    if selected_path.ends_with("..") {
                        if let Some(parent) = self.file_picker_current_dir.parent() {
                            self.file_picker_current_dir = parent.to_path_buf();
                        }
                    } else {
                        self.file_picker_current_dir = selected_path;
                    }
                    self.file_picker_search.clear();
                    self.refresh_file_picker().await?;
                } else {
                    let path_str = selected_path.to_string_lossy().to_string();
                    self.input_buffer
                        .insert_str(self.cursor_position, &path_str);
                    self.cursor_position += path_str.len();
                    self.file_picker_search.clear();
                    self.switch_mode(AppMode::Chat).await?;
                }
            }
        } else if event.code == KeyCode::Backspace {
            if self.file_picker_search.pop().is_some() {
                self.sync_file_picker_source();
                self.apply_file_picker_filter();
            }
        } else if let KeyCode::Char(c) = event.code {
            self.file_picker_search.push(c);
            self.sync_file_picker_source();
            self.apply_file_picker_filter();
        }

        Ok(())
    }

    /// Open directory picker (reuses file picker state, dirs only)
    pub(crate) async fn open_directory_picker(&mut self) -> Result<()> {
        let mut files = Vec::new();

        // Add parent directory option if not at root
        if self.file_picker_current_dir.parent().is_some() {
            files.push(self.file_picker_current_dir.join(".."));
        }

        // Read directory entries — directories only
        if let Ok(entries) = std::fs::read_dir(&self.file_picker_current_dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                if path.is_dir() {
                    files.push(path);
                }
            }
        }

        // Sort alphabetically
        files.sort_by(|a, b| a.file_name().cmp(&b.file_name()));

        self.file_picker_files = files;
        self.file_picker_selected = 0;
        self.file_picker_scroll_offset = 0;
        self.switch_mode(AppMode::DirectoryPicker).await?;

        Ok(())
    }

    /// Handle keys in directory picker mode
    pub(crate) async fn handle_directory_picker_key(
        &mut self,
        event: crossterm::event::KeyEvent,
    ) -> Result<()> {
        use super::events::keys;
        use crossterm::event::KeyCode;

        if keys::is_cancel(&event) {
            self.switch_mode(AppMode::Chat).await?;
        } else if keys::is_up(&event) {
            self.file_picker_selected = self.file_picker_selected.saturating_sub(1);
            if self.file_picker_selected < self.file_picker_scroll_offset {
                self.file_picker_scroll_offset = self.file_picker_selected;
            }
        } else if keys::is_down(&event) {
            if self.file_picker_selected + 1 < self.file_picker_files.len() {
                self.file_picker_selected += 1;
                let visible_items = 20;
                if self.file_picker_selected >= self.file_picker_scroll_offset + visible_items {
                    self.file_picker_scroll_offset = self.file_picker_selected - visible_items + 1;
                }
            }
        } else if keys::is_enter(&event) {
            // Enter navigates into directory
            if let Some(selected_path) = self
                .file_picker_files
                .get(self.file_picker_selected)
                .cloned()
            {
                if selected_path.ends_with("..") {
                    if let Some(parent) = self.file_picker_current_dir.parent() {
                        self.file_picker_current_dir = parent.to_path_buf();
                    }
                } else {
                    self.file_picker_current_dir = selected_path;
                }
                self.open_directory_picker().await?;
            }
        } else if event.code == KeyCode::Tab || event.code == KeyCode::Char(' ') {
            // Tab/Space selects the current directory as working dir
            let selected_dir = self.file_picker_current_dir.clone();
            let canonical = selected_dir
                .canonicalize()
                .unwrap_or_else(|_| selected_dir.clone());

            // Update App working directory
            self.working_directory = canonical.clone();

            // Update AgentService working directory (runtime)
            self.agent_service.set_working_directory(canonical.clone());

            // Persist to session DB — that's the source of truth for per-session WD.
            if let Some(ref session) = self.current_session {
                let _ = self
                    .session_service
                    .update_session_working_directory(
                        session.id,
                        Some(canonical.to_string_lossy().to_string()),
                    )
                    .await;
            }

            self.push_system_message(format!(
                "Working directory changed to: {}",
                canonical.display()
            ));

            // Queue context hint so the next message to the LLM knows about the cd
            self.pending_context.push(format!(
                "[User changed working directory to: {}]",
                canonical.display()
            ));

            self.switch_mode(AppMode::Chat).await?;
        }

        Ok(())
    }

    /// Open the usage dashboard — fetch data and populate state
    pub(crate) async fn open_usage_dashboard(&mut self) {
        use crate::usage::dashboard::DashboardState;
        use crate::usage::data::{DashboardData, Period};

        let period = self
            .dashboard_state
            .as_ref()
            .map(|s| s.period)
            .unwrap_or(Period::AllTime);

        let data = if let Some(pool) = crate::db::global_pool() {
            DashboardData::fetch(pool, period).await.unwrap_or_default()
        } else {
            DashboardData::default()
        };

        self.dashboard_state = Some(DashboardState {
            period,
            focused_card: 0,
            data,
        });
    }

    /// Update dashboard period and re-fetch data
    pub(crate) async fn set_dashboard_period(&mut self, period: crate::usage::data::Period) {
        if let Some(ds) = &mut self.dashboard_state
            && ds.set_period(period)
            && let Some(pool) = crate::db::global_pool()
            && let Ok(data) = crate::usage::data::DashboardData::fetch(pool, period).await
        {
            ds.data = data;
        }
    }
}

/// Download WhisperCrabs binary if not cached, return the path to the binary.
pub(crate) async fn ensure_whispercrabs() -> Result<PathBuf> {
    let bin_dir = crate::config::opencrabs_home().join("bin");
    std::fs::create_dir_all(&bin_dir)?;

    let binary_name = if cfg!(target_os = "windows") {
        "whispercrabs.exe"
    } else {
        "whispercrabs"
    };
    let binary_path = bin_dir.join(binary_name);

    if binary_path.exists() {
        return Ok(binary_path);
    }

    // Detect platform
    let (os_name, ext) = match std::env::consts::OS {
        "linux" => ("linux", "tar.gz"),
        "macos" => ("macos", "tar.gz"),
        "windows" => ("windows", "zip"),
        other => anyhow::bail!("Unsupported OS: {}", other),
    };
    let arch = std::env::consts::ARCH; // "x86_64" or "aarch64"

    // Download latest release via GitHub API
    let client = reqwest::Client::new();
    let release_url = "https://api.github.com/repos/adolfousier/whispercrabs/releases/latest";
    let release: serde_json::Value = client
        .get(release_url)
        .header("User-Agent", "opencrabs")
        .send()
        .await?
        .json()
        .await?;

    // Find matching asset
    let pattern = format!("whispercrabs-{}-{}", os_name, arch);
    let asset = release["assets"]
        .as_array()
        .and_then(|assets| {
            assets
                .iter()
                .find(|a| a["name"].as_str().is_some_and(|n| n.contains(&pattern)))
        })
        .ok_or_else(|| anyhow::anyhow!("No release found for {}-{}", os_name, arch))?;

    let download_url = asset["browser_download_url"]
        .as_str()
        .ok_or_else(|| anyhow::anyhow!("Missing download URL in release asset"))?;

    // Download the archive
    let bytes = client
        .get(download_url)
        .header("User-Agent", "opencrabs")
        .send()
        .await?
        .bytes()
        .await?;

    // Extract (tar.gz for Linux/macOS, zip for Windows)
    let tmp = bin_dir.join("whispercrabs_download");
    std::fs::write(&tmp, &bytes)?;

    if ext == "tar.gz" {
        let output = tokio::process::Command::new("tar")
            .args([
                "xzf",
                &tmp.to_string_lossy(),
                "-C",
                &bin_dir.to_string_lossy(),
            ])
            .output()
            .await?;
        if !output.status.success() {
            let _ = std::fs::remove_file(&tmp);
            anyhow::bail!("Failed to extract archive");
        }
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&binary_path, std::fs::Permissions::from_mode(0o755))?;
        }
    }

    // Clean up temp file
    let _ = std::fs::remove_file(&tmp);

    if !binary_path.exists() {
        anyhow::bail!("Binary not found after extraction — archive may use a different layout");
    }

    Ok(binary_path)
}

/// Result of a Telegram test connection attempt.
struct TelegramTestResult {
    /// Auto-detected user ID from getUpdates (set when user_id was empty)
    detected_user_id: Option<String>,
}

/// Test Telegram connection: validate token, auto-detect user ID, send greeting.
#[cfg(feature = "telegram")]
async fn test_telegram_connection(
    token: &str,
    user_id_str: &str,
    agent: std::sync::Arc<crate::brain::agent::AgentService>,
) -> Result<TelegramTestResult, String> {
    use teloxide::prelude::Requester;

    // Step 1: Validate the bot token with getMe
    let bot = teloxide::Bot::new(token);
    let me = bot.get_me().await.map_err(|e| {
        let msg = e.to_string();
        if msg.contains("Unauthorized") || msg.contains("401") {
            "Invalid bot token. Make sure you copied the full token from @BotFather.".to_string()
        } else if msg.contains("Forbidden") || msg.contains("403") {
            "Telegram rejected this token (Forbidden). Check you copied it correctly.".to_string()
        } else if msg.contains("Not Found") || msg.contains("404") {
            "Token not recognized by Telegram. It should look like 123456789:ABCdef...".to_string()
        } else {
            format!("Failed to verify bot token: {}", msg)
        }
    })?;

    tracing::info!(
        "Telegram bot token validated: @{}",
        me.username.as_deref().unwrap_or_default()
    );

    // Step 2: Resolve user ID — auto-detect via getUpdates if empty
    let trimmed = user_id_str.trim();
    let user_id: i64 = if trimmed.is_empty() {
        // Auto-detect: call getUpdates to find the most recent user who messaged the bot
        match bot.get_updates().await {
            Ok(updates) => {
                // Find the most recent message from a non-bot user
                let detected = updates.iter().rev().find_map(|u| {
                    if let teloxide::types::UpdateKind::Message(ref m) = u.kind {
                        if !m.from.as_ref().is_some_and(|f| f.is_bot) {
                            Some(m.chat.id.0)
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                });
                match detected {
                    Some(id) => {
                        tracing::info!("Telegram: auto-detected user ID {} from getUpdates", id);
                        id
                    }
                    None => {
                        return Err(
                            "No messages found for this bot yet. Message your bot on                              Telegram first (send any text), then retry. Your chat ID                              will be auto-detected."
                                .to_string(),
                        );
                    }
                }
            }
            Err(e) => {
                return Err(format!(
                    "Could not check for messages (getUpdates failed: {}).                      Paste your numeric chat ID manually.                      Message @userinfobot on Telegram to get it.",
                    e
                ));
            }
        }
    } else {
        trimmed
            .parse()
            .map_err(|_| format!("Invalid chat ID '{}': must be a numeric ID.", trimmed))?
    };

    // Reject the bot's own numeric ID
    if me.id.0 as i64 == user_id {
        return Err(
            "That's the bot's own ID, not yours. Open Telegram, message              @userinfobot, and paste the numeric ID it replies with."
                .to_string(),
        );
    }

    // Step 3: Send greeting
    let greeting = crate::channels::generate_connection_greeting(&agent, "Telegram").await;
    bot.send_message(teloxide::types::ChatId(user_id), greeting)
        .await
        .map_err(|e| {
            let msg = e.to_string();
            if msg.contains("chat not found") {
                format!(
                    "Chat ID {} not found. You must message your bot first                      so it can reply to you. Open Telegram, find @{},                      send it any message, then retry.",
                    user_id,
                    me.username
                        .as_deref()
                        .unwrap_or("your_bot")
                )
            } else if msg.contains("bot was blocked") {
                "You blocked the bot. Unblock it in Telegram and retry.".to_string()
            } else {
                format!("Telegram API error: {}", msg)
            }
        })?;

    // Return detected user ID if we auto-detected it
    let detected_user_id = if trimmed.is_empty() {
        Some(user_id.to_string())
    } else {
        None
    };

    Ok(TelegramTestResult { detected_user_id })
}

#[cfg(not(feature = "telegram"))]
async fn test_telegram_connection(
    _token: &str,
    _user_id_str: &str,
    _agent: std::sync::Arc<crate::brain::agent::AgentService>,
) -> Result<(), String> {
    Err("Telegram feature not enabled".to_string())
}

/// Test Discord connection by sending a message to a channel.
#[cfg(feature = "discord")]
async fn test_discord_connection(
    token: &str,
    channel_id_str: &str,
    agent: std::sync::Arc<crate::brain::agent::AgentService>,
) -> Result<(), String> {
    let channel_id: u64 = channel_id_str
        .parse()
        .map_err(|_| format!("Invalid channel ID: {}", channel_id_str))?;
    let greeting = crate::channels::generate_connection_greeting(&agent, "Discord").await;
    let http = serenity::http::Http::new(token);
    let channel = serenity::model::id::ChannelId::new(channel_id);
    channel
        .say(&http, greeting)
        .await
        .map_err(|e| format!("Discord API error: {}", e))?;
    Ok(())
}

#[cfg(not(feature = "discord"))]
async fn test_discord_connection(
    _token: &str,
    _channel_id_str: &str,
    _agent: std::sync::Arc<crate::brain::agent::AgentService>,
) -> Result<(), String> {
    Err("Discord feature not enabled".to_string())
}

/// Test Slack connection by posting a message to a channel.
#[cfg(feature = "slack")]
async fn test_slack_connection(
    token: &str,
    channel_id: &str,
    agent: std::sync::Arc<crate::brain::agent::AgentService>,
) -> Result<(), String> {
    use slack_morphism::prelude::*;

    let greeting = crate::channels::generate_connection_greeting(&agent, "Slack").await;
    let client = SlackClient::new(
        SlackClientHyperConnector::new().map_err(|e| format!("Slack client error: {}", e))?,
    );
    let api_token = SlackApiToken::new(SlackApiTokenValue::from(token.to_string()));
    let session = client.open_session(&api_token);
    let request = SlackApiChatPostMessageRequest::new(
        SlackChannelId::new(channel_id.to_string()),
        SlackMessageContent::new().with_text(greeting),
    );
    session
        .chat_post_message(&request)
        .await
        .map_err(|e| format!("Slack API error: {}", e))?;
    Ok(())
}

#[cfg(not(feature = "slack"))]
async fn test_slack_connection(
    _token: &str,
    _channel_id: &str,
    _agent: std::sync::Arc<crate::brain::agent::AgentService>,
) -> Result<(), String> {
    Err("Slack feature not enabled".to_string())
}

/// Test WhatsApp connection by sending a message using the paired bot's client.
#[cfg(feature = "whatsapp")]
async fn test_whatsapp_connection(
    wa_state: std::sync::Arc<crate::channels::whatsapp::WhatsAppState>,
    phone: &str,
    agent: std::sync::Arc<crate::brain::agent::AgentService>,
) -> Result<(), String> {
    // Wait for the agent bot to be connected (up to 15 seconds)
    let client = {
        let mut client = wa_state.client().await;
        if client.is_none() {
            for _ in 0..30 {
                tokio::time::sleep(std::time::Duration::from_millis(500)).await;
                client = wa_state.client().await;
                if client.is_some() {
                    break;
                }
            }
        }
        client
            .ok_or_else(|| "WhatsApp not connected. Please scan the QR code first.".to_string())?
    };

    if phone.is_empty() {
        return Err("No phone number provided.".to_string());
    }

    let jid_str = format!("{}@s.whatsapp.net", phone.trim_start_matches('+'));
    let jid: wacore_binary::jid::Jid = jid_str
        .parse()
        .map_err(|e| format!("Invalid phone number format: {}", e))?;

    let greeting = crate::channels::generate_connection_greeting(&agent, "WhatsApp").await;
    let wa_msg = waproto::whatsapp::Message {
        conversation: Some(format!(
            "{}\n\n{}",
            crate::channels::whatsapp::handler::MSG_HEADER,
            greeting
        )),
        ..Default::default()
    };

    client
        .send_message(jid, wa_msg)
        .await
        .map_err(|e| format!("WhatsApp send error: {}", e))?;

    Ok(())
}

#[cfg(feature = "trello")]
async fn test_trello_connection(api_key: &str, api_token: &str) -> Result<(), String> {
    let client = crate::channels::trello::TrelloClient::new(api_key, api_token);
    client
        .get_member_me()
        .await
        .map(|_me| ())
        .map_err(|e| format!("Trello API error: {}", e))
}

#[cfg(not(feature = "trello"))]
async fn test_trello_connection(_api_key: &str, _api_token: &str) -> Result<(), String> {
    Err("Trello feature not enabled".to_string())
}