yolop 0.5.0

Yolop — a terminal coding agent built on everruns-runtime
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
// TUI app state and event loop.
// Decision: keep the TUI surface tiny. Transcript output is inserted into the
// native terminal scrollback; ratatui owns only a short inline composer at the
// bottom.

use crate::goal::{GOAL_EVALUATE_ARG, GoalStore, parse_evaluation_response};
use crate::host_ui::UiCommand;
use crate::runtime::{BuiltRuntime, ModelState, StartupInfo};
use crate::session::Session;
use crate::user_ask::{
    USER_ASK_EVALUATE_ARG, UserAskStore, evaluation_status_message,
    parse_evaluation_response as parse_user_ask_evaluation,
};
use crate::worktree::WorktreeManager;
use anyhow::Result;
use crossterm::event::{
    self, Event as CrosstermEvent, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton,
    MouseEvent, MouseEventKind,
};
use everruns_core::command::{CommandDescriptor, CommandSource};
use everruns_core::message::ContentPart;
use everruns_core::session_task::{SessionTask, SessionTaskRegistry};
use everruns_core::typed_id::SessionId;
use ratatui::Terminal;
use ratatui::backend::Backend;
use ratatui::buffer::Buffer;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Clear, Paragraph, Widget};
use ratatui_textarea::{CursorMove, TextArea, WrapMode};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::{mpsc, oneshot};

mod markdown_table;
mod render;
mod setup;
mod viewport;

// Re-export the moved free items so the rest of the crate (and the test module)
// can keep referring to them as `crate::app::*`. `setup` exposes only `impl App`
// methods, so it needs no re-export. The rendering module is named `render`
// rather than `draw` so it does not collide with the free `draw` fn it exports.
// The view-model types and runtime-event translation live in `crate::transcript`
// (the single boundary that interprets `everruns_core` events); re-export them
// here so the TUI's own submodules keep referring to them as `crate::app::*`.
pub(crate) use self::{render::*, viewport::*};
pub(crate) use crate::presentation::*;
pub(crate) use crate::transcript::*;

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct CommandSuggestion {
    completion: String,
    label: String,
}

pub const COMPOSER_VIEWPORT_HEIGHT: u16 = 18;
const SESSION_TASK_REFRESH_INTERVAL: Duration = Duration::from_secs(1);
/// Consecutive failed event-loop iterations tolerated before the terminal is
/// considered gone and the error becomes fatal. The slowest failure mode (an
/// unanswered cursor-position query) blocks ~2s per attempt inside crossterm,
/// so this bounds a permanently dead terminal to ~10s before exit while
/// letting a briefly unresponsive emulator recover.
const MAX_TERMINAL_IO_FAILURES: usize = 5;
/// After the first Ctrl+C arms exit, typing does not disarm the prompt until
/// this grace elapses so a slow second Ctrl+C still exits.
const CTRL_C_EXIT_ARM_GRACE: Duration = Duration::from_secs(5);
const MAX_INPUT_HEIGHT: u16 = 12;
const RECENT_TRANSCRIPT_SOURCE_LINES: usize = 80;
const RECENT_TRANSCRIPT_MAX_TEXT_BYTES: usize = 4_000;
const ACCENT_BLUE: Color = Color::Rgb(45, 91, 158);
const ACCENT_GOLD: Color = Color::Rgb(126, 94, 19);
const TEXT_PRIMARY: Color = Color::Rgb(230, 230, 232);
const TEXT_MUTED: Color = Color::Rgb(140, 140, 145);
const TEXT_DIM: Color = Color::Rgb(72, 72, 78);
const DIFF_ADD: Color = Color::Rgb(132, 166, 142);
const DIFF_DELETE: Color = Color::Rgb(180, 132, 136);
const DIFF_META: Color = Color::Rgb(108, 132, 188);
const CODE_BG: Color = Color::Rgb(18, 18, 20);
const PANEL_BG: Color = Color::Rgb(28, 28, 34);

pub struct App {
    session: Session,
    startup: StartupInfo,
    model: ModelState,
    pub lines: Vec<ChatLine>,
    printed_lines: usize,
    pub input: TextArea<'static>,
    pub busy: bool,
    pub should_quit: bool,
    ctrl_c_exit: bool,
    /// When the first Ctrl+C armed exit; a second press quits.
    ctrl_c_pending_exit_at: Option<Instant>,
    /// First Esc during a busy turn armed cancellation; a second press cancels.
    esc_pending_cancel: bool,
    busy_frame: u64,
    turn_activity: Option<String>,
    /// Live tail of streaming assistant text (and other delta events).
    /// Cleared on turn completion; never enters the persistent transcript.
    stream_preview: Option<StreamPreview>,
    rx: Option<mpsc::UnboundedReceiver<TurnEvent>>,
    turn_cancel: Option<oneshot::Sender<()>>,
    /// Active setup overlay, if any. The overlay owns its own keyboard
    /// handling so provider, token, and model setup never echo through the
    /// normal chat composer.
    setup: Option<SetupStep>,
    status_layout: StatusLayout,
    session_tokens: Option<u64>,
    /// Terminal-side commands emitted by `ClientCommandsCapability` (via
    /// `runtime.execute_command`). Drained in the event loop; see
    /// [`App::apply_ui_command`].
    ui_rx: mpsc::UnboundedReceiver<UiCommand>,
    /// Settings store shared with the runtime (same instance
    /// `SetupCapability` writes). Used to resolve credentials when querying
    /// provider models APIs and to show per-provider connection status in
    /// the setup overlay.
    settings: Arc<crate::settings::SettingsStore>,
    /// Models discovered from each provider's models API, keyed by provider
    /// name. Once populated, replaces the curated fallback list in the
    /// model picker.
    model_catalog: HashMap<String, ModelPickerCatalog>,
    /// Providers with an in-flight models API fetch.
    model_fetches_in_flight: HashSet<String>,
    /// Disabled in unit tests so opening the picker never spawns real
    /// network requests.
    model_discovery_enabled: bool,
    models_tx: mpsc::UnboundedSender<ModelDiscovery>,
    models_rx: mpsc::UnboundedReceiver<ModelDiscovery>,
    /// Wake channel for everruns `spawn_background` completions (fed by the
    /// platform-store wake seam, `crate::background_wake`). Drained while idle to
    /// auto-start a turn so the agent reacts to finished work. See
    /// specs/background.md.
    background_wake: crate::background_wake::WakeReceiver,
    /// Everruns session-task registry used by `spawn_background`; the TUI reads
    /// it for the background status segment and panel.
    task_registry: Arc<dyn SessionTaskRegistry>,
    session_tasks: Vec<SessionTask>,
    session_tasks_error: Option<String>,
    last_session_tasks_refresh: Option<Instant>,
    /// Open background-tasks panel overlay, holding its scroll offset (in
    /// lines). `None` when closed. Toggled with Ctrl+B; read-only view of the
    /// session task list.
    background_panel: Option<usize>,
    goal_store: Arc<GoalStore>,
    user_ask_store: Arc<UserAskStore>,
    user_ask_enabled: bool,
    worktree: Arc<WorktreeManager>,
    workspace_host: Arc<crate::workspace_host::WorkspaceHost>,
    /// Images from `--image` / `-i` on the CLI, consumed on the first turn.
    pending_images: Vec<ContentPart>,
    /// Large paste placeholders mapped to their full clipboard/terminal payloads.
    pending_pastes: Vec<(String, String)>,
}

/// Result of one background models API fetch. `Ok(None)` means the provider
/// does not support listing; the picker keeps the curated fallback list.
pub(crate) struct ModelDiscovery {
    provider: String,
    result: Result<Option<ModelPickerCatalog>, String>,
}

/// One provider's model picker list: selectable rows plus how many leading
/// rows belong in the recommended section (before the "more models" divider).
#[derive(Clone, Debug)]
pub(crate) struct ModelPickerCatalog {
    pub options: Vec<ModelOption>,
    pub recommended_count: usize,
}

/// State of the first-run / `/setup` overlay. This enum *is* the overlay's
/// state machine; its transitions (key handling, provider/model discovery,
/// persistence) live in [`setup`]. Rendering lives in [`render`].
#[derive(Clone, Debug)]
pub(crate) enum SetupStep {
    Provider {
        selected: usize,
    },
    /// Endpoint base URL for the generic OpenAI-compatible provider.
    BaseUrlInput {
        value: String,
        error: Option<String>,
    },
    Credential {
        provider: String,
        selected: usize,
        error: Option<String>,
    },
    TokenInput {
        provider: String,
        token: String,
        error: Option<String>,
    },
    PickModel {
        provider: String,
        selected: usize,
        custom: Option<String>,
        error: Option<String>,
    },
    PickEffort {
        selected: usize,
        error: Option<String>,
    },
}

pub(crate) struct ProviderOption {
    name: &'static str,
    label: &'static str,
    hint: &'static str,
}

const PROVIDER_OPTIONS: &[ProviderOption] = &[
    ProviderOption {
        name: "openai",
        label: "OpenAI",
        hint: "GPT models",
    },
    ProviderOption {
        name: "codex",
        label: "Codex subscription",
        hint: "ChatGPT Plus/Pro login",
    },
    ProviderOption {
        name: "anthropic",
        label: "Anthropic",
        hint: "Claude",
    },
    ProviderOption {
        name: "google",
        label: "Google Gemini",
        hint: "Gemini models",
    },
    ProviderOption {
        name: "openrouter",
        label: "OpenRouter",
        hint: "many hosted models",
    },
    ProviderOption {
        name: "ollama",
        label: "Ollama local",
        hint: "local OpenAI-compatible server",
    },
    ProviderOption {
        name: "custom",
        label: "Custom endpoint",
        hint: "any OpenAI-compatible URL",
    },
    ProviderOption {
        name: "llmsim",
        label: "Offline demo mode",
        hint: "canned offline responses",
    },
];

pub(crate) struct CredentialOption {
    id: CredentialAction,
    label: String,
    hint: String,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum CredentialAction {
    UseEnv,
    BrowserLogin,
    DeviceLogin,
    PasteKey,
    Skip,
    ClearSaved,
}

#[derive(Clone, Debug)]
pub(crate) struct ModelOption {
    spec: Option<String>,
    label: String,
    hint: String,
}

/// Owned snapshot of the App fields the pure-render chrome helpers
/// (command suggestions, stream preview, separators, session status)
/// consume. Extracted from `App` so those helpers can be exercised by
/// unit tests against `ratatui::backend::TestBackend` without standing
/// up a full runtime.
///
/// Owned rather than borrowed because building it does not need to
/// borrow `App` for the duration of a draw: `draw_input` needs `&mut
/// App` for the input field's `Widget` impl, and a borrowed `ViewState`
/// would block that within a single `draw()`. The per-frame clone cost
/// is dominated by `String`-sized fields and is negligible compared to
/// the chrome render itself.
#[derive(Clone, Debug)]
pub(crate) struct ViewState {
    pub presentation: PresentationState,
    pub command_suggestions: Vec<CommandSuggestion>,
    pub busy_frame: u64,
}

impl ViewState {
    pub(crate) fn status_row_count(&self) -> u16 {
        self.presentation.status_row_count()
    }
}

impl App {
    pub fn new(runtime: BuiltRuntime, pending_images: Vec<ContentPart>) -> Self {
        let should_setup = runtime.startup.setup_recommended;
        let goal_store = runtime.goal_store.clone();
        let user_ask_store = runtime.user_ask_store.clone();
        let user_ask_enabled = runtime.user_ask_enabled;
        let session_id = runtime.handles.session_id;
        let session = Session::new(runtime.handles, runtime.model.clone());
        let (models_tx, models_rx) = mpsc::unbounded_channel::<ModelDiscovery>();
        let mut app = Self {
            session,
            startup: runtime.startup,
            model: runtime.model,
            lines: Vec::new(),
            printed_lines: 0,
            input: new_input_area(vec![String::new()]),
            busy: false,
            should_quit: false,
            ctrl_c_exit: false,
            ctrl_c_pending_exit_at: None,
            esc_pending_cancel: false,
            busy_frame: 0,
            turn_activity: None,
            stream_preview: None,
            rx: None,
            turn_cancel: None,
            setup: None,
            status_layout: StatusLayout::Compact,
            session_tokens: None,
            ui_rx: runtime.ui_rx,
            settings: runtime.settings,
            model_catalog: HashMap::new(),
            model_fetches_in_flight: HashSet::new(),
            model_discovery_enabled: true,
            models_tx,
            models_rx,
            background_wake: runtime.background_wake,
            task_registry: runtime.task_registry,
            session_tasks: Vec::new(),
            session_tasks_error: None,
            last_session_tasks_refresh: None,
            background_panel: None,
            goal_store,
            user_ask_store,
            user_ask_enabled,
            worktree: runtime.worktree,
            workspace_host: runtime.workspace_host,
            pending_images,
            pending_pastes: Vec::new(),
        };
        app.emit_system_banner();
        if should_setup {
            app.start_first_run_setup();
        } else if app.goal_store.is_paused(session_id)
            && let Some(condition) = app.goal_store.active_condition(session_id)
        {
            app.push_system(format!(
                "restored paused goal: {condition} (run /goal resume to continue)"
            ));
        } else if app.goal_store.take_pending_turn(session_id)
            && let Some(condition) = app.goal_store.active_condition(session_id)
        {
            app.push_system(format!("restored active goal: {condition}"));
            app.push_user(condition.clone());
            app.start_turn(condition);
        }
        app
    }

    pub fn should_show_resume_hint(&self) -> bool {
        self.ctrl_c_exit
    }

    pub fn session_id(&self) -> SessionId {
        self.session.session_id()
    }

    /// Snapshot the renderer-relevant fields into a `ViewState`. Called
    /// once per frame; the clones are dominated by small `String`s.
    pub(crate) fn view_state(&self) -> ViewState {
        let presentation = self.presentation_state();
        ViewState {
            command_suggestions: if !presentation.busy && self.setup.is_none() {
                self.suggestions()
            } else {
                Vec::new()
            },
            busy_frame: self.busy_frame,
            presentation,
        }
    }

    pub(crate) fn presentation_state(&self) -> PresentationState {
        PresentationState {
            stream_preview: self.stream_preview.clone(),
            busy: self.busy,
            turn_activity: self.turn_activity.clone(),
            model_id: self.model.model_id(),
            provider_name: self.model.provider_name(),
            reasoning_effort: self.model.reasoning_effort(),
            session_id: self.session.session_id().to_string(),
            lines_count: self.lines.len(),
            session_tokens: self.session_tokens,
            status_layout: self.status_layout,
            hooks_summary: self.startup.hook_summary(),
            approval_mode: self
                .settings
                .snapshot()
                .approval_mode()
                .as_str()
                .to_string(),
            background: self.background_counts(),
            goal_indicator: self.goal_indicator(),
            ask_indicator: self.ask_indicator(),
            worktree_compact: self.worktree.status_bar_compact(),
            worktree_expanded: self.worktree.status_bar_expanded(),
        }
    }

    fn ask_indicator(&self) -> Option<String> {
        if !self.user_ask_enabled {
            return None;
        }
        if !self.user_ask_store.is_active(self.session.session_id()) {
            return None;
        }
        let turns = self
            .user_ask_store
            .status(self.session.session_id())
            .active
            .map(|active| active.evaluated_turns)
            .unwrap_or(0);
        Some(format!("? ask ({turns})"))
    }

    fn background_counts(&self) -> Option<(usize, usize)> {
        crate::session_tasks_view::counts(&self.session_tasks)
    }

    fn background_panel_body(&self) -> String {
        crate::session_tasks_view::render_task_list(
            &self.session_tasks,
            self.session_tasks_error.as_deref(),
        )
    }

    async fn refresh_session_tasks(&mut self) {
        match self
            .task_registry
            .list(self.session.session_id(), None)
            .await
        {
            Ok(tasks) => {
                self.session_tasks = tasks;
                self.session_tasks_error = None;
            }
            Err(err) => {
                self.session_tasks.clear();
                self.session_tasks_error = Some(err.to_string());
            }
        }
        self.last_session_tasks_refresh = Some(Instant::now());
    }

    async fn refresh_session_tasks_if_due(&mut self) {
        if self
            .last_session_tasks_refresh
            .is_some_and(|last| last.elapsed() < SESSION_TASK_REFRESH_INTERVAL)
        {
            return;
        }
        self.refresh_session_tasks().await;
    }

    fn goal_indicator(&self) -> Option<String> {
        if !self.goal_store.is_active(self.session.session_id()) {
            return None;
        }
        let turns = self
            .goal_store
            .status(self.session.session_id(), self.session_tokens)
            .active
            .map(|active| (active.evaluated_turns, active.paused))
            .unwrap_or((0, false));
        if turns.1 {
            Some(format!("◎ goal paused ({})", turns.0))
        } else {
            Some(format!("◎ goal ({})", turns.0))
        }
    }

    fn emit_system_banner(&mut self) {
        self.push_system(format!(
            "workspace: {}",
            self.startup.workspace_root.display()
        ));
        self.push_system(format!("model: {}", self.model.provider_label()));
        self.push_system(format!("tools: {}", self.startup.tool_names.join(", ")));
        if !self.startup.capability_commands.is_empty() {
            let names: Vec<String> = self
                .startup
                .capability_commands
                .iter()
                .map(capability_command_display_usage)
                .collect();
            self.push_system(format!("commands: {}", names.join(", ")));
        }
        self.push_system(
            "type /help for commands, Ctrl+V to paste an image, large pastes attach as placeholders, press Ctrl-C twice (or Ctrl-D) to exit"
                .into(),
        );
    }

    fn push_user(&mut self, text: String) {
        self.lines.push(ChatLine {
            author: Author::User,
            text,
        });
    }
    fn push_system(&mut self, text: String) {
        self.lines.push(ChatLine {
            author: Author::System,
            text,
        });
    }

    pub async fn run<B>(&mut self, terminal: &mut Terminal<B>) -> Result<()>
    where
        B: Backend,
        B::Error: std::error::Error + Send + Sync + 'static,
    {
        self.emit_replayed_transcript().await;
        // Terminal I/O fails transiently in the wild, so one failed loop
        // iteration must not end the session. The motivating case:
        // xterm.js-backed hosts (ttyd, vhs recordings) resize the PTY
        // mid-session, ratatui re-anchors the inline viewport by querying
        // the cursor position (`CSI 6n`), and crossterm abandons that query
        // after 2s if the emulator is too busy (reflowing scrollback,
        // screencasting) to answer in time. Propagating that error killed
        // the TUI right as turns completed, while tmux — which answers the
        // query itself, instantly — never showed the bug.
        //
        // Retrying is safe because a failed iteration loses nothing and is
        // re-attempted next frame once the terminal catches up. Worst case
        // it leaves cosmetic artifacts: `flush_transcript` only advances
        // `printed_lines` after every chunk landed, so a flush interrupted
        // mid-way re-inserts its lines on retry (briefly duplicated
        // scrollback during a terminal hiccup), and the spinner skips the
        // frames spent failing. Only a run of consecutive failures
        // (terminal actually gone, e.g. PTY closed) is fatal.
        let mut io_failures = 0usize;
        loop {
            if self.busy {
                self.busy_frame = self.busy_frame.wrapping_add(1);
            }
            match self.run_loop_iteration(terminal).await {
                Ok(()) => io_failures = 0,
                Err(err) => {
                    // Redraw/anchoring can fail before input polling; let a
                    // queued exit key terminate instead of waiting for retries.
                    if let Err(input_err) =
                        self.drain_terminal_input(terminal, Duration::ZERO).await
                    {
                        tracing::warn!(
                            "terminal input drain failed after terminal i/o error: {input_err:#}"
                        );
                    }
                    if self.should_quit {
                        return Ok(());
                    }

                    io_failures += 1;
                    if io_failures >= MAX_TERMINAL_IO_FAILURES {
                        return Err(err);
                    }
                    tracing::warn!(
                        "terminal i/o failed ({io_failures}/{MAX_TERMINAL_IO_FAILURES}): {err:#}"
                    );
                }
            }
            if self.should_quit {
                return Ok(());
            }
        }
    }

