opencrabs 0.3.47

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
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
//! TUI Application State
//!
//! Core state management for the terminal user interface.

use super::events::{
    AppMode, EventHandler, SshPasswordRequest, SshPasswordResponse, SudoPasswordRequest,
    SudoPasswordResponse, ToolApprovalRequest, ToolApprovalResponse, TuiEvent,
};

/// Live tok/s accumulator for the footer field.
///
/// Tracks ACTIVE streaming time (windows where token deltas are arriving
/// continuously) and stashes the last finalized rate so the footer keeps
/// showing the previous turn's tok/s during idle until the next turn
/// produces its first token. Excludes tool execution waits, approval
/// prompts, between-stream network round-trips — anything more than 1s
/// without a token closes the current window.
///
/// 2026-05-28 user report: pre-tracker the footer divided streaming
/// tokens by full wall-clock elapsed, so a 30s tool exec turned a
/// 200 tok/s burst into "8 tok/s" mid-turn.
#[derive(Debug, Clone, Default)]
pub struct StreamingTpsTracker {
    /// Accumulated active streaming seconds for the current turn.
    active_secs: f64,
    /// Instant the current open window started.
    window_start: Option<std::time::Instant>,
    /// Instant of the most recent advance() call (= last token event).
    last_token_at: Option<std::time::Instant>,
    /// Last finalized tok/s value. Persists across idle until the next
    /// finalize().
    pub last_tps: Option<f64>,
}

impl StreamingTpsTracker {
    /// A gap longer than this between consecutive token events closes
    /// the current active window. Tool execution, approval waits, and
    /// between-response network round-trips all exceed this threshold,
    /// so they're correctly excluded from the rate denominator.
    const IDLE_GAP_SECS: f64 = 1.0;

    /// Call on every `StreamingOutputTokens` event after incrementing
    /// the token counter. `now` is `Instant::now()` (parameterized so
    /// tests can drive the clock deterministically).
    pub fn advance(&mut self, now: std::time::Instant) {
        match (self.window_start, self.last_token_at) {
            (None, _) => {
                // First token this turn — open a window starting now.
                self.window_start = Some(now);
            }
            (Some(start), Some(last)) => {
                if (now - last).as_secs_f64() > Self::IDLE_GAP_SECS {
                    // Idle gap — close the prior window and open a new one.
                    self.active_secs += (last - start).as_secs_f64();
                    self.window_start = Some(now);
                }
                // else: still inside the active window.
            }
            (Some(_), None) => {
                // window_start without last_token: shouldn't normally
                // happen but be safe — reset window start to `now`.
                self.window_start = Some(now);
            }
        }
        self.last_token_at = Some(now);
    }

    /// Total active seconds so far, including the currently-open
    /// window if any. Window time is always measured between window
    /// start and the LAST token event — never extended to `now`, so
    /// idle ticks past the last token don't inflate the rate.
    pub fn active_secs_now(&self, _now: std::time::Instant) -> f64 {
        let in_flight = match (self.window_start, self.last_token_at) {
            (Some(start), Some(last)) => (last - start).as_secs_f64().max(0.0),
            _ => 0.0,
        };
        self.active_secs + in_flight
    }

    /// Stash the just-finished turn's rate as `last_tps` and reset the
    /// accumulator for the next turn. A turn with zero tokens leaves
    /// `last_tps` untouched (preserves the previous visible rate).
    ///
    /// `authoritative` is the agent service's computed tok/s from
    /// `AgentResponse.tokens_per_second` — provider-reported output
    /// tokens divided by summed per-iteration active streaming time.
    /// When present, it overrides the local tiktoken-estimated rate
    /// because (a) tiktoken's cl100k_base tokenizer over-counts
    /// Qwen/Kimi/GLM bytes by ~1.5-2×, and (b) the local window
    /// covers only the visible final-message streaming, not earlier
    /// tool-call-iteration streaming. When `None` (CLI providers, or
    /// any turn where the streaming layer couldn't measure active
    /// time) we fall back to the local estimate so the footer
    /// continues to show something rather than going blank.
    pub fn finalize(&mut self, total_tokens: u32, authoritative: Option<f64>) {
        let active = match (self.window_start, self.last_token_at) {
            (Some(start), Some(last)) => self.active_secs + (last - start).as_secs_f64().max(0.0),
            _ => self.active_secs,
        };
        if let Some(tps) = authoritative.filter(|t| t.is_finite() && *t > 0.0) {
            self.last_tps = Some(tps);
        } else if total_tokens > 0 && active > 0.0 {
            self.last_tps = Some(total_tokens as f64 / active);
        }
        self.active_secs = 0.0;
        self.window_start = None;
        self.last_token_at = None;
    }
}
use super::onboarding::OnboardingWizard;
use super::prompt_analyzer::PromptAnalyzer;
use crate::brain::agent::AgentService;
use crate::brain::provider::Provider;
use crate::brain::{BrainLoader, CommandLoader, SelfUpdater, UserCommand};
use crate::db::models::{Message, Session};
use crate::services::{FileService, MessageService, ServiceContext, SessionService};
use crate::tui::pane::PaneManager;
use anyhow::Result;
use ratatui::text::Line;
use serde_json::Value;
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use uuid::Uuid;

/// Slash command definition
#[derive(Debug, Clone)]
pub struct SlashCommand {
    pub name: &'static str,
    pub description: &'static str,
}

/// Available slash commands for autocomplete
pub const SLASH_COMMANDS: &[SlashCommand] = &[
    SlashCommand {
        name: "/help",
        description: "Show available commands",
    },
    SlashCommand {
        name: "/models",
        description: "Switch model",
    },
    SlashCommand {
        name: "/usage",
        description: "Session usage stats",
    },
    SlashCommand {
        name: "/mission-control",
        description: "Mission control: analytics, activity, inbox & schedule",
    },
    SlashCommand {
        name: "/onboard",
        description: "Run setup wizard",
    },
    SlashCommand {
        name: "/onboard:provider",
        description: "Jump to AI provider setup",
    },
    SlashCommand {
        name: "/onboard:workspace",
        description: "Jump to workspace settings",
    },
    SlashCommand {
        name: "/onboard:channels",
        description: "Setup Telegram, Slack, Discord, WhatsApp, Trello",
    },
    SlashCommand {
        name: "/onboard:voice",
        description: "Jump to voice STT/TTS setup",
    },
    SlashCommand {
        name: "/onboard:image",
        description: "Jump to image handling setup (vision + generation)",
    },
    SlashCommand {
        name: "/onboard:brain",
        description: "Jump to brain/persona setup",
    },
    SlashCommand {
        name: "/doctor",
        description: "Run connection health check",
    },
    SlashCommand {
        name: "/cowork",
        description: "Create a Telegram cowork workspace (QR + deep link)",
    },
    SlashCommand {
        name: "/new",
        description: "Start a new session",
    },
    SlashCommand {
        name: "/sessions",
        description: "List all sessions",
    },
    SlashCommand {
        name: "/approve",
        description: "Tool approval policy",
    },
    SlashCommand {
        name: "/compact",
        description: "Compact context now",
    },
    SlashCommand {
        name: "/rebuild",
        description: "Build & restart from source",
    },
    SlashCommand {
        name: "/evolve",
        description: "Download latest release & restart",
    },
    SlashCommand {
        name: "/whisper",
        description: "Speak anywhere, paste to clipboard",
    },
    SlashCommand {
        name: "/cd",
        description: "Change working directory",
    },
    SlashCommand {
        name: "/skills",
        description: "Browse and run loaded skills",
    },
    SlashCommand {
        name: "/rtk",
        description: "Show RTK token savings statistics",
    },
];

/// Approval option selected by the user
#[derive(Debug, Clone, PartialEq)]
pub enum ApprovalOption {
    AllowOnce,
    AllowForSession,
    AllowAlways,
}

/// State of an inline approval request
#[derive(Debug, Clone, PartialEq)]
pub enum ApprovalState {
    Pending,
    Approved(ApprovalOption),
    Denied(String),
}

/// Data for an inline tool approval request embedded in a DisplayMessage
#[derive(Debug, Clone)]
pub struct ApprovalData {
    pub tool_name: String,
    pub tool_description: String,
    pub tool_input: Value,
    pub capabilities: Vec<String>,
    pub request_id: Uuid,
    pub response_tx: mpsc::UnboundedSender<ToolApprovalResponse>,
    pub requested_at: std::time::Instant,
    pub state: ApprovalState,
    /// 0-2, arrow key navigation
    pub selected_option: usize,
    /// V key toggle
    pub show_details: bool,
}

/// State for the /approve policy selector menu
#[derive(Debug, Clone, PartialEq)]
pub enum ApproveMenuState {
    Pending,
    Selected(usize),
}

/// Data for the /approve inline menu
#[derive(Debug, Clone)]
pub struct ApproveMenu {
    /// 0-2
    pub selected_option: usize,
    pub state: ApproveMenuState,
}

/// A file attached to the input (detected from pasted paths). Despite the
/// historical name, this now also covers videos — `is_video` selects which
/// marker the input pipeline emits (`<<VID:>>` vs `<<IMG:>>`).
#[derive(Debug, Clone)]
pub struct ImageAttachment {
    /// Display name (file name)
    pub name: String,
    /// Full path to the image or video
    pub path: String,
    /// True when the attachment is a video — tells the send pipeline to
    /// emit `<<VID:>>` so the agent calls `analyze_video` instead of
    /// `analyze_image`.
    pub is_video: bool,
}