    /// One iteration of the event loop: render, then drain at most one
    /// class of pending work (turn events, UI commands, keystrokes).
    ///
    /// Invariant: every terminal read/write the TUI performs belongs in
    /// here (or below), never directly in [`App::run`], so it is covered
    /// by `run`'s retry policy. A bare `?` on terminal I/O outside this
    /// function reintroduces the bug where one slow terminal reply exits
    /// the whole session.
    async fn run_loop_iteration<B>(&mut self, terminal: &mut Terminal<B>) -> Result<()>
    where
        B: Backend,
        B::Error: std::error::Error + Send + Sync + 'static,
    {
        self.flush_transcript(terminal)?;
        self.refresh_session_tasks_if_due().await;
        // Ratatui keeps the inline viewport row fixed across vertical grows and
        // resets it to the top on horizontal shrinks. Re-anchor before each draw
        // so the composer stays pinned to the terminal bottom after resize.
        terminal.autoresize()?;
        maybe_reanchor_inline_viewport(terminal)?;
        terminal.draw(|f| draw(f, self))?;

        // 1) drain background turn events
        if let Some(rx) = self.rx.as_mut() {
            match rx.try_recv() {
                Ok(TurnEvent::Lines(lines)) => {
                    self.lines.extend(lines);
                    return Ok(());
                }
                Ok(TurnEvent::Activity(activity)) => {
                    if !activity.fallback || self.turn_activity.is_none() {
                        self.turn_activity = Some(activity.text);
                    }
                    return Ok(());
                }
                Ok(TurnEvent::Stream(preview)) => {
                    self.stream_preview = preview;
                    return Ok(());
                }
                Ok(TurnEvent::Tokens(tokens)) => {
                    self.session_tokens =
                        Some(self.session_tokens.unwrap_or(0).saturating_add(tokens));
                    return Ok(());
                }
                Ok(TurnEvent::Done) => {
                    self.finish_busy();
                    self.after_turn_goal_check().await;
                    self.after_turn_user_ask_check().await;
                    return Ok(());
                }
                Ok(TurnEvent::Failed(err)) => {
                    self.finish_busy();
                    self.push_system(format!("turn failed: {err}"));
                    return Ok(());
                }
                Err(mpsc::error::TryRecvError::Empty) => {}
                Err(mpsc::error::TryRecvError::Disconnected) => {
                    self.finish_busy();
                }
            }
        }

        // 2) drain terminal-side commands emitted by capabilities. Apply
        // every queued command before re-rendering so a burst (or a future
        // capability that emits more than one) doesn't cost a full
        // flush/draw per command, matching the test dispatch helper.
        let mut applied_ui_command = false;
        while let Ok(command) = self.ui_rx.try_recv() {
            self.apply_ui_command(command);
            applied_ui_command = true;
        }
        if applied_ui_command {
            return Ok(());
        }

        // 3) drain finished models API fetches so an open picker refreshes.
        let mut applied_model_discovery = false;
        while let Ok(discovery) = self.models_rx.try_recv() {
            self.apply_model_discovery(discovery);
            applied_model_discovery = true;
        }
        if applied_model_discovery {
            return Ok(());
        }

        // 3b) proactive wake: when an everruns `spawn_background` task finishes
        // while the session is idle, auto-start a turn so the agent reacts
        // without a user prompt.
        if self.maybe_wake_from_background_channel() {
            return Ok(());
        }

        // 4) direct terminal input.
        self.drain_terminal_input(terminal, Duration::from_millis(80))
            .await
    }

    async fn drain_terminal_input<B>(
        &mut self,
        terminal: &mut Terminal<B>,
        initial_poll_timeout: Duration,
    ) -> Result<()>
    where
        B: Backend,
        B::Error: std::error::Error + Send + Sync + 'static,
    {
        let mut poll_timeout = initial_poll_timeout;
        while event::poll(poll_timeout)? {
            poll_timeout = Duration::ZERO;
            match event::read()? {
                CrosstermEvent::Key(key) => {
                    if key.kind == KeyEventKind::Release {
                        continue;
                    }
                    if key.code == KeyCode::Esc && self.handle_escape_prefixed_enter().await? {
                        continue;
                    }
                    self.handle_key(key).await;
                }
                CrosstermEvent::Mouse(mouse) => {
                    let area = terminal.get_frame().area();
                    if self.handle_mouse(mouse, area) {
                        return Ok(());
                    }
                }
                CrosstermEvent::Paste(pasted) => {
                    if self.setup.is_some() {
                        self.handle_setup_paste(pasted).await;
                    } else {
                        self.handle_paste(pasted);
                    }
                }
                _ => {}
            }
            if self.should_quit {
                break;
            }
        }
        Ok(())
    }

    async fn handle_escape_prefixed_enter(&mut self) -> Result<bool> {
        if !event::poll(Duration::from_millis(25))? {
            return Ok(false);
        }

        match event::read()? {
            CrosstermEvent::Key(next) if next.kind == KeyEventKind::Release => Ok(false),
            CrosstermEvent::Key(next) if next.code == KeyCode::Enter => {
                self.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::ALT))
                    .await;
                Ok(true)
            }
            CrosstermEvent::Key(next) if next.code == KeyCode::Esc => {
                self.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::empty()))
                    .await;
                self.handle_key(next).await;
                Ok(true)
            }
            CrosstermEvent::Key(next) => {
                let mut alt = next;
                alt.modifiers.insert(KeyModifiers::ALT);
                self.handle_key(alt).await;
                Ok(true)
            }
            _ => {
                self.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::empty()))
                    .await;
                Ok(true)
            }
        }
    }

    async fn emit_replayed_transcript(&mut self) {
        if self.startup.replayed_events == 0 {
            return;
        }

        match self
            .session
            .replayed_lines(self.startup.replayed_events)
            .await
        {
            Ok(replayed_lines) => self.lines.extend(replayed_lines),
            Err(err) => self.push_system(format!("load replayed transcript: {err}")),
        }
    }

    fn flush_transcript<B>(&mut self, terminal: &mut Terminal<B>) -> Result<()>
    where
        B: Backend,
        B::Error: std::error::Error + Send + Sync + 'static,
    {
        if self.printed_lines >= self.lines.len() {
            return Ok(());
        }

        let width = terminal.size()?.width.saturating_sub(2).max(20) as usize;
        let mut rendered: Vec<Line<'static>> = Vec::new();
        for (index, chat) in self.lines[self.printed_lines..].iter().enumerate() {
            append_chat_lines(&mut rendered, chat, width);
            let absolute = self.printed_lines + index;
            if should_insert_chat_gap(
                &chat.author,
                self.lines.get(absolute + 1).map(|line| &line.author),
            ) {
                rendered.push(Line::from(""));
            }
        }
        if rendered.is_empty() {
            self.printed_lines = self.lines.len();
            return Ok(());
        }

        for chunk in rendered.chunks(u16::MAX as usize) {
            terminal.insert_before(chunk.len() as u16, |buf| {
                Paragraph::new(chunk.to_vec()).render(buf.area, buf);
            })?;
        }
        self.printed_lines = self.lines.len();
        Ok(())
    }

    async fn handle_key(&mut self, key: KeyEvent) {
        if key.modifiers.contains(KeyModifiers::CONTROL) {
            match key.code {
                KeyCode::Char('c') => {
                    self.handle_ctrl_c();
                    return;
                }
                KeyCode::Char('d') => {
                    self.should_quit = true;
                    return;
                }
                KeyCode::Char('b') => {
                    // Clear the armed single-Ctrl+C exit ourselves, since this
                    // branch returns before the shared reset below.
                    self.disarm_ctrl_c_pending_exit();
                    self.toggle_background_panel();
                    return;
                }
                KeyCode::Char('v') => {
                    self.try_paste_clipboard();
                    return;
                }
                _ => {}
            }
        }

        self.disarm_ctrl_c_pending_exit_if_grace_elapsed();

        // The background panel overlay captures navigation keys (even mid-turn,
        // so you can watch tasks while a turn runs).
        if self.background_panel.is_some() {
            self.handle_background_panel_key(key);
            return;
        }

        if self.busy {
            // Block only input editing while a turn is running.
            self.handle_busy_key(key);
            return;
        }
        if self.setup.is_some() {
            self.handle_setup_key(key).await;
            return;
        }
        match key.code {
            KeyCode::Enter if key.modifiers == KeyModifiers::SHIFT => {
                self.input.insert_newline();
            }
            KeyCode::Enter => {
                self.submit_input().await;
            }
            KeyCode::Tab => {
                if let Some(suggestion) = self.suggestions().first() {
                    self.set_input_text(suggestion.completion.clone());
                } else {
                    let _ = self.input.input(key);
                }
            }
            _ => {
                let _ = self.input.input(normalize_printable_key(key));
            }
        }
    }

    fn suggestions(&self) -> Vec<CommandSuggestion> {
        command_suggestions(self.suggestion_input(), &self.startup.capability_commands)
    }

    fn suggestion_input(&self) -> &str {
        self.input
            .lines()
            .first()
            .map(String::as_str)
            .unwrap_or_default()
    }

    fn input_text(&self) -> String {
        self.input.lines().join("\n")
    }

    fn set_input_text(&mut self, text: String) {
        self.input = new_input_area(vec![text]);
        self.input.move_cursor(CursorMove::End);
    }

    fn reset_input(&mut self) {
        self.input = new_input_area(vec![String::new()]);
        self.pending_pastes.clear();
    }

    fn input_height(&self, input_width: u16) -> u16 {
        wrapped_input_visual_lines(&self.input, input_width).clamp(1, MAX_INPUT_HEIGHT as usize)
            as u16
    }

    fn handle_paste(&mut self, pasted: String) {
        if self.busy || self.setup.is_some() || self.background_panel.is_some() {
            return;
        }

        let pasted = crate::paste_attachment::normalize_pasted_text(&pasted);
        if pasted.is_empty() {
            return;
        }

        if pasted.len() > crate::paste_attachment::MAX_PASTE_ATTACHMENT_BYTES {
            self.push_system(format!(
                "paste too large (max {} KiB)",
                crate::paste_attachment::MAX_PASTE_ATTACHMENT_BYTES / 1024
            ));
            return;
        }

        if crate::paste_attachment::is_large_paste(&pasted) {
            let char_count = pasted.chars().count();
            let placeholder = crate::paste_attachment::next_large_paste_placeholder(
                char_count,
                &self.pending_pastes,
            );
            self.input.insert_str(&placeholder);
            self.pending_pastes.push((placeholder, pasted));
        } else {
            self.input.insert_str(&pasted);
        }
    }

    fn try_paste_clipboard(&mut self) {
        if self.busy || self.setup.is_some() || self.background_panel.is_some() {
            return;
        }
        match crate::clipboard_paste::paste_image_content_part() {
            Ok((part, info)) => {
                self.pending_images.push(part);
                let index = self.pending_images.len();
                self.push_system(format!(
                    "attached clipboard image #{index} ({}x{} PNG)",
                    info.width, info.height
                ));
            }
            Err(crate::clipboard_paste::PasteImageError::NoImage(_)) => {
                if let Ok(text) = crate::clipboard_paste::paste_clipboard_text() {
                    self.handle_paste(text);
                }
            }
            Err(err) => {
                tracing::debug!("clipboard image paste failed: {err}");
                self.push_system(format!("clipboard image paste failed: {err}"));
            }
        }
    }

    async fn submit_input(&mut self) {
        let raw = self.input_text();
        crate::paste_attachment::prune_pending_pastes(&raw, &mut self.pending_pastes);
        let pending_pastes = std::mem::take(&mut self.pending_pastes);
        let expanded = crate::paste_attachment::expand_pending_pastes(&raw, &pending_pastes);
        self.reset_input();
        let text = expanded.trim().to_string();
        let display_text = raw.trim().to_string();
        if let Some(command) = parse_bang_shell_command(&text) {
            if command.is_empty() {
                self.push_system("usage: !<command>".into());
            } else {
                self.handle_shell_alias(command.to_string()).await;
            }
            return;
        }
        if let Some(rest) = text.strip_prefix('/') {
            self.handle_command(rest).await;
            return;
        }
        if text.is_empty() && self.pending_images.is_empty() {
            return;
        }
        let image_count = self.pending_images.len();
        let display = crate::image_input::user_display_text(&display_text, image_count);
        self.push_user(display);
        if self.user_ask_enabled
            && let Err(err) = self
                .user_ask_store
                .record_user_prompt(self.session.session_id(), &text)
        {
            self.push_system(format!("user ask: {err}"));
        }
        self.start_turn(text);
    }

    /// Open the background-tasks panel (read-only) or close it if already open.
    /// Suppressed while the setup overlay is up so two modals never stack.
    fn toggle_background_panel(&mut self) {
        if self.background_panel.is_some() {
            self.background_panel = None;
        } else if self.setup.is_none() {
            self.background_panel = Some(0);
        }
    }

    /// Navigation for the open background panel: Esc/q closes, Up/Down scroll.
    fn handle_background_panel_key(&mut self, key: KeyEvent) {
        let Some(offset) = self.background_panel else {
            return;
        };
        match key.code {
            KeyCode::Esc | KeyCode::Char('q') => self.background_panel = None,
            KeyCode::Up | KeyCode::Char('k') => {
                self.background_panel = Some(offset.saturating_sub(1));
            }
            KeyCode::Down | KeyCode::Char('j') => {
                // Clamp so scrolling can't run past the last line of content.
                let max = self
                    .background_panel_body()
                    .lines()
                    .count()
                    .saturating_sub(1);
                self.background_panel = Some(offset.saturating_add(1).min(max));
            }
            _ => {}
        }
    }

    /// Proactive wake: drain any everruns `spawn_background` completion signal
    /// delivered over [`crate::background_wake`] and, while idle, start a turn so
    /// the agent reacts to the finished work (reads the result, continues, or
    /// reports) without waiting for a user prompt. Only fires when idle, so it
    /// never interrupts an in-flight turn. Only the first pending message wakes a
    /// turn (draining the rest would lose them); the remainder wake on subsequent
    /// idle ticks. Returns true if it started a turn.
    fn maybe_wake_from_background_channel(&mut self) -> bool {
        if self.busy || self.rx.is_some() || self.setup.is_some() {
            return false;
        }
        let Ok(message) = self.background_wake.try_recv() else {
            return false;
        };
        if !self.settings.snapshot().proactive_wake_enabled() {
            self.push_system(
                "✓ background task finished — see /background (proactive wake off)".to_string(),
            );
            return false;
        }
        self.push_system("↻ background task finished — waking agent to review".to_string());
        self.start_turn(crate::background_wake::frame_wake_prompt(&message));
        true
    }

    /// Dispatch a slash command. Every command — including the terminal-side
    /// ones (help/tools/mcp/cwd/model/effort/clear/shell/quit) — is now a capability
    /// command, so this is a single uniform lookup against the registry. The
    /// terminal-side commands take effect via `UiCommand`s their capability
    /// emits while executing (drained in the event loop); see
    /// [`App::apply_ui_command`].
    async fn handle_command(&mut self, cmd: &str) {
        let cmd = cmd.trim();
        let mut parts = cmd.splitn(2, char::is_whitespace);
        let head = parts.next().unwrap_or_default();
        let arg = parts.next().unwrap_or_default().trim();
        // `/exit` is an accepted alias for the declared `/quit`.
        let name = if head == "exit" { "quit" } else { head };

        if let Some(descriptor) = self
            .startup
            .capability_commands
            .iter()
            .find(|c| c.name == name)
            .cloned()
        {
            self.invoke_capability_command(descriptor, arg.to_string())
                .await;
        } else {
            self.push_system(format!("unknown command: /{head}"));
        }
    }

    /// Dispatch the TUI's `!shell <command>` alias through the same capability
    /// descriptor as `/shell`, so registration, required-arg validation, and
    /// host gating keep one source of truth.
    async fn handle_shell_alias(&mut self, command: String) {
        if let Some(descriptor) = self
            .startup
            .capability_commands
            .iter()
            .find(|c| c.name == "shell")
            .cloned()
        {
            self.invoke_capability_command(descriptor, command).await;
        } else {
            self.push_system("unknown command: !shell".into());
        }
    }

    /// Apply a terminal-side command emitted by a capability. This is the only
    /// place the host interprets the `UiCommand` vocabulary; capabilities
    /// declare commands and request effects, the host performs them.
    fn apply_ui_command(&mut self, command: UiCommand) {
        match command {
            UiCommand::ShowHelp => self.show_help(),
            UiCommand::ShowTools => {
                self.push_system(format!("tools: {}", self.startup.tool_names.join(", ")));
            }
            UiCommand::ShowMcp => {
                if self.startup.mcp_server_names.is_empty() {
                    let global = crate::mcp_config::global_mcp_config_path()
                        .map(|p| p.display().to_string())
                        .unwrap_or_else(|| "the yolop config dir".to_string());
                    self.push_system(format!(
                        "no MCP servers configured (add them to .mcp.json in the workspace \
                         root or {global})"
                    ));
                } else {
                    self.push_system(format!(
                        "MCP servers: {}",
                        self.startup.mcp_server_names.join(", ")
                    ));
                }
            }
            UiCommand::ShowCwd => {
                self.push_system(format!(
                    "workspace root: {}",
                    self.startup.workspace_root.display()
                ));
            }
            UiCommand::SetStatusLayout { arg } => self.set_status_layout(arg.as_deref()),
            UiCommand::ClearTranscript => {
                self.lines.clear();
                self.printed_lines = 0;
                self.goal_store.clear_active(self.session.session_id());
                self.user_ask_store.clear_active(self.session.session_id());
                self.emit_system_banner();
            }
            UiCommand::RunShell { command } => self.start_shell_command(command),
            UiCommand::Quit => self.should_quit = true,
            UiCommand::OpenModelOverlay { arg } => match arg {
                Some(arg) => self.start_model_setup_with_arg(&arg),
                None => self.start_model_setup(),
            },
            UiCommand::OpenEffortOverlay { arg } => {
                self.start_effort_setup(arg.as_deref().unwrap_or(""))
            }
        }
    }

    fn show_help(&mut self) {
        if !self.startup.capability_commands.is_empty() {
            let command_lines: Vec<String> = self
                .startup
                .capability_commands
                .iter()
                .map(help_command_line)
                .collect();
            self.push_system("commands:".into());
            for line in command_lines {
                self.push_system(line);
            }
        }
        self.push_system("shortcuts:".into());
        for line in help_shortcut_lines() {
            self.push_system(line.to_string());
        }
        self.push_system(
            "more: /tools · /mcp · /yolop skill · type naturally for terminal actions".into(),
        );
    }

    fn set_status_layout(&mut self, raw: Option<&str>) {
        let layout = match raw.map(str::trim).filter(|s| !s.is_empty()) {
            None | Some("toggle") => match self.status_layout {
                StatusLayout::Compact => StatusLayout::Expanded,
                StatusLayout::Expanded => StatusLayout::Compact,
            },
            Some("compact") => StatusLayout::Compact,
            Some("expanded") => StatusLayout::Expanded,
            Some(other) => {
                self.push_system(format!(
                    "usage: /status [compact|expanded|toggle] (unknown layout: {other})"
                ));
                return;
            }
        };
        self.status_layout = layout;
    }

    fn toggle_status_layout(&mut self) {
        self.status_layout = match self.status_layout {
            StatusLayout::Compact => StatusLayout::Expanded,
            StatusLayout::Expanded => StatusLayout::Compact,
        };
    }

    fn handle_mouse(&mut self, mouse: MouseEvent, terminal_area: Rect) -> bool {
        if !matches!(mouse.kind, MouseEventKind::Down(MouseButton::Left)) {
            return false;
        }
        if self.mouse_is_on_status(mouse, terminal_area) {
            self.toggle_status_layout();
            return true;
        }
        false
    }

    fn mouse_is_on_status(&self, mouse: MouseEvent, terminal_area: Rect) -> bool {
        let input_width = terminal_area.width.saturating_sub(2);
        let state = self.view_state();
        let layout = app_layout_for_frame(
            terminal_area,
            self.input_height(input_width),
            state.status_row_count(),
            chrome_preview_visible(&state),
        );
        if layout.chrome.session_status.height == 0 {
            return false;
        }
        let status_rect = layout.chrome.session_status;
        mouse.row >= status_rect.y
            && mouse.row < status_rect.y.saturating_add(status_rect.height)
            && mouse.column >= status_rect.x
            && mouse.column < status_rect.x.saturating_add(status_rect.width)
    }

    fn ctrl_c_pending_exit(&self) -> bool {
        self.ctrl_c_pending_exit_at.is_some()
    }

    fn disarm_ctrl_c_pending_exit(&mut self) {
        self.ctrl_c_pending_exit_at = None;
    }

    fn disarm_ctrl_c_pending_exit_if_grace_elapsed(&mut self) {
        if let Some(armed_at) = self.ctrl_c_pending_exit_at
            && armed_at.elapsed() >= CTRL_C_EXIT_ARM_GRACE
        {
            self.ctrl_c_pending_exit_at = None;
        }
    }

    fn handle_ctrl_c(&mut self) {
        if !self.busy && !self.input_text().trim().is_empty() {
            self.reset_input();
            self.disarm_ctrl_c_pending_exit();
            return;
        }

        if self.ctrl_c_pending_exit() {
            self.ctrl_c_exit = true;
            self.should_quit = true;
            return;
        }

        self.ctrl_c_pending_exit_at = Some(Instant::now());
        self.push_system("Press Ctrl+C again to exit".into());
    }

    fn handle_busy_key(&mut self, key: KeyEvent) {
        match key.code {
            KeyCode::Esc if self.esc_pending_cancel => self.cancel_current_turn(),
            KeyCode::Esc if self.turn_cancel.is_some() => {
                self.esc_pending_cancel = true;
                self.push_system("Press Esc again to cancel current turn".into());
            }
            _ => {
                self.esc_pending_cancel = false;
            }
        }
    }

    fn cancel_current_turn(&mut self) {
        self.esc_pending_cancel = false;
        if self.goal_store.is_active(self.session.session_id()) {
            match self.goal_store.pause_active(self.session.session_id()) {
                Ok(message) => self.push_system(message),
                Err(err) => self.push_system(format!("goal pause failed: {err}")),
            }
        }
        if let Some(cancel) = self.turn_cancel.take() {
            let _ = cancel.send(());
            self.turn_activity = Some("cancelling".into());
            self.stream_preview = None;
        }
    }

    fn finish_busy(&mut self) {
        self.busy = false;
        self.busy_frame = 0;
        self.turn_activity = None;
        self.stream_preview = None;
        self.rx = None;
        self.turn_cancel = None;
        self.esc_pending_cancel = false;
    }

    fn maybe_start_goal_turn(&mut self) {
        let session_id = self.session.session_id();
        if !self.goal_store.take_pending_turn(session_id) {
            return;
        }
        let Some(condition) = self.goal_store.active_condition(session_id) else {
            return;
        };
        self.push_user(condition.clone());
        self.start_turn(condition);
    }

    async fn after_turn_goal_check(&mut self) {
        let session_id = self.session.session_id();
        if !self.goal_store.is_active(session_id) {
            return;
        }
        if self.goal_store.is_paused(session_id) {
            return;
        }
        let result = match self
            .session
            .execute_command("goal", Some(GOAL_EVALUATE_ARG.to_string()))
            .await
        {
            Ok(result) => result,
            Err(err) => {
                self.push_system(format!("goal evaluation failed: {err}"));
                return;
            }
        };
        if !result.success {
            self.push_system(format!("goal evaluation failed: {}", result.message));
            return;
        }
        let evaluation = match parse_evaluation_response(&result.message) {
            Ok(evaluation) => evaluation,
            Err(err) => {
                self.push_system(format!("goal evaluation failed: {err}"));
                return;
            }
        };
        if evaluation.met {
            self.push_system(format!("goal achieved: {}", evaluation.reason));
            return;
        }
        self.push_system(format!("goal: {}", evaluation.reason));
        let Some(prompt) = self.goal_store.continuation_prompt(session_id) else {
            return;
        };
        self.push_user(prompt.clone());
        self.start_turn(prompt);
    }

    async fn after_turn_user_ask_check(&mut self) {
        if !self.user_ask_enabled {
            return;
        }
        let session_id = self.session.session_id();
        if !self.user_ask_store.is_active(session_id) {
            return;
        }
        let result = match self
            .session
            .execute_command("ask", Some(USER_ASK_EVALUATE_ARG.to_string()))
            .await
        {
            Ok(result) => result,
            Err(err) => {
                self.push_system(format!("user ask evaluation failed: {err}"));
                return;
            }
        };
        if !result.success {
            self.push_system(format!("user ask evaluation failed: {}", result.message));
            return;
        }
        let evaluation = match parse_user_ask_evaluation(&result.message) {
            Ok(evaluation) => evaluation,
            Err(err) => {
                self.push_system(format!("user ask evaluation failed: {err}"));
                return;
            }
        };
        self.push_system(evaluation_status_message(&evaluation));
    }

    /// Dispatch a capability-provided slash command.
    ///
    /// `System` commands execute through `runtime.execute_command` — the
    /// capability's own handler runs and the result is rendered inline. This
    /// is the path `/setup` now takes. `Skill` commands match the web UI's
    /// behavior: the literal `/name args` text is sent as a chat message so
    /// the LLM activates the skill.
    async fn invoke_capability_command(&mut self, descriptor: CommandDescriptor, args: String) {
        let trimmed = args.trim();
        let required_missing = descriptor
            .args
            .iter()
            .any(|a| a.required && trimmed.is_empty());
        if required_missing {
            let needed: Vec<&str> = descriptor
                .args
                .iter()
                .filter(|a| a.required)
                .map(|a| a.name.as_str())
                .collect();
            self.push_system(format!(
                "/{} requires: {}",
                descriptor.name,
                needed.join(", ")
            ));
            return;
        }

        match descriptor.source {
            CommandSource::System => {
                if descriptor.name == "setup" && trimmed.is_empty() {
                    self.start_setup();
                    return;
                }

                let arguments = (!trimmed.is_empty()).then(|| trimmed.to_string());
                let result = self
                    .session
                    .execute_command(&descriptor.name, arguments)
                    .await;
                match result {
                    Ok(result) => {
                        // Client-executed commands (help/clear/model/…) apply
                        // their effect via a `UiCommand` and return an empty
                        // message; don't render a blank line for those.
                        if !result.message.is_empty() {
                            let prefix = if result.success { "" } else { "error: " };
                            self.push_system(format!("{prefix}{}", result.message));
                        }
                        if descriptor.name == "goal" && result.success {
                            self.maybe_start_goal_turn();
                        }
                    }
                    Err(err) => self.push_system(format!("/{} failed: {err}", descriptor.name)),
                }
            }
            CommandSource::Skill => {
                let text = if trimmed.is_empty() {
                    format!("/{}", descriptor.name)
                } else {
                    format!("/{} {trimmed}", descriptor.name)
                };
                self.push_user(text.clone());
                self.start_turn(text);
            }
        }
    }

    fn start_shell_command(&mut self, command: String) {
        self.startup.workspace_root = self.worktree.active_root();
        self.push_user(format!("!shell {command}"));
        let handle = self.session.run_shell(command, self.workspace_host.clone());
        self.begin_turn(handle, Some("running shell command".into()));
    }

    /// Wire a freshly started [`crate::session::TurnHandle`] into the event loop:
    /// store its receiver and cancel trigger and flip into the busy state.
    fn begin_turn(&mut self, handle: crate::session::TurnHandle, activity: Option<String>) {
        self.rx = Some(handle.events);
        self.turn_cancel = Some(handle.cancel);
        self.esc_pending_cancel = false;
        self.busy = true;
        self.turn_activity = activity;
        self.stream_preview = None;
    }

    fn start_turn(&mut self, prompt: String) {
        match self.worktree.ensure_before_turn(&prompt) {
            Ok(true) => {
                self.startup.workspace_root = self.worktree.active_root();
                if let Some(notice) = self.worktree.switch_notice() {
                    self.push_system(notice);
                }
            }
            Ok(false) => {
                self.startup.workspace_root = self.worktree.active_root();
            }
            Err(err) => self.push_system(format!("worktree: {err}")),
        }

        let images = std::mem::take(&mut self.pending_images);
        let handle = self.session.run_turn(prompt, images);
        self.begin_turn(handle, None);
    }
}

fn parse_bang_shell_command(input: &str) -> Option<&str> {
    let rest = input.trim().strip_prefix('!')?;
    let rest = rest
        .trim_start()
        .strip_prefix("shell")
        .and_then(|tail| {
            tail.chars()
                .next()
                .is_none_or(char::is_whitespace)
                .then_some(tail)
        })
        .unwrap_or(rest);
    if rest.is_empty() {
        return Some("");
    }
    Some(rest.trim())
}

fn command_suggestions(
    input: &str,
    capability_commands: &[CommandDescriptor],
) -> Vec<CommandSuggestion> {
    if let Some(rest) = input.strip_prefix('!') {
        return bang_command_suggestions(rest, capability_commands);
    }
    let Some(rest) = input.strip_prefix('/') else {
        return Vec::new();
    };

    // If the user already typed a command name and a space, surface the
    // first-arg suggestions declared by the matching capability. This is
    // fully declarative — the capability populates `CommandArg::suggestions`
    // when it builds its `CommandDescriptor`, so the UI never has to call
    // back into the capability between keystrokes.
    if let Some((head, arg_prefix)) = rest.split_once(' ')
        && let Some(descriptor) = capability_commands.iter().find(|c| c.name == head)
        && let Some(arg) = descriptor.args.first()
        && !arg.suggestions.is_empty()
    {
        let prefix = arg_prefix.trim_start();
        return arg
            .suggestions
            .iter()
            .filter(|s| s.starts_with(prefix))
            .take(8)
            .map(|s| CommandSuggestion {
                completion: format!("/{} {s}", descriptor.name),
                label: format!("/{} {s}    {}", descriptor.name, descriptor.description),
            })
            .collect();
    }

    // Every command is capability-provided now (the TUI's terminal-side
    // commands come from `ClientCommandsCapability`), so there is a single
    // source of truth to filter and present.
    let mut out: Vec<CommandSuggestion> = Vec::new();
    for descriptor in capability_commands {
        if !descriptor.name.starts_with(rest) {
            continue;
        }
        let usage = capability_command_usage(descriptor);
        // If the command takes args, leave a trailing space so the user can
        // start typing immediately after accepting the suggestion.
        let completion = if descriptor.args.is_empty() {
            format!("/{}", descriptor.name)
        } else {
            format!("/{} ", descriptor.name)
        };
        out.push(CommandSuggestion {
            completion,
            label: format!("{usage}    {}", descriptor.description),
        });
    }

    // Keep the dropdown bounded but large enough to show every built-in
    // command (10 client commands + capability commands like /setup) for a
    // bare `/`, so none is hidden behind the cap.
    out.truncate(12);
    out
}

fn bang_command_suggestions(
    rest: &str,
    capability_commands: &[CommandDescriptor],
) -> Vec<CommandSuggestion> {
    let Some(descriptor) = capability_commands.iter().find(|c| c.name == "shell") else {
        return Vec::new();
    };
    if rest.contains(char::is_whitespace) || !descriptor.name.starts_with(rest) {
        return Vec::new();
    }
    vec![CommandSuggestion {
        completion: "!shell ".to_string(),
        label: format!(
            "{}    {}",
            capability_command_display_usage(descriptor),
            descriptor.description
        ),
    }]
}

fn capability_command_display_usage(descriptor: &CommandDescriptor) -> String {
    capability_command_usage_with_prefix(
        descriptor,
        if descriptor.name == "shell" { "!" } else { "/" },
    )
}

fn capability_command_usage(descriptor: &CommandDescriptor) -> String {
    capability_command_usage_with_prefix(descriptor, "/")
}

fn help_command_line(descriptor: &CommandDescriptor) -> String {
    let usage = if descriptor.name == "quit" {
        "/quit (/exit)".to_string()
    } else {
        capability_command_usage(descriptor)
    };
    format!("  {}{}", usage, descriptor.description)
}

fn help_shortcut_lines() -> [&'static str; 5] {
    [
        "  Enter send · Shift-Enter newline · Tab complete slash command · ←/→ edit",
        "  Ctrl+V paste image/text · Ctrl+B background tasks · !<cmd> shell alias",
        "  exit: Ctrl-C twice / Ctrl-D",
        "  cancel turn: Esc twice (while model is busy)",
        "  scroll: terminal scrollback (no in-app page keys)",
    ]
}

fn capability_command_usage_with_prefix(descriptor: &CommandDescriptor, prefix: &str) -> String {
    if descriptor.args.is_empty() {
        format!("{prefix}{}", descriptor.name)
    } else {
        let args = descriptor
            .args
            .iter()
            .map(|a| {
                if a.required {
                    format!("<{}>", a.name)
                } else {
                    format!("[{}]", a.name)
                }
            })
            .collect::<Vec<_>>()
            .join(" ");
        format!("{prefix}{} {args}", descriptor.name)
    }
}

fn new_input_area(lines: Vec<String>) -> TextArea<'static> {
    let mut input = TextArea::new(lines);
    input.set_wrap_mode(WrapMode::Word);
    input.set_style(Style::default().fg(TEXT_PRIMARY));
    input.set_cursor_line_style(Style::default());
    input.set_cursor_style(Style::default().add_modifier(Modifier::REVERSED));
    input
}

/// Visual rows the composer needs at `width`, including soft-wrapped logical lines.
fn wrapped_input_visual_lines(input: &TextArea<'_>, width: u16) -> usize {
    let width = width.max(1);
    let mut scratch = input.clone();
    let area = Rect {
        x: 0,
        y: 0,
        width,
        height: MAX_INPUT_HEIGHT,
    };
    let mut buf = Buffer::empty(area);
    Widget::render(&scratch, area, &mut buf);
    scratch.move_cursor(CursorMove::End);
    scratch.screen_cursor().row + 1
}

fn normalize_printable_key(mut key: KeyEvent) -> KeyEvent {
    if !key.modifiers.contains(KeyModifiers::SHIFT)
        || key
            .modifiers
            .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT)
    {
        return key;
    }

    let KeyCode::Char(ch) = key.code else {
        return key;
    };
    let Some(ch) = shifted_char(ch) else {
        return key;
    };

    key.code = KeyCode::Char(ch);
    key.modifiers.remove(KeyModifiers::SHIFT);
    key
}