/// Image file extensions for auto-detection
pub(crate) const IMAGE_EXTENSIONS: &[&str] =
    &[".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".svg"];

/// Video file extensions for auto-detection — must match the MIME table in
/// `utils::file_extract::mime_from_ext` so channels and TUI agree on what
/// counts as a video.
pub(crate) const VIDEO_EXTENSIONS: &[&str] = &[
    ".mp4", ".m4v", ".mov", ".webm", ".mkv", ".avi", ".3gp", ".flv",
];

/// Text file extensions for auto-detection (paste a path → inline content)
pub(crate) const TEXT_EXTENSIONS: &[&str] = &[
    ".txt", ".md", ".rst", ".log", ".json", ".yaml", ".yml", ".toml", ".xml", ".csv", ".tsv",
    ".js", ".mjs", ".ts", ".py", ".rb", ".sh", ".rs", ".go", ".java", ".c", ".cpp", ".h", ".html",
    ".htm", ".css", ".sql",
];

/// Document extensions for auto-detection (paste a path → the agent is given
/// the path and told to call `parse_document` / `pdf_to_images`). Binary
/// formats, so we never inline their bytes — only surface the path.
pub(crate) const DOC_EXTENSIONS: &[&str] = &[".pdf", ".docx", ".doc", ".pptx", ".xlsx", ".epub"];

/// A single tool call entry within a grouped display
#[derive(Debug, Clone)]
pub struct ToolCallEntry {
    pub description: String,
    pub success: bool,
    pub details: Option<String>,
    /// Whether the tool has finished executing
    pub completed: bool,
    /// Full raw tool input — shown untruncated in expanded view
    pub tool_input: serde_json::Value,
}

/// A group of tool calls displayed as a collapsible bullet
#[derive(Debug, Clone)]
pub struct ToolCallGroup {
    pub calls: Vec<ToolCallEntry>,
    pub expanded: bool,
}

/// Display message for UI rendering
#[derive(Debug, Clone)]
pub struct DisplayMessage {
    pub id: Uuid,
    pub role: String,
    pub content: String,
    pub timestamp: chrono::DateTime<chrono::Utc>,
    pub token_count: Option<i32>,
    pub cost: Option<f64>,
    pub approval: Option<ApprovalData>,
    pub approve_menu: Option<ApproveMenu>,
    /// Collapsible details (tool output, etc.) — shown when expanded
    pub details: Option<String>,
    /// Whether details are currently expanded
    pub expanded: bool,
    /// Grouped tool calls (for role == "tool_group")
    pub tool_group: Option<ToolCallGroup>,
}

impl From<Message> for DisplayMessage {
    fn from(msg: Message) -> Self {
        Self {
            id: msg.id,
            role: msg.role,
            content: msg.content,
            timestamp: msg.created_at,
            token_count: msg.token_count,
            cost: msg.cost,
            approval: None,
            approve_menu: None,
            details: msg.thinking,
            expanded: false,
            tool_group: None,
        }
    }
}

/// Main application state
pub struct App {
    /// Core state
    pub current_session: Option<Session>,
    pub messages: Vec<DisplayMessage>,
    pub sessions: Vec<Session>,
    /// All-time usage stats from the ledger (survives session deletes)
    pub usage_ledger_stats: Vec<crate::db::repository::usage_ledger::ModelUsageStats>,
    /// Usage dashboard state (populated when /usage is opened)
    pub dashboard_state: Option<crate::usage::dashboard::DashboardState>,

    /// UI state
    pub mode: AppMode,
    pub input_buffer: String,
    /// Cursor position within input_buffer (byte offset, always on a char boundary)
    pub cursor_position: usize,
    /// Images attached to the current input (auto-detected from pasted paths)
    pub attachments: Vec<ImageAttachment>,
    /// When Some, an attachment is focused (Up/Down to navigate, Backspace/Delete to remove).
    /// Index into `attachments`. None means input text is focused.
    pub focused_attachment: Option<usize>,
    pub scroll_offset: usize,
    /// Previous frame's total rendered line count — used to adjust scroll_offset
    /// when streaming adds lines while user is scrolled up, preventing the view
    /// from drifting downward one line per chunk.
    pub prev_rendered_lines: usize,
    /// When true, new streaming content auto-scrolls to bottom.
    /// Set to false when user scrolls up; re-enabled when they scroll back to bottom or send a message.
    pub auto_scroll: bool,
    /// When false, the runner releases terminal mouse capture so the user can
    /// drag-select text natively (terminal handles selection + clipboard).
    /// Toggled with F12. Defaults to true (mouse capture on).
    pub mouse_capture_enabled: bool,
    pub selected_session_index: usize,
    pub should_quit: bool,
    /// Pending resize dimensions — runner pre-resizes buffers to avoid blink
    pub pending_resize: Option<(u16, u16)>,

    /// Streaming state
    pub is_processing: bool,
    pub processing_started_at: Option<std::time::Instant>,
    pub streaming_response: Option<String>,
    /// Cached parsed markdown lines for the streaming response — avoids
    /// re-parsing the entire growing buffer on every render frame.
    /// Invalidated when streaming_response length changes.
    pub(crate) streaming_render_cache: Option<(usize, Vec<ratatui::text::Line<'static>>)>,
    /// Reasoning/thinking content from providers like MiniMax (display-only, cleared on complete)
    pub streaming_reasoning: Option<String>,
    pub error_message: Option<String>,
    /// When error_message was set — used to auto-dismiss after 2.5s
    pub error_message_shown_at: Option<std::time::Instant>,
    /// Transient notification (non-error, e.g. "Copied to clipboard")
    pub notification: Option<String>,
    pub notification_shown_at: Option<std::time::Instant>,
    /// Currently selected message index (left-click to select, right-click to copy)
    pub selected_message_idx: Option<usize>,
    /// Set to true when IntermediateText arrives during the current response cycle.
    /// Reset to false at the start of each new send_message call.
    /// Used in complete_response to avoid double-adding the assistant message.
    pub(crate) intermediate_text_received: bool,

    /// Rolling build output lines (last 6, cleared on RestartReady)
    pub(crate) build_lines: Vec<String>,
    /// Index of the build-progress DisplayMessage (updated in place)
    pub(crate) build_msg_idx: Option<usize>,

    /// Animation state
    pub animation_frame: usize,

    /// Escape confirmation state (double-press to clear)
    pub(crate) escape_pending_at: Option<std::time::Instant>,

    /// Ctrl+C confirmation state (first clears input, second quits)
    pub(crate) ctrl_c_pending_at: Option<std::time::Instant>,

    /// Help/Settings scroll offset
    pub help_scroll_offset: usize,

    /// Model name for display (from provider default)
    pub default_model_name: String,

    /// Approval policy state
    pub approval_auto_session: bool,
    pub approval_auto_always: bool,

    /// File picker state
    pub file_picker_files: Vec<std::path::PathBuf>,
    pub file_picker_filtered: Vec<usize>,
    pub file_picker_selected: usize,
    pub file_picker_scroll_offset: usize,
    pub file_picker_current_dir: std::path::PathBuf,
    /// Whether the directory/file picker shows dotfiles (hidden entries).
    /// Off by default (clean view, like Finder); toggled with `.` in the picker.
    pub file_picker_show_hidden: bool,
    pub file_picker_search: String,
    /// True when `file_picker_files` holds a recursive walk of the working
    /// directory rather than a flat listing of `file_picker_current_dir`.
    /// Flips on once the search query reaches 2 characters and flips off
    /// when the query falls back below the threshold or the picker reopens.
    pub file_picker_recursive: bool,

    /// Slash autocomplete state
    pub slash_suggestions_active: bool,
    /// Indices into SLASH_COMMANDS
    pub slash_filtered: Vec<usize>,
    pub slash_selected_index: usize,

    /// Emoji picker state
    pub emoji_picker_active: bool,
    /// (emoji char, shortcode) pairs matching current query
    pub emoji_filtered: Vec<(&'static str, &'static str)>,
    pub emoji_selected_index: usize,
    /// Byte offset in input_buffer where the `:` trigger starts
    pub emoji_colon_offset: usize,

    /// Session rename state
    pub session_renaming: bool,
    pub session_rename_buffer: String,

    /// Session search/filter state (activated with `/` in /sessions)
    pub session_search: String,
    pub session_search_active: bool,
    /// Viewport scroll offset for session list (first visible session index)
    pub sessions_scroll: usize,

    /// Model selector state (shared with onboarding via ProviderSelectorState)
    pub ps: crate::tui::provider_selector::ProviderSelectorState,

    /// Input history (arrow up/down to cycle through past messages)
    pub(crate) input_history: Vec<String>,
    /// None = not browsing, Some(i) = viewing history[i]
    pub(crate) input_history_index: Option<usize>,
    /// Saves current input when entering history
    pub(crate) input_history_stash: String,

    /// Working directory
    pub working_directory: std::path::PathBuf,

    /// Context hints queued by UI actions (e.g. /cd, @ file picker).
    /// Drained and prepended to the next user message so the LLM knows
    /// what just happened without the user having to explain.
    pub pending_context: Vec<String>,

    /// Brain state
    pub brain_path: PathBuf,
    pub user_commands: Vec<UserCommand>,
    /// Loaded skills (built-in + user overlay) — auto-registered as `/<name>`
    /// in the slash autocomplete and dispatched as `action=prompt`.
    pub skills: Vec<crate::brain::skills::Skill>,

    /// Mission Control state — focused panel, selection, scroll, popup.
    /// Single struct so `AppState` only carries one MC field; everything
    /// else (input, actions) lives in `tui::app::mission_control`.
    pub mc: crate::tui::app::mission_control::McState,
    /// Skills dialog state — filter buffer, selection, scroll. Same
    /// "single-struct field" pattern as MC.
    pub skills_dialog: crate::tui::app::skills_dialog::SkillsDialogState,

    /// Onboarding wizard state
    pub onboarding: Option<OnboardingWizard>,
    pub force_onboard: bool,

    /// Sessions currently processing (have in-flight agent tasks)
    pub(crate) processing_sessions: HashSet<Uuid>,
    /// Per-session cancel tokens
    pub(crate) session_cancel_tokens: HashMap<Uuid, CancellationToken>,
    /// Sessions that completed while user was in a different session (unread responses)
    pub(crate) sessions_with_unread: HashSet<Uuid>,
    /// Sessions being processed by a remote channel (Telegram, etc.) — prevents
    /// concurrent TUI sends on the same session and avoids blocking reload loops.
    pub(crate) channel_processing_sessions: HashSet<Uuid>,
    /// Pending session refresh from remote channel — debounced to avoid blocking
    /// the event loop with rapid DB queries during multi-tool runs.
    pub(crate) pending_session_refresh: Option<(Uuid, std::time::Instant)>,
    /// Sessions that have pending approval requests waiting
    pub(crate) sessions_with_pending_approval: HashSet<Uuid>,
    /// Cached provider instances keyed by provider name (e.g., "anthropic", "custom:nvidia")
    pub(crate) provider_cache: HashMap<String, Arc<dyn Provider>>,

    /// Cancellation token for aborting in-progress requests
    pub(crate) cancel_token: Option<CancellationToken>,

    /// Abort handle for the active agent task — hard-kills the tokio task on cancel
    pub(crate) task_abort_handle: Option<tokio::task::AbortHandle>,

    /// Per-session queued message stack — single source of truth for both
    /// the UI's "Queued" indicator AND the agent's mid-tool injection
    /// callback. Wrapped in `Arc<std::sync::Mutex<...>>` so the agent task
    /// (in a separate tokio task, only holding a callback closure) can
    /// read/drain the same map the TUI writes into.
    ///
    /// Per-session keying is load-bearing: prior to 2026-04-27 the agent
    /// inject path used a separate `Arc<Mutex<Option<String>>>` slot
    /// shared across ALL sessions, so a message queued in pane A could
    /// be consumed by pane B's agent loop and end up in the wrong
    /// session's chat. Keying by session id makes that impossible — a
    /// callback for session B can't see session A's queue because the
    /// lookup key is the caller's own session id.
    ///
    /// Lock is std::sync (not tokio): held only for HashMap read/write,
    /// never across an `.await`. The `!Send` guard makes "hold across
    /// await" a compile error, not a deadlock at runtime.
    pub(crate) queued_messages: Arc<std::sync::Mutex<HashMap<Uuid, Vec<String>>>>,

    /// Shared session ID — channels (Telegram, WhatsApp) read this to use the same session
    pub(crate) shared_session_id: Arc<tokio::sync::Mutex<Option<Uuid>>>,

    /// Context window tracking — FOCUSED SESSION view. These are derived
    /// from `session_input_tokens` / `session_context_max` on load_session
    /// so split-pane / sessions-list navigation shows the right numbers
    /// for whichever pane is focused. Agent events for a NON-focused
    /// session write to the maps only; they don't touch these fields.
    pub context_max_tokens: u32,
    pub last_input_tokens: Option<u32>,
    /// Per-session ctx indicators. Keyed by session_id so that a
    /// background turn's token updates don't leak into the other pane's
    /// ctx display. Without isolation, two panes racing to update
    /// `last_input_tokens` showed each other's numbers — the user saw
    /// "150K" on pane A sourced from pane B's long turn.
    pub session_input_tokens: HashMap<Uuid, u32>,
    pub session_context_max: HashMap<Uuid, u32>,
    /// Per-response output token count (streaming, counted via tiktoken)
    pub streaming_output_tokens: u32,

    /// Live tok/s accumulator + persisted last rate. Excludes idle time
    /// (tool execution, between-stream waits) so the footer shows actual
    /// model speed rather than total turn duration. See
    /// [`StreamingTpsTracker`].
    pub tps_tracker: StreamingTpsTracker,

    /// Active tool call group (during processing)
    pub active_tool_group: Option<ToolCallGroup>,

    /// Self-update state
    pub rebuild_status: Option<String>,

    /// Version string when an update is available (shown in update prompt dialog)
    pub update_available_version: Option<String>,

    /// Session to resume after restart (set via --session CLI arg)
    pub resume_session_id: Option<Uuid>,

    /// Cache of rendered lines per message to avoid re-parsing markdown every frame.
    /// Key: (message_id, content_width). Invalidated on terminal resize.
    pub render_cache: HashMap<(Uuid, u16), Vec<Line<'static>>>,

    /// Mapping from rendered line index → message index (for click-to-copy).
    /// Updated each frame by render_chat.
    pub chat_line_to_msg: Vec<Option<usize>>,
    /// The scroll offset used during the last render (for coordinate mapping)
    pub chat_render_scroll: usize,
    /// The top-left Y coordinate of the chat area in the terminal
    pub chat_area_y: u16,
    /// The top-left X coordinate of the chat area in the terminal
    pub chat_area_x: u16,
    /// The width of the chat area in the terminal
    pub chat_area_width: u16,
    /// The height of the chat area in the terminal
    pub chat_area_height: u16,
    /// Plain-text snapshot of rendered chat lines (for drag-select text extraction).
    /// Indexed by logical line (matches `chat_line_to_msg` / `chat_render_scroll`).
    pub chat_rendered_lines: Vec<String>,

    /// Drag selection: anchor point in terminal-screen coords (col, row), set on first drag event.
    pub drag_anchor: Option<(u16, u16)>,
    /// Drag selection: current point in terminal-screen coords (col, row), updated during drag.
    pub drag_current: Option<(u16, u16)>,

    /// Input area screen coordinates (set each render frame)
    pub input_area_x: u16,
    pub input_area_y: u16,
    pub input_area_width: u16,
    pub input_area_height: u16,
    /// Input drag selection state
    pub input_drag_anchor: Option<(u16, u16)>,
    pub input_drag_current: Option<(u16, u16)>,
    pub input_drag_selecting: bool,

    /// History paging — how many DB messages are hidden above the current view
    pub hidden_older_messages: usize,
    pub oldest_displayed_sequence: i32,
    pub display_token_count: usize,

    /// Pending sudo password request (shown as inline dialog)
    pub sudo_pending: Option<SudoPasswordRequest>,
    /// Raw password text being typed (never displayed, only dots)
    pub sudo_input: String,

    /// Pending SSH password request (shown as inline dialog, same UX as sudo)
    pub ssh_pending: Option<SshPasswordRequest>,
    /// Raw SSH password text being typed (never displayed, only dots)
    pub ssh_input: String,

    /// Active plan document for the current session (loaded from disk)
    pub plan_document: Option<crate::tui::plan::PlanDocument>,
    /// Path to the plan JSON file for the current session
    pub plan_file_path: Option<std::path::PathBuf>,

    /// Split pane manager — tracks pane layout, focus, and per-pane state
    pub pane_manager: PaneManager,
    /// Cached messages for inactive panes (keyed by session_id).
    /// Snapshotted when focus leaves a pane so it can be rendered read-only.
    pub(crate) pane_message_cache: HashMap<Uuid, Vec<DisplayMessage>>,
    /// Per-non-focused-session live state — see
    /// `super::background_session` for the shape and routing model.
    /// Entries are created lazily when an event arrives for a
    /// non-focused session and dropped on `ResponseComplete` or
    /// when the session becomes the focused pane (in which case
    /// the state is promoted into the `AppState` live fields).
    pub(crate) background_sessions:
        HashMap<Uuid, crate::tui::app::background_session::BackgroundSessionState>,

    /// Shared WhatsApp state — single bot instance broadcasts QR/connected events.
    #[cfg(feature = "whatsapp")]
    pub(crate) whatsapp_state: Arc<crate::channels::whatsapp::WhatsAppState>,

    /// Services
    pub(crate) agent_service: Arc<AgentService>,
    pub(crate) session_service: SessionService,
    pub(crate) message_service: MessageService,
    pub(crate) file_service: FileService,

    /// Session files state (populated when F is pressed in /sessions)
    pub(crate) session_files: Vec<crate::db::models::File>,
    pub(crate) selected_file_index: usize,

    /// Projects state (populated when P is pressed in /sessions)
    pub(crate) project_service: crate::services::ProjectService,
    pub(crate) projects: Vec<crate::db::models::Project>,
    pub(crate) selected_project_index: usize,
    pub(crate) project_sessions: Vec<crate::db::models::Session>,
    pub(crate) selected_project_session_index: usize,
    pub(crate) project_detail_view: bool,
    pub(crate) project_name_input: String,
    pub(crate) project_name_input_active: bool,
    /// When set, we're in "assign session to project" mode.
    /// The UUID is the target project_id. The user picks from session list.
    pub(crate) assigning_to_project: Option<uuid::Uuid>,
    /// Cached project names for session list display: project_id -> name
    pub(crate) project_name_cache: std::collections::HashMap<uuid::Uuid, String>,

    /// Events
    pub(crate) event_handler: EventHandler,

    /// Prompt analyzer
    pub(crate) prompt_analyzer: PromptAnalyzer,
}

impl App {
    /// Create a new app instance
    pub fn new(
        agent_service: Arc<AgentService>,
        context: ServiceContext,
        #[cfg(feature = "whatsapp")] whatsapp_state: Arc<crate::channels::whatsapp::WhatsAppState>,
    ) -> Self {
        let brain_path = BrainLoader::resolve_path();
        let command_loader = CommandLoader::from_brain_path(&brain_path);
        let user_commands = command_loader.load();
        let skills = crate::brain::skills::load_all_skills();

        // Load persisted approval policy from config.toml
        let (approval_auto_session, approval_auto_always) =
            Self::read_approval_policy_from_config();

        let this = Self {
            current_session: None,
            messages: Vec::new(),
            sessions: Vec::new(),
            usage_ledger_stats: Vec::new(),
            dashboard_state: None,
            mode: AppMode::Chat,
            input_buffer: String::new(),
            cursor_position: 0,
            attachments: Vec::new(),
            focused_attachment: None,
            scroll_offset: 0,
            prev_rendered_lines: 0,
            auto_scroll: true,
            mouse_capture_enabled: true,
            selected_session_index: 0,
            should_quit: false,
            pending_resize: None,
            is_processing: false,
            processing_started_at: None,
            streaming_response: None,
            streaming_render_cache: None,
            streaming_reasoning: None,
            error_message: None,
            error_message_shown_at: None,
            notification: None,
            notification_shown_at: None,
            selected_message_idx: None,
            intermediate_text_received: false,
            build_lines: Vec::new(),
            build_msg_idx: None,
            animation_frame: 0,

            escape_pending_at: None,
            ctrl_c_pending_at: None,
            help_scroll_offset: 0,
            approval_auto_session,
            approval_auto_always,
            file_picker_files: Vec::new(),
            file_picker_filtered: Vec::new(),
            file_picker_selected: 0,
            file_picker_scroll_offset: 0,
            file_picker_current_dir: std::env::current_dir().unwrap_or_default(),
            file_picker_show_hidden: false,
            file_picker_search: String::new(),
            file_picker_recursive: false,
            slash_suggestions_active: false,
            slash_filtered: Vec::new(),
            slash_selected_index: 0,
            emoji_picker_active: false,
            emoji_filtered: Vec::new(),
            emoji_selected_index: 0,
            emoji_colon_offset: 0,
            session_renaming: false,
            session_rename_buffer: String::new(),
            session_search: String::new(),
            session_search_active: false,
            sessions_scroll: 0,
            ps: crate::tui::provider_selector::ProviderSelectorState::default(),
            input_history: Self::load_history(),
            input_history_index: None,
            input_history_stash: String::new(),
            working_directory: std::env::current_dir().unwrap_or_default(),
            pending_context: Vec::new(),
            brain_path,
            user_commands,
            skills,
            mc: crate::tui::app::mission_control::McState::default(),
            skills_dialog: crate::tui::app::skills_dialog::SkillsDialogState::default(),
            onboarding: None,
            force_onboard: false,
            processing_sessions: HashSet::new(),
            session_cancel_tokens: HashMap::new(),
            sessions_with_unread: HashSet::new(),
            channel_processing_sessions: HashSet::new(),
            pending_session_refresh: None,
            sessions_with_pending_approval: HashSet::new(),
            provider_cache: HashMap::new(),
            cancel_token: None,
            task_abort_handle: None,
            queued_messages: Arc::new(std::sync::Mutex::new(HashMap::new())),
            shared_session_id: Arc::new(tokio::sync::Mutex::new(None)),
            default_model_name: agent_service.provider_model(),
            session_input_tokens: HashMap::new(),
            session_context_max: HashMap::new(),
            context_max_tokens: agent_service
                .context_window_for_model(&agent_service.provider_model()),
            last_input_tokens: None,
            streaming_output_tokens: 0,
            tps_tracker: StreamingTpsTracker::default(),
            active_tool_group: None,
            rebuild_status: None,
            update_available_version: None,
            resume_session_id: None,
            render_cache: HashMap::new(),
            chat_line_to_msg: Vec::new(),
            chat_render_scroll: 0,
            chat_area_y: 0,
            chat_area_x: 0,
            chat_area_width: 0,
            chat_area_height: 0,
            chat_rendered_lines: Vec::new(),
            drag_anchor: None,
            drag_current: None,
            input_area_x: 0,
            input_area_y: 0,
            input_area_width: 0,
            input_area_height: 0,
            input_drag_anchor: None,
            input_drag_current: None,
            input_drag_selecting: false,
            hidden_older_messages: 0,
            oldest_displayed_sequence: 0,
            display_token_count: 0,
            sudo_pending: None,
            sudo_input: String::new(),
            ssh_pending: None,
            ssh_input: String::new(),
            plan_document: None,
            plan_file_path: None,
            pane_manager: PaneManager::load_layout(),
            pane_message_cache: HashMap::new(),
            background_sessions: HashMap::new(),
            #[cfg(feature = "whatsapp")]
            whatsapp_state,
            session_service: SessionService::new(context.clone()),
            message_service: MessageService::new(context.clone()),
            file_service: FileService::new(context.clone()),
            project_service: crate::services::ProjectService::new(context),
            session_files: Vec::new(),
            selected_file_index: 0,
            projects: Vec::new(),
            selected_project_index: 0,
            project_sessions: Vec::new(),
            selected_project_session_index: 0,
            project_detail_view: false,
            project_name_input: String::new(),
            project_name_input_active: false,
            assigning_to_project: None,
            project_name_cache: std::collections::HashMap::new(),
            agent_service,
            event_handler: EventHandler::new(),
            prompt_analyzer: PromptAnalyzer::new(),
        };
        tracing::info!(
            "App created — provider: {} / {}",
            this.agent_service.provider_name(),
            this.agent_service.provider_model(),
        );
        this
    }

    /// Get the provider name
    pub fn provider_name(&self) -> String {
        self.agent_service.provider_name()
    }

    /// Get the provider model
    pub fn provider_model(&self) -> String {
        self.agent_service.provider_model()
    }

    /// Check if a session_id matches the currently active session
    pub(crate) fn is_current_session(&self, session_id: Uuid) -> bool {
        self.current_session.as_ref().map(|s| s.id) == Some(session_id)
    }

    /// Returns indices into `self.sessions` that match the current search filter.
    /// When no search is active, returns all indices.
    pub(crate) fn visible_session_indices(&self) -> Vec<usize> {
        if self.session_search.is_empty() {
            (0..self.sessions.len()).collect()
        } else {
            let search = self.session_search.to_lowercase();
            self.sessions
                .iter()
                .enumerate()
                .filter(|(_, s)| {
                    let name = s.title.as_deref().unwrap_or("New Chat").to_lowercase();
                    name.contains(&search)
                })
                .map(|(i, _)| i)
                .collect()
        }
    }

    /// Route a per-session mutator to either the foreground
    /// `AppState` fields or the matching background-session sidecar.
    /// Used by the `TuiEvent` handlers in this file so each one is a
    /// one-liner regardless of whether the targeted session happens
    /// to be the focused one.
    ///
    /// Lazily creates a `BackgroundSessionState` entry on first
    /// background hit so handlers don't have to .or_default()
    /// themselves. Cleanup happens in `complete_response_for` (drops
    /// the entry when its turn finalises) and `demote_to_background`
    /// (snapshots foreground state in, drops empty entries).
    pub(crate) fn session_state_mut(
        &mut self,
        session_id: Uuid,
    ) -> super::background_session::SessionStateMut<'_> {
        if self.is_current_session(session_id) {
            super::background_session::SessionStateMut::Foreground(self)
        } else {
            super::background_session::SessionStateMut::Background(
                self.background_sessions.entry(session_id).or_default(),
            )
        }
    }

    /// Snapshot the current `AppState` live-turn fields into the
    /// background-sessions map for `session_id` (typically the
    /// session that just lost focus). Called from the focus-switch
    /// path BEFORE the new pane's state is loaded so the leaving
    /// session keeps accumulating events while it's off-screen.
    ///
    /// An empty snapshot (no live state) skips insertion to keep
    /// the map bounded.
    pub(crate) fn demote_to_background(&mut self, session_id: Uuid) {
        // Preserve any pending_messages that accumulated while this
        // session was previously in background — they're flushed
        // entries waiting to merge back on the next promote. New
        // demote, same session: extend rather than overwrite.
        let prior_pending = self
            .background_sessions
            .remove(&session_id)
            .map(|prev| prev.pending_messages)
            .unwrap_or_default();
        let bg = super::background_session::BackgroundSessionState {
            streaming_response: self.streaming_response.clone(),
            streaming_reasoning: self.streaming_reasoning.clone(),
            active_tool_group: self.active_tool_group.clone(),
            is_processing: self.is_processing,
            processing_started_at: self.processing_started_at,
            last_input_tokens: self.last_input_tokens,
            streaming_output_tokens: self.streaming_output_tokens,
            display_token_count: self.display_token_count,
            tps_tracker: self.tps_tracker.clone(),
            pending_messages: prior_pending,
        };
        if bg.has_live_state() {
            self.background_sessions.insert(session_id, bg);
        }
    }

    /// Pop the background entry for `session_id` (typically the
    /// session that just gained focus) into the `AppState` live
    /// fields. Returns true when an entry was found and promoted,
    /// false otherwise (caller falls back to the DB-reload path).
    pub(crate) fn promote_to_foreground(&mut self, session_id: Uuid) -> bool {
        let Some(bg) = self.background_sessions.remove(&session_id) else {
            return false;
        };
        self.streaming_response = bg.streaming_response;
        self.streaming_reasoning = bg.streaming_reasoning;
        self.active_tool_group = bg.active_tool_group;
        self.is_processing = bg.is_processing;
        self.processing_started_at = bg.processing_started_at;
        self.last_input_tokens = bg.last_input_tokens;
        self.streaming_output_tokens = bg.streaming_output_tokens;
        self.display_token_count = bg.display_token_count;
        self.tps_tracker = bg.tps_tracker;
        // Merge the per-session message delta into the freshly DB-
        // loaded `self.messages`. The caller (`load_session`) has
        // already trimmed `self.messages` to the display budget;
        // pending_messages from the background are the deltas
        // accumulated AFTER that DB snapshot, so they belong at
        // the tail. Each `DisplayMessage` carries its own UUID so
        // a future DB reload that picks up the persisted form
        // won't collide.
        if !bg.pending_messages.is_empty() {
            self.messages.extend(bg.pending_messages);
        }
        true
    }

    /// Set the plan file path for a session and attempt to load it.
    pub(crate) fn set_plan_file_for_session(&mut self, session_id: Uuid) {
        let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".to_string());
        let path = std::path::PathBuf::from(format!(
            "{}/.opencrabs/agents/session/.opencrabs_plan_{}.json",
            home, session_id
        ));
        self.plan_file_path = Some(path);
        self.reload_plan();
    }

    /// Reload the plan document from disk.
    ///
    /// Stale plans (terminal status, or InProgress but not actively processing)
    /// are discarded automatically so they don't linger across restarts.
    pub(crate) fn reload_plan(&mut self) {
        self.plan_document = self.plan_file_path.as_ref().and_then(|path| {
            let content = std::fs::read_to_string(path).ok()?;
            serde_json::from_str::<crate::tui::plan::PlanDocument>(&content).ok()
        });

        // Clean up stale plans that shouldn't be displayed.
        //
        // IMPORTANT: Completed plans are intentionally KEPT. They serve as
        // execution history the agent can reference, and the plan file is
        // session-scoped (auto-cleaned with the session).  Only rejected or
        // cancelled plans are discarded, and InProgress plans from stale runs.
        if let Some(ref plan) = self.plan_document {
            use crate::tui::plan::PlanStatus;
            let should_discard = match plan.status {
                PlanStatus::Rejected | PlanStatus::Cancelled => true,
                PlanStatus::InProgress => {
                    // If the agent isn't actively processing, this plan is stale
                    // (left over from a previous run or a failed tool call)
                    !self.is_processing
                }
                _ => false,
            };
            if should_discard {
                self.discard_plan_file();
                self.plan_document = None;
            }
        }
    }

    /// Clear the in-memory plan and delete the backing file.
    pub(crate) fn discard_plan_file(&mut self) {
        if let Some(path) = &self.plan_file_path {
            let _ = std::fs::remove_file(path);
        }
    }

    /// Get the shared session ID handle (for channels like Telegram/WhatsApp)
    pub fn shared_session_id(&self) -> Arc<tokio::sync::Mutex<Option<Uuid>>> {
        self.shared_session_id.clone()
    }

    /// Fast synchronous init: decide mode (Onboarding vs Chat) and arm the
    /// header card overlay. Does no DB work, so the first frame can render
    /// immediately. The actual session load happens in `initialize_async`.
    ///
    /// Returns `true` if the caller should render a first frame before
    /// running `initialize_async` (i.e. we're going to Chat and want the
    /// card visible while the session loads).
    pub fn initialize_sync(&mut self) -> bool {
        // Remove ghost custom provider entries left by previous saves
        crate::config::Config::cleanup_empty_custom_providers();

        let is_first = super::onboarding::is_first_time();
        if self.force_onboard || is_first {
            self.force_onboard = false;
            tracing::info!("[init] Starting onboarding wizard");
            let mut wizard = OnboardingWizard::new();
            wizard.is_first_time = is_first;
            self.onboarding = Some(wizard);
            self.mode = AppMode::Onboarding;
            return false;
        }
        self.mode = AppMode::Chat;

        true
    }

    /// Initialize the app by loading or creating a session
    pub async fn initialize(&mut self) -> Result<()> {
        // Resume a specific session (e.g. after /rebuild restart) or load the most recent
        if let Some(session_id) = self.resume_session_id.take() {
            self.load_session(session_id).await?;
            self.mode = AppMode::Chat;
            // Send a hidden wake-up message to the agent (not shown in UI)
            // If we also evolved, merge the evolution context into the same message
            // to avoid sending two separate prompts that produce duplicate responses.
            self.processing_sessions.insert(session_id);
            self.is_processing = true;
            self.processing_started_at = Some(std::time::Instant::now());
            let agent_service = self.agent_service.clone();
            let event_sender = self.event_sender();
            let token = CancellationToken::new();
            self.cancel_token = Some(token.clone());
            let evolution_context = std::env::var("OPENCRABS_EVOLVED_FROM")
                .ok()
                .filter(|old| old != crate::VERSION)
                .map(|old| {
                    // Clear env var so it doesn't fire again
                    // SAFETY: single-threaded at this point in startup
                    unsafe { std::env::remove_var("OPENCRABS_EVOLVED_FROM") };
                    format!(
                        " You just evolved from v{old} to v{new}. \
                         Check the CHANGELOG at the repo root for what's new in v{new}. \
                         Compare the brain templates in src/docs/reference/templates/ against \
                         the user's brain files in ~/.opencrabs/ (TOOLS.md, AGENTS.md, etc.) \
                         and tell the user what changed. Offer to update their brain files \
                         with the new content. Be specific about what's new.",
                        new = crate::VERSION,
                    )
                })
                .unwrap_or_default();
            tokio::spawn(async move {
                let wake_up = format!(
                    "[System: You just rebuilt yourself from source and restarted \
                    via exec(). Greet the user, confirm the restart succeeded, and continue \
                    where you left off.{evolution_context}]"
                );
                match agent_service
                    .send_message_with_tools_and_mode(
                        session_id,
                        wake_up.to_string(),
                        None,
                        Some(token),
                    )
                    .await
                {
                    Ok(response) => {
                        let _ = event_sender.send(TuiEvent::ResponseComplete {
                            session_id,
                            response,
                        });
                    }
                    Err(e) => {
                        let _ = event_sender.send(TuiEvent::Error {
                            session_id,
                            message: e.to_string(),
                        });
                    }
                }
            });
        } else if let Some(last_id) = Self::read_last_session_id()
            && self.session_service.get_session(last_id).await?.is_some()
        {
            self.load_session(last_id).await?;
        } else if let Some(session) = self.session_service.get_most_recent_session().await? {
            self.load_session(session.id).await?;
        } else {
            // Create a new session if none exists
            self.create_new_session().await?;
        }

        tracing::info!(
            "Session loaded — provider: {} / {}, session: {:?}",
            self.agent_service.provider_name(),
            self.default_model_name,
            self.current_session.as_ref().map(|s| s.id),
        );

        // Pre-load sessions for restored split panes so they render
        // immediately instead of showing empty until focused.
        if self.pane_manager.is_split() {
            let focused = self.pane_manager.focused;
            let pane_sessions: Vec<Uuid> = self
                .pane_manager
                .panes
                .iter()
                .filter(|p| p.id != focused)
                .filter_map(|p| p.session_id)
                .collect();
            for sid in pane_sessions {
                self.preload_pane_session(sid).await;
            }
        }

        // Load sessions list
        self.load_sessions().await?;

        // Post-evolve fallback: if OPENCRABS_EVOLVED_FROM is still set
        // (e.g. /evolve without resume_session_id), handle it here.
        // Normally this is merged into the wake-up message above.
        if let Ok(old_version) = std::env::var("OPENCRABS_EVOLVED_FROM") {
            unsafe { std::env::remove_var("OPENCRABS_EVOLVED_FROM") };
            if old_version != crate::VERSION && self.current_session.is_some() {
                let msg = format!(
                    "[SYSTEM: You just evolved from v{old} to v{new}. \
                     Check the CHANGELOG at the repo root for what's new in v{new}. \
                     Compare the brain templates in src/docs/reference/templates/ against \
                     the user's brain files in ~/.opencrabs/ (TOOLS.md, AGENTS.md, etc.) \
                     and tell the user what changed. Offer to update their brain files \
                     with the new content. Be specific about what's new.]",
                    old = old_version,
                    new = crate::VERSION,
                );
                let tx = self.event_sender();
                let _ = tx.send(TuiEvent::MessageSubmitted(msg));
            }
        }

        // Spawn background release check (immediately on startup, then daily).
        // No initial delay — if an update exists, behavior depends on
        // `agent.auto_update` (default true): silently install + restart.
        // When false, show the UpdatePrompt dialog so the user can confirm.
        {
            let tx = self.event_sender();
            let auto_update = crate::config::Config::load()
                .map(|c| c.agent.auto_update)
                .unwrap_or(true);
            tokio::spawn(async move {
                loop {
                    if let Some(latest) = crate::brain::tools::evolve::check_for_update().await {
                        if auto_update {
                            // Auto-update notice is global (not tied to any
                            // session) — Uuid::nil() bypasses the session
                            // filter in the SystemMessage handler.
                            let _ = tx.send(TuiEvent::SystemMessage {
                                session_id: Uuid::nil(),
                                text: format!("Auto-updating to v{}...", latest),
                            });
                            super::messaging::run_evolve_directly(Uuid::nil(), tx.clone()).await;
                        } else {
                            let _ = tx.send(TuiEvent::UpdateAvailable(latest));
                        }
                    }
                    // Check again in 24 hours
                    tokio::time::sleep(std::time::Duration::from_secs(86400)).await;
                }
            });
        }

        // Notify user if config was recovered from last-known-good snapshot
        if crate::config::Config::was_recovered() {
            self.push_system_message(
                "🔧 Config recovered from last-known-good snapshot. \
                 Review ~/.opencrabs/config.toml for issues."
                    .to_string(),
            );
        }

        // Notify user about unknown config keys (possible typos)
        let typo_warnings = crate::config::Config::take_typo_warnings();
        if !typo_warnings.is_empty() {
            self.push_system_message(format!(
                "⚠️ Unknown keys in config.toml (possible typos): {}",
                typo_warnings.join(", ")
            ));
        }

        // Notify user if DB integrity check failed
        if crate::db::db_integrity_failed() {
            self.push_system_message(
                "⚠️ Database integrity check FAILED — data may be corrupted. \
                 Consider backing up and recreating the database."
                    .to_string(),
            );
        }

        // Notify user if the autonomous RSI loop has filed proposals
        // they haven't reviewed yet. The banner points at the
        // direct-action path (Mission Control's Inbox panel, where
        // `a` applies and `r` rejects) first, then mentions the
        // agent-driven path as a fallback for users who prefer the
        // chat surface.
        let pending = crate::brain::rsi_proposals::ProposalsStore::new().pending_count();
        if pending > 0 {
            self.push_system_message(format!(
                "🔧 RSI proposed {pending} new item(s) (tools / commands / skills). \
                 Open Mission Control with `/mission-control` → Inbox to review \
                 (press `a` to apply, `r` to reject), or ask me to \"show proposed\" \
                 / \"implement proposed\" if you'd rather work from the chat."
            ));
        }

        Ok(())
    }

    /// Get event handler
    pub fn event_handler(&self) -> &EventHandler {
        &self.event_handler
    }

    /// Get mutable event handler
    pub fn event_handler_mut(&mut self) -> &mut EventHandler {
        &mut self.event_handler
    }

    /// Get event sender
    pub fn event_sender(&self) -> tokio::sync::mpsc::UnboundedSender<TuiEvent> {
        self.event_handler.sender()
    }

    /// Set agent service (used to inject configured agent after app creation)
    pub fn set_agent_service(&mut self, agent_service: Arc<AgentService>) {
        self.default_model_name = agent_service.provider_model();
        self.agent_service = agent_service;
    }

    /// Rebuild agent service with a new provider
    pub(crate) async fn rebuild_agent_service(&mut self) -> Result<()> {
        // Load config - API keys are stored in keys.toml and merged with config
        let config = crate::config::Config::load()
            .map_err(|e| anyhow::anyhow!("Failed to load config: {}", e))?;

        // Check all providers dynamically - log enabled providers for debugging
        let enabled_providers: Vec<&str> = vec![
            config
                .providers
                .anthropic
                .as_ref()
                .filter(|p| p.enabled)
                .map(|_| "anthropic"),
            config
                .providers
                .openai
                .as_ref()
                .filter(|p| p.enabled)
                .map(|_| "openai"),
            config
                .providers
                .gemini
                .as_ref()
                .filter(|p| p.enabled)
                .map(|_| "gemini"),
            config
                .providers
                .openrouter
                .as_ref()
                .filter(|p| p.enabled)
                .map(|_| "openrouter"),
            config
                .providers
                .minimax
                .as_ref()
                .filter(|p| p.enabled)
                .map(|_| "minimax"),
            config
                .providers
                .zhipu
                .as_ref()
                .filter(|p| p.enabled)
                .map(|_| "zhipu"),
            config.providers.active_custom().map(|_| "custom"),
        ]
        .into_iter()
        .flatten()
        .collect();

        tracing::debug!(
            "rebuild_agent_service: enabled_providers = {:?}",
            enabled_providers
        );

        // Create new provider from config
        let (provider, provider_warning) =
            crate::brain::provider::create_provider_with_warning(&config)
                .await
                .map_err(|e| anyhow::anyhow!("Failed to create provider: {}", e))?;

        // Get existing context from current agent service
        let context = self.agent_service.context().clone();

        // Get existing tool registry from current agent service
        let tool_registry = self.agent_service.tool_registry().clone();

        // Get existing system brain from current agent service
        let system_brain = self.agent_service.system_brain().cloned();

        // Carry the live-brain handle forward so brain-file edits keep taking
        // effect after a provider/model rebuild without re-reading disk (#213).
        let brain_rebuild = self.agent_service.brain_rebuild();

        // Get event sender for approval callback
        let event_sender = self.event_sender();

        // Create approval callback that sends requests to TUI
        let approval_callback: crate::brain::agent::ApprovalCallback = Arc::new(move |tool_info| {
            let sender = event_sender.clone();
            Box::pin(async move {
                use crate::tui::events::{ToolApprovalRequest, TuiEvent};
                use tokio::sync::mpsc;

                let (response_tx, mut response_rx) = mpsc::unbounded_channel();

                let request = ToolApprovalRequest {
                    request_id: uuid::Uuid::new_v4(),
                    session_id: tool_info.session_id,
                    tool_name: tool_info.tool_name,
                    tool_description: tool_info.tool_description,
                    tool_input: tool_info.tool_input,
                    capabilities: tool_info.capabilities,
                    response_tx,
                    requested_at: std::time::Instant::now(),
                };

                sender
                    .send(TuiEvent::ToolApprovalRequested(request))
                    .map_err(|e| {
                        crate::brain::agent::AgentError::Internal(format!(
                            "Failed to send approval request: {}",
                            e
                        ))
                    })?;

                let response = response_rx.recv().await.ok_or_else(|| {
                    crate::brain::agent::AgentError::Internal("Approval channel closed".to_string())
                })?;

                // TUI handles "always" internally via approval_auto_session;
                // return false for always_approve so tool_loop doesn't duplicate it
                Ok((response.approved, false))
            })
        });

        // Preserve existing callbacks from the current agent service
        let progress_callback = self.agent_service.progress_callback().clone();
        let message_queue_callback = self.agent_service.message_queue_callback().clone();
        let sudo_callback = self.agent_service.sudo_callback().clone();
        let ssh_callback = self.agent_service.ssh_callback().clone();
        let session_updated_tx = self.agent_service.session_updated_tx();
        let working_dir = self
            .agent_service
            .working_directory()
            .read()
            .expect("working_directory lock poisoned")
            .clone();
        let brain_path = self.agent_service.brain_path().clone();

        // Create new agent service with new provider — preserve ALL callbacks
        let mut new_agent_service = AgentService::new(provider, context, &config)
            .await
            .with_tool_registry(tool_registry)
            .with_approval_callback(Some(approval_callback))
            .with_progress_callback(progress_callback)
            .with_message_queue_callback(message_queue_callback)
            .with_sudo_callback(sudo_callback)
            .with_ssh_callback(ssh_callback)
            .with_working_directory(working_dir)
            .with_auto_approve_tools(self.approval_auto_always);

        if let Some(tx) = session_updated_tx {
            new_agent_service = new_agent_service.with_session_updated_tx(tx);
        }

        if let Some(bp) = brain_path {
            new_agent_service = new_agent_service.with_brain_path(bp);
        }

        // Add system brain if it exists
        if let Some(brain) = system_brain {
            new_agent_service = new_agent_service.with_system_brain(brain);
        }

        // Re-attach live brain rebuilding (#213) so /models switches don't
        // revert the agent to a static, startup-frozen brain.
        if let Some(handle) = brain_rebuild {
            new_agent_service = new_agent_service.with_brain_rebuild_handle(handle);
        }

        // Preserve per-session provider entries across the rebuild so
        // other sessions (especially active pane-B turns) don't lose
        // their provider choice when the user reconfigures via /models.
        // Without this, any rebuild silently reverts every session to
        // the new global default.
        let preserved_session_providers = self.agent_service.session_provider_snapshot();
        // Carry each session's locked model so the rebuild restores the
        // exact provider+model pair, not the provider's default.
        let preserved_session_models: std::collections::HashMap<uuid::Uuid, String> = self
            .agent_service
            .session_model_snapshot()
            .into_iter()
            .collect();

        let new_agent_service = Arc::new(new_agent_service);
        for (sid, prov) in preserved_session_providers {
            let model = preserved_session_models
                .get(&sid)
                .cloned()
                .unwrap_or_else(|| prov.default_model().to_string());
            new_agent_service.swap_provider_for_session(sid, prov, model);
        }

        // Update app state
        self.default_model_name = new_agent_service.provider_model();
        self.agent_service = new_agent_service;

        // Surface fallback warning as TUI system message
        if let Some(warning) = provider_warning {
            self.push_system_message(warning);
        }

        Ok(())
    }

    /// Convenience wrappers around the tps_tracker so call sites don't
    /// have to know the field name. Match the names used before the
    /// tracker was extracted into a standalone struct.
    pub(crate) fn advance_streaming_window(&mut self) {
        self.tps_tracker.advance(std::time::Instant::now());
    }
    pub(crate) fn current_streaming_active_secs(&self) -> f64 {
        self.tps_tracker.active_secs_now(std::time::Instant::now())
    }
    pub(crate) fn finalize_tps(&mut self, authoritative: Option<f64>) {
        self.tps_tracker
            .finalize(self.streaming_output_tokens, authoritative);
    }
    pub(crate) fn last_tps(&self) -> Option<f64> {
        self.tps_tracker.last_tps
    }

    /// Sync the current session's provider_name and model to match the active agent service.
    /// Call after rebuild_agent_service() so the footer and sessions screen reflect the change.
    pub(crate) async fn sync_session_to_provider(&mut self) {
        let provider_name = self.agent_service.provider_name();
        let model = self.default_model_name.clone();
        if let Some(ref mut session) = self.current_session {
            session.provider_name = Some(provider_name.clone());
            session.model = Some(model);
            let session_copy = session.clone();
            if let Err(e) = self.session_service.update_session(&session_copy).await {
                tracing::warn!("Failed to persist provider to session: {}", e);
            }
        }
        // Cache provider instance
        let provider_arc = self.agent_service.provider();
        self.provider_cache.insert(provider_name, provider_arc);
    }

    /// Get the agent service
    pub fn agent_service(&self) -> &Arc<AgentService> {
        &self.agent_service
    }

    /// Receive next event (blocks until available)
    pub async fn next_event(&mut self) -> Option<TuiEvent> {
        self.event_handler.next().await
    }

    /// Try to receive next event without blocking (returns None if queue is empty)
    pub fn try_next_event(&mut self) -> Option<TuiEvent> {
        self.event_handler.try_next()
    }

    /// Handle an event
    pub async fn handle_event(&mut self, event: TuiEvent) -> Result<()> {
        match event {
            TuiEvent::Key(key_event) => {
                self.handle_key_event(key_event).await?;
            }
            TuiEvent::MouseScroll(direction) => {
                if self.mode == AppMode::Chat {
                    if direction > 0 {
                        // Scrolling up — disable auto-scroll
                        let before = self.scroll_offset;
                        self.scroll_offset = self.scroll_offset.saturating_add(1);
                        self.auto_scroll = false;
                        tracing::debug!(
                            "[SCROLL] mouse up: {} -> {} (auto_scroll=false)",
                            before,
                            self.scroll_offset
                        );
                    } else {
                        let before = self.scroll_offset;
                        self.scroll_offset = self.scroll_offset.saturating_sub(1);
                        tracing::debug!(
                            "[SCROLL] mouse down: {} -> {}",
                            before,
                            self.scroll_offset
                        );
                        // Re-enable auto-scroll when back at bottom
                        if self.scroll_offset == 0 {
                            self.auto_scroll = true;
                        }
                    }
                }
            }
            TuiEvent::MouseClick(_col, row) => {
                if self.mode == AppMode::Chat {
                    // Clear input drag selection if clicking outside input
                    if row < self.input_area_y || row >= self.input_area_y + self.input_area_height
                    {
                        self.input_drag_selecting = false;
                        self.input_drag_anchor = None;
                        self.input_drag_current = None;
                    }
                    self.handle_click_select(row);
                }
            }
            TuiEvent::MouseRightClick(_col, row) => {
                if self.mode == AppMode::Chat {
                    self.handle_right_click_copy(row);
                }
            }
            TuiEvent::MouseDrag(col, row) => {
                if self.mode == AppMode::Chat {
                    // Check input area first
                    if self.input_drag_selecting
                        || (row >= self.input_area_y
                            && row < self.input_area_y + self.input_area_height)
                    {
                        self.handle_input_mouse_drag(col, row);
                    } else {
                        self.handle_mouse_drag(col, row);
                    }
                }
            }
            TuiEvent::MouseUp(col, row) => {
                if self.mode == AppMode::Chat {
                    // Check input area first
                    if self.input_drag_selecting
                        || (row >= self.input_area_y
                            && row < self.input_area_y + self.input_area_height)
                    {
                        if self.handle_input_mouse_up(col, row) {
                            self.notification = Some("Copied to clipboard".to_string());
                            self.notification_shown_at = Some(std::time::Instant::now());
                        }
                    } else {
                        self.handle_mouse_up(col, row);
                    }
                }
            }
            TuiEvent::Paste(text) => {
                // Handle paste events in Chat mode or Onboarding mode
                if self.mode == AppMode::Chat {
                    // Filter out terminal escape sequences that leak through on
                    // focus switch (mouse tracking, SGR mode, etc.).  These look
                    // like \x1b[<35;118;37M or CSI sequences and should never
                    // appear in user-typed text.
                    let mut filtered = Self::strip_terminal_escapes(&text);

                    // Normalize Unicode whitespace (non-breaking spaces, zero-width chars)
                    // that web pages use for table formatting. These paste as invisible
                    // bytes in terminals, gluing columns together.
                    filtered = Self::normalize_unicode_whitespace(&filtered);

                    // Convert tabs to spaces so pasted table data doesn't collapse.
                    // Terminal TUI can't render tab stops, so \t chars show as
                    // zero-width, gluing columns together.  Replacing with spaces
                    // preserves visual column alignment from web pages.
                    if filtered.contains('\t') {
                        filtered = Self::expand_tabs(&filtered);
                    }
                    if filtered.trim().is_empty() {
                        // No usable text. The clipboard may instead hold raw
                        // image bytes (copied from a browser, WhatsApp, a
                        // screenshot) that bracketed paste can't carry as text.
                        // Read them straight from the OS clipboard and attach.
                        if let Some(att) = Self::attach_clipboard_image() {
                            let label = att.name.clone();
                            // Track pasted image in file service
                            if let Some(session) = &self.current_session {
                                let file_svc = self.file_service.clone();
                                let sid = session.id;
                                let path = std::path::PathBuf::from(&att.path);
                                tokio::spawn(async move {
                                    if let Err(e) =
                                        file_svc.get_or_create_file(sid, path, None).await
                                    {
                                        tracing::warn!("Failed to track pasted image: {e}");
                                    }
                                });
                            }
                            self.attachments.push(att);
                            self.notification = Some(format!("📎 Attached pasted image: {label}"));
                            self.notification_shown_at = Some(std::time::Instant::now());
                        } else {
                            tracing::debug!(
                                "Paste event contained only escape sequences ({} bytes) — dropped",
                                text.len()
                            );
                        }
                    } else {
                        // Ensure cursor is on a valid char boundary before inserting
                        // (defensive — prevents panics from corrupted cursor state, issue #69).
                        self.cursor_position = self
                            .input_buffer
                            .floor_char_boundary(self.cursor_position.min(self.input_buffer.len()));

                        // Check if pasted text contains image paths — extract as attachments
                        let (clean_text, new_attachments) = Self::extract_image_paths(&filtered);
                        if !new_attachments.is_empty() {
                            self.attachments.extend(new_attachments);
                            if !clean_text.trim().is_empty() {
                                self.input_buffer
                                    .insert_str(self.cursor_position, &clean_text);
                                self.cursor_position += clean_text.len();
                            }
                        } else {
                            self.input_buffer
                                .insert_str(self.cursor_position, &filtered);
                            self.cursor_position += filtered.len();
                        }
                    } // end else (non-empty after filtering)
                    self.update_slash_suggestions();
                } else if self.mode == AppMode::Onboarding {
                    // Handle paste in onboarding wizard (for API keys, etc.)
                    if let Some(ref mut wizard) = self.onboarding {
                        wizard.handle_paste(&text);
                        // Trigger model fetch if provider supports it
                        // Custom providers: fetch if base_url is set (no key needed for local endpoints)
                        // Built-in providers: require non-empty api_key_input
                        let should_fetch = if wizard.ps.is_custom() {
                            wizard.ps.supports_model_fetch()
                        } else {
                            wizard.ps.supports_model_fetch() && !wizard.ps.api_key_input.is_empty()
                        };
                        if should_fetch {
                            let provider_idx = wizard.ps.selected_provider;
                            let api_key = if wizard.ps.api_key_input.is_empty() {
                                None
                            } else {
                                Some(wizard.ps.api_key_input.clone())
                            };
                            let base_url =
                                if wizard.ps.is_custom() && !wizard.ps.base_url.is_empty() {
                                    Some(wizard.ps.base_url.clone())
                                } else {
                                    None
                                };
                            wizard.ps.models_fetching = true;
                            let sender = self.event_sender();
                            tokio::spawn(async move {
                                let models = super::onboarding::fetch_provider_models(
                                    provider_idx,
                                    api_key.as_deref(),
                                    base_url.as_deref(),
                                    None,
                                )
                                .await;
                                let _ = sender.send(TuiEvent::OnboardingModelsFetched(models));
                            });
                        }
                    }
                }
            }
            TuiEvent::MessageSubmitted(content) => {
                self.send_message(content).await?;
            }
            TuiEvent::ResponseChunk { session_id, text } => {
                let is_current = self.is_current_session(session_id);
                tracing::debug!(
                    "[TUI] ResponseChunk: len={} is_current={} streaming_len={}",
                    text.len(),
                    is_current,
                    self.streaming_response
                        .as_ref()
                        .map(|s| s.len())
                        .unwrap_or(0)
                );
                // Route to foreground OR the per-session background
                // sidecar so the inactive pane sees streaming chunks
                // live instead of catching up on focus switch.
                self.session_state_mut(session_id)
                    .append_streaming_chunk(&text);
            }
            TuiEvent::StripStreamedContent {
                session_id,
                bytes,
                reason,
            } => {
                if self.is_current_session(session_id) {
                    // The gaslighting preamble is always leading in the
                    // streaming buffer, so drain exactly `bytes` bytes from
                    // the start — not the entire buffer. Prior behavior
                    // wiped everything, which also destroyed any legitimate
                    // draft that followed the preamble in the same block.
                    if let Some(ref mut buf) = self.streaming_response {
                        let prior_len = buf.len();
                        // Clamp to a valid char boundary ≤ bytes to avoid
                        // panicking on multi-byte codepoints.
                        let mut cut = bytes.min(prior_len);
                        while cut > 0 && !buf.is_char_boundary(cut) {
                            cut -= 1;
                        }
                        tracing::warn!(
                            "[TUI] StripStreamedContent: draining {}/{} bytes from start of streaming response — {}",
                            cut,
                            prior_len,
                            reason
                        );
                        buf.drain(..cut);
                        if buf.is_empty() {
                            self.streaming_response = None;
                            self.streaming_render_cache = None;
                        }
                    } else {
                        tracing::warn!(
                            "[TUI] StripStreamedContent: no buffer to strip ({} bytes requested) — {}",
                            bytes,
                            reason
                        );
                    }
                }
            }
            TuiEvent::ReasoningChunk { session_id, text } => {
                // Route to foreground OR background sidecar. The
                // routing helper handles empty/whitespace filtering
                // and the foreground-only `scroll_offset = 0` nudge
                // for the auto-scroll behaviour.
                self.session_state_mut(session_id)
                    .append_reasoning_chunk(&text);
            }
            TuiEvent::ResponseComplete {
                session_id,
                response,
            } => {
                if self.is_current_session(session_id) {
                    if self.is_processing {
                        self.complete_response(response).await?;
                    } else {
                        // Session was cancelled (Esc×2) — agent finished after cancel.
                        // Reload from DB to pick up any final content the agent wrote
                        // before detecting the cancellation token.
                        self.load_session(session_id).await?;
                    }
                } else {
                    // Background session completed — mark as unread
                    self.processing_sessions.remove(&session_id);
                    self.session_cancel_tokens.remove(&session_id);
                    self.sessions_with_unread.insert(session_id);
                    // Drop the background live-state sidecar — the
                    // turn is finalised and the next focus switch
                    // re-reads from the DB anyway. Without this the
                    // sidecar's `streaming_response` / `active_tool_group`
                    // would linger forever for a session the user
                    // never re-focuses, leaking memory in long sessions.
                    self.background_sessions.remove(&session_id);
                    // Refresh pane cache so inactive pane shows the completed response
                    if self.pane_manager.is_split() {
                        self.preload_pane_session(session_id).await;
                    }
                }
            }
            TuiEvent::Error {
                session_id,
                message,
            } => {
                // Always clear session processing state — missing this for current sessions
                // caused subsequent messages to be silently queued after errors.
                self.processing_sessions.remove(&session_id);
                self.session_cancel_tokens.remove(&session_id);
                if self.is_current_session(session_id) {
                    if message == "Cancelled" {
                        // Esc×2: the input handler already promoted
                        // in-flight streaming text, reasoning, and the
                        // active tool group into `self.messages` BEFORE
                        // aborting the agent task. Reloading from DB here
                        // races the async persist_streaming_state writes
                        // and wipes what the user just watched stream —
                        // the cancel erased the visible chat until
                        // restart. Leave the in-memory state alone; the
                        // DB write is for restart-resume, not for this
                        // render.
                    } else {
                        // Non-cancel errors: reload so the user sees
                        // whatever DID get persisted and the error toast.
                        self.load_session(session_id).await?;
                        self.show_error(message);
                    }
                } else {
                    tracing::warn!("Background session {} error: {}", session_id, message);
                    // Refresh pane cache so inactive pane shows whatever was written
                    if self.pane_manager.is_split() {
                        self.preload_pane_session(session_id).await;
                    }
                }
            }
            TuiEvent::SwitchMode(mode) => {
                self.switch_mode(mode).await?;
            }
            TuiEvent::SelectSession(session_id) => {
                self.load_session(session_id).await?;
            }
            TuiEvent::NewSession => {
                self.create_new_session().await?;
            }
            TuiEvent::Quit => {
                self.pane_manager.save_layout();
                self.should_quit = true;
            }
            TuiEvent::Tick => {
                // Update animation frame for spinner
                self.animation_frame = self.animation_frame.wrapping_add(1);

                // Resolve deferred health checks (shows Pending for one frame first)
                if let Some(ref mut wizard) = self.onboarding
                    && wizard.health_running
                    && !wizard.health_complete
                {
                    wizard.tick_health_check();
                }

                // Auto-dismiss error/warning messages after 2.5 seconds
                if let Some(shown_at) = self.error_message_shown_at
                    && shown_at.elapsed() >= std::time::Duration::from_millis(2500)
                {
                    self.error_message = None;
                    self.error_message_shown_at = None;
                }
            }
            TuiEvent::ToolApprovalRequested(request) => {
                self.handle_approval_requested(request);
            }
            TuiEvent::ToolApprovalResponse(_response) => {
                // Response is sent via channel, auto-scroll if enabled
                if self.auto_scroll {
                    self.scroll_offset = 0;
                }
            }
            TuiEvent::ToolCallStarted {
                session_id,
                tool_name,
                tool_input,
            } => {
                // Drop the original `is_current_session && is_processing`
                // guard. Background sessions are still mid-turn from
                // the agent's perspective; the `is_processing` check
                // would have been false on the foreground `AppState`
                // for any non-focused session anyway. Each session's
                // processing flag is now tracked per-state by
                // `ChannelProcessingStarted`/`Finished` and migrates
                // with focus, so the gating is meaningful per
                // session rather than only for the focused one.
                let desc = Self::format_tool_description(&tool_name, &tool_input);
                let entry = ToolCallEntry {
                    description: desc,
                    success: true,
                    details: None,
                    completed: false,
                    tool_input: tool_input.clone(),
                };
                {
                    let mut state = self.session_state_mut(session_id);
                    if let Some(group) = state.active_tool_group_mut() {
                        group.calls.push(entry);
                    } else {
                        state.set_active_tool_group(Some(ToolCallGroup {
                            calls: vec![entry],
                            expanded: false,
                        }));
                    }
                }
                if self.is_current_session(session_id) {
                    tracing::info!(
                        "[TUI] ToolCallStarted: {} (active_group={}, msg_count={})",
                        tool_name,
                        self.active_tool_group.is_some(),
                        self.messages.len()
                    );
                    if self.auto_scroll {
                        self.scroll_offset = 0;
                    }
                }
            }
            TuiEvent::IntermediateText {
                session_id,
                text,
                reasoning,
            } => {
                // Background sessions also flush text + tool groups
                // between agent rounds — routing this through the
                // session_state_mut helper means the inactive pane
                // sees flushed assistant messages and tool-group
                // bullets as they happen instead of only on focus
                // switch. The original `is_processing` guard moves
                // into the foreground-only `intermediate_text_received`
                // mirror at the bottom; background sessions don't
                // use that flag (it gates the foreground "the agent
                // is mid-stream" detection and would force-clear
                // useful state if mirrored).
                let is_foreground = self.is_current_session(session_id);
                if is_foreground {
                    tracing::info!(
                        "[TUI] IntermediateText: len={} active_group={} streaming={}",
                        text.len(),
                        self.active_tool_group.is_some(),
                        self.streaming_response.is_some()
                    );
                }

                // Capture reasoning from the routed state's streaming
                // accumulator: foreground uses self.streaming_reasoning,
                // background uses the sidecar's. Either way the take()
                // clears the source so the next round starts fresh.
                let reasoning_details = if let Some(r) = reasoning {
                    Some(r)
                } else {
                    let mut state = self.session_state_mut(session_id);
                    match &mut state {
                        super::background_session::SessionStateMut::Foreground(app) => {
                            app.streaming_reasoning.take()
                        }
                        super::background_session::SessionStateMut::Background(bg) => {
                            bg.streaming_reasoning.take()
                        }
                    }
                };

                // Build a tool_group DisplayMessage helper.
                let make_tool_group = |group: ToolCallGroup| DisplayMessage {
                    id: Uuid::new_v4(),
                    role: "tool_group".to_string(),
                    content: format!(
                        "{} tool call{}",
                        group.calls.len(),
                        if group.calls.len() == 1 { "" } else { "s" }
                    ),
                    timestamp: chrono::Utc::now(),
                    token_count: None,
                    cost: None,
                    approval: None,
                    approve_menu: None,
                    details: None,
                    expanded: false,
                    tool_group: Some(group),
                };

                // Raw vs stripped accounting for the "eating intermediate
                // text" diagnosis (2026-06-05). Three IntermediateText
                // events emitted with text len=82/23/66 but only TWO
                // rows showed in chat. Cause: `strip_llm_artifacts` was
                // zeroing some inputs (e.g. text that was 100% HTML
                // comments or XML tool markers), which then fell into
                // the `has_reasoning && !has_text` branch and merged
                // into prior thinking — silently swallowing what the
                // model actually said.
                let raw_text_trimmed_len = text.trim().chars().count();
                let raw_text_was_nonempty = raw_text_trimmed_len > 0;
                let text_clean = crate::utils::sanitize::strip_llm_artifacts(&text);
                let stripped_len = text_clean.trim().chars().count();
                let stripped_to_empty = raw_text_was_nonempty && stripped_len == 0;

                if stripped_to_empty {
                    // Loud trace so the next repro nails which marker
                    // is over-stripping. Quote the raw text (cap so a
                    // pathological 10 KB block doesn't flood the log)
                    // for offline analysis.
                    let preview: String = text.chars().take(500).collect();
                    tracing::warn!(
                        "[IntermediateText] strip_llm_artifacts ate ALL {} chars of intermediate text — \
                         falling back to RAW text so the message isn't lost. \
                         Raw preview (up to 500 chars): {:?}",
                        raw_text_trimmed_len,
                        preview
                    );
                } else if raw_text_was_nonempty && stripped_len < raw_text_trimmed_len {
                    tracing::debug!(
                        "[IntermediateText] strip_llm_artifacts trimmed {} → {} chars",
                        raw_text_trimmed_len,
                        stripped_len
                    );
                }

                // Pick the text to actually display: stripped when it
                // kept ANY content, raw when the strip zeroed it out.
                // Raw fallback preserves the visible intermediate so it
                // doesn't get silently rolled into reasoning — markdown
                // rendering hides HTML comments naturally; CODE_EDIT_BLOCK
                // fences render as code blocks (still ugly but visible
                // beats vanished).
                let display_text = if stripped_to_empty {
                    text.clone()
                } else {
                    text_clean.clone()
                };
                let has_text = !display_text.trim().is_empty();
                let has_reasoning = reasoning_details
                    .as_ref()
                    .is_some_and(|r| !r.trim().is_empty());

                {
                    let mut state = self.session_state_mut(session_id);
                    // Clear the in-flight streaming response — the
                    // text is now becoming a permanent message.
                    match &mut state {
                        super::background_session::SessionStateMut::Foreground(app) => {
                            app.streaming_response = None;
                            app.streaming_render_cache = None;
                        }
                        super::background_session::SessionStateMut::Background(bg) => {
                            bg.streaming_response = None;
                        }
                    }

                    state.reset_processing_clock();

                    if has_text {
                        // Standard case: flush prior tool group, then
                        // push assistant text+reasoning message.
                        if let Some(group) = state.take_active_tool_group() {
                            state.push_message(make_tool_group(group));
                        }
                        state.push_message(DisplayMessage {
                            id: Uuid::new_v4(),
                            role: "assistant".to_string(),
                            content: display_text,
                            timestamp: chrono::Utc::now(),
                            token_count: None,
                            cost: None,
                            approval: None,
                            approve_menu: None,
                            details: reasoning_details.clone(),
                            expanded: false,
                            tool_group: None,
                        });
                        // DB persistence happens in tool_loop's per-iteration
                        // append_content with `<!-- reasoning -->` markers — this
                        // DisplayMessage.id is TUI-local and intentionally does NOT
                        // match any DB row, so writing here would silently no-op.
                    } else if has_reasoning {
                        // Reasoning-only iteration: push a SEPARATE
                        // thinking row per LLM iteration. The previous
                        // implementation merged consecutive thinking-
                        // only events into one giant `details` blob —
                        // logs from 2026-06-05 showed six consecutive
                        // reasoning-only IntermediateText events
                        // (len=0 visible text) fusing into a single
                        // unreadable wall of thought. Each reasoning
                        // pass is its own logical step (the model
                        // explicitly decided to think more before
                        // emitting a tool call or text), so render
                        // them as discrete `▸ Thinking` rows the user
                        // can expand individually. Tool group flush
                        // still happens AFTER the thinking row so
                        // order stays: think → tools → next.
                        let reasoning_text = reasoning_details.unwrap_or_default();
                        state.push_message(DisplayMessage {
                            id: Uuid::new_v4(),
                            role: "assistant".to_string(),
                            content: String::new(),
                            timestamp: chrono::Utc::now(),
                            token_count: None,
                            cost: None,
                            approval: None,
                            approve_menu: None,
                            details: Some(reasoning_text),
                            expanded: false,
                            tool_group: None,
                        });
                        if let Some(group) = state.take_active_tool_group() {
                            state.push_message(make_tool_group(group));
                        }
                    } else {
                        // Pure flush trigger (CLI Ping with no
                        // pending content) — just flush the tool
                        // group if any.
                        if let Some(group) = state.take_active_tool_group() {
                            state.push_message(make_tool_group(group));
                        }
                    }
                }

                if is_foreground {
                    self.intermediate_text_received = true;
                    if self.auto_scroll {
                        self.scroll_offset = 0;
                    }
                }
            }
            TuiEvent::QueuedUserMessage { session_id, text } => {
                let is_foreground = self.is_current_session(session_id);
                if is_foreground {
                    tracing::info!(
                        "[TUI] QueuedUserMessage inline: len={} active_group={}",
                        text.len(),
                        self.active_tool_group.is_some()
                    );
                }

                {
                    let mut state = self.session_state_mut(session_id);
                    // Flush any active tool group so the queued user
                    // message appears after it in the chronological
                    // chat flow. Background sessions accumulate this
                    // in pending_messages and merge on focus return.
                    if let Some(group) = state.take_active_tool_group() {
                        let count = group.calls.len();
                        state.push_message(DisplayMessage {
                            id: Uuid::new_v4(),
                            role: "tool".to_string(),
                            content: format!(
                                "{} tool call{} completed",
                                count,
                                if count == 1 { "" } else { "s" }
                            ),
                            timestamp: chrono::Utc::now(),
                            token_count: None,
                            cost: None,
                            approval: None,
                            approve_menu: None,
                            details: None,
                            expanded: false,
                            tool_group: Some(group),
                        });
                    }

                    state.push_message(DisplayMessage {
                        id: Uuid::new_v4(),
                        role: "user".to_string(),
                        content: text,
                        timestamp: chrono::Utc::now(),
                        token_count: None,
                        cost: None,
                        approval: None,
                        approve_menu: None,
                        details: None,
                        expanded: false,
                        tool_group: None,
                    });
                }

                // Foreground-only post-hooks: the queued message has now been
                // echoed into the chat, so drop it from the per-session queue
                // map, and reset scroll. Do NOT touch input_buffer — it holds
                // whatever the user has started typing for their NEXT message,
                // which must survive a queued message entering mid-turn (else
                // their in-progress text is silently wiped, and arrow-up can't
                // get it back). Background sessions' queues are cleared by their
                // own send-loop on the channels side.
                if is_foreground {
                    if let Some(sid) = self.current_session.as_ref().map(|s| s.id)
                        && let Ok(mut q) = self.queued_messages.lock()
                    {
                        q.remove(&sid);
                    }
                    if self.auto_scroll {
                        self.scroll_offset = 0;
                    }
                }
            }
            TuiEvent::ToolCallCompleted {
                session_id,
                tool_name,
                tool_input,
                success,
                summary,
            } => {
                let desc = Self::format_tool_description(&tool_name, &tool_input);
                let details = if summary.is_empty() {
                    None
                } else {
                    Some(summary)
                };

                // Update the matching Started entry in the active
                // tool group (foreground OR background). Foreground
                // edits affect the active pane's render; background
                // edits keep the inactive pane's "X tool calls"
                // badge accurate live.
                {
                    let mut state = self.session_state_mut(session_id);
                    let updated = if let Some(group) = state.active_tool_group_mut() {
                        if let Some(existing) = group
                            .calls
                            .iter_mut()
                            .rev()
                            .find(|c| c.description == desc && !c.completed)
                        {
                            existing.success = success;
                            existing.details = details.clone();
                            existing.completed = true;
                            true
                        } else {
                            false
                        }
                    } else {
                        false
                    };
                    if !updated {
                        let entry = ToolCallEntry {
                            description: desc,
                            success,
                            details,
                            completed: true,
                            tool_input: tool_input.clone(),
                        };
                        if let Some(group) = state.active_tool_group_mut() {
                            group.calls.push(entry);
                        } else {
                            state.set_active_tool_group(Some(ToolCallGroup {
                                calls: vec![entry],
                                expanded: false,
                            }));
                        }
                    }
                }

                // Foreground-only flushes: message append, plan
                // reload, scroll. Background sessions accumulate
                // their group inside `active_tool_group` until the
                // session is promoted to foreground (where the next
                // IntermediateText / ResponseComplete handles the
                // flush) or until the agent's own DB-persisted
                // message arrives on focus switch via the
                // `preload_pane_session` reload path.
                if self.is_current_session(session_id) && self.is_processing {
                    self.processing_started_at = Some(std::time::Instant::now());
                    if tool_name == "plan" {
                        self.reload_plan();
                    }
                    if self.auto_scroll {
                        self.scroll_offset = 0;
                    }
                    let all_done = self
                        .active_tool_group
                        .as_ref()
                        .is_some_and(|g| g.calls.iter().all(|c| c.completed));
                    if all_done && let Some(group) = self.active_tool_group.take() {
                        let count = group.calls.len();
                        self.messages.push(DisplayMessage {
                            id: Uuid::new_v4(),
                            role: "tool_group".to_string(),
                            content: format!(
                                "{} tool call{}",
                                count,
                                if count == 1 { "" } else { "s" }
                            ),
                            timestamp: chrono::Utc::now(),
                            token_count: None,
                            cost: None,
                            approval: None,
                            approve_menu: None,
                            details: None,
                            expanded: false,
                            tool_group: Some(group),
                        });
                    }
                }
            }
            TuiEvent::BuildLine(line) => {
                // Keep a rolling window of the last 6 build lines
                self.build_lines.push(line);
                if self.build_lines.len() > 6 {
                    self.build_lines.remove(0);
                }
                // Build the display content: header + rolling lines
                let content = format!("🦀 Building OpenCrabs...\n{}", self.build_lines.join("\n"));
                if let Some(idx) = self.build_msg_idx {
                    // Update existing build message in place
                    if let Some(msg) = self.messages.get_mut(idx) {
                        msg.content = content;
                    }
                } else {
                    // Create the build progress message
                    self.messages.push(DisplayMessage {
                        id: Uuid::new_v4(),
                        role: "system".to_string(),
                        content,
                        timestamp: chrono::Utc::now(),
                        token_count: None,
                        cost: None,
                        approval: None,
                        approve_menu: None,
                        details: None,
                        expanded: false,
                        tool_group: None,
                    });
                    self.build_msg_idx = Some(self.messages.len() - 1);
                }
                self.scroll_offset = 0;
            }
            TuiEvent::RestartReady {
                status,
                binary_path,
            } => {
                // Clear build progress
                if let Some(idx) = self.build_msg_idx.take()
                    && idx < self.messages.len()
                {
                    self.messages.remove(idx);
                }
                self.build_lines.clear();
                self.rebuild_status = None;
                tracing::info!("RestartReady: {status}");
                // Auto exec() restart — no prompt, no permission needed.
                if let Some(session) = &self.current_session {
                    let session_id = session.id;
                    // Prefer the exact binary the producer built (/rebuild);
                    // fall back to current_exe() via auto_detect only when no
                    // path was given (/evolve replaced the exe in place).
                    let result = match &binary_path {
                        Some(path) => SelfUpdater::restart_into(path, session_id),
                        None => SelfUpdater::auto_detect().and_then(|u| u.restart(session_id)),
                    };
                    // Only reached on error — exec() replaces the process.
                    if let Err(e) = result {
                        self.show_error(format!("Restart failed: {}", e));
                        self.switch_mode(AppMode::Chat).await?;
                    }
                }
            }
            TuiEvent::ConfigReloaded => {
                // Refresh commands autocomplete
                self.reload_user_commands();
                // Refresh approval policy
                (self.approval_auto_session, self.approval_auto_always) =
                    Self::read_approval_policy_from_config();
                // Refresh the context-budget footer. A changed
                // `providers.<name>.context_window` (or a provider swap from new
                // keys) changes the effective window; the watcher fires this
                // event AFTER swapping the provider, so re-read it now. Mirrors
                // the load_session path so the active session updates at once.
                if let Some(session) = self.current_session.as_ref() {
                    let sid = session.id;
                    let max_ctx = self.agent_service.context_limit_for_session(sid);
                    self.context_max_tokens = max_ctx;
                    self.session_context_max.insert(sid, max_ctx);
                }
                // Provider swap is already handled by the ConfigWatcher callback
                // (ui.rs). Do NOT re-create the provider here — it causes a
                // redundant create_provider call every reload, and the model-name
                // comparison (config alias vs provider full ID) never matches,
                // so it would fire on every single reload.
                tracing::info!(
                    "Config reloaded — refreshed commands, approval policy, context budget"
                );
            }
            TuiEvent::TokenCountUpdated { session_id, count } => {
                // Always cache the per-session value so a future
                // focus switch shows accurate context usage.
                self.session_input_tokens.insert(session_id, count as u32);
                // Mirror into the visible display fields via the
                // routing helper so the inactive pane's footer
                // updates live, not just on focus switch.
                let mut state = self.session_state_mut(session_id);
                state.set_display_token_count(count);
                state.set_last_input_tokens(count as u32);
            }
            TuiEvent::StreamingOutputTokens { session_id, tokens } => {
                self.session_state_mut(session_id)
                    .add_streaming_output_tokens(tokens);
            }
            // Automatic compaction is fully silent — the agent's
            // `ProgressEvent::CompactionSummary` is dropped at the
            // channel bridge (`cli/ui.rs:528-530`, "summary goes to
            // memory log only") and manual `/compact` triggers a
            // normal `MessageSubmitted` rather than this variant.
            // Nothing in the codebase constructs
            // `TuiEvent::CompactionSummary` today; this no-op arm
            // exists only so a future re-wiring of visible
            // compaction has a designated landing site rather than
            // silently falling through to a panic.
            TuiEvent::CompactionSummary { .. } => {}

            TuiEvent::SessionTitleUpdated { session_id, title } => {
                // Cheap in-memory refresh — update the title field on
                // current_session if it matches, and on the cached
                // sessions list entry so the /sessions screen reflects
                // the new title without a re-query. No DB roundtrip, no
                // message reload, no scroll disturbance. Fires from the
                // auto-title spawn in tool_loop after the first user
                // message of a fresh session.
                if let Some(ref mut s) = self.current_session
                    && s.id == session_id
                {
                    s.title = Some(title.clone());
                }
                if let Some(entry) = self.sessions.iter_mut().find(|s| s.id == session_id) {
                    entry.title = Some(title);
                }
            }

            TuiEvent::SessionUpdated(session_id) => {
                // A remote channel updated a session. Don't reload immediately —
                // during multi-tool runs this fires after every tool call, and each
                // reload is a blocking DB query that freezes the event loop (making
                // Ctrl+C unresponsive and garbling the display). Instead, debounce:
                // schedule a refresh and let the main loop's idle tick handle it.
                if self.is_current_session(session_id) {
                    // Only schedule refresh if the session isn't being processed
                    // by the TUI itself (channel processing is fine — the refresh
                    // fires after ChannelProcessingFinished).
                    if !self.processing_sessions.contains(&session_id)
                        || self.channel_processing_sessions.contains(&session_id)
                    {
                        self.pending_session_refresh =
                            Some((session_id, std::time::Instant::now()));
                    }
                } else {
                    self.sessions_with_unread.insert(session_id);
                }
            }

            TuiEvent::ChannelProcessingStarted(session_id) => {
                self.channel_processing_sessions.insert(session_id);
                self.processing_sessions.insert(session_id);
                // Mark the session as processing in foreground OR
                // background state so the inactive pane's
                // `[processing...]` label fires the moment a remote
                // channel starts a turn, not on focus switch.
                self.session_state_mut(session_id).set_processing(true);
            }

            TuiEvent::ChannelProcessingFinished(session_id) => {
                self.channel_processing_sessions.remove(&session_id);
                // Foreground-only safeguard: only clear the
                // foreground's processing/cancel_token state when
                // this is the focused session AND no local task is
                // also running. Background sessions clear via the
                // routing helper unconditionally — their turn really
                // did just finish.
                let clear_state = if self.is_current_session(session_id) {
                    self.cancel_token.is_none()
                } else {
                    true
                };
                if clear_state {
                    self.processing_sessions.remove(&session_id);
                    self.session_state_mut(session_id).set_processing(false);
                    if self.is_current_session(session_id) {
                        // Schedule a debounced refresh instead of blocking with
                        // load_session().await — a direct DB query here freezes the
                        // event loop, eating queued terminal events and garbling the
                        // display when channels process messages in parallel.
                        self.pending_session_refresh =
                            Some((session_id, std::time::Instant::now()));
                    }
                }
            }

            TuiEvent::PendingResumed {
                session_id,
                cancel_token,
            } => {
                // A pending request was resumed on startup — wire the cancel token
                // so double-Escape can abort it.
                self.processing_sessions.insert(session_id);
                if self.is_current_session(session_id) {
                    self.is_processing = true;
                    self.processing_started_at = Some(std::time::Instant::now());
                    self.cancel_token = Some(cancel_token);
                } else {
                    self.session_cancel_tokens.insert(session_id, cancel_token);
                }
            }

            TuiEvent::OnboardingModelsFetched(models) => {
                if let Some(ref mut wizard) = self.onboarding {
                    wizard.ps.models_fetching = false;
                    if !models.is_empty() {
                        wizard.ps.models = models;
                        wizard.ps.resolve_selected_model_index();
                    } else {
                        // Fetch returned empty — fall back to static PROVIDERS models
                        let provider = wizard.ps.current_provider();
                        if !provider.models.is_empty() {
                            wizard.ps.models =
                                provider.models.iter().map(|s| s.to_string()).collect();
                            wizard.ps.resolve_selected_model_index();
                        }
                    }
                }
            }
            TuiEvent::GitHubDeviceCode(code) => {
                if let Some(ref mut wizard) = self.onboarding {
                    wizard.github_user_code = Some(code);
                    wizard.github_device_flow_status =
                        super::onboarding::GitHubDeviceFlowStatus::WaitingForUser;
                }
            }
            TuiEvent::GitHubOAuthComplete(oauth_token) => {
                if let Some(ref mut wizard) = self.onboarding {
                    wizard.github_device_flow_status =
                        super::onboarding::GitHubDeviceFlowStatus::Complete;
                    // Save the OAuth token to keys.toml
                    if let Err(e) =
                        crate::config::write_secret_key("providers.github", "api_key", &oauth_token)
                    {
                        tracing::warn!("Failed to save Copilot OAuth token: {}", e);
                    }
                    // Mark key as existing and advance to model selection
                    wizard.ps.api_key_input = super::onboarding::EXISTING_KEY_SENTINEL.to_string();
                    wizard.auth_field = super::onboarding::AuthField::Model;
                    wizard.ps.models.clear();
                    wizard.ps.selected_model = 0;
                    // Trigger model fetch using the OAuth token
                    let token = oauth_token.clone();
                    let sender = self.event_sender();
                    tokio::spawn(async move {
                        let models =
                            super::onboarding::fetch_provider_models(2, Some(&token), None, None)
                                .await;
                        let _ = sender.send(TuiEvent::OnboardingModelsFetched(models));
                    });
                }
            }
            TuiEvent::GitHubOAuthError(err) => {
                if let Some(ref mut wizard) = self.onboarding {
                    wizard.github_device_flow_status =
                        super::onboarding::GitHubDeviceFlowStatus::Failed(err);
                    wizard.github_user_code = None;
                }
            }
            TuiEvent::CodexDeviceCode(code) => {
                if let Some(ref mut wizard) = self.onboarding {
                    wizard.ps.codex_user_code = Some(code);
                    wizard.ps.codex_device_flow_status =
                        super::onboarding::CodexDeviceFlowStatus::WaitingForUser;
                }
            }
            TuiEvent::CodexOAuthComplete => {
                if let Some(ref mut wizard) = self.onboarding {
                    wizard.ps.codex_device_flow_status =
                        super::onboarding::CodexDeviceFlowStatus::Complete;
                    // Mark as authenticated (no API key needed, tokens stored separately)
                    wizard.ps.api_key_input = super::onboarding::EXISTING_KEY_SENTINEL.to_string();
                    wizard.auth_field = super::onboarding::AuthField::Model;
                    wizard.ps.models.clear();
                    wizard.ps.selected_model = 0;
                    // Enable the provider in config
                    let _ = crate::config::Config::write_key("providers.codex", "enabled", "true");
                    // Trigger model fetch
                    let sender = self.event_sender();
                    tokio::spawn(async move {
                        let models =
                            super::onboarding::fetch_provider_models(2, None, None, None).await;
                        let _ = sender.send(TuiEvent::OnboardingModelsFetched(models));
                    });
                }
            }
            TuiEvent::CodexOAuthError(err) => {
                if let Some(ref mut wizard) = self.onboarding {
                    wizard.ps.codex_device_flow_status =
                        super::onboarding::CodexDeviceFlowStatus::Failed(err);
                    wizard.ps.codex_user_code = None;
                }
            }
            TuiEvent::WhatsAppQrCode(qr_data) => {
                if let Some(ref mut wizard) = self.onboarding {
                    wizard.set_whatsapp_qr(&qr_data);
                }
            }
            TuiEvent::WhatsAppConnected => {
                if let Some(ref mut wizard) = self.onboarding {
                    wizard.set_whatsapp_connected();
                    let _ =
                        crate::config::Config::write_key("channels.whatsapp", "enabled", "true");
                }
            }
            TuiEvent::WhatsAppError(err) => {
                if let Some(ref mut wizard) = self.onboarding {
                    wizard.set_whatsapp_error(err);
                }
            }
            TuiEvent::ChannelTestResult {
                success,
                error,
                detected_telegram_user_id,
                ..
            } => {
                if let Some(ref mut wizard) = self.onboarding {
                    wizard.channel_test_status = if success {
                        super::onboarding::ChannelTestStatus::Success
                    } else {
                        super::onboarding::ChannelTestStatus::Failed(
                            error.unwrap_or_else(|| "Unknown error".to_string()),
                        )
                    };
                    // Auto-fill detected Telegram user ID
                    if let Some(ref uid) = detected_telegram_user_id
                        && wizard.telegram_user_id_input.is_empty()
                    {
                        wizard.telegram_user_id_input = uid.clone();
                    }
                }
            }
            TuiEvent::BrainGenerationResult { result } => match result {
                Ok(msg) => {
                    self.push_system_message(format!("{}", msg));
                }
                Err(e) => {
                    self.push_system_message(format!("Brain generation: {}", e));
                }
            },
            TuiEvent::WhisperDownloadProgress(progress) => {
                if let Some(ref mut wizard) = self.onboarding {
                    wizard.stt_model_download_progress = Some(progress);
                }
            }
            TuiEvent::WhisperDownloadComplete(result) => {
                if let Some(ref mut wizard) = self.onboarding {
                    wizard.stt_model_download_progress = None;
                    match result {
                        Ok(()) => {
                            wizard.stt_model_downloaded = true;
                            wizard.stt_model_download_error = None;
                        }
                        Err(e) => {
                            wizard.stt_model_download_error = Some(e);
                        }
                    }
                }
            }
            TuiEvent::PiperDownloadProgress(progress) => {
                if let Some(ref mut wizard) = self.onboarding {
                    // Ignore stale progress events after download completed
                    if !wizard.tts_voice_downloaded {
                        wizard.tts_voice_download_progress = Some(progress);
                    }
                }
            }
            TuiEvent::PiperDownloadComplete(result) => {
                if let Some(ref mut wizard) = self.onboarding {
                    wizard.tts_voice_download_progress = None;
                    match result {
                        #[cfg(feature = "local-tts")]
                        Ok(voice_id) => {
                            wizard.tts_voice_downloaded = true;
                            wizard.tts_voice_download_error = None;
                            tokio::spawn(async move {
                                if let Err(e) =
                                    crate::channels::voice::local_tts::preview_voice(&voice_id)
                                        .await
                                {
                                    tracing::warn!("Voice preview failed: {}", e);
                                }
                            });
                        }
                        #[cfg(not(feature = "local-tts"))]
                        Ok(_) => {
                            wizard.tts_voice_downloaded = true;
                            wizard.tts_voice_download_error = None;
                        }
                        Err(e) => {
                            wizard.tts_voice_download_error = Some(e);
                        }
                    }
                }
            }
            TuiEvent::SudoPasswordRequested(request) => {
                self.sudo_pending = Some(request);
                self.sudo_input.clear();
            }
            TuiEvent::SshPasswordRequested(request) => {
                self.ssh_pending = Some(request);
                self.ssh_input.clear();
            }
            TuiEvent::SystemMessage { session_id, text } => {
                // Self-healing alerts and other session-scoped system
                // messages must stay in the session that triggered them so
                // other open sessions never see a 🔧 alert that belongs to a
                // different chat. `Uuid::nil()` is a sentinel for global
                // notices (e.g. auto-update banner) that always show in the
                // currently focused session.
                if session_id == Uuid::nil() || self.is_current_session(session_id) {
                    self.push_system_message(text);
                }
            }
            TuiEvent::ProviderSwitched {
                session_id,
                to_name,
                to_model,
                reason: _,
            } => {
                // A fallback in one session must never leak into another
                // pane's footer, AND must always stick — both in DB (survives
                // restart) and in session_providers (so the next turn doesn't
                // re-walk the failing primary). Background sessions are the
                // critical case: if the session isn't currently focused, the
                // sessions cache may not contain it and the in-memory pin may
                // still point at the wrapper that just failed.
                let mut updated_in_cache = false;
                if let Some(target_session) = self.sessions.iter_mut().find(|s| s.id == session_id)
                {
                    target_session.provider_name = Some(to_name.clone());
                    target_session.model = Some(to_model.clone());
                    let target_copy = target_session.clone();
                    updated_in_cache = true;
                    if let Err(e) = self.session_service.update_session(&target_copy).await {
                        tracing::warn!(
                            "Failed to persist provider swap to session {}: {}",
                            session_id,
                            e
                        );
                    }
                }
                if !updated_in_cache {
                    // Cache miss — fetch fresh from DB and update directly so
                    // the swap persists regardless of what's loaded into the
                    // sessions sidebar. Without this, fallbacks fired on a
                    // session that isn't currently in the cache silently drop
                    // their persistence and the next turn re-runs the bounce.
                    match self.session_service.get_session(session_id).await {
                        Ok(Some(mut s)) => {
                            s.provider_name = Some(to_name.clone());
                            s.model = Some(to_model.clone());
                            if let Err(e) = self.session_service.update_session(&s).await {
                                tracing::warn!(
                                    "Failed to persist provider swap to uncached session {}: {}",
                                    session_id,
                                    e
                                );
                            }
                        }
                        Ok(None) => {
                            tracing::warn!("ProviderSwitched for unknown session {}", session_id);
                        }
                        Err(e) => {
                            tracing::warn!(
                                "Failed to load session {} for provider swap persistence: {}",
                                session_id,
                                e
                            );
                        }
                    }
                }

                // Always rebuild a clean session_providers entry from config
                // by name — for every session, focused or not. The agent's
                // own swap at tool_loop.rs:1302 reuses the fallback Arc,
                // which can still carry the failing primary internally. A
                // fresh by-name build is what makes the swap actually stick.
                if let Ok(config) = crate::config::Config::load()
                    && let Ok(new_provider) =
                        crate::brain::provider::factory::create_provider_by_name(&config, &to_name)
                            .await
                {
                    // Pair the rebuilt provider with the fallback's remapped
                    // model (to_model) atomically.
                    self.agent_service.swap_provider_for_session(
                        session_id,
                        new_provider.clone(),
                        to_model.clone(),
                    );
                    self.provider_cache.insert(to_name.clone(), new_provider);
                    tracing::info!(
                        "[ProviderSwitched] rebuilt session_providers for session {} → {}",
                        session_id,
                        to_name
                    );
                }

                // Footer + current_session mirror only when the swapped
                // session is the focused one. Other panes keep their own.
                if self.is_current_session(session_id) {
                    self.default_model_name = to_model.clone();
                    if let Some(ref mut session) = self.current_session {
                        session.provider_name = Some(to_name.clone());
                        session.model = Some(to_model.clone());
                    }
                }
            }
            TuiEvent::UpdateAvailable(version) => {
                self.update_available_version = Some(version);
                self.switch_mode(AppMode::UpdatePrompt).await?;
            }
            TuiEvent::FocusGained | TuiEvent::FocusLost => {
                // Handled by the event loop for tick coalescing
            }
            TuiEvent::Resize(w, h) => {
                // Invalidate render cache on terminal resize (content width changes)
                self.render_cache.clear();
                // Store new dimensions so the runner can pre-resize ratatui
                // buffers without clearing the screen (avoids blink).
                self.pending_resize = Some((w, h));
            }
            TuiEvent::AgentProcessing => {
                // Handled by the render loop
            }
        }
        Ok(())
    }

    /// Handle keyboard input
    async fn handle_key_event(&mut self, event: crossterm::event::KeyEvent) -> Result<()> {
        use super::events::keys;
        use crossterm::event::{KeyCode, KeyModifiers};

        // F12 toggles mouse capture so the user can drag-select text natively.
        // Handled before everything else (including modal dialogs) so it always
        // works as an escape hatch when the TUI is hogging mouse events.
        if event.code == KeyCode::F(12) {
            self.mouse_capture_enabled = !self.mouse_capture_enabled;
            self.notification = Some(if self.mouse_capture_enabled {
                "Mouse capture ON (F12 to enable text selection)".to_string()
            } else {
                "Mouse capture OFF — drag to select, F12 to re-enable".to_string()
            });
            self.notification_shown_at = Some(std::time::Instant::now());
            return Ok(());
        }

        // Sudo password dialog intercepts all keys when active
        if self.sudo_pending.is_some() {
            match event.code {
                KeyCode::Enter => {
                    // Submit password
                    if let Some(request) = self.sudo_pending.take() {
                        let password = std::mem::take(&mut self.sudo_input);
                        let _ = request.response_tx.send(SudoPasswordResponse {
                            password: Some(password),
                        });
                    }
                }
                KeyCode::Esc => {
                    // Cancel sudo
                    if let Some(request) = self.sudo_pending.take() {
                        let _ = request
                            .response_tx
                            .send(SudoPasswordResponse { password: None });
                    }
                    self.sudo_input.clear();
                }
                KeyCode::Backspace => {
                    self.sudo_input.pop();
                }
                KeyCode::Char(c) => {
                    self.sudo_input.push(c);
                }
                _ => {}
            }
            return Ok(());
        }

        // SSH password dialog intercepts all keys when active. Same UX as sudo.
        if self.ssh_pending.is_some() {
            match event.code {
                KeyCode::Enter => {
                    if let Some(request) = self.ssh_pending.take() {
                        let password = std::mem::take(&mut self.ssh_input);
                        let _ = request.response_tx.send(SshPasswordResponse {
                            password: Some(password),
                        });
                    }
                }
                KeyCode::Esc => {
                    if let Some(request) = self.ssh_pending.take() {
                        let _ = request
                            .response_tx
                            .send(SshPasswordResponse { password: None });
                    }
                    self.ssh_input.clear();
                }
                KeyCode::Backspace => {
                    self.ssh_input.pop();
                }
                KeyCode::Char(c) => {
                    self.ssh_input.push(c);
                }
                _ => {}
            }
            return Ok(());
        }

        // Ctrl+C: first press clears input, second press (within 3s) quits.
        // When scrolled up, first press snaps back to bottom instead.
        if keys::is_quit(&event) {
            if !self.auto_scroll {
                // User is scrolled up — snap to bottom, clear input, no quit hint
                self.scroll_offset = 0;
                self.auto_scroll = true;
                self.input_buffer.clear();
                self.cursor_position = 0;
                self.slash_suggestions_active = false;
                self.error_message = None;
                self.error_message_shown_at = None;
                self.ctrl_c_pending_at = None;
                return Ok(());
            }
            if let Some(pending_at) = self.ctrl_c_pending_at
                && pending_at.elapsed() < std::time::Duration::from_secs(3)
            {
                // Second Ctrl+C within window — quit
                // Cancel any running agent task
                if let Some(token) = &self.cancel_token {
                    token.cancel();
                }
                self.pane_manager.save_layout();
                self.should_quit = true;
                // Force exit after 1s in case spawn_blocking tasks are stuck
                tokio::spawn(async {
                    tokio::time::sleep(std::time::Duration::from_secs(1)).await;
                    std::process::exit(0);
                });
                return Ok(());
            }
            // First Ctrl+C — clear input and show hint
            self.input_buffer.clear();
            self.cursor_position = 0;
            self.slash_suggestions_active = false;
            self.error_message = Some("Press Ctrl+C again to quit".to_string());
            self.error_message_shown_at = Some(std::time::Instant::now());
            self.ctrl_c_pending_at = Some(std::time::Instant::now());
            return Ok(());
        }

        // Any non-Ctrl+C key resets the quit confirmation
        self.ctrl_c_pending_at = None;

        // Delete word — comprehensive handling across platforms.
        // macOS Option+Delete, Ctrl+Backspace, Ctrl+W, Ctrl+H — all delete the
        // previous word.  Terminals encode these in many ways:
        //   - KeyCode::Backspace + ALT/CONTROL modifier (standard)
        //   - KeyCode::Char('\x7f') + ALT (macOS Option+Delete with enhancement)
        //   - KeyCode::Char('\x08') + CONTROL (Ctrl+Backspace as Ctrl+H)
        //   - KeyCode::Char('h') + CONTROL (Ctrl+H without enhancement)
        //   - KeyCode::Char('w') + CONTROL (Ctrl+W)
        //   - KeyCode::Char('\x17') + CONTROL or NONE (Ctrl+W raw)
        {
            let is_delete_word = match event.code {
                KeyCode::Backspace => {
                    event.modifiers.contains(KeyModifiers::CONTROL)
                        || event.modifiers.contains(KeyModifiers::ALT)
                        || event.modifiers.contains(KeyModifiers::SUPER)
                }
                KeyCode::Char('\x7f') => {
                    // DEL char — macOS Option+Delete with keyboard enhancement
                    event.modifiers.contains(KeyModifiers::ALT)
                        || event.modifiers.contains(KeyModifiers::CONTROL)
                        || event.modifiers.contains(KeyModifiers::SUPER)
                        || event.modifiers.is_empty()
                }
                KeyCode::Char('\x08') => true, // raw Ctrl+H / Ctrl+Backspace
                KeyCode::Char('\x17') => true, // raw Ctrl+W
                KeyCode::Char('h') => event.modifiers.contains(KeyModifiers::CONTROL),
                KeyCode::Char('w') => event.modifiers.contains(KeyModifiers::CONTROL),
                _ => false,
            };
            if is_delete_word {
                self.delete_last_word();
                return Ok(());
            }
        }

        // Ctrl+Left or Alt+Left — jump to previous word boundary
        if event.code == KeyCode::Left
            && (event.modifiers.contains(KeyModifiers::CONTROL)
                || event.modifiers.contains(KeyModifiers::ALT))
        {
            let before = &self.input_buffer[..self.cursor_position];
            // Skip whitespace, then find start of word
            let trimmed = before.trim_end();
            self.cursor_position = trimmed
                .rfind(char::is_whitespace)
                .map(|pos| trimmed.ceil_char_boundary(pos + 1))
                .unwrap_or(0);
            return Ok(());
        }
        // macOS: Option+Left sends Char('b') with Alt modifier in some terminals
        if event.code == KeyCode::Char('b') && event.modifiers.contains(KeyModifiers::ALT) {
            let before = &self.input_buffer[..self.cursor_position];
            let trimmed = before.trim_end();
            self.cursor_position = trimmed
                .rfind(char::is_whitespace)
                .map(|pos| trimmed.ceil_char_boundary(pos + 1))
                .unwrap_or(0);
            return Ok(());
        }

        // Ctrl+Right or Alt+Right — jump to next word boundary
        if event.code == KeyCode::Right
            && (event.modifiers.contains(KeyModifiers::CONTROL)
                || event.modifiers.contains(KeyModifiers::ALT))
        {
            let after = &self.input_buffer[self.cursor_position..];
            // Skip current word chars, then skip whitespace
            let word_end = after.find(char::is_whitespace).unwrap_or(after.len());
            let rest = &after[word_end..];
            let space_end = rest
                .find(|c: char| !c.is_whitespace())
                .unwrap_or(rest.len());
            self.cursor_position += word_end + space_end;
            return Ok(());
        }
        // macOS: Option+Right sends Char('f') with Alt modifier in some terminals
        if event.code == KeyCode::Char('f') && event.modifiers.contains(KeyModifiers::ALT) {
            let after = &self.input_buffer[self.cursor_position..];
            let word_end = after.find(char::is_whitespace).unwrap_or(after.len());
            let rest = &after[word_end..];
            let space_end = rest
                .find(|c: char| !c.is_whitespace())
                .unwrap_or(rest.len());
            self.cursor_position += word_end + space_end;
            return Ok(());
        }

        // Ctrl+U — delete to start of current line
        if event.code == KeyCode::Char('u') && event.modifiers == KeyModifiers::CONTROL {
            let line_start = self.input_buffer[..self.cursor_position]
                .rfind('\n')
                .map(|i| i + 1)
                .unwrap_or(0);
            self.input_buffer.drain(line_start..self.cursor_position);
            self.cursor_position = line_start;
            return Ok(());
        }

        if keys::is_new_session(&event) {
            self.create_new_session().await?;
            return Ok(());
        }

        if keys::is_list_sessions(&event) {
            self.switch_mode(AppMode::Sessions).await?;
            return Ok(());
        }

        if keys::is_clear_session(&event) {
            self.clear_session().await?;
            return Ok(());
        }

        // Split pane focus & close (global — work from Chat mode)
        if keys::is_close_pane(&event) && self.pane_manager.is_split() {
            self.pane_manager.close_focused();
            self.pane_manager.save_layout();
            if let Some(pane) = self.pane_manager.focused_pane()
                && let Some(session_id) = pane.session_id
            {
                self.load_session(session_id).await?;
                // Ensure the session's provider entry exists in the HashMap
                // after load. load_session skips swap if saved == current,
                // but current may be from global fallback (closed pane's
                // provider), causing contamination in the footer.
                if let Some(ref session) = self.current_session
                    && let Some(ref saved_provider) = session.provider_name
                {
                    let current_prov = self.agent_service.provider_name_for_session(session.id);
                    if saved_provider != &current_prov
                        && let Some(cached) = self.provider_cache.get(saved_provider).cloned()
                    {
                        // Restore the session's saved provider+model pair.
                        let model = session
                            .model
                            .clone()
                            .unwrap_or_else(|| cached.default_model().to_string());
                        self.agent_service
                            .swap_provider_for_session(session.id, cached, model);
                    }
                }
            }
            return Ok(());
        }
        if keys::is_focus_next_pane(&event) && self.pane_manager.is_split() {
            self.pane_manager.focus_next();
            if let Some(pane) = self.pane_manager.focused_pane()
                && let Some(session_id) = pane.session_id
            {
                self.load_session(session_id).await?;
                // Ensure the session's provider entry exists in the HashMap
                // after load. load_session skips swap if saved == current,
                // but current may be from global fallback (other pane's
                // provider), causing contamination in the footer.
                if let Some(ref session) = self.current_session
                    && let Some(ref saved_provider) = session.provider_name
                {
                    let current_prov = self.agent_service.provider_name_for_session(session.id);
                    if saved_provider != &current_prov
                        && let Some(cached) = self.provider_cache.get(saved_provider).cloned()
                    {
                        // Restore the session's saved provider+model pair.
                        let model = session
                            .model
                            .clone()
                            .unwrap_or_else(|| cached.default_model().to_string());
                        self.agent_service
                            .swap_provider_for_session(session.id, cached, model);
                    }
                }
            }
            return Ok(());
        }

        // Mode-specific handling
        tracing::trace!("Current mode: {:?}", self.mode);
        match self.mode {
            AppMode::Chat => self.handle_chat_key(event).await?,
            AppMode::Sessions => self.handle_sessions_key(event).await?,
            AppMode::FilePicker => self.handle_file_picker_key(event).await?,
            AppMode::DirectoryPicker => self.handle_directory_picker_key(event).await?,
            AppMode::UsageDashboard => {
                use crossterm::event::KeyCode;
                match event.code {
                    KeyCode::Esc => {
                        self.dashboard_state = None;
                        self.switch_mode(AppMode::Chat).await?;
                    }
                    KeyCode::Tab => {
                        if let Some(ds) = &mut self.dashboard_state {
                            ds.focus_next();
                        }
                    }
                    KeyCode::BackTab => {
                        if let Some(ds) = &mut self.dashboard_state {
                            ds.focus_prev();
                        }
                    }
                    KeyCode::Char('t') | KeyCode::Char('T') => {
                        self.set_dashboard_period(crate::usage::data::Period::Today)
                            .await;
                    }
                    KeyCode::Char('w') | KeyCode::Char('W') => {
                        self.set_dashboard_period(crate::usage::data::Period::Week)
                            .await;
                    }
                    KeyCode::Char('m') | KeyCode::Char('M') => {
                        self.set_dashboard_period(crate::usage::data::Period::Month)
                            .await;
                    }
                    KeyCode::Char('a') | KeyCode::Char('A') => {
                        self.set_dashboard_period(crate::usage::data::Period::AllTime)
                            .await;
                    }
                    _ => {}
                }
            }
            AppMode::RestartPending => {
                if keys::is_cancel(&event) {
                    self.rebuild_status = None;
                    self.switch_mode(AppMode::Chat).await?;
                } else if keys::is_enter(&event) {
                    // Perform the restart
                    if let Some(session) = &self.current_session {
                        let session_id = session.id;
                        if let Ok(updater) = SelfUpdater::auto_detect()
                            && let Err(e) = updater.restart(session_id)
                        {
                            self.show_error(format!("Restart failed: {}", e));
                            self.switch_mode(AppMode::Chat).await?;
                        }
                        // If restart succeeds, this process is replaced — we never reach here
                    }
                }
            }
            AppMode::UpdatePrompt => {
                if keys::is_cancel(&event) {
                    // Decline — return to chat so user keeps working on current version
                    self.update_available_version = None;
                    self.switch_mode(AppMode::Chat).await?;
                } else if keys::is_enter(&event) {
                    let version = self.update_available_version.take();
                    self.switch_mode(AppMode::Chat).await?;
                    if let Some(v) = version {
                        self.push_system_message(format!("Updating to v{}...", v));
                        let tx = self.event_sender();
                        let sid = self
                            .current_session
                            .as_ref()
                            .map(|s| s.id)
                            .unwrap_or(Uuid::nil());
                        tokio::spawn(async move {
                            super::messaging::run_evolve_directly(sid, tx).await;
                        });
                    }
                }
            }
            AppMode::Onboarding => {
                self.handle_onboarding_key(event).await?;
            }
            AppMode::Help | AppMode::Settings => {
                if keys::is_cancel(&event) {
                    self.help_scroll_offset = 0;
                    self.switch_mode(AppMode::Chat).await?;
                } else if keys::is_up(&event) {
                    self.help_scroll_offset = self.help_scroll_offset.saturating_sub(1);
                } else if keys::is_down(&event) {
                    self.help_scroll_offset = self.help_scroll_offset.saturating_add(1);
                } else if keys::is_page_up(&event) {
                    self.help_scroll_offset = self.help_scroll_offset.saturating_sub(10);
                } else if keys::is_page_down(&event) {
                    self.help_scroll_offset = self.help_scroll_offset.saturating_add(10);
                }
            }
            AppMode::MissionControl => {
                crate::tui::app::mission_control::input::handle_key(self, event).await;
            }
            AppMode::SkillsList => {
                crate::tui::app::skills_dialog::input::handle_key(self, event).await;
            }
            AppMode::SessionFiles => {
                self.handle_session_files_key(event).await?;
            }
            AppMode::Projects => {
                self.handle_projects_key(event).await?;
            }
        }

        Ok(())
    }

    /// Show an error message
    pub(crate) fn show_error(&mut self, error: String) {
        self.is_processing = false;
        self.processing_started_at = None;
        self.streaming_response = None;
        self.streaming_render_cache = None;
        self.streaming_reasoning = None;
        self.cancel_token = None;
        self.task_abort_handle = None;
        self.escape_pending_at = None;
        // Preserve context token count from real-time updates if we never got a complete response
        if self.last_input_tokens.is_none() && self.display_token_count > 0 {
            self.last_input_tokens = Some(self.display_token_count as u32);
        }
        // Deny any pending approvals so agent callbacks don't hang, then remove
        for msg in &mut self.messages {
            if let Some(ref mut approval) = msg.approval
                && approval.state == ApprovalState::Pending
            {
                let _ = approval.response_tx.send(ToolApprovalResponse {
                    request_id: approval.request_id,
                    approved: false,
                    reason: Some("Error occurred".to_string()),
                });
                approval.state = ApprovalState::Denied("Error occurred".to_string());
            }
        }
        // Finalize any active tool group
        if let Some(group) = self.active_tool_group.take() {
            let count = group.calls.len();
            self.messages.push(DisplayMessage {
                id: Uuid::new_v4(),
                role: "tool_group".to_string(),
                content: format!("{} tool call{}", count, if count == 1 { "" } else { "s" }),
                timestamp: chrono::Utc::now(),
                token_count: None,
                cost: None,
                approval: None,
                approve_menu: None,
                details: None,
                expanded: false,
                tool_group: Some(group),
            });
        }
        // Persist the error as a permanent chat bubble so the user
        // can see (and scroll back to) what went wrong AFTER the
        // 2.5s transient toast expires. Without this the toast
        // disappears and the user is left staring at a turn with
        // tool calls + thinking but no completion, with no way to
        // tell self-heal already gave up. Confirmed user report
        // 2026-06-01: a 5xx exhaustion fired `TuiEvent::Error` →
        // `show_error` → 2.5s toast → vanished. User saw nothing
        // and assumed the agent silently dropped the request.
        //
        // Filter out the special `"Cancelled"` and
        // `"Press Ctrl+C again to quit"` sentinels — those aren't
        // turn-failure errors, they're transient UI hints.
        if error != "Cancelled" && !error.starts_with("Press Ctrl+C") {
            self.messages.push(DisplayMessage {
                id: Uuid::new_v4(),
                role: "error".to_string(),
                content: error.clone(),
                timestamp: chrono::Utc::now(),
                token_count: None,
                cost: None,
                approval: None,
                approve_menu: None,
                details: None,
                expanded: false,
                tool_group: None,
            });
        }
        self.error_message = Some(error);
        self.error_message_shown_at = Some(std::time::Instant::now());
        // Auto-scroll to show the error
        self.scroll_offset = 0;
    }

    /// Switch to a different mode
    pub(crate) async fn switch_mode(&mut self, mode: AppMode) -> Result<()> {
        tracing::info!("🔄 Switching mode to: {:?}", mode);
        self.mode = mode;

        if mode == AppMode::Sessions {
            self.load_sessions().await?;
        }

        Ok(())
    }

    /// Get total token count for current session (from DB, not in-memory messages).
    /// In-memory messages only cover the current context window — the DB has the
    /// cumulative total across all compactions.
    pub fn total_tokens(&self) -> i32 {
        self.current_session
            .as_ref()
            .map(|s| s.token_count)
            .unwrap_or(0)
    }

    /// Get context usage as a percentage
    /// Uses the calibrated message token count (excludes tool schema overhead)
    pub fn context_usage_percent(&self) -> f64 {
        if self.context_max_tokens == 0 {
            return 0.0;
        }
        let used = self.last_input_tokens.unwrap_or(0) as f64;
        (used / self.context_max_tokens as f64) * 100.0
    }

    /// Get total cost for current session (from DB, not in-memory messages).
    pub fn total_cost(&self) -> f64 {
        self.current_session
            .as_ref()
            .map(|s| s.total_cost)
            .unwrap_or(0.0)
    }

    /// Handle tool approval request — inline in chat (session-aware)
    fn handle_approval_requested(&mut self, request: ToolApprovalRequest) {
        let is_current = self.is_current_session(request.session_id);

        // Always read approval policy from config at runtime — never trust
        // cached flags. This ensures changes to config.toml or /approve
        // take effect immediately without session restart.
        let (auto_session, auto_always) = Self::read_approval_policy_from_config();
        // Sync cached state for render/display consistency
        self.approval_auto_session = auto_session;
        self.approval_auto_always = auto_always;

        tracing::info!(
            "[APPROVAL] handle_approval_requested tool='{}' session={} is_current={} auto_session={} auto_always={}",
            request.tool_name,
            request.session_id,
            is_current,
            auto_session,
            auto_always
        );

        // Auto-approve silently if policy allows
        if auto_always || auto_session {
            let response = ToolApprovalResponse {
                request_id: request.request_id,
                approved: true,
                reason: None,
            };
            let _ = request.response_tx.send(response.clone());
            let _ = self
                .event_sender()
                .send(TuiEvent::ToolApprovalResponse(response));
            return;
        }

        // Background session approval — auto-approve (user can't interact with it)
        // They'll see the results when they switch to that session
        if !is_current {
            tracing::info!(
                "[APPROVAL] Auto-approving background session {} tool '{}'",
                request.session_id,
                request.tool_name
            );
            let response = ToolApprovalResponse {
                request_id: request.request_id,
                approved: true,
                reason: Some("Auto-approved (background session)".to_string()),
            };
            let _ = request.response_tx.send(response.clone());
            let _ = self
                .event_sender()
                .send(TuiEvent::ToolApprovalResponse(response));
            return;
        }

        // Deny stale pending approvals from previous requests in THIS session only
        for msg in &mut self.messages {
            if let Some(ref mut approval) = msg.approval
                && approval.state == ApprovalState::Pending
            {
                let _ = approval.response_tx.send(ToolApprovalResponse {
                    request_id: approval.request_id,
                    approved: false,
                    reason: Some("Superseded by new request".to_string()),
                });
                approval.state = ApprovalState::Denied("Superseded by new request".to_string());
            }
        }

        // Clear streaming overlay so the approval dialog is visible
        self.streaming_render_cache = None;
        if let Some(text) = self.streaming_response.take()
            && !text.trim().is_empty()
        {
            // Persist any streamed text as a regular message before showing approval
            self.messages.push(DisplayMessage {
                id: Uuid::new_v4(),
                role: "assistant".to_string(),
                content: text,
                timestamp: chrono::Utc::now(),
                token_count: None,
                cost: None,
                approval: None,
                approve_menu: None,
                details: None,
                expanded: false,
                tool_group: None,
            });
        }

        // Show inline approval in chat
        self.messages.push(DisplayMessage {
            id: Uuid::new_v4(),
            role: "approval".to_string(),
            content: String::new(),
            timestamp: chrono::Utc::now(),
            token_count: None,
            cost: None,
            approval: Some(ApprovalData {
                tool_name: request.tool_name,
                tool_description: request.tool_description,
                tool_input: request.tool_input,
                capabilities: request.capabilities,
                request_id: request.request_id,
                response_tx: request.response_tx,
                requested_at: request.requested_at,
                state: ApprovalState::Pending,
                selected_option: 0,
                show_details: false,
            }),
            approve_menu: None,
            details: None,
            expanded: false,
            tool_group: None,
        });
        // Auto-collapse all tool groups so the approval dialog is immediately visible
        if let Some(ref mut group) = self.active_tool_group {
            group.expanded = false;
        }
        for msg in self.messages.iter_mut() {
            if let Some(ref mut group) = msg.tool_group {
                group.expanded = false;
            }
        }
        self.auto_scroll = true;
        self.scroll_offset = 0;
        tracing::info!(
            "[APPROVAL] Pushed approval message for tool='{}', total messages={}, has_pending={}",
            self.messages
                .last()
                .map(|m| m
                    .approval
                    .as_ref()
                    .map(|a| a.tool_name.as_str())
                    .unwrap_or("?"))
                .unwrap_or("?"),
            self.messages.len(),
            self.has_pending_approval()
        );
        // Stay in AppMode::Chat — no mode switch
    }

    /// Update slash command autocomplete suggestions (built-in + user-defined)
    pub(crate) fn update_slash_suggestions(&mut self) {
        let input = self.input_buffer.trim_start();
        if input.starts_with('/') && !input.contains(' ') && !input.is_empty() {
            let prefix = input.to_lowercase();

            // Built-in commands: indices 0..SLASH_COMMANDS.len()
            self.slash_filtered = SLASH_COMMANDS
                .iter()
                .enumerate()
                .filter(|(_, cmd)| cmd.name.starts_with(&prefix))
                .map(|(i, _)| i)
                .collect();

            // User-defined commands: indices starting at SLASH_COMMANDS.len()
            // Skip user commands that shadow a built-in name
            let base_user = SLASH_COMMANDS.len();
            for (i, ucmd) in self.user_commands.iter().enumerate() {
                if ucmd.name.to_lowercase().starts_with(&prefix)
                    && !SLASH_COMMANDS.iter().any(|b| b.name == ucmd.name)
                {
                    self.slash_filtered.push(base_user + i);
                }
            }

            // Skills: indices starting at SLASH_COMMANDS.len() + user_commands.len()
            // Skip skills shadowed by a built-in or a user command of the same
            // `/<name>`. The skill's precomputed `slash_name` already carries
            // the leading slash for direct comparison.
            let base_skill = SLASH_COMMANDS.len() + self.user_commands.len();
            for (i, skill) in self.skills.iter().enumerate() {
                let lower = skill.slash_name.to_lowercase();
                if lower.starts_with(&prefix)
                    && !SLASH_COMMANDS.iter().any(|b| b.name == skill.slash_name)
                    && !self
                        .user_commands
                        .iter()
                        .any(|c| c.name == skill.slash_name)
                {
                    self.slash_filtered.push(base_skill + i);
                }
            }

            // Sort suggestions alphabetically by command name. Inline the
            // index → name resolution to avoid an immutable borrow of self
            // inside the sort_by closure (which holds a mutable borrow of
            // self.slash_filtered).
            let n_builtin = SLASH_COMMANDS.len();
            let n_user = self.user_commands.len();
            let name_at = |idx: usize| -> &str {
                if idx < n_builtin {
                    SLASH_COMMANDS[idx].name
                } else if idx < n_builtin + n_user {
                    self.user_commands
                        .get(idx - n_builtin)
                        .map(|c| c.name.as_str())
                        .unwrap_or("")
                } else {
                    self.skills
                        .get(idx - n_builtin - n_user)
                        .map(|s| s.slash_name.as_str())
                        .unwrap_or("")
                }
            };
            self.slash_filtered
                .sort_by(|&a, &b| name_at(a).cmp(name_at(b)));

            self.slash_suggestions_active = !self.slash_filtered.is_empty();
            // Clamp selected index
            if self.slash_selected_index >= self.slash_filtered.len() {
                self.slash_selected_index = 0;
            }
        } else {
            self.slash_suggestions_active = false;
            self.slash_filtered.clear();
            self.slash_selected_index = 0;
        }
    }

    /// Get the name of a slash command by its combined index
    /// (0..N built-ins, N..M user commands, M.. skills as `/<slug>`).
    pub fn slash_command_name(&self, index: usize) -> Option<&str> {
        let n_builtin = SLASH_COMMANDS.len();
        let n_user = self.user_commands.len();
        if index < n_builtin {
            Some(SLASH_COMMANDS[index].name)
        } else if index < n_builtin + n_user {
            self.user_commands
                .get(index - n_builtin)
                .map(|c| c.name.as_str())
        } else {
            self.skills
                .get(index - n_builtin - n_user)
                .map(|s| s.slash_name.as_str())
        }
    }

    /// Get the description of a slash command by its combined index
    pub fn slash_command_description(&self, index: usize) -> Option<&str> {
        let n_builtin = SLASH_COMMANDS.len();
        let n_user = self.user_commands.len();
        if index < n_builtin {
            Some(SLASH_COMMANDS[index].description)
        } else if index < n_builtin + n_user {
            self.user_commands
                .get(index - n_builtin)
                .map(|c| c.description.as_str())
        } else {
            self.skills
                .get(index - n_builtin - n_user)
                .map(|s| s.description.as_str())
        }
    }

    /// Reload user commands from brain workspace (called after agent responses)
    pub(crate) fn reload_user_commands(&mut self) {
        let command_loader = CommandLoader::from_brain_path(&self.brain_path);
        self.user_commands = command_loader.load();
        // Skills can also be edited live (~/.opencrabs/skills/<name>/SKILL.md);
        // reload alongside user commands so the autocomplete reflects edits
        // without restart.
        self.skills = crate::brain::skills::load_all_skills();
    }

    /// Update emoji picker based on the text behind the cursor.
    /// Triggers when there's `:query` (colon + at least 1 char, no spaces).
    pub(crate) fn update_emoji_picker(&mut self) {
        // Search backwards from cursor for an unmatched ':'
        let before_cursor = &self.input_buffer[..self.cursor_position];
        if let Some(colon_pos) = before_cursor.rfind(':') {
            let query = &before_cursor[colon_pos + 1..];
            // Must have at least 1 char, no spaces, no other ':'
            if !query.is_empty() && !query.contains(' ') && !query.contains(':') {
                let query_lower = query.to_lowercase();
                let max_results = 8;
                self.emoji_filtered = emojis::iter()
                    .filter_map(|e| {
                        e.shortcodes()
                            .find(|sc| sc.contains(&*query_lower))
                            .map(|sc| (e.as_str(), sc))
                    })
                    .take(max_results)
                    .collect();
                if !self.emoji_filtered.is_empty() {
                    self.emoji_picker_active = true;
                    self.emoji_colon_offset = colon_pos;
                    if self.emoji_selected_index >= self.emoji_filtered.len() {
                        self.emoji_selected_index = 0;
                    }
                    return;
                }
            }
        }
        self.dismiss_emoji_picker();
    }

    /// Dismiss the emoji picker.
    pub(crate) fn dismiss_emoji_picker(&mut self) {
        self.emoji_picker_active = false;
        self.emoji_filtered.clear();
        self.emoji_selected_index = 0;
    }

    /// Insert the selected emoji, replacing `:query` with the emoji char.
    pub(crate) fn accept_emoji(&mut self) {
        if let Some(&(emoji, _)) = self.emoji_filtered.get(self.emoji_selected_index) {
            let colon = self.emoji_colon_offset;
            let end = self.cursor_position;
            self.input_buffer.replace_range(colon..end, emoji);
            self.cursor_position = colon + emoji.len();
            self.dismiss_emoji_picker();
        }
    }
}

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

    #[test]
    fn test_display_message_from_db_message() {
        let msg = Message {
            id: Uuid::new_v4(),
            session_id: Uuid::new_v4(),
            role: "user".to_string(),
            content: "Hello".to_string(),
            sequence: 1,
            created_at: chrono::Utc::now(),
            token_count: Some(10),
            cost: Some(0.001),
            input_tokens: None,
            cache_creation_tokens: None,
            cache_read_tokens: None,
            thinking: None,
        };

        let display_msg: DisplayMessage = msg.into();
        assert_eq!(display_msg.role, "user");
        assert_eq!(display_msg.content, "Hello");
        assert!(display_msg.details.is_none());
    }

    #[test]
    fn test_display_message_thinking_from_db() {
        let msg = Message {
            id: Uuid::new_v4(),
            session_id: Uuid::new_v4(),
            role: "assistant".to_string(),
            content: "Here is the answer.".to_string(),
            sequence: 2,
            created_at: chrono::Utc::now(),
            token_count: Some(50),
            cost: Some(0.005),
            input_tokens: Some(200),
            cache_creation_tokens: None,
            cache_read_tokens: None,
            thinking: Some("I need to analyze this carefully...".to_string()),
        };

        let display_msg: DisplayMessage = msg.into();
        assert_eq!(display_msg.role, "assistant");
        assert_eq!(display_msg.content, "Here is the answer.");
        assert_eq!(
            display_msg.details,
            Some("I need to analyze this carefully...".to_string())
        );
    }
}