fn shifted_char(ch: char) -> Option<char> {
    let shifted = match ch {
        'a'..='z' => ch.to_ascii_uppercase(),
        'A'..='Z' | ' ' => ch,
        '`' => '~',
        '1' => '!',
        '2' => '@',
        '3' => '#',
        '4' => '$',
        '5' => '%',
        '6' => '^',
        '7' => '&',
        '8' => '*',
        '9' => '(',
        '0' => ')',
        '-' => '_',
        '=' => '+',
        '[' => '{',
        ']' => '}',
        '\\' => '|',
        ';' => ':',
        '\'' => '"',
        ',' => '<',
        '.' => '>',
        '/' => '?',
        '~' | '!' | '@' | '#' | '$' | '%' | '^' | '&' | '*' | '(' | ')' | '_' | '+' | '{' | '}'
        | '|' | ':' | '"' | '<' | '>' | '?' => ch,
        _ => return None,
    };
    Some(shifted)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::capabilities::model_discovery::DiscoveredProviderModel;
    use everruns_core::events::{
        Event as RuntimeEvent, EventContext, InputMessageData, OutputMessageCompletedData,
        OutputMessageStartedData, ReasonCompletedData, ToolCompletedData,
    };
    use everruns_core::message::Message;
    use everruns_core::session_task::{
        CreateSessionTask, SessionTaskState, TASK_KIND_BACKGROUND_TOOL,
    };
    use everruns_core::tool_types::ToolCall;
    use everruns_core::{SessionId, TurnId};

    use everruns_core::command::{CommandArg, CommandDescriptor, CommandSource};

    fn setup_capability_command() -> CommandDescriptor {
        CommandDescriptor {
            name: "setup".to_string(),
            description: "Configure provider, API key, and model.".to_string(),
            source: CommandSource::System,
            args: vec![],
        }
    }

    /// The terminal-side command descriptors as declared by
    /// `ClientCommandsCapability` (help/tools/cwd/model/effort/clear/shell/quit).
    /// These now flow through the same registry as every other command, so
    /// suggestion tests source them the same way the running TUI does.
    fn client_command_descriptors() -> Vec<CommandDescriptor> {
        use everruns_core::capabilities::Capability;
        struct NoopUi;
        impl crate::host_ui::HostUi for NoopUi {
            fn send(&self, _: crate::host_ui::UiCommand) {}
        }
        crate::capabilities::client_commands::ClientCommandsCapability::new(std::sync::Arc::new(
            NoopUi,
        ))
        .commands()
    }

    /// Client commands plus a representative capability command, in the order
    /// the TUI would see them at startup.
    fn caps_with_client_commands(extra: Vec<CommandDescriptor>) -> Vec<CommandDescriptor> {
        let mut caps = client_command_descriptors();
        caps.extend(extra);
        caps
    }

    fn command_with_arg_suggestions() -> CommandDescriptor {
        CommandDescriptor {
            name: "pick".to_string(),
            description: "Pick a value.".to_string(),
            source: CommandSource::System,
            args: vec![CommandArg {
                name: "value".to_string(),
                description: "value".to_string(),
                required: false,
                suggestions: vec![
                    "alpha-one".to_string(),
                    "alpha-two".to_string(),
                    "beta-one".to_string(),
                ],
            }],
        }
    }

    #[test]
    fn command_suggestions_list_commands_for_slash() {
        let caps = caps_with_client_commands(vec![setup_capability_command()]);
        let suggestions = command_suggestions("/", &caps);

        assert!(suggestions.iter().any(|s| s.completion == "/help"));
        assert!(
            suggestions
                .iter()
                .any(|s| s.completion == "/setup" || s.completion == "/setup "),
            "capability-provided /setup should appear in suggestions: {suggestions:?}"
        );
    }

    #[test]
    fn suggestion_preview_line_shows_command_dropdown() {
        let caps = vec![setup_capability_command()];
        let suggestions = command_suggestions("/s", &caps);
        let rendered = line_text(&suggestion_preview_line(&suggestions, 96));

        assert!(rendered.starts_with("Tab /setup"));
        assert!(rendered.contains("/setup"));
    }

    #[test]
    fn suggestion_preview_line_keeps_first_match_when_truncated() {
        let caps = caps_with_client_commands(vec![setup_capability_command()]);
        let suggestions = command_suggestions("/", &caps);
        let rendered = line_text(&suggestion_preview_line(&suggestions, 18));

        assert!(rendered.starts_with("Tab /help"));
        assert!(rendered.ends_with(''));
    }

    #[test]
    fn command_suggestions_filter_first_arg_by_prefix() {
        // After `/pick <prefix>`, the suggestion source must be the arg's
        // declared `suggestions` — read straight from the descriptor with
        // no extra plumbing.
        let caps = vec![command_with_arg_suggestions()];
        let suggestions = command_suggestions("/pick alpha-", &caps);

        assert_eq!(
            suggestions
                .iter()
                .map(|s| s.completion.as_str())
                .collect::<Vec<_>>(),
            vec!["/pick alpha-one", "/pick alpha-two"]
        );
    }

    #[test]
    fn command_suggestions_no_arg_suggestions_means_free_form() {
        // A capability command whose first arg has no suggestions returns an
        // empty list once the user types past the command name — the renderer
        // should fall back to plain text entry instead of fabricating items.
        let caps = vec![CommandDescriptor {
            name: "echo".to_string(),
            description: "echo".to_string(),
            source: CommandSource::System,
            args: vec![CommandArg {
                name: "text".to_string(),
                description: "text".to_string(),
                required: true,
                suggestions: vec![],
            }],
        }];

        let suggestions = command_suggestions("/echo hello", &caps);
        assert!(suggestions.is_empty(), "got: {suggestions:?}");
    }

    #[test]
    fn bang_shell_parser_accepts_shell_alias_and_bare_command() {
        assert_eq!(parse_bang_shell_command("!shell"), Some(""));
        assert_eq!(parse_bang_shell_command("  !shell   pwd  "), Some("pwd"));
        assert_eq!(
            parse_bang_shell_command("!shell	printf hi"),
            Some("printf hi")
        );
        assert_eq!(
            parse_bang_shell_command("!printf shell-ok"),
            Some("printf shell-ok")
        );
        assert_eq!(
            parse_bang_shell_command("!shellshock echo yes"),
            Some("shellshock echo yes")
        );
        assert_eq!(parse_bang_shell_command("!"), Some(""));
    }

    #[test]
    fn bang_shell_suggestions_use_client_command_registry() {
        let caps = caps_with_client_commands(vec![setup_capability_command()]);
        let suggestions = command_suggestions("!s", &caps);

        assert_eq!(suggestions.len(), 1, "got: {suggestions:?}");
        assert_eq!(suggestions[0].completion, "!shell ");
        assert!(suggestions[0].label.starts_with("!shell <command>"));
        assert!(command_suggestions("!shell echo", &caps).is_empty());
        assert!(command_suggestions("!s", &[setup_capability_command()]).is_empty());
    }

    #[test]
    fn capability_commands_appear_in_suggestions() {
        let caps = vec![CommandDescriptor {
            name: "btw".to_string(),
            description: "Ask a side question.".to_string(),
            source: CommandSource::System,
            args: vec![CommandArg {
                name: "question".to_string(),
                description: "the question".to_string(),
                required: true,
                suggestions: vec![],
            }],
        }];

        let suggestions = command_suggestions("/b", &caps);

        let btw = suggestions
            .iter()
            .find(|s| s.completion == "/btw ")
            .expect("capability command surfaced in suggestions");
        assert!(btw.label.starts_with("/btw <question>"));
    }

    #[test]
    fn suggestions_come_solely_from_the_command_registry() {
        // There are no hard-coded built-ins anymore: every command — including
        // /help — is a capability command (the TUI's come from
        // `ClientCommandsCapability`). So suggestions reflect exactly the
        // descriptor list, one entry per declared command.
        let caps = vec![CommandDescriptor {
            name: "help".to_string(),
            description: "show commands".to_string(),
            source: CommandSource::System,
            args: vec![],
        }];

        let suggestions = command_suggestions("/help", &caps);

        let help_entries: Vec<_> = suggestions
            .iter()
            .filter(|s| s.completion.starts_with("/help"))
            .collect();
        assert_eq!(help_entries.len(), 1);
        assert_eq!(help_entries[0].completion, "/help");
    }

    #[test]
    fn input_area_supports_multiline_and_cursor_editing() {
        let mut input = new_input_area(vec![String::new()]);

        for key in [
            KeyEvent::new(KeyCode::Char('a'), KeyModifiers::empty()),
            KeyEvent::new(KeyCode::Char('c'), KeyModifiers::empty()),
            KeyEvent::new(KeyCode::Left, KeyModifiers::empty()),
            KeyEvent::new(KeyCode::Char('b'), KeyModifiers::empty()),
            KeyEvent::new(KeyCode::Right, KeyModifiers::empty()),
            KeyEvent::new(KeyCode::Enter, KeyModifiers::ALT),
            KeyEvent::new(KeyCode::Char('d'), KeyModifiers::empty()),
        ] {
            let _ = input.input(key);
        }

        assert_eq!(input.lines(), ["abc", "d"]);
    }

    #[test]
    fn newline_shortcut_hint_uses_shift_enter_only() {
        assert_eq!(newline_shortcut_hint(), "Shift-Enter");
    }

    #[test]
    fn chrome_height_reserves_four_expanded_status_rows() {
        assert_eq!(chrome_height(1, 1, false), 4);
        assert_eq!(chrome_height(1, 1, true), 5);
        assert_eq!(chrome_height(1, 4, false), 7);
        assert_eq!(chrome_height(1, 4, true), 8);
        assert_eq!(chrome_height(3, 1, false), 5);
        assert_eq!(chrome_height(3, 4, false), 8);
        assert_eq!(chrome_height(4, 1, false), 6);
        assert_eq!(chrome_height(4, 4, false), 9);
    }

    #[test]
    fn chrome_dimensions_clamp_input_to_visible_frame() {
        assert_eq!(chrome_dimensions(7, MAX_INPUT_HEIGHT, 4, false), (7, 1));
        assert_eq!(chrome_dimensions(5, MAX_INPUT_HEIGHT, 1, false), (5, 3));
        assert_eq!(chrome_dimensions(0, MAX_INPUT_HEIGHT, 1, false), (0, 0));
    }

    fn rect_inside(parent: Rect, child: Rect) -> bool {
        let parent_right = parent.x as u32 + parent.width as u32;
        let parent_bottom = parent.y as u32 + parent.height as u32;
        let child_right = child.x as u32 + child.width as u32;
        let child_bottom = child.y as u32 + child.height as u32;
        child.x >= parent.x
            && child.y >= parent.y
            && child_right <= parent_right
            && child_bottom <= parent_bottom
    }

    #[test]
    fn app_layout_rectangles_stay_inside_frame_across_sizes() {
        let widths = [0, 1, 2, 4, 8, 16, 40, 120];
        let heights = [0, 1, 2, 3, 4, 5, 7, 12, 24, 60];
        let desired_inputs = [0, 1, 2, 3, MAX_INPUT_HEIGHT, MAX_INPUT_HEIGHT + 8];
        for status_layout in [StatusLayout::Compact, StatusLayout::Expanded] {
            for width in widths {
                for height in heights {
                    for desired_input in desired_inputs {
                        let frame = Rect {
                            x: 2,
                            y: 3,
                            width,
                            height,
                        };
                        let layout = app_layout_for_frame(
                            frame,
                            desired_input,
                            status_layout.base_row_count(),
                            false,
                        );
                        assert_eq!(layout.frame, frame);
                        assert!(
                            rect_inside(frame, layout.transcript),
                            "transcript escaped frame: {layout:?}"
                        );
                        assert!(
                            rect_inside(frame, layout.chrome.area),
                            "chrome escaped frame: {layout:?}"
                        );
                        assert!(
                            rect_inside(layout.chrome.area, layout.chrome.preview),
                            "preview escaped chrome: {layout:?}"
                        );
                        assert!(
                            rect_inside(layout.chrome.area, layout.chrome.message_separator),
                            "message separator escaped chrome: {layout:?}"
                        );
                        assert!(
                            rect_inside(layout.chrome.area, layout.chrome.input),
                            "input escaped chrome: {layout:?}"
                        );
                        assert!(
                            rect_inside(layout.chrome.area, layout.chrome.status_separator),
                            "status separator escaped chrome: {layout:?}"
                        );
                        assert!(
                            rect_inside(layout.chrome.area, layout.chrome.session_status),
                            "session status escaped chrome: {layout:?}"
                        );
                        assert!(
                            layout.chrome.area.height <= frame.height,
                            "chrome taller than frame: {layout:?}"
                        );
                        assert!(
                            layout.chrome.input_height <= MAX_INPUT_HEIGHT,
                            "input height exceeded cap: {layout:?}"
                        );
                    }
                }
            }
        }
    }

    #[test]
    fn replayed_events_render_user_assistant_and_tool_lines() {
        let session_id = SessionId::new();
        let user_event = RuntimeEvent::new(
            session_id,
            EventContext::empty(),
            InputMessageData::new(Message::user("What changed?")),
        );
        let assistant_event = RuntimeEvent::new(
            session_id,
            EventContext::empty(),
            OutputMessageCompletedData::new(Message::assistant("I updated the renderer.")),
        );
        let mut tool_data = ToolCompletedData::success(
            "call_bash".to_string(),
            "bash".to_string(),
            vec![ContentPart::text(
                serde_json::json!({
                    "command": "cargo test",
                    "exit_code": 0
                })
                .to_string(),
            )],
            None,
        );
        tool_data.narration = Some("Ran tests".to_string());
        let tool_event = RuntimeEvent::new(session_id, EventContext::empty(), tool_data);

        let lines = [user_event, assistant_event, tool_event]
            .iter()
            .flat_map(lines_for_replayed_event)
            .map(|line| (line.author, line.text))
            .collect::<Vec<_>>();

        assert!(matches!(lines[0].0, Author::User));
        assert_eq!(lines[0].1, "What changed?");
        assert!(matches!(lines[1].0, Author::Assistant));
        assert_eq!(lines[1].1, "I updated the renderer.");
        assert!(matches!(lines[2].0, Author::Tool));
        assert!(lines[2].1.contains("Ran tests"));
    }

    #[test]
    fn lines_for_event_surfaces_tool_call_monologue() {
        let event = RuntimeEvent::new(
            SessionId::new(),
            EventContext::empty(),
            ReasonCompletedData::success("I'll check the manifests first.", true, 2, None, None),
        );

        let lines = lines_for_event(&event);

        assert_eq!(lines.len(), 1);
        assert!(matches!(lines[0].author, Author::Narration));
        assert_eq!(lines[0].text, "I'll check the manifests first.");
        assert_eq!(lines[0].author.label(), "note");
        assert_eq!(
            status_for_event(&event)
                .map(|status| status.text)
                .as_deref(),
            Some("planned 2 tool call(s)")
        );
    }

    #[test]
    fn lines_for_event_renders_reason_item_summary_segments() {
        use everruns_core::events::ReasonItemData;

        let event = RuntimeEvent::new(
            SessionId::new(),
            EventContext::empty(),
            ReasonItemData {
                turn_id: TurnId::new(),
                provider: "openai".to_string(),
                model: Some("gpt-5".to_string()),
                item_id: "rs_abc".to_string(),
                encrypted_content: Some("opaque".to_string()),
                summary: vec![
                    "Considering file layout".to_string(),
                    "".to_string(),
                    "  Plan the read order  ".to_string(),
                ],
                token_count: None,
            },
        );

        let lines = lines_for_event(&event);

        assert_eq!(lines.len(), 2, "blank summary segments are dropped");
        assert!(matches!(lines[0].author, Author::Narration));
        assert_eq!(lines[0].text, "Considering file layout");
        assert_eq!(lines[1].text, "Plan the read order");
    }

    #[test]
    fn lines_for_event_hides_output_message_thinking() {
        let mut message = everruns_core::Message::assistant_with_tools(
            "",
            vec![ToolCall {
                id: "call_read".to_string(),
                name: "read_file".to_string(),
                arguments: serde_json::json!({ "path": "/workspace/Cargo.toml" }),
            }],
        );
        message.thinking = Some(
            "**Inspecting package files**\n\nI should read the package manifest first.".to_string(),
        );
        let event = RuntimeEvent::new(
            SessionId::new(),
            EventContext::empty(),
            OutputMessageCompletedData::new(message),
        );

        let lines = lines_for_event(&event);

        assert!(lines.is_empty(), "thinking must not be rendered: {lines:?}");
    }

    #[test]
    fn status_for_event_labels_output_iteration() {
        let event = RuntimeEvent::new(
            SessionId::new(),
            EventContext::empty(),
            OutputMessageStartedData {
                turn_id: TurnId::new(),
                model: None,
                iteration: Some(3),
            },
        );

        assert!(lines_for_event(&event).is_empty());
        assert_eq!(
            status_for_event(&event)
                .map(|status| status.text)
                .as_deref(),
            Some("iteration 3: writing response")
        );
    }

    #[test]
    fn lines_for_event_renders_short_write_todos_inline() {
        let event = RuntimeEvent::new(
            SessionId::new(),
            EventContext::empty(),
            ToolCompletedData::success(
                "call_todos".to_string(),
                "write_todos".to_string(),
                vec![ContentPart::text(
                    serde_json::json!({
                        "success": true,
                        "total_tasks": 3,
                        "pending": 1,
                        "in_progress": 1,
                        "completed": 1,
                        "todos": [
                            {
                                "content": "Read current CLI renderer",
                                "activeForm": "Reading current CLI renderer",
                                "status": "completed"
                            },
                            {
                                "content": "Render todos in transcript",
                                "activeForm": "Rendering todos in transcript",
                                "status": "in_progress"
                            },
                            {
                                "content": "Run focused tests",
                                "activeForm": "Running focused tests",
                                "status": "pending"
                            }
                        ]
                    })
                    .to_string(),
                )],
                None,
            ),
        );

        let lines = lines_for_event(&event)
            .into_iter()
            .map(|line| (line.author, line.text))
            .collect::<Vec<_>>();

        assert!(matches!(lines[0].0, Author::Tool));
        assert_eq!(
            lines[0].1,
            "1 of 3 todos completed  ✓ Read current CLI renderer  › Rendering todos in transcript  ○ Run focused tests"
        );
        assert_eq!(lines.len(), 1);
    }

    #[test]
    fn handle_live_event_renders_write_todos_from_started_args_when_result_is_counts_only() {
        use everruns_core::events::ToolStartedData;
        use everruns_core::tool_types::ToolCall;

        let (tx, mut rx) = mpsc::unbounded_channel::<TurnEvent>();
        let mut emitted = HashSet::new();
        let mut router = DeltaRouter::default();
        let session_id = SessionId::new();

        let started = RuntimeEvent::new(
            session_id,
            EventContext::empty(),
            ToolStartedData {
                tool_call: ToolCall {
                    id: "call_todos".to_string(),
                    name: "write_todos".to_string(),
                    arguments: serde_json::json!({
                        "todos": [
                            {
                                "content": "Read current CLI renderer",
                                "activeForm": "Reading current CLI renderer",
                                "status": "completed"
                            },
                            {
                                "content": "Render todos in transcript",
                                "activeForm": "Rendering todos in transcript",
                                "status": "in_progress"
                            },
                            {
                                "content": "Run focused tests",
                                "activeForm": "Running focused tests",
                                "status": "pending"
                            }
                        ]
                    }),
                },
                tool_call_fingerprint: None,
                display_name: Some("Write Todos".to_string()),
                narration: None,
            },
        );
        let completed = RuntimeEvent::new(
            session_id,
            EventContext::empty(),
            ToolCompletedData::success(
                "call_todos".to_string(),
                "write_todos".to_string(),
                vec![ContentPart::text(
                    serde_json::json!({
                        "success": true,
                        "total_tasks": 3,
                        "pending": 1,
                        "in_progress": 1,
                        "completed": 1
                    })
                    .to_string(),
                )],
                None,
            ),
        );

        handle_live_event(&started, &mut emitted, &mut router, &tx);
        handle_live_event(&completed, &mut emitted, &mut router, &tx);

        let mut lines = Vec::new();
        while let Ok(event) = rx.try_recv() {
            if let TurnEvent::Lines(batch) = event {
                lines.extend(batch.into_iter().map(|line| line.text));
            }
        }

        assert!(lines.iter().all(|line| line != "✓ Write Todos"));
        assert_eq!(
            lines,
            vec![
                "1 of 3 todos completed  ✓ Read current CLI renderer  › Rendering todos in transcript  ○ Run focused tests"
            ]
        );
    }

    #[test]
    fn lines_for_event_renders_long_write_todos_as_rows() {
        let event = RuntimeEvent::new(
            SessionId::new(),
            EventContext::empty(),
            ToolCompletedData::success(
                "call_todos".to_string(),
                "write_todos".to_string(),
                vec![ContentPart::text(
                    serde_json::json!({
                        "success": true,
                        "total_tasks": 4,
                        "pending": 2,
                        "in_progress": 1,
                        "completed": 1,
                        "todos": [
                            {
                                "content": "Read current CLI renderer",
                                "activeForm": "Reading current CLI renderer",
                                "status": "completed"
                            },
                            {
                                "content": "Render todos in transcript",
                                "activeForm": "Rendering todos in transcript",
                                "status": "in_progress"
                            },
                            {
                                "content": "Run focused tests",
                                "activeForm": "Running focused tests",
                                "status": "pending"
                            },
                            {
                                "content": "Summarize changes",
                                "activeForm": "Summarizing changes",
                                "status": "pending"
                            }
                        ]
                    })
                    .to_string(),
                )],
                None,
            ),
        );

        let lines = lines_for_event(&event)
            .into_iter()
            .map(|line| (line.author, line.text))
            .collect::<Vec<_>>();

        assert!(matches!(lines[0].0, Author::Tool));
        assert_eq!(lines[0].1, "1 of 4 todos completed");
        assert!(
            lines
                .iter()
                .any(|(author, line)| matches!(author, Author::ToolDetail)
                    && line == "✓ Read current CLI renderer")
        );
        assert!(
            lines
                .iter()
                .any(|(author, line)| matches!(author, Author::ToolDetail)
                    && line == "› Rendering todos in transcript")
        );
        assert!(
            lines
                .iter()
                .any(|(author, line)| matches!(author, Author::ToolDetail)
                    && line == "○ Run focused tests")
        );
    }

    #[test]
    fn lines_for_event_limits_write_todo_rows_and_truncates_text() {
        let total = MAX_RENDERED_TODOS + 5;
        let long_text = "x".repeat(MAX_TODO_TEXT_CHARS + 60);
        let todos = (0..total)
            .map(|_| {
                serde_json::json!({
                    "content": &long_text,
                    "activeForm": &long_text,
                    "status": "pending"
                })
            })
            .collect::<Vec<_>>();
        let event = RuntimeEvent::new(
            SessionId::new(),
            EventContext::empty(),
            ToolCompletedData::success(
                "call_todos".to_string(),
                "write_todos".to_string(),
                vec![ContentPart::text(
                    serde_json::json!({
                        "success": true,
                        "todos": todos,
                        "warning": "w".repeat(MAX_TODO_TEXT_CHARS + 60)
                    })
                    .to_string(),
                )],
                None,
            ),
        );

        let lines = lines_for_event(&event);
        let detail_lines = lines
            .iter()
            .filter(|line| matches!(line.author, Author::ToolDetail))
            .map(|line| line.text.as_str())
            .collect::<Vec<_>>();

        let omitted = total - MAX_RENDERED_TODOS;
        assert_eq!(
            detail_lines
                .iter()
                .filter(|line| line.starts_with(""))
                .count(),
            MAX_RENDERED_TODOS
        );
        assert!(
            detail_lines
                .iter()
                .any(|line| *line == format!("{omitted} more todo(s) omitted"))
        );
        assert!(
            detail_lines
                .iter()
                .any(|line| line.starts_with("warning: "))
        );
        assert!(
            detail_lines
                .iter()
                .filter(|line| line.starts_with(""))
                .all(|line| line.ends_with(''))
        );
    }

    #[test]
    fn handle_live_event_routes_assistant_delta_to_stream_preview() {
        use everruns_core::events::{OutputMessageDeltaData, ToolOutputDeltaData};
        use everruns_core::typed_id::TurnId;

        let (tx, mut rx) = mpsc::unbounded_channel::<TurnEvent>();
        let mut emitted = HashSet::new();
        let mut router = DeltaRouter::default();
        let turn_id = TurnId::new();

        let delta_event = RuntimeEvent::new(
            SessionId::new(),
            EventContext::empty(),
            OutputMessageDeltaData {
                turn_id,
                delta: "Hel".to_string(),
                accumulated: "Hel".to_string(),
            },
        );
        handle_live_event(&delta_event, &mut emitted, &mut router, &tx);

        let more = RuntimeEvent::new(
            SessionId::new(),
            EventContext::empty(),
            OutputMessageDeltaData {
                turn_id,
                delta: "lo, world".to_string(),
                accumulated: "Hello, world".to_string(),
            },
        );
        handle_live_event(&more, &mut emitted, &mut router, &tx);

        let completed = RuntimeEvent::new(
            SessionId::new(),
            EventContext::empty(),
            OutputMessageCompletedData::new(Message::assistant("Hello, world")),
        );
        handle_live_event(&completed, &mut emitted, &mut router, &tx);

        // Tool delta event surfaces a separate preview kind.
        let tool_delta = RuntimeEvent::new(
            SessionId::new(),
            EventContext::empty(),
            ToolOutputDeltaData {
                tool_call_id: "call-99".to_string(),
                tool_name: "bash".to_string(),
                delta: "compiling...\n".to_string(),
                stream: "stdout".to_string(),
            },
        );
        handle_live_event(&tool_delta, &mut emitted, &mut router, &tx);

        let mut previews = Vec::new();
        while let Ok(event) = rx.try_recv() {
            if let TurnEvent::Stream(preview) = event {
                previews.push(preview);
            }
        }

        // Expect: first delta → Assistant preview, second delta → Assistant
        // preview with accumulated text, completed → None, tool delta → Tool preview.
        assert_eq!(previews.len(), 4);
        match &previews[0] {
            Some(p) => {
                assert_eq!(p.kind, StreamKind::Assistant);
                assert_eq!(p.text, "Hel");
            }
            None => panic!("expected first preview to be Some"),
        }
        match &previews[1] {
            Some(p) => {
                assert_eq!(p.kind, StreamKind::Assistant);
                assert_eq!(p.text, "Hello, world");
            }
            None => panic!("expected second preview to be Some"),
        }
        assert!(previews[2].is_none(), "completed must clear preview");
        match &previews[3] {
            Some(p) => {
                assert_eq!(p.kind, StreamKind::Tool);
                assert!(
                    p.text.contains("bash") && p.text.contains("compiling"),
                    "tool preview text: {:?}",
                    p.text
                );
            }
            None => panic!("expected tool delta to surface preview"),
        }
    }

    #[test]
    fn handle_live_event_hides_thinking_delta_from_stream_preview() {
        use everruns_core::events::ReasonThinkingDeltaData;
        use everruns_core::typed_id::TurnId;

        let (tx, mut rx) = mpsc::unbounded_channel::<TurnEvent>();
        let mut emitted = HashSet::new();
        let mut router = DeltaRouter::default();

        let event = RuntimeEvent::new(
            SessionId::new(),
            EventContext::empty(),
            ReasonThinkingDeltaData {
                turn_id: TurnId::new(),
                delta: "private chain".to_string(),
                accumulated: "private chain".to_string(),
            },
        );
        handle_live_event(&event, &mut emitted, &mut router, &tx);

        while let Ok(event) = rx.try_recv() {
            assert!(
                !matches!(event, TurnEvent::Stream(_)),
                "private thinking must not create a stream preview: {event:?}"
            );
        }
    }

    #[test]
    fn handle_live_event_deduplicates_by_event_id() {
        let (tx, mut rx) = mpsc::unbounded_channel::<TurnEvent>();
        let mut emitted = HashSet::new();
        let mut router = DeltaRouter::default();

        let event = RuntimeEvent::new(
            SessionId::new(),
            EventContext::empty(),
            ReasonCompletedData::success("plan", true, 1, None, None),
        );
        handle_live_event(&event, &mut emitted, &mut router, &tx);
        handle_live_event(&event, &mut emitted, &mut router, &tx);

        let mut count = 0;
        while rx.try_recv().is_ok() {
            count += 1;
        }
        assert_eq!(
            count, 2,
            "first dispatch yields Activity + Lines; second is suppressed"
        );
    }

    #[test]
    fn handle_live_event_emits_known_token_counts() {
        use everruns_core::events::ReasonItemData;

        let (tx, mut rx) = mpsc::unbounded_channel::<TurnEvent>();
        let mut emitted = HashSet::new();
        let mut router = DeltaRouter::default();

        let event = RuntimeEvent::new(
            SessionId::new(),
            EventContext::empty(),
            ReasonItemData {
                turn_id: TurnId::new(),
                provider: "openai".to_string(),
                model: Some("gpt-5".to_string()),
                item_id: "rs_tokens".to_string(),
                encrypted_content: None,
                summary: Vec::new(),
                token_count: Some(120),
            },
        );
        handle_live_event(&event, &mut emitted, &mut router, &tx);

        let mut tokens = Vec::new();
        while let Ok(event) = rx.try_recv() {
            if let TurnEvent::Tokens(count) = event {
                tokens.push(count);
            }
        }
        assert_eq!(tokens, vec![120]);
    }

    #[test]
    fn truncate_tail_keeps_visible_cursor() {
        assert_eq!(truncate_tail_chars("hello", 10), "hello");
        let out = truncate_tail_chars("0123456789abcdef", 8);
        assert!(out.starts_with(''), "expected ellipsis prefix: {out:?}");
        assert!(
            out.ends_with("cdef"),
            "expected tail of the text to survive: {out:?}"
        );
    }

    #[test]
    fn truncate_end_handles_tiny_limits() {
        assert_eq!(truncate_end_chars("hello", 0), "");
        assert_eq!(truncate_end_chars("hello", 1), "");
        assert_eq!(truncate_end_chars("hello", 99), "hello");
    }

    #[test]
    fn first_line_truncates_on_char_boundaries() {
        // Regression: byte-index slicing panicked when `max` landed inside a
        // multi-byte code point. "héllo" — the limit of 2 must split between
        // 'h' and 'é' (a 2-byte char), not mid-codepoint.
        assert_eq!(first_line("héllo", 2), "hé…");
        // Only the first line is kept, and short non-ASCII text is untouched.
        assert_eq!(first_line("résumé\nsecond", 99), "résumé");
    }

    fn line_text(line: &Line<'_>) -> String {
        line.spans
            .iter()
            .map(|span| span.content.as_ref())
            .collect::<String>()
    }

    fn line_content_color(line: &Line<'_>) -> Option<Color> {
        line.spans.get(1).and_then(|span| span.style.fg)
    }

    #[test]
    fn diff_lines_style_adds_deletes_and_metadata() {
        let mut lines = Vec::new();
        append_chat_lines(
            &mut lines,
            &ChatLine {
                author: Author::Diff,
                text: "--- /workspace/src/app.rs (before)\n+++ /workspace/src/app.rs (after)\n@@ -1 +1 @@\n-old\n+new\n unchanged".to_string(),
            },
            96,
        );

        assert_eq!(line_content_color(&lines[0]), Some(DIFF_DELETE));
        assert_eq!(line_content_color(&lines[1]), Some(DIFF_ADD));
        assert_eq!(line_content_color(&lines[2]), Some(DIFF_META));
        assert_eq!(line_content_color(&lines[3]), Some(DIFF_DELETE));
        assert_eq!(line_content_color(&lines[4]), Some(DIFF_ADD));
        assert_eq!(line_content_color(&lines[5]), Some(TEXT_PRIMARY));
    }

    #[test]
    fn narration_lines_use_note_label_and_muted_text() {
        let mut lines = Vec::new();
        append_chat_lines(
            &mut lines,
            &ChatLine {
                author: Author::Narration,
                text: "Considering installation steps".to_string(),
            },
            96,
        );

        assert_eq!(
            line_text(&lines[0]),
            "note › Considering installation steps"
        );
        assert_eq!(lines[0].spans[0].style.fg, Some(TEXT_MUTED));
        assert_eq!(line_content_color(&lines[0]), Some(TEXT_MUTED));
    }

    #[test]
    fn markdown_table_renders_columns_within_width() {
        let width = 48;
        let mut lines = Vec::new();
        append_chat_lines(
            &mut lines,
            &ChatLine {
                author: Author::Assistant,
                text: "| Name | Value |\n| --- | --- |\n| foo | bar |".to_string(),
            },
            width,
        );

        let body = lines.iter().map(line_text).collect::<Vec<_>>().join("\n");
        assert!(
            body.contains("Name") && body.contains("foo"),
            "table content should survive rendering: {body}"
        );
        assert!(
            lines.iter().all(|line| line_width(line) <= width),
            "table rows should fit width {width}: {lines:?}"
        );
        assert!(
            lines
                .iter()
                .flat_map(|line| line.spans.iter())
                .any(|span| span.style.fg == Some(TEXT_DIM)),
            "table borders should use dim styling: {lines:?}"
        );
    }

    #[test]
    fn markdown_table_reflows_when_terminal_width_changes() {
        let text = "| Key | Notes |\n| --- | --- |\n| resize | should reflow columns cleanly |"
            .to_string();
        let chat = ChatLine {
            author: Author::Assistant,
            text,
        };

        let mut narrow = Vec::new();
        append_chat_lines(&mut narrow, &chat, 28);
        let mut wide = Vec::new();
        append_chat_lines(&mut wide, &chat, 80);

        assert_ne!(
            narrow.iter().map(line_text).collect::<Vec<_>>(),
            wide.iter().map(line_text).collect::<Vec<_>>(),
            "table layout should change with width"
        );
        for (width, rendered) in [(28, &narrow), (80, &wide)] {
            assert!(
                rendered.iter().all(|line| line_width(line) <= width),
                "table should fit width {width}: {rendered:?}"
            );
        }
    }

    #[test]
    fn markdown_table_inside_code_fence_stays_literal() {
        let mut lines = Vec::new();
        append_chat_lines(
            &mut lines,
            &ChatLine {
                author: Author::Assistant,
                text: "```\n| not | a table |\n| --- | --- |\n```".to_string(),
            },
            60,
        );

        let body = lines.iter().map(line_text).collect::<Vec<_>>().join("\n");
        assert!(
            !body.contains('') && !body.contains(''),
            "fenced pipe rows should not be rendered as a table: {body}"
        );
        assert!(
            body.contains("| not | a table |"),
            "literal pipes preserved"
        );
    }

    #[test]
    fn markdown_lines_wrap_styled_content_to_available_width() {
        let width = 32;
        let mut lines = Vec::new();
        append_chat_lines(
            &mut lines,
            &ChatLine {
                author: Author::Assistant,
                text: "Use `very-long-command-name` before continuing with the next operation."
                    .to_string(),
            },
            width,
        );

        assert!(
            lines.len() > 1,
            "styled markdown should wrap into multiple rows: {lines:?}"
        );
        assert!(
            lines.iter().all(|line| line_width(line) <= width),
            "all rendered rows should fit width {width}: {lines:?}"
        );
        assert!(
            lines
                .iter()
                .flat_map(|line| line.spans.iter())
                .any(|span| span.style.bg == Some(CODE_BG)),
            "wrapped inline-code spans should keep code styling: {lines:?}"
        );
    }

    #[test]
    fn wrapped_plain_lines_do_not_use_wider_than_view_floor() {
        let width = 14;
        let mut lines = Vec::new();
        append_chat_lines(
            &mut lines,
            &ChatLine {
                author: Author::User,
                text: "supercalifragilistic".to_string(),
            },
            width,
        );

        assert!(
            lines.iter().all(|line| line_width(line) <= width),
            "hard-wrapped rows should fit narrow width {width}: {lines:?}"
        );
    }

    #[test]
    fn rendered_chat_lines_fit_available_width_across_authors() {
        let chats = [
            ChatLine {
                author: Author::User,
                text: "this is a deliberately long user prompt with one-super-long-token".into(),
            },
            ChatLine {
                author: Author::Assistant,
                text: "| Col A | Col B |\n| --- | --- |\n| alpha | beta |".into(),
            },
            ChatLine {
                author: Author::Assistant,
                text: "Use `cargo test --all-features` before resizing the terminal again.".into(),
            },
            ChatLine {
                author: Author::Narration,
                text: "reviewing layout constraints before drawing bottom chrome".into(),
            },
            ChatLine {
                author: Author::Diff,
                text: "+changed line with a very long path /workspace/src/app/render.rs".into(),
            },
            ChatLine {
                author: Author::ToolDetail,
                text: "stdout: output with a long uninterrupted token abcdefghijklmnopqrstuvwxyz"
                    .into(),
            },
        ];

        for width in [12, 16, 24, 40, 80] {
            for chat in &chats {
                let mut lines = Vec::new();
                append_chat_lines(&mut lines, chat, width);
                assert!(
                    lines.iter().all(|line| line_width(line) <= width),
                    "rendered line escaped width {width} for {chat:?}: {lines:?}"
                );
            }
        }
    }

    #[test]
    fn should_not_insert_chat_gap_inside_tool_blocks() {
        assert!(!should_insert_chat_gap(&Author::Tool, Some(&Author::Tool)));
        assert!(!should_insert_chat_gap(
            &Author::Tool,
            Some(&Author::ToolDetail)
        ));
        assert!(!should_insert_chat_gap(
            &Author::ToolDetail,
            Some(&Author::Tool)
        ));
        assert!(!should_insert_chat_gap(
            &Author::ToolDetail,
            Some(&Author::ToolDetail)
        ));
        assert!(should_insert_chat_gap(
            &Author::ToolDetail,
            Some(&Author::Assistant)
        ));
        assert!(!should_insert_chat_gap(&Author::ToolDetail, None));
    }

    // ====================================================================
    // ViewState + draw_chrome snapshot tests.
    //
    // These render the non-input chrome (stream preview, message
    // separator, status separator, session status) into a TestBackend
    // buffer and assert on its textual contents. The point is to lock
    // down what each UI mode (idle / busy / streaming)
    // looks like end-to-end on the screen, without spinning up a runtime.
    // ====================================================================

    use ratatui::Terminal;
    use ratatui::backend::TestBackend;

    fn presentation_state_idle() -> PresentationState {
        PresentationState {
            stream_preview: None,
            busy: false,
            turn_activity: None,
            model_id: "gpt-5.5".to_string(),
            provider_name: "openai".to_string(),
            reasoning_effort: Some("medium".to_string()),
            session_id: SessionId::from_seed(770001).to_string(),
            lines_count: 3,
            session_tokens: None,
            status_layout: StatusLayout::Compact,
            hooks_summary: "none".to_string(),
            approval_mode: "normal".to_string(),
            background: None,
            goal_indicator: None,
            ask_indicator: None,
            worktree_compact: None,
            worktree_expanded: None,
        }
    }

    fn view_state_idle() -> ViewState {
        ViewState {
            presentation: presentation_state_idle(),
            command_suggestions: Vec::new(),
            busy_frame: 0,
        }
    }

    #[test]
    fn status_bar_shows_background_task_count() {
        let state = ViewState {
            presentation: PresentationState {
                status_layout: StatusLayout::Expanded,
                background: Some((1, 2)),
                ..presentation_state_idle()
            },
            ..view_state_idle()
        };
        let lines = render_chrome_lines(&state, 120, 8).join("\n");
        assert!(
            lines.contains("bg"),
            "status should show bg segment: {lines}"
        );
        assert!(
            lines.contains("1▸/2"),
            "status should show running/total: {lines}"
        );
    }

    #[test]
    fn status_bar_hides_background_segment_when_no_tasks() {
        let state = ViewState {
            presentation: PresentationState {
                status_layout: StatusLayout::Expanded,
                background: None,
                ..presentation_state_idle()
            },
            ..view_state_idle()
        };
        let lines = render_chrome_lines(&state, 120, 8).join("\n");
        assert!(
            !lines.contains(""),
            "no background segment expected when there are no tasks: {lines}"
        );
    }

    /// Render `draw_chrome` into a TestBackend and collect the buffer
    /// rows as plain strings (style information dropped). Width and
    /// height are minimums; if the chrome layout would need more space
    /// it will be silently clipped, which is fine for substring asserts.
    fn render_chrome_lines(state: &ViewState, width: u16, height: u16) -> Vec<String> {
        render_chrome_lines_with_input_height(state, width, height, 1)
    }

    fn render_chrome_lines_with_input_height(
        state: &ViewState,
        width: u16,
        height: u16,
        input_height: u16,
    ) -> Vec<String> {
        let backend = TestBackend::new(width, height);
        let mut terminal = Terminal::new(backend).expect("terminal");
        terminal
            .draw(|f| {
                let _input_rect = draw_chrome(f, f.area(), input_height, state);
            })
            .expect("draw");
        let buffer = terminal.backend().buffer();
        (0..buffer.area.height)
            .map(|y| {
                let mut row = String::with_capacity(buffer.area.width as usize);
                for x in 0..buffer.area.width {
                    let cell = &buffer[(x, y)];
                    row.push_str(cell.symbol());
                }
                row.trim_end().to_string()
            })
            .collect()
    }

    fn render_app_lines(app: &mut App, width: u16, height: u16) -> Vec<String> {
        let backend = TestBackend::new(width, height);
        let mut terminal = Terminal::new(backend).expect("terminal");
        terminal.draw(|f| draw(f, app)).expect("draw");
        let buffer = terminal.backend().buffer();
        (0..buffer.area.height)
            .map(|y| {
                let mut row = String::with_capacity(buffer.area.width as usize);
                for x in 0..buffer.area.width {
                    let cell = &buffer[(x, y)];
                    row.push_str(cell.symbol());
                }
                row.trim_end().to_string()
            })
            .collect()
    }

    fn setup_overlay_text(app: &App) -> Vec<String> {
        setup_overlay_content(app)
            .0
            .iter()
            .map(|line| spans_plain_text(&line.spans))
            .collect()
    }

    struct TestApp {
        app: App,
        _workspace: tempfile::TempDir,
        _sessions: tempfile::TempDir,
    }

    async fn app_with_llmsim() -> TestApp {
        let workspace = tempfile::tempdir().expect("workspace tempdir");
        let sessions = tempfile::tempdir().expect("sessions tempdir");
        let settings = std::sync::Arc::new(crate::settings::SettingsStore::open(
            sessions.path().join("settings.toml"),
        ));
        let runtime = crate::runtime::build_with_options(
            workspace.path().to_path_buf(),
            crate::runtime::ProviderChoice::Sim,
            None,
            sessions.path().to_path_buf(),
            settings,
            crate::runtime::BuildOptions {
                client_commands: true,
                ..crate::runtime::BuildOptions::default()
            },
        )
        .await
        .expect("build llmsim runtime");
        let mut app = App::new(runtime, vec![]);
        // Never let unit tests hit real provider models APIs.
        app.model_discovery_enabled = false;
        TestApp {
            app,
            _workspace: workspace,
            _sessions: sessions,
        }
    }

    /// Seed a synthetic everruns completion signal onto the app's wake channel,
    /// standing in for the platform-store `send_message` a finished
    /// `spawn_background` run makes. Returns the sender so the caller can push
    /// more (or drop it to close the channel).
    fn seed_background_wake(app: &mut App, message: &str) -> mpsc::UnboundedSender<String> {
        let (tx, rx) = mpsc::unbounded_channel::<String>();
        app.background_wake = rx;
        tx.send(message.to_string()).expect("seed wake");
        tx
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn proactive_wake_starts_turn_when_background_task_finishes() {
        let mut test = app_with_llmsim().await;
        let app = &mut test.app;
        // The setup/onboarding overlay opens when no provider credentials are
        // configured (the case in CI, which has no API keys). Wake is correctly
        // suppressed while it's open, so clear it to exercise the idle path.
        app.setup = None;

        // Idle with no signal: nothing to wake for.
        assert!(!app.maybe_wake_from_background_channel());

        // A completion signal arrives on the wake channel ⇒ a turn is started.
        let _tx = seed_background_wake(app, "Background run completed.\n- run_id: bg_1");
        assert!(
            app.maybe_wake_from_background_channel(),
            "a finished background task should wake the agent"
        );
        assert!(app.busy, "proactive wake must start a turn");
        assert!(
            app.lines.iter().any(|l| l.text.contains("waking")),
            "a notice explaining the auto-wake should be shown"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn proactive_wake_suppressed_during_setup_overlay() {
        let mut test = app_with_llmsim().await;
        let app = &mut test.app;
        // With the setup overlay open, a finished task must NOT auto-start a turn
        // and must NOT consume the signal (so it can still wake once closed).
        let _tx = seed_background_wake(app, "Background run completed.\n- run_id: bg_1");
        app.setup = Some(SetupStep::Provider { selected: 0 });
        assert!(
            !app.maybe_wake_from_background_channel(),
            "no wake during setup"
        );
        assert!(!app.busy);
        app.setup = None;
        assert!(
            app.maybe_wake_from_background_channel(),
            "wake should fire once the overlay closes — the signal wasn't consumed"
        );
        assert!(app.busy);
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn proactive_wake_disabled_by_setting_does_not_start_turn() {
        let mut test = app_with_llmsim().await;
        let app = &mut test.app;
        app.setup = None;
        app.settings
            .set_proactive_wake(false)
            .expect("disable wake");

        let _tx = seed_background_wake(app, "Background run completed.\n- run_id: bg_1");
        // Setting off: no turn, but the completion is still surfaced once.
        assert!(!app.maybe_wake_from_background_channel());
        assert!(!app.busy, "wake setting off must not start a turn");
        assert!(
            app.lines
                .iter()
                .any(|l| l.text.contains("background task finished")),
            "finished task should still be surfaced as a notice"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn background_panel_toggle_scroll_and_close() {
        let mut test = app_with_llmsim().await;
        let app = &mut test.app;
        app.setup = None;
        assert!(app.background_panel.is_none());

        app.toggle_background_panel();
        assert_eq!(app.background_panel, Some(0));

        // With no tasks the body is a single line, so Down can't scroll past it.
        app.handle_background_panel_key(KeyEvent::new(KeyCode::Down, KeyModifiers::empty()));
        assert_eq!(app.background_panel, Some(0));

        app.handle_background_panel_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::empty()));
        assert!(app.background_panel.is_none());
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn ctrl_b_clears_armed_ctrl_c_exit() {
        let mut test = app_with_llmsim().await;
        let app = &mut test.app;
        app.setup = None;
        app.handle_ctrl_c(); // first Ctrl+C arms the pending exit
        assert!(app.ctrl_c_pending_exit());

        app.handle_key(KeyEvent::new(KeyCode::Char('b'), KeyModifiers::CONTROL))
            .await;
        assert!(
            !app.ctrl_c_pending_exit(),
            "Ctrl+B must disarm the pending Ctrl+C exit"
        );
        assert_eq!(app.background_panel, Some(0));
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn background_panel_not_opened_over_setup_overlay() {
        let mut test = app_with_llmsim().await;
        let app = &mut test.app;
        app.setup = Some(SetupStep::Provider { selected: 0 });
        app.toggle_background_panel();
        assert!(
            app.background_panel.is_none(),
            "panel must not stack on top of the setup overlay"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn background_panel_renders_everruns_session_task_rows() {
        let mut test = app_with_llmsim().await;
        let app = &mut test.app;
        app.setup = None;
        app.task_registry
            .create(CreateSessionTask {
                session_id: app.session.session_id(),
                id: Some("task_panel".to_string()),
                kind: TASK_KIND_BACKGROUND_TOOL.to_string(),
                display_name: "write marker".to_string(),
                spec: serde_json::json!({ "tool": "bash", "command": "echo hi" }),
                state: SessionTaskState::Running,
                links: Default::default(),
                wake_policy: Default::default(),
            })
            .await
            .expect("create session task");
        app.refresh_session_tasks().await;
        app.background_panel = Some(0);

        assert_eq!(app.presentation_state().background, Some((1, 1)));
        let lines = render_app_lines(app, 120, 20).join("\n");
        assert!(lines.contains("Background tasks"), "panel header: {lines}");
        assert!(
            lines.contains("background task(s), 1 active"),
            "panel should summarize session tasks: {lines}"
        );
        assert!(
            lines.contains("[task_panel] background_tool running: write marker"),
            "panel should list the session task row: {lines}"
        );
    }

    #[test]
    fn background_panel_lines_header_and_scroll() {
        let body = "row-a\nrow-b\nrow-c\nrow-d";
        let lines = render::background_panel_lines(body, 1, 3);
        assert!(lines[0].contains("Background tasks"));
        // height 3 ⇒ 1 header + 2 body rows, starting at offset 1.
        assert_eq!(lines.len(), 3);
        assert_eq!(lines[1], "row-b");
        assert_eq!(lines[2], "row-c");
        // A zero-height rect yields no lines (not even the header).
        assert!(render::background_panel_lines(body, 0, 0).is_empty());
    }

    impl App {
        /// Test-only: dispatch a slash command and pump any `UiCommand`s it
        /// emits, mirroring what the event loop does between frames. Needed
        /// because terminal-side commands now take effect asynchronously via
        /// the host UI channel rather than synchronously inside
        /// `handle_command`.
        async fn dispatch_command_for_test(&mut self, cmd: &str) {
            self.handle_command(cmd).await;
            self.pump_ui_commands_for_test();
        }

        fn pump_ui_commands_for_test(&mut self) {
            while let Ok(command) = self.ui_rx.try_recv() {
                self.apply_ui_command(command);
            }
        }

        /// Drain turn events the way [`App::run_loop_iteration`] does until
        /// the background turn finishes or the deadline passes.
        async fn pump_turn_until_idle_for_test(&mut self) {
            use std::time::Duration;

            let deadline = tokio::time::Instant::now() + Duration::from_secs(15);
            while self.busy {
                if tokio::time::Instant::now() >= deadline {
                    panic!(
                        "turn did not complete within 15s: busy={} lines={:?}",
                        self.busy, self.lines
                    );
                }
                if let Some(rx) = self.rx.as_mut() {
                    match rx.try_recv() {
                        Ok(TurnEvent::Lines(lines)) => self.lines.extend(lines),
                        Ok(TurnEvent::Activity(activity)) => {
                            if !activity.fallback || self.turn_activity.is_none() {
                                self.turn_activity = Some(activity.text);
                            }
                        }
                        Ok(TurnEvent::Stream(preview)) => self.stream_preview = preview,
                        Ok(TurnEvent::Tokens(tokens)) => {
                            self.session_tokens =
                                Some(self.session_tokens.unwrap_or(0).saturating_add(tokens));
                        }
                        Ok(TurnEvent::Done) => {
                            self.finish_busy();
                        }
                        Ok(TurnEvent::Failed(err)) => {
                            self.finish_busy();
                            self.push_system(format!("turn failed: {err}"));
                        }
                        Err(mpsc::error::TryRecvError::Empty) => {}
                        Err(mpsc::error::TryRecvError::Disconnected) => {
                            self.finish_busy();
                        }
                    }
                }
                if self.busy {
                    tokio::time::sleep(Duration::from_millis(20)).await;
                }
            }
        }

        /// Mirror [`App::run`]'s startup replay without standing up a terminal.
        async fn replay_transcript_for_test(&mut self) {
            self.emit_replayed_transcript().await;
        }
    }

    async fn llmsim_settings(
        sessions: &tempfile::TempDir,
    ) -> std::sync::Arc<crate::settings::SettingsStore> {
        let settings_path = sessions.path().join("settings.toml");
        std::fs::write(settings_path, "provider = \"llmsim\"\n").expect("write settings");
        std::sync::Arc::new(crate::settings::SettingsStore::open(
            sessions.path().join("settings.toml"),
        ))
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn enter_submit_completes_llmsim_turn_in_transcript() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = None;
        app.lines.clear();

        for ch in "hello turn".chars() {
            app.handle_key(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::empty()))
                .await;
        }
        app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::empty()))
            .await;

        assert!(app.busy, "submit should start a background turn");
        app.pump_turn_until_idle_for_test().await;

        assert!(
            app.lines
                .iter()
                .any(|line| matches!(line.author, Author::User) && line.text == "hello turn"),
            "user prompt should land in the transcript: {:?}",
            app.lines
        );
        assert!(
            app.lines.iter().any(|line| {
                matches!(line.author, Author::Assistant) && line.text.contains("offline mode")
            }),
            "assistant reply should finalize into the transcript: {:?}",
            app.lines
        );
        assert!(!app.busy);
        assert!(app.stream_preview.is_none());
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn bang_shell_input_runs_shell_from_workspace_without_model_turn() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = None;
        app.lines.clear();
        app.set_input_text(
            "!shell printf shell-output > shell-marker.txt && cat shell-marker.txt".into(),
        );

        app.submit_input().await;
        app.pump_ui_commands_for_test();

        assert!(
            app.busy,
            "!shell should run as a bounded background command"
        );
        app.pump_turn_until_idle_for_test().await;

        let marker = app.startup.workspace_root.join("shell-marker.txt");
        assert_eq!(
            std::fs::read_to_string(marker).expect("shell marker"),
            "shell-output"
        );
        assert!(
            app.lines.iter().any(|line| {
                matches!(line.author, Author::User)
                    && line
                        .text
                        .starts_with("!shell printf shell-output > shell-marker.txt")
            }),
            "the submitted shell command should be echoed in the transcript: {:?}",
            app.lines
        );
        assert!(
            app.lines
                .iter()
                .any(|line| matches!(line.author, Author::ToolDetail)
                    && line.text.contains("shell-output")),
            "shell stdout should render in the transcript: {:?}",
            app.lines
        );
        assert!(
            !app.lines
                .iter()
                .any(|line| matches!(line.author, Author::Assistant)),
            "!shell should not start a model turn: {:?}",
            app.lines
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn bang_input_runs_shell_without_model_turn() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = None;
        app.lines.clear();
        app.set_input_text("!printf bare-output".into());

        app.submit_input().await;
        app.pump_ui_commands_for_test();

        assert!(app.busy, "! should run as a bounded background command");
        app.pump_turn_until_idle_for_test().await;

        assert!(
            app.lines
                .iter()
                .any(|line| matches!(line.author, Author::ToolDetail)
                    && line.text.contains("bare-output")),
            "shell stdout should render in the transcript: {:?}",
            app.lines
        );
        assert!(
            !app.lines
                .iter()
                .any(|line| matches!(line.author, Author::Assistant)),
            "! should not start a model turn: {:?}",
            app.lines
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn resume_replays_prior_turn_into_transcript() {
        let workspace = tempfile::tempdir().expect("workspace tempdir");
        let sessions = tempfile::tempdir().expect("sessions tempdir");
        let settings = llmsim_settings(&sessions).await;

        let first = crate::runtime::build_with_options(
            workspace.path().to_path_buf(),
            crate::runtime::ProviderChoice::Sim,
            None,
            sessions.path().to_path_buf(),
            settings.clone(),
            crate::runtime::BuildOptions {
                client_commands: true,
                ..crate::runtime::BuildOptions::default()
            },
        )
        .await
        .expect("build first runtime");
        let session_id = first.handles.session_id;
        let prompt = "prior turn";
        let input = first.model.input_message(prompt.to_string());
        first
            .handles
            .runtime
            .run_turn(session_id, input)
            .await
            .expect("first turn");
        drop(first);

        let mut resumed = None;
        for _ in 0..20 {
            match crate::runtime::build_with_options(
                workspace.path().to_path_buf(),
                crate::runtime::ProviderChoice::Sim,
                Some(session_id),
                sessions.path().to_path_buf(),
                settings.clone(),
                crate::runtime::BuildOptions {
                    client_commands: true,
                    ..crate::runtime::BuildOptions::default()
                },
            )
            .await
            {
                Ok(runtime) => {
                    resumed = Some(runtime);
                    break;
                }
                Err(err) if err.to_string().contains("another yolop process") => {
                    tokio::time::sleep(Duration::from_millis(25)).await;
                }
                Err(err) => panic!("build resumed runtime: {err}"),
            }
        }
        let resumed = resumed.expect("build resumed runtime after releasing first log lock");
        assert!(
            resumed.startup.replayed_events > 0,
            "resume should report replayed events"
        );

        let mut app = App::new(resumed, vec![]);
        app.setup = None;
        app.lines.clear();
        app.replay_transcript_for_test().await;

        assert!(
            app.lines
                .iter()
                .any(|line| matches!(line.author, Author::User) && line.text == prompt),
            "replayed transcript should include the prior user prompt: {:?}",
            app.lines
        );
        assert!(
            app.lines.iter().any(|line| {
                matches!(line.author, Author::Assistant) && line.text.contains("offline mode")
            }),
            "replayed transcript should include the prior assistant reply: {:?}",
            app.lines
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn startup_banner_names_ctrl_c_and_ctrl_d_as_exit_keys() {
        let fixture = app_with_llmsim().await;

        assert!(
            fixture
                .app
                .lines
                .iter()
                .any(|line| line.text.contains("Ctrl+V to paste an image")),
            "startup banner should mention image paste: {:?}",
            fixture.app.lines
        );
        assert!(
            fixture
                .app
                .lines
                .iter()
                .any(|line| line.text.contains("press Ctrl-C twice (or Ctrl-D) to exit")),
            "startup banner should name Ctrl-C/Ctrl-D exits: {:?}",
            fixture.app.lines
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn large_paste_attaches_placeholder_and_expands_on_submit() {
        use crate::paste_attachment::LARGE_PASTE_CHAR_THRESHOLD;

        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = None;
        app.lines.clear();

        let payload = format!("paste-marker-{}", "x".repeat(LARGE_PASTE_CHAR_THRESHOLD));
        app.handle_paste(payload.clone());
        let placeholder = app.input_text();
        assert!(
            placeholder.contains("[Pasted Content"),
            "large paste should insert a placeholder: {placeholder:?}"
        );
        assert_eq!(app.pending_pastes.len(), 1);

        app.submit_input().await;

        assert!(
            app.busy,
            "submit should start a turn with the expanded paste"
        );
        assert!(
            app.lines.iter().any(|line| {
                matches!(line.author, Author::User) && line.text.contains("[Pasted Content")
            }),
            "transcript should show the compact placeholder: {:?}",
            app.lines
        );
        assert!(
            !app.lines.iter().any(|line| {
                matches!(line.author, Author::User) && line.text.contains("paste-marker-")
            }),
            "transcript should not inline the full pasted payload: {:?}",
            app.lines
        );
        assert!(app.pending_pastes.is_empty());
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn startup_banner_is_kept_out_of_inline_viewport() {
        let mut fixture = app_with_llmsim().await;
        let rows = render_app_lines(&mut fixture.app, 96, COMPOSER_VIEWPORT_HEIGHT);

        assert!(
            !rows.iter().any(|row| row.contains("workspace:")),
            "startup transcript should render through scrollback, not the inline viewport: {rows:?}"
        );
        assert!(
            !rows.iter().any(|row| row.contains("type /help")),
            "startup transcript should not be mirrored above the composer: {rows:?}"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn inline_viewport_shows_recent_transcript_lines() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = None;
        app.lines.clear();
        app.push_user("What changed last time?".into());
        app.lines.push(ChatLine {
            author: Author::Assistant,
            text: "The renderer now mirrors resumed history.".into(),
        });

        let rows = render_app_lines(app, 96, COMPOSER_VIEWPORT_HEIGHT);

        assert!(
            rows.iter()
                .any(|row| row.contains("What changed last time?")),
            "inline viewport should show recent user transcript: {rows:?}"
        );
        assert!(
            rows.iter()
                .any(|row| row.contains("mirrors resumed history")),
            "inline viewport should show recent assistant transcript: {rows:?}"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn inline_viewport_bottom_aligns_recent_transcript_tail() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = None;
        app.lines.clear();
        app.lines.push(ChatLine {
            author: Author::Assistant,
            text: "Latest answer tail".into(),
        });

        let rows = render_app_lines(app, 96, COMPOSER_VIEWPORT_HEIGHT);
        let answer_row = rows
            .iter()
            .position(|row| row.contains("Latest answer tail"))
            .expect("recent answer rendered");
        let separator_row = rows
            .iter()
            .position(|row| row.contains("Enter to send"))
            .expect("message separator rendered");

        assert_eq!(
            answer_row + 1,
            separator_row,
            "recent answer should sit above the input chrome without a large blank gap: {rows:?}"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn inline_viewport_does_not_mirror_flushed_transcript_lines() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = None;
        app.lines.clear();
        app.push_user("Do something".into());
        app.lines.push(ChatLine {
            author: Author::Assistant,
            text: "Done.".into(),
        });
        app.printed_lines = app.lines.len();

        let rows = render_app_lines(app, 96, COMPOSER_VIEWPORT_HEIGHT);

        assert!(
            !rows.iter().any(|row| row.contains("Do something")),
            "flushed user transcript should stay in scrollback only: {rows:?}"
        );
        assert!(
            !rows.iter().any(|row| row.contains("Done.")),
            "flushed assistant transcript should stay in scrollback only: {rows:?}"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn inline_viewport_uses_recent_transcript_tail() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = None;
        app.lines.clear();
        for index in 0..20 {
            app.push_user(format!("old line {index}"));
        }
        app.lines.push(ChatLine {
            author: Author::Assistant,
            text: "newest resumed line".into(),
        });

        let rows = render_app_lines(app, 96, COMPOSER_VIEWPORT_HEIGHT);

        assert!(
            !rows.iter().any(|row| row.contains("old line 0")),
            "inline viewport should drop old transcript head: {rows:?}"
        );
        assert!(
            rows.iter().any(|row| row.contains("newest resumed line")),
            "inline viewport should keep transcript tail: {rows:?}"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn inline_viewport_bounds_large_recent_entries() {
        let bounded = bounded_recent_chat_line(&ChatLine {
            author: Author::Assistant,
            text: format!(
                "{} visible-tail",
                "hidden-head ".repeat(RECENT_TRANSCRIPT_MAX_TEXT_BYTES)
            ),
        });

        assert!(
            bounded.text.len() <= RECENT_TRANSCRIPT_MAX_TEXT_BYTES,
            "bounded text should fit the inline render budget"
        );
        assert!(bounded.text.starts_with(''), "bounded text: {bounded:?}");
        assert!(
            bounded.text.ends_with("visible-tail"),
            "recent transcript should keep the tail: {bounded:?}"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn inline_viewport_stops_rendering_after_visible_tail_is_full() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = None;
        app.lines.clear();
        app.lines.push(ChatLine {
            author: Author::Assistant,
            text: "older invisible line".repeat(200),
        });
        for index in 0..20 {
            app.push_user(format!("new line {index}"));
        }

        let rows = render_app_lines(app, 96, COMPOSER_VIEWPORT_HEIGHT);

        assert!(
            !rows.iter().any(|row| row.contains("older invisible")),
            "inline viewport should avoid rendering invisible older entries: {rows:?}"
        );
        assert!(
            rows.iter().any(|row| row.contains("new line 19")),
            "inline viewport should keep newest entries: {rows:?}"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn resumed_session_renders_replayed_history_in_inline_viewport() {
        let workspace = tempfile::tempdir().expect("workspace tempdir");
        let sessions = tempfile::tempdir().expect("sessions tempdir");
        let session_id = SessionId::from_seed(321987);
        let session_dir = crate::session_log::session_dir_path(sessions.path(), session_id);
        std::fs::create_dir_all(&session_dir).expect("session dir");
        let log_path = crate::session_log::session_log_path(&session_dir);
        let events = [
            RuntimeEvent::new(
                session_id,
                EventContext::empty(),
                InputMessageData::new(Message::user("previous question")),
            ),
            RuntimeEvent::new(
                session_id,
                EventContext::empty(),
                OutputMessageCompletedData::new(Message::assistant("previous answer")),
            ),
        ];
        let jsonl = events
            .iter()
            .map(|event| serde_json::to_string(event).expect("serialize event"))
            .collect::<Vec<_>>()
            .join("\n");
        std::fs::write(&log_path, format!("{jsonl}\n")).expect("session log");

        let settings = std::sync::Arc::new(crate::settings::SettingsStore::open(
            sessions.path().join("settings.toml"),
        ));
        let runtime = crate::runtime::build_with_options(
            workspace.path().to_path_buf(),
            crate::runtime::ProviderChoice::Sim,
            Some(session_id),
            sessions.path().to_path_buf(),
            settings,
            crate::runtime::BuildOptions {
                client_commands: true,
                ..crate::runtime::BuildOptions::default()
            },
        )
        .await
        .expect("build resumed runtime");
        let mut app = App::new(runtime, vec![]);
        app.setup = None;

        app.emit_replayed_transcript().await;
        let rows = render_app_lines(&mut app, 96, COMPOSER_VIEWPORT_HEIGHT);

        assert!(
            rows.iter().any(|row| row.contains("previous question")),
            "inline viewport should show replayed user message: {rows:?}"
        );
        assert!(
            rows.iter().any(|row| row.contains("previous answer")),
            "inline viewport should show replayed assistant message: {rows:?}"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn help_command_lists_commands_shortcuts_and_exit_keys() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.lines.clear();

        app.dispatch_command_for_test("help").await;

        let help_lines: Vec<_> = app.lines.iter().map(|line| line.text.as_str()).collect();
        assert!(
            help_lines.contains(&"commands:"),
            "help should introduce the command list: {help_lines:?}"
        );
        assert!(
            help_lines.iter().any(|line| line.starts_with("  /help —")),
            "help should list /help with a description: {help_lines:?}"
        );
        assert!(
            help_lines.contains(&"shortcuts:"),
            "help should introduce keyboard shortcuts: {help_lines:?}"
        );
        assert!(
            help_lines
                .iter()
                .any(|line| line.contains("exit: Ctrl-C twice / Ctrl-D")),
            "help output should name Ctrl-C/Ctrl-D exits: {help_lines:?}"
        );
        assert!(
            help_lines.iter().any(|line| line.contains("cancel turn")),
            "help output should label Esc as cancel turn: {help_lines:?}"
        );
        assert!(
            help_lines.iter().any(|line| line.contains("/exit")),
            "help output should mention /exit alias for /quit: {help_lines:?}"
        );
        assert!(
            help_lines
                .iter()
                .any(|line| line.contains("Ctrl+V paste image/text")),
            "help output should mention image paste: {help_lines:?}"
        );
        assert!(
            help_lines.iter().any(|line| line.contains("/yolop skill")),
            "help output should point at the yolop skill: {help_lines:?}"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn first_ctrl_c_prompts_for_second_press_to_exit() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = None;

        app.handle_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL))
            .await;

        assert!(!app.should_quit, "first Ctrl-C should not quit immediately");
        assert!(app.ctrl_c_pending_exit(), "first Ctrl-C should arm exit");
        assert!(
            app.lines
                .iter()
                .any(|line| { line.text.contains("Press Ctrl+C again to exit") }),
            "first Ctrl-C should invite a second press: {:?}",
            app.lines
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn second_ctrl_c_exits_after_prompt() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = None;
        let ctrl_c = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL);

        app.handle_key(ctrl_c).await;
        app.handle_key(ctrl_c).await;

        assert!(app.should_quit, "second Ctrl-C should quit");
        assert!(app.ctrl_c_exit, "second Ctrl-C should count as Ctrl-C exit");
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn ctrl_c_clears_nonempty_input_without_exiting() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = None;
        app.set_input_text("draft prompt".into());

        app.handle_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL))
            .await;

        assert!(!app.should_quit, "Ctrl-C with draft input should not quit");
        assert!(
            app.input_text().trim().is_empty(),
            "Ctrl-C should clear draft input"
        );
        assert!(
            !app.ctrl_c_pending_exit(),
            "clearing input should not arm exit"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn typing_within_ctrl_c_grace_keeps_exit_prompt_armed() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = None;

        app.handle_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL))
            .await;
        app.handle_key(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::empty()))
            .await;

        assert!(
            app.ctrl_c_pending_exit(),
            "typing during the grace window should not disarm exit"
        );
        assert!(!app.should_quit);
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn typing_after_ctrl_c_grace_disarms_exit_prompt() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = None;

        app.handle_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL))
            .await;
        tokio::time::sleep(CTRL_C_EXIT_ARM_GRACE + Duration::from_millis(50)).await;
        app.handle_key(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::empty()))
            .await;

        assert!(
            !app.ctrl_c_pending_exit(),
            "typing after the grace window should disarm the pending exit prompt"
        );
        assert!(!app.should_quit);
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn second_ctrl_c_within_grace_exits_after_prompt() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = None;
        let ctrl_c = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL);

        app.handle_key(ctrl_c).await;
        tokio::time::sleep(Duration::from_secs(2)).await;
        app.handle_key(ctrl_c).await;

        assert!(app.should_quit, "second Ctrl-C within grace should quit");
        assert!(app.ctrl_c_exit, "second Ctrl-C should count as Ctrl-C exit");
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn first_esc_while_busy_prompts_for_second_press_to_cancel() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        let (cancel_tx, mut cancel_rx) = oneshot::channel::<()>();
        app.setup = None;
        app.busy = true;
        app.turn_cancel = Some(cancel_tx);

        app.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::empty()))
            .await;

        assert!(!app.should_quit, "first Esc should not quit");
        assert!(app.busy, "first Esc should keep the turn running");
        assert!(
            app.esc_pending_cancel,
            "first Esc should arm turn cancellation"
        );
        assert!(
            cancel_rx.try_recv().is_err(),
            "first Esc should not send cancellation yet"
        );
        assert!(
            app.lines
                .iter()
                .any(|line| line.text.contains("Press Esc again to cancel current turn")),
            "first Esc should invite a second press: {:?}",
            app.lines
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn second_esc_while_busy_sends_turn_cancel() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        let (cancel_tx, cancel_rx) = oneshot::channel::<()>();
        app.setup = None;
        app.busy = true;
        app.turn_cancel = Some(cancel_tx);

        app.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::empty()))
            .await;
        app.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::empty()))
            .await;

        assert!(
            !app.esc_pending_cancel,
            "second Esc should disarm cancellation prompt"
        );
        assert!(
            app.turn_cancel.is_none(),
            "second Esc should consume the active cancel sender"
        );
        assert!(
            cancel_rx.await.is_ok(),
            "second Esc should notify the turn worker"
        );
        assert_eq!(app.turn_activity.as_deref(), Some("cancelling"));
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn second_esc_while_goal_active_pauses_goal_continuation() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        let session_id = app.session.session_id();
        let (cancel_tx, cancel_rx) = oneshot::channel::<()>();
        app.setup = None;
        app.goal_store
            .set_active(session_id, "ship the change".into())
            .expect("set active goal");
        assert!(
            app.goal_store.take_pending_turn(session_id),
            "test starts from an in-progress goal turn"
        );
        app.busy = true;
        app.turn_cancel = Some(cancel_tx);

        app.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::empty()))
            .await;
        app.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::empty()))
            .await;

        assert!(cancel_rx.await.is_ok(), "second Esc should cancel the turn");
        assert!(
            app.goal_store.is_paused(session_id),
            "cancelled goal turn should pause auto-continuation"
        );
        assert!(
            !app.goal_store.take_pending_turn(session_id),
            "paused goal should not keep a pending continuation"
        );
        assert!(
            app.lines
                .iter()
                .any(|line| line.text.contains("goal paused")),
            "cancellation should explain how to resume the goal: {:?}",
            app.lines
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn second_esc_while_busy_clears_stream_preview_immediately() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        let (cancel_tx, _cancel_rx) = oneshot::channel::<()>();
        app.setup = None;
        app.busy = true;
        app.turn_cancel = Some(cancel_tx);
        app.stream_preview = Some(StreamPreview {
            kind: StreamKind::Assistant,
            text: "partial answer".into(),
        });

        app.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::empty()))
            .await;
        app.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::empty()))
            .await;

        assert!(
            app.stream_preview.is_none(),
            "cancellation confirmation should clear stale streaming text immediately"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn esc_after_cancel_requested_does_not_reprompt() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        let (cancel_tx, _cancel_rx) = oneshot::channel::<()>();
        app.setup = None;
        app.busy = true;
        app.turn_cancel = Some(cancel_tx);

        app.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::empty()))
            .await;
        app.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::empty()))
            .await;
        let prompt_count = app
            .lines
            .iter()
            .filter(|line| line.text.contains("Press Esc again to cancel current turn"))
            .count();

        app.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::empty()))
            .await;

        assert!(
            !app.esc_pending_cancel,
            "Esc after cancellation was requested should not re-arm"
        );
        assert_eq!(
            app.lines
                .iter()
                .filter(|line| line.text.contains("Press Esc again to cancel current turn"))
                .count(),
            prompt_count,
            "Esc after cancellation was requested should not add another prompt"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn non_esc_while_busy_disarms_cancel_prompt() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        let (cancel_tx, mut cancel_rx) = oneshot::channel::<()>();
        app.setup = None;
        app.busy = true;
        app.turn_cancel = Some(cancel_tx);

        app.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::empty()))
            .await;
        app.handle_key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::empty()))
            .await;

        assert!(
            !app.esc_pending_cancel,
            "non-Esc busy input should disarm cancellation prompt"
        );
        assert!(
            cancel_rx.try_recv().is_err(),
            "non-Esc busy input should not cancel the turn"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn cwd_command_prints_workspace_root() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.lines.clear();

        app.dispatch_command_for_test("cwd").await;

        let root = app.startup.workspace_root.display().to_string();
        assert!(
            app.lines
                .iter()
                .any(|line| line.text.contains("workspace root:") && line.text.contains(&root)),
            "cwd should print the workspace root: {:?}",
            app.lines
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn status_command_switches_between_compact_and_expanded_layouts() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.lines.clear();

        assert_eq!(app.status_layout, StatusLayout::Compact);
        app.dispatch_command_for_test("status expanded").await;
        assert_eq!(app.status_layout, StatusLayout::Expanded);

        app.dispatch_command_for_test("status compact").await;
        assert_eq!(app.status_layout, StatusLayout::Compact);

        app.dispatch_command_for_test("status nonsense").await;
        assert_eq!(app.status_layout, StatusLayout::Compact);
        assert!(
            app.lines
                .iter()
                .any(|line| line.text.contains("usage: /status")),
            "invalid status layout should render usage: {:?}",
            app.lines
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn clicking_status_rows_toggles_layout() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = None;

        let area = Rect {
            x: 0,
            y: 10,
            width: 120,
            height: 24,
        };

        assert_eq!(app.status_layout, StatusLayout::Compact);
        assert!(app.handle_mouse(
            MouseEvent {
                kind: MouseEventKind::Down(MouseButton::Left),
                column: 3,
                row: 33,
                modifiers: KeyModifiers::empty(),
            },
            area,
        ));
        assert_eq!(app.status_layout, StatusLayout::Expanded);

        assert!(app.handle_mouse(
            MouseEvent {
                kind: MouseEventKind::Down(MouseButton::Left),
                column: 3,
                row: 31,
                modifiers: KeyModifiers::empty(),
            },
            area,
        ));
        assert_eq!(app.status_layout, StatusLayout::Compact);
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn tools_command_lists_available_tools() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.lines.clear();

        app.dispatch_command_for_test("tools").await;

        // The llmsim runtime registers the standard coding toolset, so the
        // listing must be non-empty and name a known tool.
        assert!(
            app.lines
                .iter()
                .any(|line| line.text.starts_with("tools:") && line.text.contains("bash")),
            "tools should list available tools: {:?}",
            app.lines
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn clear_command_wipes_transcript_and_re_emits_banner() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.push_system("sentinel line that must be cleared".into());
        // Advance the print cursor so the reset assertion below actually
        // guards the behavior rather than passing on the initial value.
        app.printed_lines = app.lines.len();
        assert_ne!(app.printed_lines, 0);

        app.dispatch_command_for_test("clear").await;

        assert!(
            !app.lines
                .iter()
                .any(|line| line.text.contains("sentinel line")),
            "clear should wipe prior transcript lines: {:?}",
            app.lines
        );
        assert_eq!(app.printed_lines, 0, "clear should reset the print cursor");
        // The banner is re-emitted so the cleared screen still shows context.
        assert!(
            app.lines
                .iter()
                .any(|line| line.text.contains("type /help")),
            "clear should re-emit the startup banner: {:?}",
            app.lines
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn quit_command_and_exit_alias_request_shutdown() {
        for command in ["quit", "exit"] {
            let mut fixture = app_with_llmsim().await;
            let app = &mut fixture.app;
            assert!(!app.should_quit);

            app.dispatch_command_for_test(command).await;

            assert!(
                app.should_quit,
                "/{command} should request shutdown via the UI channel"
            );
        }
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn app_slash_input_renders_command_suggestions_end_to_end() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = None;

        app.handle_key(KeyEvent::new(KeyCode::Char('/'), KeyModifiers::empty()))
            .await;

        let state = app.view_state();
        assert!(
            state
                .command_suggestions
                .iter()
                .any(|suggestion| suggestion.completion == "/help"),
            "expected /help suggestion in view state: {:?}",
            state.command_suggestions
        );
        let rows = render_chrome_lines(&state, 80, 5);
        assert!(
            rows[0].contains("Tab /help"),
            "slash input should render command suggestions in chrome row: {:?}",
            rows
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn shift_enter_inserts_newline_without_submitting() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = None;

        for key in [
            KeyEvent::new(KeyCode::Char('a'), KeyModifiers::empty()),
            KeyEvent::new(KeyCode::Enter, KeyModifiers::SHIFT),
            KeyEvent::new(KeyCode::Char('b'), KeyModifiers::empty()),
            KeyEvent::new(KeyCode::Enter, KeyModifiers::SHIFT),
            KeyEvent::new(KeyCode::Char('c'), KeyModifiers::empty()),
        ] {
            app.handle_key(key).await;
        }

        assert_eq!(app.input_text(), "a\nb\nc");
        assert_eq!(app.input_height(80), 3);
        assert!(
            app.lines
                .iter()
                .all(|line| !matches!(line.author, Author::User)),
            "Shift-Enter should edit the composer, not submit: {:?}",
            app.lines
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn alt_shift_enter_submits_instead_of_inserting_newline() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = None;

        app.handle_key(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::empty()))
            .await;
        app.handle_key(KeyEvent::new(
            KeyCode::Enter,
            KeyModifiers::ALT | KeyModifiers::SHIFT,
        ))
        .await;

        assert_eq!(app.input_text(), "");
        assert!(
            app.lines
                .iter()
                .any(|line| matches!(line.author, Author::User) && line.text == "a"),
            "Alt-Shift-Enter should submit the composer: {:?}",
            app.lines
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn shifted_printable_chars_insert_literal_character() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = None;

        for key in [
            KeyEvent::new(KeyCode::Char('/'), KeyModifiers::SHIFT),
            KeyEvent::new(KeyCode::Char('a'), KeyModifiers::SHIFT),
            KeyEvent::new(KeyCode::Char('1'), KeyModifiers::SHIFT),
        ] {
            app.handle_key(key).await;
        }

        assert_eq!(app.input_text(), "?A!");
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn multiline_input_height_is_bounded() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;

        assert_eq!(app.input_height(80), 1);
        for expected in 2..=MAX_INPUT_HEIGHT {
            app.input.insert_newline();
            assert_eq!(app.input_height(80), expected);
        }
        app.input.insert_newline();
        assert_eq!(app.input_height(80), MAX_INPUT_HEIGHT);
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn wrapped_single_line_input_grows_height_with_narrow_width() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = None;

        for word in ["hello", "world", "again", "here"] {
            for ch in word.chars() {
                app.handle_key(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::empty()))
                    .await;
            }
            app.handle_key(KeyEvent::new(KeyCode::Char(' '), KeyModifiers::empty()))
                .await;
        }

        assert_eq!(
            app.input.lines().len(),
            1,
            "composer stays one logical line"
        );
        let input_width = 10;
        let measured = app.input_height(input_width) as usize;
        assert!(
            measured >= 2,
            "soft-wrapped composer should grow past one row (got {measured})"
        );

        let mut textarea = new_input_area(vec![app.input_text()]);
        let area = Rect {
            x: 0,
            y: 0,
            width: input_width,
            height: MAX_INPUT_HEIGHT,
        };
        let mut buf = Buffer::empty(area);
        Widget::render(&textarea, area, &mut buf);
        textarea.move_cursor(CursorMove::End);
        let expected = textarea.screen_cursor().row as usize + 1;
        assert_eq!(
            measured, expected,
            "composer height should match textarea wrap layout"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn wrapped_input_allocates_multiple_render_rows() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = None;
        app.set_input_text("alpha beta gamma delta epsilon zeta".into());

        let terminal_width: u16 = 16;
        let input_width = terminal_width.saturating_sub(2);
        let input_height = app.input_height(input_width);
        assert!(
            input_height >= 2,
            "narrow composer should reserve multiple input rows (got {input_height})"
        );

        let rows = render_app_lines(app, terminal_width, COMPOSER_VIEWPORT_HEIGHT);
        let input_rows: Vec<_> = rows
            .iter()
            .filter(|row| row.contains("alpha") || row.contains("beta") || row.contains("gamma"))
            .collect();
        assert!(
            input_rows.len() >= 2,
            "wrapped composer text should appear on multiple screen rows: {rows:?}"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn setup_command_starts_guided_wizard() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = None;
        app.lines.clear();

        app.handle_command("setup").await;

        let llmsim_index = PROVIDER_OPTIONS
            .iter()
            .position(|option| option.name == "llmsim")
            .expect("llmsim provider option");
        assert!(matches!(
            app.setup,
            Some(SetupStep::Provider { selected }) if selected == llmsim_index
        ));
        assert!(
            app.lines.is_empty(),
            "plain /setup should open the overlay without transcript chatter: {:?}",
            app.lines
        );
        let rendered = setup_overlay_text(app);
        assert!(rendered.iter().any(|line| line.contains("Set Up Yolop")));
        assert!(rendered.iter().any(|line| line.contains("OpenAI")));
        assert!(rendered.iter().any(|line| line.contains("Offline demo")));
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn setup_overlay_renders_full_provider_picker() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.lines.clear();
        app.setup = Some(SetupStep::Provider { selected: 0 });

        let rows = render_app_lines(app, 110, COMPOSER_VIEWPORT_HEIGHT);

        assert!(
            rows.iter().any(|line| line.contains("Set Up Yolop")),
            "setup title should be visible: {rows:?}"
        );
        assert!(
            rows.iter().any(|line| line.contains("OpenAI")),
            "provider choices should be visible: {rows:?}"
        );
        assert!(
            !rows.iter().any(|line| line.contains("recommended")),
            "setup should not recommend a specific provider: {rows:?}"
        );
        assert!(
            rows.iter().any(|line| line.contains("Offline demo mode")),
            "last provider choice should not be clipped: {rows:?}"
        );
        assert!(
            rows.iter().any(|line| line.contains("Esc cancel")),
            "footer should not be clipped: {rows:?}"
        );
    }

    // Holding the env lock across awaits is deliberate: the overlay reads
    // env vars throughout the test, so releasing early would let another
    // env-mutating test change them mid-assertion. The guard owner always
    // makes progress, so this cannot deadlock.
    #[allow(clippy::await_holding_lock)]
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn setup_provider_picker_enters_credential_panel() {
        // Serialize against other env-mutating tests; a present
        // OPENAI_API_KEY would make the provider "connected" and skip the
        // credential panel entirely.
        let _guard = crate::test_env::lock();
        unsafe {
            std::env::remove_var("OPENAI_API_KEY");
        }
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.lines.clear();
        app.setup = Some(SetupStep::Provider { selected: 0 });

        app.handle_setup_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::empty()))
            .await;

        assert!(matches!(
            app.setup,
            Some(SetupStep::Credential {
                ref provider,
                selected: 0,
                ..
            }) if provider == "openai"
        ));
        let rendered = setup_overlay_text(app);
        assert!(
            rendered
                .iter()
                .any(|line| line.contains("API Key for OpenAI"))
        );
        assert!(
            rendered
                .iter()
                .any(|line| line.contains("Use OPENAI_API_KEY from environment"))
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn setup_row_keeps_a_gap_when_label_overflows_column() {
        // "Use OPENAI_API_KEY from environment" overflows the 28-col label
        // column; the hint must not butt against it ("environmentnot detected").
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = Some(SetupStep::Credential {
            provider: "openai".to_string(),
            selected: 0,
            error: None,
        });

        let rendered = setup_overlay_text(app);
        let env_row = rendered
            .iter()
            .find(|line| line.contains("from environment"))
            .expect("credential panel should render the use-env row");
        assert!(
            env_row.contains("environment  "),
            "hint must stay separated from the overflowing label: {env_row:?}"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn setup_token_input_masks_secret_and_moves_to_model_picker() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.lines.clear();
        app.setup = Some(SetupStep::TokenInput {
            provider: "openai".to_string(),
            token: String::new(),
            error: None,
        });

        for ch in "test-token".chars() {
            app.handle_setup_key(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::empty()))
                .await;
        }
        let rendered = setup_overlay_text(app);
        assert!(
            !rendered.iter().any(|line| line.contains("test-token")),
            "raw token should never render: {rendered:?}"
        );
        assert!(
            rendered.iter().any(|line| line.contains("••••••••••")),
            "masked token should render: {rendered:?}"
        );
        app.handle_setup_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::empty()))
            .await;

        assert!(matches!(
            app.setup,
            Some(SetupStep::PickModel {
                ref provider,
                ..
            }) if provider == "openai"
        ));
        assert!(
            !app.lines
                .iter()
                .any(|line| line.text.starts_with("setup token stored for")),
            "wizard should hide internal setup command success output"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn setup_wizard_can_select_offline_provider() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.lines.clear();
        let llmsim_index = PROVIDER_OPTIONS
            .iter()
            .position(|option| option.name == "llmsim")
            .expect("llmsim provider option");
        app.setup = Some(SetupStep::Provider {
            selected: llmsim_index,
        });

        app.handle_setup_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::empty()))
            .await;

        assert!(app.setup.is_none());
        assert_eq!(app.model.provider_label(), "llmsim/llmsim-yolop");
        assert!(
            app.lines
                .iter()
                .any(|line| line.text == "setup complete: offline demo mode")
        );
        assert!(
            !app.lines
                .iter()
                .any(|line| line.text.starts_with("setup provider changed:")),
            "wizard should hide internal setup command success output"
        );
    }

    // See setup_provider_picker_enters_credential_panel for why the env
    // lock is held across awaits.
    #[allow(clippy::await_holding_lock)]
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn setup_provider_picker_shows_connection_status() {
        let _guard = crate::test_env::lock();
        unsafe {
            std::env::remove_var("OPENAI_API_KEY");
            std::env::remove_var("CUSTOM_BASE_URL");
        }
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = Some(SetupStep::Provider { selected: 0 });

        let rendered = setup_overlay_text(app);
        let openai_row = rendered
            .iter()
            .find(|line| line.contains("OpenAI") && !line.contains("compatible"))
            .expect("openai row");
        assert!(
            openai_row.contains("needs API key"),
            "unconnected provider should say so: {openai_row:?}"
        );
        let custom_row = rendered
            .iter()
            .find(|line| line.contains("Custom endpoint"))
            .expect("custom row");
        assert!(
            custom_row.contains("needs base URL"),
            "custom without URL should say so: {custom_row:?}"
        );

        app.settings
            .set_token("openai".to_string(), "sk-test".to_string())
            .expect("save token");
        let rendered = setup_overlay_text(app);
        let openai_row = rendered
            .iter()
            .find(|line| line.contains("OpenAI") && !line.contains("compatible"))
            .expect("openai row");
        assert!(
            openai_row.contains("✓ saved key"),
            "saved key should mark the provider connected: {openai_row:?}"
        );
    }

    fn discovered(model_id: &str, display_name: Option<&str>) -> DiscoveredProviderModel {
        DiscoveredProviderModel {
            model_id: model_id.to_string(),
            display_name: display_name.map(str::to_string),
            description: None,
        }
    }

    #[test]
    fn model_window_centers_selection_in_long_lists() {
        assert_eq!(model_window(0, 5, 8), (0, 5));
        assert_eq!(model_window(0, 300, 8), (0, 8));
        assert_eq!(model_window(150, 300, 8), (146, 154));
        assert_eq!(model_window(299, 300, 8), (292, 300));
    }

    #[test]
    fn discovered_models_convert_to_options_with_custom_escape_hatch() {
        let mut described = discovered("openai/gpt-5.5", Some("OpenAI: GPT-5.5"));
        described.description = Some("frontier model for complex coding".to_string());
        let catalog = model_options_from_discovered(
            "openrouter",
            vec![
                described,
                discovered("nvidia/nemotron-3-super-120b-a12b", None),
            ],
            2,
        );

        assert_eq!(catalog.options.len(), 3);
        assert_eq!(catalog.recommended_count, 2);
        assert_eq!(catalog.options[0].spec.as_deref(), Some("openai/gpt-5.5"));
        assert_eq!(catalog.options[0].label, "openai/gpt-5.5");
        assert_eq!(
            catalog.options[0].hint,
            "OpenAI: GPT-5.5 · frontier model for complex coding"
        );
        assert_eq!(
            catalog.options[1].spec.as_deref(),
            Some("nvidia/nemotron-3-super-120b-a12b")
        );
        assert!(
            catalog.options[2].spec.is_none(),
            "last option must stay Custom..."
        );
    }

    #[test]
    fn discovered_model_hints_are_truncated_for_one_row_display() {
        let mut model = discovered("verbose/model", None);
        model.description = Some("x".repeat(200));

        let catalog = model_options_from_discovered("openrouter", vec![model], 1);

        assert!(
            catalog.options[0].hint.chars().count() <= 72,
            "hint must fit one picker row: {} chars",
            catalog.options[0].hint.chars().count()
        );
        assert!(catalog.options[0].hint.ends_with(''));
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn openrouter_model_picker_shows_recommended_divider() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = Some(SetupStep::PickModel {
            provider: "openrouter".to_string(),
            selected: 0,
            custom: None,
            error: None,
        });

        let ranked = crate::capabilities::model_ranking::rank_discovered_models(
            "openrouter",
            vec![
                discovered("zai/glm-5", None),
                discovered("openai/gpt-5.5", None),
                discovered("anthropic/claude-opus-4-8", None),
            ],
            None,
        );
        app.apply_model_discovery(ModelDiscovery {
            provider: "openrouter".to_string(),
            result: Ok(Some(model_options_from_discovered(
                "openrouter",
                ranked.models,
                ranked.recommended_count,
            ))),
        });

        let options = app.model_options("openrouter");
        assert_eq!(options[0].spec.as_deref(), Some("openai/gpt-5.5"));
        assert_eq!(
            options[1].spec.as_deref(),
            Some("anthropic/claude-opus-4-8")
        );
        assert_eq!(options[2].spec.as_deref(), Some("zai/glm-5"));
        assert_eq!(app.model_recommended_count("openrouter"), 2);

        let rendered = setup_overlay_text(app);
        assert!(
            rendered.iter().any(|line| line.contains("more models")),
            "recommended section should be separated from the full catalog: {rendered:?}"
        );
    }

    #[test]
    fn openrouter_ranking_applies_curated_order_and_alphabetical_rest() {
        use crate::capabilities::model_ranking::rank_discovered_models;

        let ranked = rank_discovered_models(
            "openrouter",
            vec![
                discovered("zai/glm-5", None),
                discovered("openai/gpt-5.5", None),
                discovered("anthropic/claude-opus-4-8", None),
                discovered("moon/kimi-k3", None),
            ],
            None,
        );

        assert_eq!(ranked.recommended_count, 2);
        let ids: Vec<&str> = ranked
            .models
            .iter()
            .map(|model| model.model_id.as_str())
            .collect();
        assert_eq!(
            ids,
            &[
                "openai/gpt-5.5",
                "anthropic/claude-opus-4-8",
                "moon/kimi-k3",
                "zai/glm-5",
            ]
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn discovered_models_replace_fallback_options_in_open_picker() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = Some(SetupStep::PickModel {
            provider: "openrouter".to_string(),
            selected: 0,
            custom: None,
            error: None,
        });

        app.apply_model_discovery(ModelDiscovery {
            provider: "openrouter".to_string(),
            result: Ok(Some(model_options_from_discovered(
                "openrouter",
                vec![
                    discovered("zai/glm-5", None),
                    discovered("moon/kimi-k3", None),
                ],
                0,
            ))),
        });

        let options = app.model_options("openrouter");
        assert_eq!(options.len(), 3);
        assert_eq!(options[0].spec.as_deref(), Some("zai/glm-5"));
        let rendered = setup_overlay_text(app);
        assert!(
            rendered.iter().any(|line| line.contains("zai/glm-5")),
            "open picker should render discovered models: {rendered:?}"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn unsupported_model_discovery_keeps_fallback_options() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;

        app.apply_model_discovery(ModelDiscovery {
            provider: "ollama".to_string(),
            result: Ok(None),
        });

        let options = app.model_options("ollama");
        assert_eq!(options[0].spec.as_deref(), Some("llama3.2"));

        // The unsupported outcome is cached so reopening the picker doesn't
        // re-query an API that can't answer.
        app.model_discovery_enabled = true;
        app.request_model_discovery("ollama");
        assert!(!app.is_fetching_models("ollama"));
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn failed_model_discovery_surfaces_error_in_open_picker() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = Some(SetupStep::PickModel {
            provider: "openai".to_string(),
            selected: 0,
            custom: None,
            error: None,
        });

        app.apply_model_discovery(ModelDiscovery {
            provider: "openai".to_string(),
            result: Err("connection refused".to_string()),
        });

        assert!(matches!(
            app.setup,
            Some(SetupStep::PickModel { ref error, .. })
                if error.as_deref() == Some("model list unavailable: connection refused")
        ));
        // The curated list must remain usable after a failed fetch.
        let options = app.model_options("openai");
        assert_eq!(options[0].spec.as_deref(), Some("gpt-5.5"));
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn setup_connected_provider_jumps_straight_to_model_picker() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.lines.clear();
        app.settings
            .set_token("openai".to_string(), "sk-test".to_string())
            .expect("save token");
        app.setup = Some(SetupStep::Provider { selected: 0 });

        app.handle_setup_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::empty()))
            .await;

        assert!(
            matches!(
                app.setup,
                Some(SetupStep::PickModel { ref provider, .. }) if provider == "openai"
            ),
            "connected provider should skip the credential step: {:?}",
            app.setup
        );
        assert_eq!(app.model.provider_label(), "openai/gpt-5.5 medium");
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn setup_model_picker_preset_selection_applies_and_persists() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.lines.clear();
        app.settings
            .set_token("openai".to_string(), "sk-test".to_string())
            .expect("save token");
        app.setup = Some(SetupStep::Provider { selected: 0 });

        // Enter the wizard the way a user does: the connected-provider fast
        // path switches to openai first, so the provider-relative
        // `model <id>` the picker emits resolves against it.
        app.handle_setup_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::empty()))
            .await;
        assert!(
            matches!(app.setup, Some(SetupStep::PickModel { .. })),
            "fast path should open the model picker: {:?}",
            app.setup
        );

        // Navigate to the second preset (gpt-5.4) and confirm it.
        app.handle_setup_key(KeyEvent::new(KeyCode::Down, KeyModifiers::empty()))
            .await;
        app.handle_setup_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::empty()))
            .await;

        assert!(app.setup.is_none(), "wizard should finish: {:?}", app.setup);
        assert_eq!(app.model.provider_label(), "openai/gpt-5.4 none");
        assert!(
            app.lines
                .iter()
                .any(|line| line.text == "setup complete: openai/gpt-5.4 none"),
            "completion line should report the picked model: {:?}",
            app.lines
        );
        // The pick persists, so the next run restores it (see
        // pick_provider_applies_saved_model_for_saved_provider in main.rs).
        let snapshot = app.settings.snapshot();
        assert_eq!(snapshot.default_provider.as_deref(), Some("openai"));
        assert_eq!(snapshot.model_for("openai"), Some("gpt-5.4 none"));
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn setup_c_key_opens_credential_panel_even_when_connected() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.settings
            .set_token("openai".to_string(), "sk-test".to_string())
            .expect("save token");
        app.setup = Some(SetupStep::Provider { selected: 0 });

        app.handle_setup_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::empty()))
            .await;

        assert!(
            matches!(
                app.setup,
                Some(SetupStep::Credential { ref provider, .. }) if provider == "openai"
            ),
            "c should open credential config: {:?}",
            app.setup
        );
    }

    // See setup_provider_picker_enters_credential_panel for why the env
    // lock is held across awaits.
    #[allow(clippy::await_holding_lock)]
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn setup_custom_endpoint_flow_collects_url_and_model() {
        let _guard = crate::test_env::lock();
        unsafe {
            std::env::remove_var("CUSTOM_BASE_URL");
            std::env::remove_var("CUSTOM_API_KEY");
        }
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.lines.clear();
        let custom_index = PROVIDER_OPTIONS
            .iter()
            .position(|option| option.name == "custom")
            .expect("custom provider option");
        app.setup = Some(SetupStep::Provider {
            selected: custom_index,
        });

        // Not connected yet → Enter opens the base URL input.
        app.handle_setup_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::empty()))
            .await;
        assert!(
            matches!(app.setup, Some(SetupStep::BaseUrlInput { .. })),
            "custom without URL should ask for one: {:?}",
            app.setup
        );

        for ch in "http://localhost:8000/v1".chars() {
            app.handle_setup_key(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::empty()))
                .await;
        }
        app.handle_setup_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::empty()))
            .await;
        assert!(
            matches!(
                app.setup,
                Some(SetupStep::Credential { ref provider, selected: 0, .. }) if provider == "custom"
            ),
            "saved URL should advance to the credential step: {:?}",
            app.setup
        );

        // "Continue without key" → model picker. With discovery disabled in
        // tests the list holds only the "Custom..." escape hatch; confirming
        // it opens the free-form input.
        app.handle_setup_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::empty()))
            .await;
        assert!(
            matches!(
                app.setup,
                Some(SetupStep::PickModel { ref provider, custom: None, .. })
                    if provider == "custom"
            ),
            "custom credential step should advance to the model picker: {:?}",
            app.setup
        );
        app.handle_setup_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::empty()))
            .await;
        assert!(
            matches!(
                app.setup,
                Some(SetupStep::PickModel { ref provider, custom: Some(_), .. })
                    if provider == "custom"
            ),
            "Custom... should open the free-form model input: {:?}",
            app.setup
        );

        for ch in "qwen3-coder".chars() {
            app.handle_setup_key(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::empty()))
                .await;
        }
        app.handle_setup_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::empty()))
            .await;

        assert!(app.setup.is_none(), "wizard should finish: {:?}", app.setup);
        assert_eq!(app.model.provider_label(), "custom/qwen3-coder");
        let snapshot = app.settings.snapshot();
        assert_eq!(
            snapshot.base_url_for("custom"),
            Some("http://localhost:8000/v1")
        );
        assert_eq!(snapshot.default_provider.as_deref(), Some("custom"));
        assert_eq!(snapshot.model_for("custom"), Some("qwen3-coder"));
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn model_command_opens_model_picker_overlay() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.lines.clear();

        app.dispatch_command_for_test("model").await;

        assert!(matches!(
            app.setup,
            Some(SetupStep::PickModel {
                ref provider,
                ..
            }) if provider == "llmsim"
        ));
        let rendered = setup_overlay_text(app);
        assert!(rendered.iter().any(|line| line.contains("Select Model")));
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn model_command_preselects_current_raw_model_id() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.lines.clear();
        app.setup = None;

        app.handle_command("setup token openai sk-test").await;
        app.run_setup_command(Some("provider openai"))
            .await
            .expect("set openai provider");
        app.run_setup_command(Some("model gpt-5.4"))
            .await
            .expect("set openai model");
        app.lines.clear();

        app.dispatch_command_for_test("model").await;

        assert!(matches!(
            app.setup,
            Some(SetupStep::PickModel {
                ref provider,
                selected,
                ..
            }) if provider == "openai" && selected == 1
        ));
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn model_command_with_arg_opens_prefilled_model_modal() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.lines.clear();
        app.setup = None;

        app.handle_command("setup token openai sk-test").await;
        app.run_setup_command(Some("provider openai"))
            .await
            .expect("set openai provider");
        app.lines.clear();
        app.dispatch_command_for_test("model gpt-5.4 high").await;

        assert_eq!(app.model.provider_label(), "openai/gpt-5.5 medium");
        assert!(matches!(
            app.setup,
            Some(SetupStep::PickModel {
                ref provider,
                ref custom,
                ..
            }) if provider == "openai" && custom.as_deref() == Some("gpt-5.4 high")
        ));

        app.handle_setup_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::empty()))
            .await;

        assert!(app.setup.is_none());
        assert_eq!(app.model.provider_label(), "openai/gpt-5.4 high");
        assert!(
            app.lines
                .iter()
                .any(|line| line.text == "setup complete: openai/gpt-5.4 high"),
            "model modal should report completion: {:?}",
            app.lines
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn effort_command_opens_effort_modal_and_confirms_selection() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.lines.clear();
        app.setup = None;

        app.handle_command("setup token openai sk-test").await;
        app.run_setup_command(Some("provider openai"))
            .await
            .expect("set openai provider");
        app.run_setup_command(Some("model gpt-5.4"))
            .await
            .expect("set openai model");
        app.lines.clear();
        app.dispatch_command_for_test("effort high").await;

        assert_eq!(app.model.provider_label(), "openai/gpt-5.4 none");
        assert!(matches!(
            app.setup,
            Some(SetupStep::PickEffort { selected: 3, .. })
        ));
        let rendered = setup_overlay_text(app);
        assert!(
            rendered
                .iter()
                .any(|line| line.contains("Select Reasoning Effort"))
        );

        app.handle_setup_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::empty()))
            .await;

        assert!(app.setup.is_none());
        assert_eq!(app.model.provider_label(), "openai/gpt-5.4 high");
        assert!(
            app.lines
                .iter()
                .any(|line| line.text == "setup complete: openai/gpt-5.4 high"),
            "effort modal should report completion: {:?}",
            app.lines
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn effort_modal_does_not_mark_unset_openrouter_effort_current() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.lines.clear();
        app.setup = None;

        app.handle_command("setup token openrouter sk-test").await;
        app.run_setup_command(Some("provider openrouter"))
            .await
            .expect("set openrouter provider");
        app.run_setup_command(Some("model nvidia/nemotron-3-super-120b-a12b"))
            .await
            .expect("set openrouter model");
        app.lines.clear();
        app.dispatch_command_for_test("effort").await;

        assert_eq!(
            app.model.provider_label(),
            "openrouter/nvidia/nemotron-3-super-120b-a12b"
        );
        let rendered = setup_overlay_text(app);
        assert!(
            !rendered.iter().any(|line| line.contains("· current")),
            "unset OpenRouter effort should not render a current marker: {rendered:?}"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn app_view_state_hides_command_suggestions_when_input_disabled() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = None;

        app.handle_key(KeyEvent::new(KeyCode::Char('/'), KeyModifiers::empty()))
            .await;
        assert!(
            !app.view_state().command_suggestions.is_empty(),
            "slash input should produce suggestions before input is disabled"
        );

        app.busy = true;
        assert!(
            app.view_state().command_suggestions.is_empty(),
            "busy turns should not render suggestions"
        );
    }

    #[test]
    fn chrome_command_suggestions_override_stream_preview_row() {
        let state = ViewState {
            presentation: PresentationState {
                stream_preview: Some(StreamPreview {
                    kind: StreamKind::Assistant,
                    text: "streaming response".to_string(),
                }),
                ..presentation_state_idle()
            },
            command_suggestions: vec![CommandSuggestion {
                completion: "/help".to_string(),
                label: "/help    show commands".to_string(),
            }],
            ..view_state_idle()
        };
        let rows = render_chrome_lines(&state, 80, 5);
        assert!(
            rows[0].contains("Tab /help"),
            "suggestions should render in the top chrome row: {:?}",
            rows
        );
        assert!(
            !rows[0].contains("agent"),
            "command suggestions should replace the stream preview row: {}",
            rows[0]
        );
    }

    #[test]
    fn draw_suggestions_ignores_empty_areas() {
        let suggestions = vec![CommandSuggestion {
            completion: "/help".to_string(),
            label: "/help    show commands".to_string(),
        }];
        let backend = TestBackend::new(4, 1);
        let mut terminal = Terminal::new(backend).expect("terminal");

        terminal
            .draw(|f| {
                draw_suggestions(
                    f,
                    Rect {
                        x: 0,
                        y: 0,
                        width: 0,
                        height: 1,
                    },
                    &suggestions,
                );
                draw_suggestions(
                    f,
                    Rect {
                        x: 0,
                        y: 0,
                        width: 4,
                        height: 0,
                    },
                    &suggestions,
                );
            })
            .expect("draw");

        let buffer = terminal.backend().buffer();
        assert_eq!(buffer[(0, 0)].symbol(), " ");
    }

    #[test]
    fn chrome_idle_shows_enter_to_send_hint() {
        let state = view_state_idle();
        let rows = render_chrome_lines(&state, 80, 4);
        // Row 0 = message separator. Idle mode shows the keystroke hint.
        assert!(
            rows[0].contains("Enter to send"),
            "idle separator missing Enter hint: rows={rows:?}"
        );
    }

    #[test]
    fn chrome_busy_shows_thinking_spinner_and_activity() {
        let state = ViewState {
            presentation: PresentationState {
                busy: true,
                turn_activity: Some("reading files".to_string()),
                ..presentation_state_idle()
            },
            busy_frame: 4,
            ..view_state_idle()
        };
        let rows = render_chrome_lines(&state, 80, 4);
        assert!(
            rows[0].contains("reading files"),
            "busy separator should display turn activity: {}",
            rows[0]
        );
        assert!(
            rows[0].contains("input disabled"),
            "busy separator should signal input is disabled: {}",
            rows[0]
        );
    }

    #[test]
    fn chrome_busy_falls_back_to_thinking_when_activity_unset() {
        let state = ViewState {
            presentation: PresentationState {
                busy: true,
                ..presentation_state_idle()
            },
            ..view_state_idle()
        };
        let rows = render_chrome_lines(&state, 80, 4);
        assert!(
            rows[0].contains("thinking"),
            "busy separator without activity should show 'thinking': {}",
            rows[0]
        );
    }

    #[test]
    fn chrome_renders_stream_preview_tail_with_kind_label() {
        let state = ViewState {
            presentation: PresentationState {
                stream_preview: Some(StreamPreview {
                    kind: StreamKind::Assistant,
                    text: "first line\nsecond line tail".to_string(),
                }),
                ..presentation_state_idle()
            },
            ..view_state_idle()
        };
        let rows = render_chrome_lines(&state, 80, 5);
        // The preview shows the latest non-blank tail line of the stream
        // prefixed by the kind label.
        assert!(
            rows[0].contains("agent"),
            "stream preview should show kind label 'agent': {}",
            rows[0]
        );
        assert!(
            rows[0].contains("second line tail"),
            "stream preview should show the tail, not the head: {}",
            rows[0]
        );
        assert!(
            !rows[0].contains("first line"),
            "stream preview should not show earlier lines: {}",
            rows[0]
        );
    }

    #[test]
    fn chrome_session_status_compact_shows_provider_model_effort_approval_and_messages() {
        let state = ViewState {
            presentation: PresentationState {
                provider_name: "openrouter".to_string(),
                lines_count: 42,
                ..presentation_state_idle()
            },
            ..view_state_idle()
        };
        let rows = render_chrome_lines(&state, 120, 4);
        let status = &rows[3];
        assert!(
            status.contains("[expand ↓]"),
            "compact status should include expand affordance: {status}"
        );
        assert!(
            status.contains("openrouter"),
            "compact status should include provider: {status}"
        );
        assert!(
            status.contains("gpt-5.5"),
            "compact status should include model id: {status}"
        );
        assert!(
            status.contains("effort medium"),
            "compact status should include effort: {status}"
        );
        assert!(
            status.contains("approval normal"),
            "compact status should include approval: {status}"
        );
        assert!(
            status.contains("42 msgs"),
            "compact status should include message count: {status}"
        );
        assert!(
            !status.contains("session "),
            "compact status should keep session id for expanded layout: {status}"
        );
    }

    #[test]
    fn chrome_session_status_compact_shows_worktree_indicator() {
        let state = ViewState {
            presentation: PresentationState {
                worktree_compact: Some("bump-outdated-crates-ship".to_string()),
                ..presentation_state_idle()
            },
            ..view_state_idle()
        };
        let rows = render_chrome_lines(&state, 120, 4);
        let status = &rows[3];
        assert!(
            status.contains("wt bump-out"),
            "compact status should include worktree slug: {status}"
        );
    }

    #[test]
    fn chrome_session_status_expanded_shows_worktree_subsection() {
        let state = ViewState {
            presentation: PresentationState {
                status_layout: StatusLayout::Expanded,
                worktree_compact: Some("bump-outdated-crates-ship".to_string()),
                worktree_expanded: Some((
                    "bump-outdated-crates-ship-f6dd3e41".to_string(),
                    "…/session_019ee6c2dfd27223853ea56ff6dd3e41".to_string(),
                )),
                ..presentation_state_idle()
            },
            ..view_state_idle()
        };
        assert_eq!(state.status_row_count(), 5);
        let rows = render_chrome_lines(&state, 180, 8);
        assert!(
            rows[7].contains("worktree bump-outdated-crates-ship-f6dd3e41")
                && rows[7].contains("path …/session_019ee6"),
            "expanded status should include worktree branch and path: {:?}",
            rows[7]
        );
    }

    #[test]
    fn view_state_status_row_count_adds_worktree_row_only_when_expanded() {
        let compact = ViewState {
            presentation: PresentationState {
                worktree_expanded: Some(("branch".into(), "path".into())),
                ..presentation_state_idle()
            },
            ..view_state_idle()
        };
        assert_eq!(compact.status_row_count(), 1);

        let expanded = ViewState {
            presentation: PresentationState {
                status_layout: StatusLayout::Expanded,
                worktree_expanded: Some(("branch".into(), "path".into())),
                ..presentation_state_idle()
            },
            ..view_state_idle()
        };
        assert_eq!(expanded.status_row_count(), 5);
    }

    #[test]
    fn chrome_session_status_expanded_groups_details_across_four_lines() {
        let session_id = SessionId::from_seed(99887766).to_string();
        let state = ViewState {
            presentation: PresentationState {
                model_id: "nvidia/nemotron-3-super-120b-a12b".to_string(),
                provider_name: "openrouter".to_string(),
                reasoning_effort: Some("high".to_string()),
                session_id: session_id.clone(),
                lines_count: 42,
                session_tokens: Some(1234),
                status_layout: StatusLayout::Expanded,
                ..presentation_state_idle()
            },
            ..view_state_idle()
        };
        let rows = render_chrome_lines(&state, 180, 7);
        assert!(
            rows[3].contains("[collapse ↑]")
                && rows[3].contains("provider openrouter")
                && rows[3].contains("model nvidia/nemotron-3-super-120b-a12b"),
            "expanded provider/model row should include selected model and provider: {:?}",
            rows[3]
        );
        assert!(
            !rows[3].contains("full "),
            "expanded model row should not duplicate model/provider as a full label: {:?}",
            rows[3]
        );
        assert!(
            rows[4].contains("effort high")
                && rows[4].contains("approval normal")
                && rows[4].contains("hooks none")
                && rows[4].contains("goal"),
            "expanded controls row should include effort, approval, hooks, and goal: {:?}",
            rows[4]
        );
        assert!(
            rows[5].contains("42 msgs") && rows[5].contains("tokens 1234"),
            "expanded counts row should include messages and tokens: {:?}",
            rows[5]
        );
        assert!(
            rows[6].contains("session ") && rows[6].contains(&session_id),
            "expanded session row should include the full session id: {:?}",
            rows[6]
        );
        assert!(
            !rows[6].contains(''),
            "expanded session row should not shorten the session id: {:?}",
            rows[6]
        );
    }

    #[test]
    fn chrome_session_status_stays_visible_with_multiline_input() {
        let state = ViewState {
            presentation: PresentationState {
                status_layout: StatusLayout::Expanded,
                ..presentation_state_idle()
            },
            ..view_state_idle()
        };
        let rows = render_chrome_lines_with_input_height(&state, 120, 8, 3);
        assert!(
            rows[4].contains("[collapse ↑]") && rows[4].contains("provider openai"),
            "expanded model row should remain visible with multiline input: {:?}",
            rows
        );
        assert!(
            rows[5].contains("effort medium") && rows[5].contains("hooks none"),
            "expanded controls row should remain visible with multiline input: {:?}",
            rows
        );
        assert!(
            rows[6].contains("3 msgs") && rows[6].contains("tokens n/a"),
            "expanded counts row should remain visible with multiline input: {:?}",
            rows
        );
        assert!(
            rows[7].contains("session "),
            "expanded session row should remain visible with multiline input: {:?}",
            rows
        );
    }

    #[test]
    fn chrome_idle_does_not_reserve_empty_stream_preview_row() {
        let state = view_state_idle();
        let rows = render_chrome_lines(&state, 80, 4);
        assert!(
            rows[0].contains("Enter to send"),
            "idle chrome should start with the separator instead of an empty preview row: {:?}",
            rows
        );
    }
}