yolop 0.11.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
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
// 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::exec::worktree::WorktreeManager;
use crate::runtime::session::Session;
use crate::runtime::{BuiltRuntime, ModelState, StartupInfo};
use crate::session_state::goal::{GOAL_EVALUATE_ARG, GoalStore, parse_evaluation_response};
use crate::session_state::user_ask::{
    AskOutcome, USER_ASK_EVALUATE_ARG, UserAskStore, evaluation_status_message,
    parse_evaluation_response as parse_user_ask_evaluation,
};
use crate::tui::host_ui::UiCommand;
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::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 std::collections::{HashMap, HashSet, VecDeque};
use std::path::Path;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::{mpsc, oneshot};

pub(crate) mod fullscreen;
mod render;
mod setup;
mod viewport;

pub mod host_ui;
pub mod input;
pub mod presentation;
pub mod prompt_history;
pub mod session_tasks_view;
pub mod transcript;

// Re-export the moved free items so the rest of the crate (and the test module)
// can keep referring to them as `crate::tui::*`. `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::tui::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::tui::*`.
pub(crate) use self::{render::*, viewport::*};
pub(crate) use crate::tui::presentation::*;
pub(crate) use crate::tui::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 ERROR_RED: Color = Color::Rgb(196, 78, 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);

/// Upper bound on retained transcript `ChatLine`s. A session that never stops
/// producing output would otherwise grow `App::lines` — and the full-screen
/// wrap cache built from it — without bound. Past this watermark the oldest
/// lines are dropped from the front (see [`App::trim_transcript`]): in inline
/// mode they have already been flushed to native scrollback, and in full-screen
/// mode this bounds how far back the in-app scrollback reaches. The window is
/// generous so only pathologically long sessions ever reach it.
const MAX_RETAINED_TRANSCRIPT_LINES: usize = 50_000;

/// Memoized wrapping for the full-screen transcript.
/// [`render::append_transcript_range`] markdown/syntax-highlights and word-wraps
/// every `ChatLine`; doing that for the whole history on every frame is
/// O(session) work to show O(viewport).
/// Because `App::lines` only grows at the tail (or is reset, which bumps
/// `App::transcript_generation`), the wrapped output is stable except for the
/// newly-appended lines, which is all this cache re-wraps per frame.
#[derive(Default)]
struct TranscriptWrapCache {
    /// Wrap width the cached lines were built at; a change invalidates them.
    width: usize,
    /// Generation the cache was built against; a bump invalidates it.
    generation: u64,
    /// Number of `App::lines` already wrapped into `lines`.
    source_len: usize,
    /// Author of the last emitted chat, so an incremental pass reproduces the
    /// inter-author gap exactly as a full pass would.
    prev_author: Option<Author>,
    /// The wrapped, gap-spaced transcript rows.
    lines: Vec<Line<'static>>,
}

pub struct App {
    session: Session,
    startup: StartupInfo,
    model: ModelState,
    pub lines: Vec<ChatLine>,
    printed_lines: usize,
    /// The single composer model, shared by **both** renderers: a tuika
    /// [`TextInputState`](tuika::TextInputState) that owns the draft text and
    /// cursor and applies its own edits (emacs bindings, word movement, wrapping).
    /// Inline and full-screen both read and write it, render it through the same
    /// [`TextInput`](tuika::TextInput) view, and place the terminal cursor via
    /// [`cursor_screen`](tuika::TextInputState::cursor_screen) — so the two modes
    /// can never drift.
    composer: tuika::TextInputState,
    /// User messages submitted while a turn is active. The embedded runtime
    /// cannot accept concurrent inputs, so these start in FIFO order at the
    /// next turn boundary. Cancellation deliberately leaves the queue intact.
    queued_messages: VecDeque<QueuedMessage>,
    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>,
    /// Codex login runs outside the terminal input handler. The task owns any
    /// network wait; the event loop only polls its channel between frames.
    codex_login: Option<PendingCodexLogin>,
    codex_login_tx: mpsc::UnboundedSender<CodexLoginEvent>,
    codex_login_rx: mpsc::UnboundedReceiver<CodexLoginEvent>,
    next_codex_login_id: u64,
    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>,
    /// Live status-bar text per extension (`ext:<name>` → status), pushed by
    /// extension servers over `status/changed`. Rendered in the status bar via
    /// [`App::presentation_state`].
    extension_status: std::collections::BTreeMap<String, String>,
    /// Incoming extension `ui/ask` requests; each is prompted one at a time via
    /// [`App::pending_ask`].
    ask_rx: mpsc::UnboundedReceiver<crate::tui::host_ui::AskRequest>,
    /// The `ui/ask` prompt currently shown, if any. Owns the keyboard (even
    /// mid-turn) until the user answers or dismisses it.
    pending_ask: Option<PendingAsk>,
    sandbox_approval_rx: crate::sandbox_approval::ApprovalReceiver,
    pending_sandbox_approval: Option<PendingSandboxApproval>,
    /// 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::config::SettingsStore>,
    /// Per-process override, when one differs from persisted settings.
    sandbox_mode_override: Option<crate::config::SandboxMode>,
    /// 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::runtime::background_wake`). Drained while idle to
    /// auto-start a turn so the agent reacts to finished work. See
    /// specs/background.md.
    background_wake: crate::runtime::background_wake::WakeReceiver,
    /// Retained for the TUI lifetime so due local schedules keep polling.
    _schedule_runner: everruns_local::LocalScheduleRunnerHandle,
    /// 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::exec::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)>,
    /// Which renderer this session drives. `Inline` is the default
    /// scrollback-native composer; `Fullscreen` is the experimental
    /// alternate-screen `tuika` renderer (`--fullscreen`).
    render_mode: RenderMode,
    /// Full-screen transcript scroll position (unused in inline mode).
    scroll: tuika::ScrollState,
    /// Last (content_height, viewport_height) the full-screen transcript drew,
    /// so mouse/paging handlers can clamp scrolling without re-laying out.
    scroll_metrics: (usize, usize),
    /// Memoized full-screen transcript wrapping (see
    /// [`App::full_transcript_lines_cached`]). Bumped whenever `lines` is reset
    /// out from under the cache (clear, checkpoint restore, or a front trim);
    /// tail appends leave it untouched so only the new lines are re-wrapped.
    transcript_generation: u64,
    transcript_cache: TranscriptWrapCache,
    /// Full-screen mouse text selection over the transcript. `selection_area`
    /// is the transcript's inner rect recorded by the last draw (so the event
    /// handler can bound drags to it); `pending_copy` defers the OSC 52 copy to
    /// the next draw, where the freshly rendered frame buffer is readable.
    selection: tuika::SelectionState,
    selection_area: Rect,
    pending_copy: bool,
    pending_link_click: Option<tuika::Mouse>,
    pending_open_url: Option<String>,
    /// Drives the terminal's native OSC 9;4 progress indicator (Ghostty top
    /// bar / taskbar) while a turn runs. Works in both renderers. Enabled only
    /// for real TUI sessions via [`App::enable_native_progress`] so tests and
    /// non-terminal hosts emit no escape sequences.
    term_progress: tuika::TerminalProgress,
    native_progress: bool,
    /// Shell-style Up/Down recall of previously submitted composer prompts,
    /// persisted across sessions. See [`crate::tui::prompt_history`].
    history: crate::tui::prompt_history::PromptHistory,
    /// Active Ctrl+R reverse-history search, if any. While set it owns the
    /// keyboard and the composer previews the current match.
    history_search: Option<HistorySearch>,
    /// When the active turn began, for the live elapsed timer on the busy
    /// indicator. `None` while idle.
    turn_started_at: Option<Instant>,
    /// Prompt tokens the most recent LLM generation consumed — the current fill
    /// of the model's context window. `None` until the first generation.
    context_used_tokens: Option<u32>,
}

/// In-progress Ctrl+R reverse search over [`App::history`].
#[derive(Clone, Debug)]
pub(crate) struct HistorySearch {
    /// The incremental search query typed so far.
    query: String,
    /// Index of the entry currently matched, or `None` when nothing matches.
    match_index: Option<usize>,
    /// The composer rows captured on entry, restored if the search is cancelled.
    saved_lines: Vec<String>,
}

/// The renderer backing a TUI session.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum RenderMode {
    /// Scrollback-native inline composer (default).
    #[default]
    Inline,
    /// Experimental full-screen alternate-screen renderer (`tuika`).
    Fullscreen,
}

impl RenderMode {
    pub(crate) fn is_fullscreen(self) -> bool {
        matches!(self, RenderMode::Fullscreen)
    }
}

/// 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>,
    },
    CodexLogin {
        selected: usize,
        method: CodexLoginMethod,
        device_code: Option<(String, 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>,
    },
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum CodexLoginMethod {
    Browser,
    Device,
}

struct PendingCodexLogin {
    id: u64,
    task: tokio::task::JoinHandle<()>,
}

/// An in-flight extension `ui/ask`: the prompt shown, the answer being typed,
/// and the oneshot that delivers it back to the extension server.
pub(crate) struct PendingAsk {
    prompt: String,
    placeholder: Option<String>,
    value: String,
    reply: Option<oneshot::Sender<crate::tui::host_ui::AskAnswer>>,
}

struct PendingSandboxApproval {
    reply: oneshot::Sender<crate::sandbox_approval::ApprovalDecision>,
}

enum CodexLoginEvent {
    DeviceCode {
        id: u64,
        verification_uri: String,
        user_code: String,
    },
    Finished {
        id: u64,
        selected: usize,
        result: Result<crate::config::CodexAuth, 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,
}

struct QueuedMessage {
    prompt: String,
    display: String,
    images: Vec<ContentPart>,
}

#[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` borrows `App`
/// to paint the composer, 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>,
    /// Active Ctrl+R reverse-search prompt, if any. Takes over the chrome
    /// preview row and suppresses command suggestions.
    pub history_search: Option<HistorySearchView>,
    pub busy_frame: u64,
}

/// Render-facing view of an active reverse-history search.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct HistorySearchView {
    pub query: String,
    pub matched: bool,
}

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 (codex_login_tx, codex_login_rx) = mpsc::unbounded_channel::<CodexLoginEvent>();
        let mut app = Self {
            session,
            startup: runtime.startup,
            model: runtime.model,
            lines: Vec::new(),
            printed_lines: 0,
            composer: {
                let mut composer = tuika::TextInputState::new();
                composer.set_mode(tuika::TextInputMode::SubmitOnEnter);
                composer
            },
            queued_messages: VecDeque::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,
            codex_login: None,
            codex_login_tx,
            codex_login_rx,
            next_codex_login_id: 0,
            status_layout: StatusLayout::Compact,
            session_tokens: None,
            ui_rx: runtime.ui_rx,
            extension_status: std::collections::BTreeMap::new(),
            ask_rx: runtime.ask_rx,
            pending_ask: None,
            sandbox_approval_rx: runtime.sandbox_approval_rx,
            pending_sandbox_approval: None,
            settings: runtime.settings,
            sandbox_mode_override: runtime.sandbox_mode_override,
            model_catalog: HashMap::new(),
            model_fetches_in_flight: HashSet::new(),
            model_discovery_enabled: true,
            models_tx,
            models_rx,
            background_wake: runtime.background_wake,
            _schedule_runner: runtime.schedule_runner,
            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(),
            render_mode: RenderMode::default(),
            scroll: tuika::ScrollState::new(),
            scroll_metrics: (0, 0),
            transcript_generation: 0,
            transcript_cache: TranscriptWrapCache::default(),
            selection: tuika::SelectionState::new(),
            selection_area: Rect::ZERO,
            pending_copy: false,
            pending_link_click: None,
            pending_open_url: None,
            term_progress: tuika::TerminalProgress::new(),
            native_progress: false,
            // Tests run in-memory so recall never reads or appends to the real
            // per-user history file.
            history: if cfg!(test) {
                crate::tui::prompt_history::PromptHistory::in_memory()
            } else {
                crate::tui::prompt_history::PromptHistory::load()
            },
            history_search: None,
            turn_started_at: None,
            context_used_tokens: None,
        };
        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
    }

    /// Switch this session to the experimental full-screen renderer. Called by
    /// `run_tui` before the loop when `--fullscreen` is set.
    pub(crate) fn set_render_mode(&mut self, mode: RenderMode) {
        self.render_mode = mode;
    }

    /// The active full-screen transcript selection, if any (read by the draw to
    /// highlight and copy it).
    pub(crate) fn resolve_selection(&mut self, buffer: &ratatui::buffer::Buffer) {
        if self.selection.resolve(buffer, self.selection_area) {
            self.pending_copy = true;
        }
    }

    pub(crate) fn resolve_link_click(&mut self, buffer: &ratatui::buffer::Buffer) {
        let Some(event) = self.pending_link_click.take() else {
            return;
        };
        self.pending_open_url = tuika::ctrl_click_url(&event, buffer, self.selection_area);
    }

    pub(crate) fn take_pending_open_url(&mut self) -> Option<String> {
        self.pending_open_url.take()
    }

    pub(crate) fn selection_range(&self) -> Option<tuika::SelectionRange> {
        self.selection.range()
    }

    /// Record the transcript's inner rect (the selectable region) from the draw.
    pub(crate) fn set_selection_area(&mut self, area: Rect) {
        self.selection_area = area;
    }

    /// Take and clear the deferred-copy flag set when a drag was released.
    pub(crate) fn take_pending_copy(&mut self) -> bool {
        std::mem::take(&mut self.pending_copy)
    }

    /// Route a full-screen mouse event to transcript text selection. Returns
    /// `true` when the event was consumed (a redraw follows). A left-drag that
    /// starts inside the transcript selects; releasing it arms a clipboard copy
    /// (performed in the next draw). Shift/Ctrl/Alt gestures are left alone so
    /// the terminal's own Shift-drag selection still works.
    fn handle_fullscreen_selection(&mut self, mouse: MouseEvent) -> bool {
        let Some(tuika::Event::Mouse(m)) = tuika::translate_event(CrosstermEvent::Mouse(mouse))
        else {
            return false;
        };
        if m.kind == tuika::MouseKind::Up(tuika::MouseButton::Left) && m.ctrl && !m.shift && !m.alt
        {
            self.selection.clear();
            self.pending_link_click = Some(m);
            return true;
        }
        if !m.plain() {
            return false;
        }
        match m.kind {
            tuika::MouseKind::Down(tuika::MouseButton::Left) => {
                let a = self.selection_area;
                let inside = a.width > 0
                    && a.height > 0
                    && m.column >= a.x
                    && m.column < a.right()
                    && m.row >= a.y
                    && m.row < a.bottom();
                if inside {
                    self.selection.handle(&m);
                    true
                } else {
                    // A press elsewhere dismisses any existing selection but is
                    // otherwise left for the normal mouse handler (e.g. status).
                    let had = self.selection.range().is_some();
                    self.selection.clear();
                    had
                }
            }
            tuika::MouseKind::Drag(tuika::MouseButton::Left)
            | tuika::MouseKind::Up(tuika::MouseButton::Left) => {
                if self.selection.handle(&m) {
                    if matches!(m.kind, tuika::MouseKind::Up(tuika::MouseButton::Left))
                        && self.selection.range().is_some()
                    {
                        self.pending_copy = true;
                    }
                    true
                } else {
                    false
                }
            }
            _ => false,
        }
    }

    /// Drop any full-screen selection (on scroll, key input, or new output —
    /// its cell coordinates no longer point at the same text).
    fn clear_selection(&mut self) {
        self.selection.clear();
    }

    /// Enable the terminal's native OSC 9;4 progress indicator for this session.
    /// Called by `run_tui`; left off for tests and non-terminal hosts.
    pub(crate) fn enable_native_progress(&mut self) {
        self.native_progress = true;
    }

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

    /// Final assistant text to leave visible after the full-screen UI closes.
    pub fn last_assistant_message(&self) -> Option<&str> {
        self.lines
            .iter()
            .rev()
            .find(|line| line.author == Author::Assistant)
            .map(|line| line.text.as_str())
    }

    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();
        let history_search = self.history_search_view();
        ViewState {
            // The search prompt owns the chrome row while active, so suppress
            // command suggestions to avoid two things fighting for it.
            command_suggestions: if history_search.is_none()
                && !presentation.busy
                && self.setup.is_none()
            {
                self.suggestions()
            } else {
                Vec::new()
            },
            history_search,
            busy_frame: self.busy_frame,
            presentation,
        }
    }

    /// The active model's context-window size in tokens, from its static
    /// profile. `None` for models without a profile (e.g. the `llmsim` sim), in
    /// which case no context gauge is shown.
    fn context_window_tokens(&self) -> Option<u32> {
        let driver =
            crate::runtime::Provider::from_name(&self.model.provider_name())?.driver_id()?;
        let profile = everruns_core::get_model_profile(&driver, &self.model.model_id())?;
        u32::try_from(profile.limits?.context).ok()
    }

    pub(crate) fn presentation_state(&self) -> PresentationState {
        let settings = self.settings.snapshot();
        let sandbox = self
            .sandbox_mode_override
            .unwrap_or_else(|| settings.sandbox_mode());
        let approval_mode = if sandbox == crate::config::SandboxMode::DangerFullAccess {
            format!(
                "{} · {} · UNSAFE HOST",
                settings.approval_mode().as_str(),
                settings.approval_policy().as_str()
            )
        } else {
            format!(
                "{} · {} · {}",
                settings.approval_mode().as_str(),
                sandbox.as_str(),
                settings.approval_policy().as_str()
            )
        };
        PresentationState {
            stream_preview: self.stream_preview.clone(),
            busy: self.busy,
            queued_messages: self.queued_messages.len(),
            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,
            turn_elapsed_secs: self.turn_started_at.map(|start| start.elapsed().as_secs()),
            context_used_tokens: self.context_used_tokens,
            context_window_tokens: self.context_window_tokens(),
            compaction_budget_percent: Some(crate::runtime::COMPACTION_BUDGET_PERCENT),
            status_layout: self.status_layout,
            hooks_summary: self.startup.hook_summary(),
            approval_mode,
            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(),
            extension_status: self
                .extension_status
                .iter()
                .map(|(ext, status)| {
                    // `ext:<name>` → `<name>` for a compact status-bar label.
                    let label = ext.strip_prefix("ext:").unwrap_or(ext).to_string();
                    (label, status.clone())
                })
                .collect(),
        }
    }

    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<crate::tui::session_tasks_view::BackgroundCounts> {
        crate::tui::session_tasks_view::counts(&self.session_tasks)
    }

    fn background_panel_body(&self) -> String {
        crate::tui::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()));
        let sandbox_mode = self
            .sandbox_mode_override
            .unwrap_or_else(|| self.settings.snapshot().sandbox_mode());
        self.push_system(format!("sandbox: {}", sandbox_mode.as_str()));
        self.push_system(format!(
            "approval policy: {}",
            self.settings.snapshot().approval_policy().as_str()
        ));
        if let Some(warning) = crate::exec::sandbox::danger_warning(sandbox_mode) {
            self.push_system(warning.to_string());
        }
        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,
        });
    }

    /// Refresh the memoized full-screen transcript wrapping for `width` and
    /// return the total wrapped-line count.
    ///
    /// Re-wraps only the lines appended since the last call while the width and
    /// [`transcript_generation`](Self::transcript_generation) are unchanged; a
    /// width change or a generation bump (transcript reset) rebuilds from
    /// scratch. The cached rows match a full [`render::append_transcript_range`]
    /// pass over the whole history. Read them back with [`transcript_window`] so
    /// a caller can clone just the slice it paints instead of the whole cache.
    ///
    /// [`transcript_window`]: Self::transcript_window
    fn refresh_transcript_cache(&mut self, width: usize) -> usize {
        // Move the cache out so we can borrow `self.lines` immutably alongside.
        let mut cache = std::mem::take(&mut self.transcript_cache);
        let stale = cache.width != width
            || cache.generation != self.transcript_generation
            || cache.source_len > self.lines.len();
        if stale {
            cache.lines.clear();
            cache.width = width;
            cache.generation = self.transcript_generation;
            cache.source_len = 0;
            cache.prev_author = None;
        }
        cache.prev_author = render::append_transcript_range(
            &mut cache.lines,
            &self.lines,
            cache.source_len,
            width,
            cache.prev_author.take(),
        );
        cache.source_len = self.lines.len();
        let len = cache.lines.len();
        self.transcript_cache = cache;
        len
    }

    /// Clone the cached wrapped rows in `start..end`. Call
    /// [`refresh_transcript_cache`](Self::refresh_transcript_cache) first; `end`
    /// must not exceed the count it returned. Cloning just the visible window
    /// (rather than the whole cache) is what keeps a full-screen frame
    /// O(viewport) for a long transcript.
    fn transcript_window(&self, start: usize, end: usize) -> Vec<Line<'static>> {
        self.transcript_cache.lines[start..end].to_vec()
    }

    /// The whole cached transcript, cloned. Convenience over
    /// [`refresh_transcript_cache`](Self::refresh_transcript_cache) +
    /// [`transcript_window`](Self::transcript_window) for callers that want every
    /// row; the full-screen renderer takes only the visible window instead.
    #[cfg(test)]
    fn full_transcript_lines_cached(&mut self, width: usize) -> Vec<Line<'static>> {
        let len = self.refresh_transcript_cache(width);
        self.transcript_window(0, len)
    }

    /// Drop transcript history beyond [`MAX_RETAINED_TRANSCRIPT_LINES`] so a very
    /// long session can't grow `lines` (and the wrap cache) without bound.
    ///
    /// Only lines already flushed to native scrollback are dropped in inline
    /// mode — dropping an unflushed line would erase it from scrollback entirely
    /// — so the cap is a soft target there. Full-screen mode has no native
    /// flush, so the drop bounds how far back its in-app scrollback reaches.
    /// Draining the front shifts the flush cursor and
    /// invalidates the wrap cache.
    fn trim_transcript(&mut self) {
        let len = self.lines.len();
        if len <= MAX_RETAINED_TRANSCRIPT_LINES {
            return;
        }
        let want = len - MAX_RETAINED_TRANSCRIPT_LINES;
        let drop = if self.render_mode.is_fullscreen() {
            want
        } else {
            want.min(self.printed_lines)
        };
        if drop == 0 {
            return;
        }
        self.lines.drain(0..drop);
        self.printed_lines = self.printed_lines.saturating_sub(drop);
        self.transcript_generation = self.transcript_generation.wrapping_add(1);
    }

    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 {
                        self.deny_pending_sandbox_approval();
                        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 {
                self.deny_pending_sandbox_approval();
                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,
    {
        // Inline mode streams finalized lines into native scrollback via
        // `insert_before`; full-screen keeps the whole transcript in `lines`
        // and redraws it into the alternate screen each frame, so it skips both
        // the flush and the inline-viewport re-anchoring.
        if !self.render_mode.is_fullscreen() {
            self.flush_transcript(terminal)?;
        }
        // Bound retained history now that inline mode has flushed this frame's
        // lines, so `trim_transcript` can drop the freshly-flushed prefix.
        self.trim_transcript();
        self.refresh_session_tasks_if_due().await;
        terminal.autoresize()?;
        if !self.render_mode.is_fullscreen() {
            // Ratatui keeps an inline viewport's cursor offset across resizes
            // and resets its origin on horizontal shrinks. Normalize the
            // viewport to the terminal bottom before every draw.
            maybe_reanchor_inline_viewport(terminal)?;
        }
        terminal.draw(|f| draw(f, self))?;

        if let Some(url) = self.take_pending_open_url()
            && let Err(error) = crate::auth::oauth_flow::open_browser(&url)
        {
            tracing::warn!(%error, %url, "failed to open ctrl-clicked link");
        }

        // 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::ContextUsed(used)) => {
                    self.context_used_tokens = Some(used);
                    return Ok(());
                }
                Ok(TurnEvent::Done) => {
                    self.finish_busy();
                    if let Some(notice) = self.session.take_checkpoint_notice() {
                        self.refresh_after_checkpoint_restore(notice).await;
                        for display in self
                            .queued_messages
                            .iter()
                            .map(|message| message.display.clone())
                            .collect::<Vec<_>>()
                        {
                            self.push_user(display);
                        }
                        self.start_next_queued_turn();
                        return Ok(());
                    }
                    if self.start_next_queued_turn() {
                        return Ok(());
                    }
                    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}"));
                    self.start_next_queued_turn();
                    return Ok(());
                }
                Err(mpsc::error::TryRecvError::Empty) => {}
                Err(mpsc::error::TryRecvError::Disconnected) => {
                    self.finish_busy();
                    self.start_next_queued_turn();
                }
            }
        }

        // 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).await;
            applied_ui_command = true;
        }
        // Extension `ui/ask` prompts. One at a time; a request arriving while a
        // prompt is open is answered "cancelled" rather than stacking overlays.
        while let Ok(request) = self.ask_rx.try_recv() {
            if self.pending_ask.is_some() {
                let _ = request.reply.send(crate::tui::host_ui::AskAnswer {
                    answer: String::new(),
                    cancelled: true,
                });
                continue;
            }
            self.push_system(format!("extension asks: {}", request.prompt));
            self.pending_ask = Some(PendingAsk {
                prompt: request.prompt,
                placeholder: request.placeholder,
                value: String::new(),
                reply: Some(request.reply),
            });
            applied_ui_command = true;
        }
        if self.pending_ask.is_none()
            && self.pending_sandbox_approval.is_none()
            && let Ok((request, reply)) = self.sandbox_approval_rx.try_recv()
        {
            self.push_system(format!("approval needed: {}", request.reason));
            self.lines.push(ChatLine {
                author: Author::Tool,
                text: request.command,
            });
            let scope = if request.full_access {
                "danger-full-access"
            } else {
                "this command inside the active sandbox"
            };
            self.push_system(format!(
                "press y to approve {scope} once, a to approve {scope} for this session, n or Esc to deny"
            ));
            self.pending_sandbox_approval = Some(PendingSandboxApproval { reply });
            return Ok(());
        }
        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(());
        }

        // 3a) Codex login is intentionally a background operation so a browser
        // close or an abandoned device flow cannot stop terminal input.
        if self.apply_codex_login_events().await {
            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;
                    }
                    if self.render_mode.is_fullscreen() {
                        self.clear_selection();
                    }
                    self.handle_key(key).await;
                }
                CrosstermEvent::Mouse(mouse) => {
                    if self.render_mode.is_fullscreen() {
                        if self.handle_fullscreen_scroll(mouse.kind) {
                            continue;
                        }
                        if self.handle_fullscreen_selection(mouse) {
                            continue;
                        }
                    }
                    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}")),
        }
    }

    async fn refresh_after_checkpoint_restore(&mut self, notice: String) {
        match self.session.active_lines().await {
            Ok(lines) => {
                self.lines = lines;
                self.printed_lines = 0;
                self.transcript_generation = self.transcript_generation.wrapping_add(1);
            }
            Err(error) => self.push_system(format!("refresh restored transcript: {error}")),
        }
        self.push_system(notice);
        if let Some(prompt) = self.session.take_restored_prompt() {
            self.set_input_text(prompt);
        }
    }

    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) {
        // Reverse-history search owns the keyboard while active (even Ctrl+C,
        // which cancels the search rather than arming exit).
        if self.history_search.is_some() {
            self.handle_search_key(key);
            return;
        }
        if self.busy && key.code != KeyCode::Esc {
            self.esc_pending_cancel = false;
        }
        // Ctrl+R opens reverse-history search from the idle composer.
        if key.modifiers.contains(KeyModifiers::CONTROL) && matches!(key.code, KeyCode::Char('r')) {
            self.history_search_start();
            return;
        }
        if key.modifiers.contains(KeyModifiers::CONTROL) {
            match key.code {
                KeyCode::Char('c') => {
                    self.handle_ctrl_c();
                    return;
                }
                KeyCode::Char('d') => {
                    self.abort_codex_login();
                    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();

        if self.pending_sandbox_approval.is_some() {
            match key.code {
                KeyCode::Char('y') | KeyCode::Char('Y') => {
                    if let Some(pending) = self.pending_sandbox_approval.take() {
                        let _ = pending
                            .reply
                            .send(crate::sandbox_approval::ApprovalDecision::ApproveOnce);
                        self.push_system("approved".into());
                    }
                }
                KeyCode::Char('a') | KeyCode::Char('A') => {
                    if let Some(pending) = self.pending_sandbox_approval.take() {
                        let _ = pending
                            .reply
                            .send(crate::sandbox_approval::ApprovalDecision::ApproveForSession);
                        self.push_system("approved for this session".into());
                    }
                }
                KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => {
                    self.deny_pending_sandbox_approval();
                }
                _ => {}
            }
            return;
        }

        // 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;
        }

        // An extension `ui/ask` prompt owns the keyboard even mid-turn, since
        // the server typically asks while a tool is running.
        if self.pending_ask.is_some() {
            self.handle_ask_key(key);
            return;
        }

        if self.busy && key.code == KeyCode::Esc {
            self.handle_busy_key(key);
            return;
        }
        if self.setup.is_some() {
            self.handle_setup_key(key).await;
            return;
        }
        match key.code {
            KeyCode::Enter => match self
                .composer
                .handle_enter(key.modifiers == KeyModifiers::SHIFT)
            {
                tuika::TextInputEvent::Changed => {}
                tuika::TextInputEvent::Submit => self.submit_input().await,
            },
            KeyCode::Tab => {
                if !self.busy
                    && let Some(suggestion) = self.suggestions().first()
                {
                    self.set_input_text(suggestion.completion.clone());
                } else {
                    self.composer_edit_key(key);
                }
            }
            KeyCode::Up if self.try_history_prev() => {}
            KeyCode::Down if self.try_history_next() => {}
            _ => {
                self.composer_edit_key(normalize_printable_key(key));
            }
        }
    }

    /// Feed one editing key to the composer. The tuika `TextInputState` handles
    /// the event itself (component-driven input) after translation from crossterm.
    fn composer_edit_key(&mut self, key: KeyEvent) {
        if let Some(event) = tuika::translate_event(CrosstermEvent::Key(key)) {
            self.composer.handle(&event);
        }
    }

    /// Whether pressing Up should recall an older prompt rather than move the
    /// composer cursor. Recall only kicks in when the composer is empty, or when
    /// an unmodified recalled entry is showing and the cursor sits on the first
    /// line — so editing a multi-line prompt (or a fresh draft) never loses text
    /// to an accidental recall. Mirrors Codex's line-boundary gating.
    fn history_recall_prev_allowed(&self) -> bool {
        let text = self.input_text();
        if text.is_empty() {
            return true;
        }
        match self.history.current_entry() {
            Some(entry) if entry == text => self.composer_cursor_row() == 0,
            _ => false,
        }
    }

    /// Handle Up as history recall. Returns `true` when the key was consumed
    /// (recall began, moved, or is parked at the oldest entry), `false` to let
    /// the textarea move the cursor normally.
    fn try_history_prev(&mut self) -> bool {
        if !self.history_recall_prev_allowed() {
            return false;
        }
        let current = self.input_text();
        if let Some(entry) = self.history.navigate_up(&current) {
            self.set_input_text(entry);
            true
        } else {
            // No entries at all → let the textarea handle Up. Already browsing at
            // the oldest entry → swallow the key so it doesn't move the cursor.
            self.history.is_browsing()
        }
    }

    /// Handle Down as history recall. Only active while browsing an unmodified
    /// recalled entry with the cursor on the last line; otherwise the textarea
    /// moves the cursor.
    fn try_history_next(&mut self) -> bool {
        if !self.history.is_browsing() {
            return false;
        }
        let current = self.input_text();
        match self.history.current_entry() {
            Some(entry) if entry == current => {
                let last_row = self.composer_line_count().saturating_sub(1);
                if self.composer_cursor_row() != last_row {
                    return false;
                }
            }
            // The user edited the recalled entry; treat Down as normal movement.
            _ => return false,
        }
        if let Some(text) = self.history.navigate_down(&current) {
            self.set_input_text(text);
        }
        true
    }

    /// Open Ctrl+R reverse-history search from the idle composer. No-op while a
    /// turn or overlay owns the keyboard, or when there is no history to search.
    fn history_search_start(&mut self) {
        if self.busy
            || self.setup.is_some()
            || self.background_panel.is_some()
            || self.pending_ask.is_some()
            || self.history.is_empty()
        {
            return;
        }
        self.history.reset_navigation();
        self.history_search = Some(HistorySearch {
            query: String::new(),
            match_index: None,
            saved_lines: self.composer_lines(),
        });
        // An empty query lands on the newest entry, so Ctrl+R immediately
        // previews the last prompt — like a shell.
        self.history_search_refresh();
    }

    /// Keyboard handling while reverse search owns the composer.
    fn handle_search_key(&mut self, key: KeyEvent) {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        match key.code {
            KeyCode::Char('r') if ctrl => self.history_search_cycle(),
            // Ctrl+C / Ctrl+G / Esc abandon the search and restore the draft.
            KeyCode::Char('c' | 'g') if ctrl => self.history_search_cancel(),
            KeyCode::Esc => self.history_search_cancel(),
            KeyCode::Enter => self.history_search_accept(),
            KeyCode::Backspace => {
                if let Some(search) = self.history_search.as_mut() {
                    search.query.pop();
                }
                self.history_search_refresh();
            }
            KeyCode::Char(c) if !ctrl => {
                if let Some(search) = self.history_search.as_mut() {
                    search.query.push(c);
                }
                self.history_search_refresh();
            }
            // Ignore anything else so stray keys don't leak into the composer.
            _ => {}
        }
    }

    /// Recompute the match from the newest entry for the current query and
    /// preview it in the composer. Called after every query edit.
    fn history_search_refresh(&mut self) {
        let Some(search) = self.history_search.as_ref() else {
            return;
        };
        let Some(newest) = self.history.newest_index() else {
            return;
        };
        let hit = self.history.reverse_search(&search.query, newest);
        self.apply_search_hit(hit);
    }

    /// Advance to the next older match for the current query (repeated Ctrl+R).
    /// Holds on the current match when nothing older matches.
    fn history_search_cycle(&mut self) {
        let Some(search) = self.history_search.as_ref() else {
            return;
        };
        let query = search.query.clone();
        let start = match search.match_index {
            Some(0) => return, // already at the oldest match
            Some(i) => i - 1,
            None => match self.history.newest_index() {
                Some(n) => n,
                None => return,
            },
        };
        if let Some(hit) = self.history.reverse_search(&query, start) {
            self.apply_search_hit(Some(hit));
        }
    }

    /// Store the resolved match and mirror it into the composer (or clear the
    /// composer when nothing matches).
    fn apply_search_hit(&mut self, hit: Option<(usize, String)>) {
        let Some(search) = self.history_search.as_mut() else {
            return;
        };
        match hit {
            Some((index, entry)) => {
                search.match_index = Some(index);
                self.set_input_text(entry);
            }
            None => {
                search.match_index = None;
                self.clear_composer_text();
            }
        }
    }

    /// Accept the current match: keep it in the composer and leave search mode
    /// so the user can edit or submit. With no match, restore the saved draft.
    fn history_search_accept(&mut self) {
        let Some(search) = self.history_search.take() else {
            return;
        };
        match search.match_index.and_then(|i| self.history.entry_at(i)) {
            Some(entry) => {
                let entry = entry.to_string();
                self.set_input_text(entry);
            }
            None => self.restore_saved_input(search.saved_lines),
        }
    }

    /// Abandon the search and restore the composer to its pre-search contents.
    fn history_search_cancel(&mut self) {
        if let Some(search) = self.history_search.take() {
            self.restore_saved_input(search.saved_lines);
        }
    }

    fn restore_saved_input(&mut self, lines: Vec<String>) {
        self.set_input_text(lines.join("\n"));
    }

    /// Snapshot of the active reverse search for rendering, if any.
    pub(crate) fn history_search_view(&self) -> Option<HistorySearchView> {
        self.history_search
            .as_ref()
            .map(|search| HistorySearchView {
                query: search.query.clone(),
                matched: search.match_index.is_some(),
            })
    }

    fn suggestions(&self) -> Vec<CommandSuggestion> {
        // `@`-triggered file-path completion takes over the suggestion row when
        // the word being typed starts with `@`. Restricted to single-line input
        // so completion can safely rebuild the whole line (matching how slash
        // completion works).
        if self.composer_line_count() == 1
            && let Some(file) =
                file_path_suggestions(&self.suggestion_input(), &self.startup.workspace_root)
        {
            return file;
        }
        command_suggestions(&self.suggestion_input(), &self.startup.capability_commands)
    }

    fn composer_line_count(&self) -> usize {
        self.composer.line_count()
    }

    /// The composer's first line — the anchor for `@`/slash completion.
    fn suggestion_input(&self) -> String {
        self.composer_lines().into_iter().next().unwrap_or_default()
    }

    // ---- composer read/write surface (over the shared `TextInputState`) --------

    fn input_text(&self) -> String {
        self.composer.text()
    }

    /// The composer's logical lines.
    fn composer_lines(&self) -> Vec<String> {
        self.composer
            .text()
            .split('\n')
            .map(str::to_string)
            .collect()
    }

    /// The composer cursor's logical row (line index).
    fn composer_cursor_row(&self) -> usize {
        self.composer.cursor().0
    }

    fn set_input_text(&mut self, text: String) {
        // `set_text` splits on newlines (restoring a recalled multi-line prompt as
        // multiple rows) and parks the cursor at the end.
        self.composer.set_text(&text);
    }

    /// Clear the composer text (only) to a single empty line, leaving pending
    /// pastes intact — used by reverse-search's "no match" state.
    fn clear_composer_text(&mut self) {
        self.composer.clear();
    }

    fn reset_input(&mut self) {
        self.clear_composer_text();
        self.pending_pastes.clear();
    }

    fn input_height(&self, input_width: u16) -> u16 {
        self.composer
            .visual_height(input_width)
            .clamp(1, MAX_INPUT_HEIGHT)
    }

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

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

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

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

    /// Insert a string at the composer cursor (honoring embedded newlines).
    fn composer_insert_str(&mut self, s: &str) {
        self.composer.insert_str(s);
    }

    fn try_paste_clipboard(&mut self) {
        if self.setup.is_some() || self.background_panel.is_some() {
            return;
        }
        match crate::tui::input::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::tui::input::clipboard_paste::PasteImageError::NoImage(_)) => {
                if let Ok(text) = crate::tui::input::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}"));
            }
        }
    }

    /// Keyboard handling while an extension `ui/ask` prompt is open: edit the
    /// answer, Enter to submit, Esc to cancel.
    fn handle_ask_key(&mut self, key: KeyEvent) {
        let Some(ask) = self.pending_ask.as_mut() else {
            return;
        };
        match key.code {
            KeyCode::Enter => {
                let answer = ask.value.clone();
                self.resolve_ask(crate::tui::host_ui::AskAnswer {
                    answer,
                    cancelled: false,
                });
            }
            KeyCode::Esc => {
                self.resolve_ask(crate::tui::host_ui::AskAnswer {
                    answer: String::new(),
                    cancelled: true,
                });
            }
            KeyCode::Backspace => {
                ask.value.pop();
            }
            KeyCode::Char(c) => {
                ask.value.push(c);
            }
            _ => {}
        }
    }

    /// Deliver an answer to the extension and close the prompt.
    fn resolve_ask(&mut self, answer: crate::tui::host_ui::AskAnswer) {
        if let Some(mut ask) = self.pending_ask.take() {
            let shown = if answer.cancelled {
                "(cancelled)".to_string()
            } else {
                answer.answer.clone()
            };
            if let Some(reply) = ask.reply.take() {
                let _ = reply.send(answer);
            }
            self.push_system(format!("answered: {shown}"));
        }
    }

    fn deny_pending_sandbox_approval(&mut self) {
        if let Some(pending) = self.pending_sandbox_approval.take() {
            let _ = pending
                .reply
                .send(crate::sandbox_approval::ApprovalDecision::Deny);
            self.push_system("denied".into());
        }
    }

    async fn submit_input(&mut self) {
        let raw = self.input_text();
        crate::tui::input::paste_attachment::prune_pending_pastes(&raw, &mut self.pending_pastes);
        let pending_pastes = std::mem::take(&mut self.pending_pastes);
        let expanded =
            crate::tui::input::paste_attachment::expand_pending_pastes(&raw, &pending_pastes);
        self.reset_input();
        let text = expanded.trim().to_string();
        let display_text = raw.trim().to_string();
        // Record what the user typed (including slash/bang commands) for
        // shell-style Up/Down recall. Uses the pre-expansion display text so
        // paste placeholders recall as the user saw them.
        self.history.record(&display_text);
        if !self.busy {
            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::tui::input::image_input::user_display_text(&display_text, image_count);
        self.push_user(display.clone());
        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}"));
        }
        let images = std::mem::take(&mut self.pending_images);
        if self.busy {
            self.queued_messages.push_back(QueuedMessage {
                prompt: text,
                display,
                images,
            });
        } else {
            self.start_turn_with_images(text, images);
        }
    }

    /// 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::runtime::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::runtime::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.
    async 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::ManageMcp { arg } => self.manage_mcp_command(arg.as_deref()).await,
            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.transcript_generation = self.transcript_generation.wrapping_add(1);
                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(""))
            }
            UiCommand::SetExtensionStatus { ext, status } => {
                // Empty status clears the field; a live value replaces it.
                if status.trim().is_empty() {
                    self.extension_status.remove(&ext);
                } else {
                    self.extension_status.insert(ext, status);
                }
            }
            UiCommand::SetExtensionActive {
                capability_id,
                name,
                activate,
            } => {
                // enable_extension/disable_extension already persisted the
                // setting; here we apply it to the running session so it takes
                // effect on the next turn (EVE-795) rather than only next start.
                let result = if activate {
                    self.session.activate_capability(&capability_id).await
                } else {
                    self.session.deactivate_capability(&capability_id).await
                };
                match result {
                    Ok(delta) if delta.changed => self.push_system(format!(
                        "extension `{name}` {} for this session; effective on the next turn.",
                        if activate { "enabled" } else { "disabled" }
                    )),
                    // No overlay change: already in the desired state, or (on
                    // disable) it rides the harness layer from startup and only
                    // settings can drop it — which happens next session.
                    Ok(_) if !activate => self.push_system(format!(
                        "extension `{name}` will be disabled on the next session."
                    )),
                    Ok(_) => {}
                    Err(err) => self.push_system(format!(
                        "extension `{name}` saved, but applying it to this session failed: {err}. \
                         It will load on the next session."
                    )),
                }
            }
        }
    }

    const MCP_USAGE: &'static str =
        "usage: /mcp [reload | login <name> | enable|disable|remove <name> [global|workspace]]";

    async fn manage_mcp_command(&mut self, raw: Option<&str>) {
        let Some(raw) = raw.map(str::trim).filter(|s| !s.is_empty()) else {
            if self.startup.mcp_server_names.is_empty() {
                let global = crate::config::mcp::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 with `yolop mcp add`, .mcp.json in the workspace root, or {global})"
                ));
            } else {
                self.push_system(format!(
                    "active MCP servers: {}",
                    self.startup.mcp_server_names.join(", ")
                ));
            }
            self.push_system(Self::MCP_USAGE.into());
            return;
        };

        let mut parts = raw.split_whitespace();
        let action = parts.next().unwrap_or_default();

        // `reload` re-reads config from disk (picking up `yolop mcp add`,
        // hand edits, or the agent's own config tools) and applies it live.
        if action == "reload" {
            if parts.next().is_some() {
                self.push_system(Self::MCP_USAGE.into());
                return;
            }
            self.reload_mcp_and_report(None).await;
            return;
        }

        // `login <name>` runs the interactive OAuth flow for a remote server.
        if action == "login" {
            let name = parts.next();
            if parts.next().is_some() {
                self.push_system(Self::MCP_USAGE.into());
                return;
            }
            match name {
                Some(name) => self.mcp_login(name).await,
                None => self.push_system(Self::MCP_USAGE.into()),
            }
            return;
        }

        let name = parts.next();
        let scope = match parts.next() {
            None | Some("global") => crate::config::mcp::McpConfigScope::Global,
            Some("workspace") => crate::config::mcp::McpConfigScope::Workspace,
            Some(other) => {
                self.push_system(format!("{} (unknown scope: {other})", Self::MCP_USAGE));
                return;
            }
        };
        if parts.next().is_some() {
            self.push_system(Self::MCP_USAGE.into());
            return;
        }
        let Some(name) = name else {
            self.push_system(Self::MCP_USAGE.into());
            return;
        };

        let store =
            crate::config::mcp::McpConfigStore::default_for_workspace(&self.startup.workspace_root);
        let result = match action {
            "enable" => store
                .set_enabled(scope, name, true)
                .map(|_| format!("enabled MCP server `{name}`")),
            "disable" => store
                .set_enabled(scope, name, false)
                .map(|_| format!("disabled MCP server `{name}`")),
            "remove" => store.remove(scope, name).map(|removed| {
                if removed {
                    format!("removed MCP server `{name}`")
                } else {
                    format!("MCP server `{name}` was not configured")
                }
            }),
            other => {
                self.push_system(format!("{} (unknown action: {other})", Self::MCP_USAGE));
                return;
            }
        };
        match result {
            Ok(message) => self.reload_mcp_and_report(Some(message)).await,
            Err(error) => self.push_system(format!("failed to update MCP config: {error}")),
        }
    }

    /// Run the interactive OAuth login flow for a remote MCP server and persist
    /// the resulting tokens. Because the runtime resolves credentials per turn
    /// through the shared auth provider, the token is used on the next turn with
    /// no restart or reload needed.
    async fn mcp_login(&mut self, name: &str) {
        let servers = crate::config::mcp::load_mcp_servers(&self.startup.workspace_root);
        let Some(server) = servers.get(name) else {
            self.push_system(format!(
                "MCP server `{name}` is not configured or is disabled; add it and run `/mcp reload` first"
            ));
            return;
        };
        if server.transport_type != everruns_core::McpServerTransportType::Http {
            self.push_system(format!(
                "`{name}` is a stdio server; OAuth login only applies to remote HTTP servers"
            ));
            return;
        }
        let url = server.url.clone();
        let provider_key = server
            .oauth_provider_id
            .clone()
            .unwrap_or_else(|| name.to_string());

        self.push_system(format!("opening browser for `{name}` OAuth login…"));
        match crate::auth::mcp_oauth_login::login(&url, None, None).await {
            Ok(tokens) => {
                match crate::auth::mcp_oauth::save_tokens(
                    &self.session.connections(),
                    &provider_key,
                    tokens,
                ) {
                    Ok(()) => self.push_system(format!(
                        "signed in to `{name}` — the token is active on your next message"
                    )),
                    Err(error) => self.push_system(format!(
                        "saved login for `{name}` failed to persist: {error}"
                    )),
                }
            }
            Err(error) => self.push_system(format!("`{name}` OAuth login failed: {error}")),
        }
    }

    /// Apply the on-disk MCP config to the live session and report the active
    /// set. `prelude`, when set, is printed first (e.g. the mutation summary).
    async fn reload_mcp_and_report(&mut self, prelude: Option<String>) {
        if let Some(message) = prelude {
            self.push_system(message);
        }
        match self.session.reload_mcp_servers().await {
            Ok(names) => {
                self.startup.mcp_server_names = names;
                if self.startup.mcp_server_names.is_empty() {
                    self.push_system("active MCP servers: none".into());
                } else {
                    self.push_system(format!(
                        "active MCP servers: {}",
                        self.startup.mcp_server_names.join(", ")
                    ));
                }
            }
            Err(error) => self.push_system(format!("failed to reload MCP servers: {error}")),
        }
    }

    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;
    }

    /// Route a mouse-wheel event to the full-screen transcript scroll. Returns
    /// true when consumed. Uses the metrics recorded by the last full-screen
    /// draw so it need not re-run layout.
    fn handle_fullscreen_scroll(&mut self, kind: MouseEventKind) -> bool {
        let tuika_kind = match kind {
            MouseEventKind::ScrollUp => tuika::MouseKind::ScrollUp,
            MouseEventKind::ScrollDown => tuika::MouseKind::ScrollDown,
            _ => return false,
        };
        // Scrolling moves the text under any selection; drop it.
        self.clear_selection();
        let (content_h, viewport_h) = self.scroll_metrics;
        let event = tuika::Event::Mouse(tuika::Mouse::at(tuika_kind, 0, 0));
        self.scroll.handle(&event, content_h, viewport_h).consumed()
    }

    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.set_status_layout(None);
            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.input_text().trim().is_empty() {
            self.reset_input();
            self.disarm_ctrl_c_pending_exit();
            return;
        }

        if self.ctrl_c_pending_exit() {
            self.abort_codex_login();
            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.turn_started_at = None;
        self.stream_preview = None;
        self.rx = None;
        self.turn_cancel = None;
        if self.native_progress {
            self.term_progress.clear();
        }
        self.esc_pending_cancel = false;
    }

    /// Start the oldest steering message after the active turn has fully
    /// settled. One runtime turn runs at a time; later messages remain queued.
    fn start_next_queued_turn(&mut self) -> bool {
        let Some(message) = self.queued_messages.pop_front() else {
            return false;
        };
        self.start_turn_with_images(message.prompt, message.images);
        true
    }

    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;
            }
        };
        if evaluation.outcome == AskOutcome::Blocked {
            self.session
                .report_herdr_state(crate::capabilities::herdr::HerdrState::Blocked);
        }
        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.success
                            && matches!(descriptor.name.as_str(), "rewind" | "undo" | "redo")
                            && result.message.starts_with("restored ")
                        {
                            self.refresh_after_checkpoint_restore(result.message).await;
                        } else 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::runtime::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::runtime::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.turn_started_at = Some(Instant::now());
        self.stream_preview = None;
        if self.native_progress {
            // Turn length is unknown, so show the terminal's busy/indeterminate
            // indicator until the turn completes.
            self.term_progress.indeterminate();
        }
    }

    fn start_turn(&mut self, prompt: String) {
        let images = std::mem::take(&mut self.pending_images);
        self.start_turn_with_images(prompt, images);
    }

    fn start_turn_with_images(&mut self, prompt: String, images: Vec<ContentPart>) {
        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 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
        ),
    }]
}

/// Maximum `@file` completions surfaced at once.
const FILE_SUGGESTION_LIMIT: usize = 12;

/// File-path completions for an `@`-prefixed token in the composer, mirroring
/// the Codex `@file` mention. Returns `None` when the word being typed is not an
/// `@` mention (so command completion can take over). The returned `completion`
/// rebuilds the whole single-line input with the mention replaced, matching how
/// the Tab handler applies suggestions.
fn file_path_suggestions(line: &str, workspace_root: &Path) -> Option<Vec<CommandSuggestion>> {
    let (head, token) = split_trailing_token(line);
    let path_prefix = token.strip_prefix('@')?;
    let matches = list_path_completions(workspace_root, path_prefix, FILE_SUGGESTION_LIMIT);
    if matches.is_empty() {
        return None;
    }
    Some(
        matches
            .into_iter()
            .map(|rel| CommandSuggestion {
                completion: format!("{head}@{rel}"),
                label: format!("@{rel}"),
            })
            .collect(),
    )
}

/// Split a line into `(everything up to and including the last whitespace, last
/// token)`. For `"explain @src/ma"` this yields `("explain ", "@src/ma")`.
fn split_trailing_token(line: &str) -> (&str, &str) {
    match line.rfind(char::is_whitespace) {
        Some(idx) => line.split_at(idx + 1),
        None => ("", line),
    }
}

/// List workspace entries matching `prefix` (a path relative to the workspace
/// root, `/`-separated). Directories get a trailing `/` so the user can keep
/// descending. Hidden entries and `.git` are skipped unless explicitly typed.
fn list_path_completions(workspace_root: &Path, prefix: &str, limit: usize) -> Vec<String> {
    // Split the prefix into its directory part (already-typed dirs) and the
    // final filename fragment we match against.
    let (dir_part, frag) = match prefix.rfind('/') {
        Some(idx) => (&prefix[..idx + 1], &prefix[idx + 1..]),
        None => ("", prefix),
    };
    let scan_dir = workspace_root.join(dir_part);
    let Ok(entries) = std::fs::read_dir(&scan_dir) else {
        return Vec::new();
    };
    let want_hidden = frag.starts_with('.');
    let mut names: Vec<String> = Vec::new();
    for entry in entries.flatten() {
        let name = entry.file_name().to_string_lossy().into_owned();
        if name == ".git" {
            continue;
        }
        if name.starts_with('.') && !want_hidden {
            continue;
        }
        if !name.starts_with(frag) {
            continue;
        }
        let is_dir = entry.file_type().map(|t| t.is_dir()).unwrap_or(false);
        let suffix = if is_dir { "/" } else { "" };
        names.push(format!("{dir_part}{name}{suffix}"));
    }
    // Directories first, then files, each alphabetical — a predictable order.
    names.sort_by(|a, b| {
        let a_dir = a.ends_with('/');
        let b_dir = b.ends_with('/');
        b_dir.cmp(&a_dir).then_with(|| a.cmp(b))
    });
    names.truncate(limit);
    names
}

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 (cmds, @files) · ↑/↓ history · Ctrl+R search",
        "  Ctrl+V paste image/text · Ctrl+B background tasks · !<cmd> shell alias",
        "  exit: Ctrl-C twice / Ctrl-D",
        "  steer while busy: type and Enter to queue · cancel turn: Esc twice",
        "  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 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::{MessageId, SessionId, TurnId};

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

    #[tokio::test]
    async fn last_assistant_message_ignores_later_non_assistant_lines() {
        let mut test = app_with_llmsim().await;
        test.app.lines.extend([
            ChatLine {
                author: Author::Assistant,
                text: "first".into(),
            },
            ChatLine {
                author: Author::Tool,
                text: "tool output".into(),
            },
            ChatLine {
                author: Author::Assistant,
                text: "last answer".into(),
            },
            ChatLine {
                author: Author::System,
                text: "done".into(),
            },
        ]);

        assert_eq!(test.app.last_assistant_message(), Some("last answer"));
    }

    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::tui::host_ui::HostUi for NoopUi {
            fn send(&self, _: crate::tui::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 code_fence_gets_language_aware_highlighting() {
        let mut lines: Vec<Line> = Vec::new();
        append_markdown_lines(
            &mut lines,
            "",
            Style::default(),
            "```rust\nfn demo() {}\n```",
            80,
        );
        let text: String = lines
            .iter()
            .flat_map(|line| line.spans.iter())
            .map(|span| span.content.as_ref())
            .collect();
        assert!(
            text.contains("fn demo() {}"),
            "code content should render: {text:?}"
        );
        // Tree-sitter highlighting must color at least one token gold (keyword),
        // proving the language-aware path ran rather than the flat fallback.
        let has_keyword_color = lines
            .iter()
            .flat_map(|line| line.spans.iter())
            .any(|span| span.style.fg == Some(ACCENT_GOLD));
        assert!(
            has_keyword_color,
            "rust fence should be syntax-highlighted: {lines:?}"
        );
    }

    #[test]
    fn transcript_paragraph_links_urls() {
        let mut lines: Vec<Line> = Vec::new();
        append_markdown_lines(
            &mut lines,
            "",
            Style::default(),
            "Visit https://rust-lang.org for docs",
            120,
        );
        let has_link = lines.iter().flat_map(|line| line.spans.iter()).any(|span| {
            span.content.contains("https://rust-lang.org")
                && span.style.add_modifier.contains(Modifier::UNDERLINED)
        });
        assert!(
            has_link,
            "paragraph URL should be styled as a link: {lines:?}"
        );
    }

    #[test]
    fn transcript_markdown_renders_commonmark_emphasis() {
        // Assistant transcript now flows through tuika's CommonMark renderer, so
        // inline **bold** / *italic* are resolved — the previous line-oriented
        // formatter could not. Drive the real transcript entry point
        // (`append_chat_lines` for an assistant line) and assert on the
        // presentation model (styled spans), not the terminal buffer.
        let mut lines: Vec<Line> = Vec::new();
        append_chat_lines(
            &mut lines,
            &ChatLine {
                author: Author::Assistant,
                text: "a **bold** and *italic* word".to_string(),
            },
            80,
        );
        let spans: Vec<&Span> = lines.iter().flat_map(|line| line.spans.iter()).collect();
        let bold = spans
            .iter()
            .find(|s| s.content.contains("bold"))
            .expect("a span carrying the bold word");
        assert!(
            bold.style.add_modifier.contains(Modifier::BOLD),
            "**bold** should render bold: {lines:?}"
        );
        let italic = spans
            .iter()
            .find(|s| s.content.contains("italic"))
            .expect("a span carrying the italic word");
        assert!(
            italic.style.add_modifier.contains(Modifier::ITALIC),
            "*italic* should render italic: {lines:?}"
        );
    }

    #[test]
    fn history_search_preview_line_shows_query_and_no_match_flag() {
        let matched = HistorySearchView {
            query: "deploy".to_string(),
            matched: true,
        };
        let rendered = line_text(&history_search_preview_line(&matched, 96));
        assert!(rendered.starts_with("(reverse-search) 'deploy'"));
        assert!(!rendered.contains("no match"));

        let missed = HistorySearchView {
            query: "zzz".to_string(),
            matched: false,
        };
        let rendered = line_text(&history_search_preview_line(&missed, 96));
        assert!(rendered.contains("'zzz'"));
        assert!(rendered.contains("no match"));
    }

    #[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 split_trailing_token_isolates_the_last_word() {
        assert_eq!(
            split_trailing_token("explain @src/ma"),
            ("explain ", "@src/ma")
        );
        assert_eq!(split_trailing_token("@src"), ("", "@src"));
        assert_eq!(split_trailing_token(""), ("", ""));
    }

    #[test]
    fn list_path_completions_scopes_by_prefix_and_hides_dotfiles() {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path();
        std::fs::create_dir(root.join("src")).unwrap();
        std::fs::create_dir(root.join(".git")).unwrap();
        std::fs::write(root.join("src/main.rs"), b"").unwrap();
        std::fs::write(root.join("src/lib.rs"), b"").unwrap();
        std::fs::write(root.join("README.md"), b"").unwrap();
        std::fs::write(root.join(".env"), b"").unwrap();

        // Bare prefix: directories first, dotfiles and .git hidden.
        let top = list_path_completions(root, "", 12);
        assert_eq!(top, vec!["src/".to_string(), "README.md".to_string()]);

        // Into a directory.
        let inside = list_path_completions(root, "src/", 12);
        assert_eq!(
            inside,
            vec!["src/lib.rs".to_string(), "src/main.rs".to_string()]
        );

        // Filename fragment filters within a directory.
        let filtered = list_path_completions(root, "src/ma", 12);
        assert_eq!(filtered, vec!["src/main.rs".to_string()]);

        // Explicitly typing a dot reveals dotfiles.
        let dotted = list_path_completions(root, ".e", 12);
        assert_eq!(dotted, vec![".env".to_string()]);
    }

    #[test]
    fn file_path_suggestions_only_fire_on_at_mentions() {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path();
        std::fs::write(root.join("hello.txt"), b"").unwrap();

        assert!(file_path_suggestions("no mention here", root).is_none());

        let suggestions =
            file_path_suggestions("please read @hel", root).expect("mention suggestions");
        assert_eq!(suggestions.len(), 1);
        assert_eq!(suggestions[0].label, "@hello.txt");
        // The completion rebuilds the whole line with the mention replaced.
        assert_eq!(suggestions[0].completion, "please read @hello.txt");
    }

    #[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");
    }

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

        // Type "ac", move left, insert "b" → "abc", move right, newline, "d".
        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::SHIFT),
            KeyEvent::new(KeyCode::Char('d'), KeyModifiers::empty()),
        ] {
            app.handle_key(key).await;
        }

        assert_eq!(app.composer.text(), "abc\nd");
    }

    #[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": "/repo/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(),
                message_id: MessageId::new(),
                model: None,
                iteration: Some(3),
                phase: None,
            },
        );

        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 message_id = MessageId::new();

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

        let more = RuntimeEvent::new(
            SessionId::new(),
            EventContext::empty(),
            OutputMessageDeltaData {
                turn_id,
                message_id,
                delta: "lo, world".to_string(),
                accumulated: "Hello, world".to_string(),
                phase: None,
            },
        );
        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: "--- /repo/src/app.rs (before)\n+++ /repo/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 stderr_lines_use_a_red_dot_marker() {
        let mut lines = Vec::new();
        append_chat_lines(
            &mut lines,
            &ChatLine {
                author: Author::Stderr,
                text: "stderr:\nOperation not permitted".to_string(),
            },
            96,
        );

        assert!(line_text(&lines[0]).starts_with("         ● stderr:"));
        assert_eq!(lines[0].spans[0].style.fg, Some(ERROR_RED));
    }

    #[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 /repo/src/app/render.rs".into(),
            },
            ChatLine {
                author: Author::ToolDetail,
                text: "stdout: output with a long uninterrupted token abcdefghijklmnopqrstuvwxyz"
                    .into(),
            },
            ChatLine {
                author: Author::Stderr,
                text: "stderr: permission denied for a deliberately-long-path".into(),
            },
            ChatLine {
                author: Author::Sandbox,
                text: "native sandbox likely blocked this operation".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_or_diff_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));
        assert!(!should_insert_chat_gap(&Author::Diff, Some(&Author::Diff)));
        assert!(should_insert_chat_gap(
            &Author::Diff,
            Some(&Author::Assistant)
        ));
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn recent_transcript_mirror_includes_image_notice_before_first_chat() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.lines = vec![ChatLine {
            author: Author::System,
            text: "workspace: /tmp".into(),
        }];
        app.push_system("attached clipboard image #1 (640x480 PNG)".into());

        let visible = recent_transcript_lines(app, 80, 10);
        let visible = visible.iter().map(line_text).collect::<Vec<_>>();
        assert!(visible.iter().any(|line| line.contains("workspace: /tmp")));
        assert!(
            visible
                .iter()
                .any(|line| line.contains("attached clipboard image #1 (640x480 PNG)"))
        );
    }

    // ====================================================================
    // 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::TerminalOptions;
    use ratatui::Viewport;
    use ratatui::backend::TestBackend;
    use ratatui::layout::Position;

    struct InlineComposerRender {
        lines: Vec<String>,
        scrollback_height: u16,
        viewport_bottom: u16,
    }

    /// Render the composer through the same inline viewport + bottom anchoring
    /// path the real TUI uses (`Terminal::with_options` + `maybe_reanchor`).
    fn inline_terminal(width: u16, height: u16) -> Terminal<TestBackend> {
        let mut backend = TestBackend::new(width, height);
        backend
            .set_cursor_position(Position { x: 0, y: 1 })
            .unwrap();
        let mut terminal = Terminal::with_options(
            backend,
            TerminalOptions {
                viewport: Viewport::Inline(COMPOSER_VIEWPORT_HEIGHT),
            },
        )
        .expect("terminal");
        maybe_reanchor_inline_viewport(&mut terminal).expect("anchor inline viewport");
        terminal
    }

    fn inline_transcript_rows(terminal: &mut Terminal<TestBackend>) -> Vec<String> {
        let viewport_top = terminal.get_frame().area().y;
        let buffer = terminal.backend().buffer();
        let height = buffer.area.height;
        let width = buffer.area.width;
        (viewport_top..height)
            .map(|y| {
                let mut row = String::with_capacity(width as usize);
                for x in 0..width {
                    row.push_str(buffer[(x, y)].symbol());
                }
                row.trim_end().to_string()
            })
            .filter(|row| row.contains(''))
            .collect()
    }

    fn render_inline_composer(
        app: &mut App,
        width: u16,
        terminal_height: u16,
        cursor_row: u16,
    ) -> InlineComposerRender {
        let mut backend = TestBackend::new(width, terminal_height);
        backend
            .set_cursor_position(Position {
                x: 0,
                y: cursor_row,
            })
            .unwrap();
        let mut terminal = Terminal::with_options(
            backend,
            TerminalOptions {
                viewport: Viewport::Inline(COMPOSER_VIEWPORT_HEIGHT),
            },
        )
        .expect("terminal");
        maybe_reanchor_inline_viewport(&mut terminal).expect("anchor inline viewport");
        terminal.draw(|f| draw(f, app)).expect("draw");
        let viewport = terminal.get_frame().area();
        let buffer = terminal.backend().buffer();
        let lines = (0..buffer.area.height)
            .map(|y| {
                let mut row = String::with_capacity(buffer.area.width as usize);
                for x in 0..buffer.area.width {
                    row.push_str(buffer[(x, y)].symbol());
                }
                row.trim_end().to_string()
            })
            .collect();
        InlineComposerRender {
            lines,
            scrollback_height: terminal.backend().scrollback().area.height,
            viewport_bottom: viewport.y.saturating_add(viewport.height),
        }
    }

    fn presentation_state_idle() -> PresentationState {
        PresentationState {
            stream_preview: None,
            busy: false,
            queued_messages: 0,
            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,
            turn_elapsed_secs: None,
            context_used_tokens: None,
            context_window_tokens: None,
            compaction_budget_percent: 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,
            extension_status: Vec::new(),
        }
    }

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

    #[test]
    fn status_bar_shows_background_task_count() {
        let state = ViewState {
            presentation: PresentationState {
                status_layout: StatusLayout::Expanded,
                background: Some(crate::tui::session_tasks_view::BackgroundCounts {
                    running: 1,
                    scheduled: 0,
                    total: 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 running · 0 scheduled · 2 total"),
            "status should distinguish running, scheduled, and 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()
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn fullscreen_matches_regular_presentation() {
        let mut test = app_with_llmsim().await;
        // Dismiss the first-run setup overlay so the base transcript is visible;
        // overlay compositing is covered by the tuika suite.
        test.app.setup = None;
        test.app.push_user("hello from user".to_string());
        // Both renderers share one composer model, so the same draft appears in
        // either mode.
        test.app.composer.set_text("draft reply");

        test.app.set_render_mode(RenderMode::Inline);
        let regular = render_app_lines(&mut test.app, 60, 20).join("\n");
        test.app.set_render_mode(RenderMode::Fullscreen);
        let fullscreen = render_app_lines(&mut test.app, 60, 20).join("\n");

        // Full-screen is composed with tuika and is *visually equivalent* to the
        // inline renderer (not necessarily byte-identical): the same transcript,
        // separators, composer prompt, and status content appear in both.
        for needle in ["hello from user", "draft reply", "llmsim", "───", "> "] {
            assert!(
                fullscreen.contains(needle),
                "full-screen should render {needle:?}: {fullscreen}"
            );
            assert!(
                regular.contains(needle),
                "inline should render {needle:?}: {regular}"
            );
        }
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn fullscreen_renders_blue_and_gold_separators() {
        use ratatui::backend::TestBackend;
        let mut test = app_with_llmsim().await;
        test.app.setup = None;
        test.app.set_render_mode(RenderMode::Fullscreen);
        test.app.push_user("hello".to_string());

        let backend = TestBackend::new(60, 20);
        let mut terminal = Terminal::new(backend).expect("terminal");
        terminal.draw(|f| draw(f, &mut test.app)).expect("draw");
        let buffer = terminal.backend().buffer();

        // tuika paints the message separator in blue and the status separator in
        // gold — the design's "blue/gold line". Find a rule cell of each color.
        let mut blue_rule = false;
        let mut gold_rule = false;
        for y in 0..buffer.area.height {
            for x in 0..buffer.area.width {
                let cell = &buffer[(x, y)];
                if cell.symbol() == "" {
                    blue_rule |= cell.fg == ACCENT_BLUE;
                    gold_rule |= cell.fg == ACCENT_GOLD;
                }
            }
        }
        assert!(
            blue_rule,
            "message separator should render in blue via tuika"
        );
        assert!(
            gold_rule,
            "status separator should render in gold via tuika"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn fullscreen_composer_renders_multiline_input_via_tuika() {
        use ratatui::backend::TestBackend;
        let mut test = app_with_llmsim().await;
        test.app.setup = None;
        test.app.set_render_mode(RenderMode::Fullscreen);
        // Two composer rows in full-screen's own model of record (the tuika
        // TextInputState); the TextInput must render both, after the blue "> ".
        test.app.composer.set_text("first line\nsecond line");

        let backend = TestBackend::new(60, 20);
        let mut terminal = Terminal::new(backend).expect("terminal");
        terminal.draw(|f| draw(f, &mut test.app)).expect("draw");
        let buffer = terminal.backend().buffer();

        let text: String = (0..buffer.area.height)
            .map(|y| {
                (0..buffer.area.width)
                    .map(|x| buffer[(x, y)].symbol().to_string())
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n");
        for needle in ["first line", "second line", "> "] {
            assert!(
                text.contains(needle),
                "tuika composer should render {needle:?}:\n{text}"
            );
        }
        // The blue prompt is bold accent-blue at the composer's left edge.
        let has_prompt = (0..buffer.area.height).any(|y| {
            let cell = &buffer[(0, y)];
            cell.symbol() == ">" && cell.fg == ACCENT_BLUE
        });
        assert!(has_prompt, "the blue '>' prompt should render");
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn fullscreen_keys_route_into_the_composer() {
        let mut test = app_with_llmsim().await;
        test.app.setup = None;
        test.app.set_render_mode(RenderMode::Fullscreen);
        // Editing keys drive the shared TextInputState (component-driven input).
        for c in "hi".chars() {
            test.app
                .handle_key(KeyEvent::new(KeyCode::Char(c), KeyModifiers::empty()))
                .await;
        }
        test.app
            .handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::SHIFT))
            .await;
        test.app
            .handle_key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::empty()))
            .await;
        assert_eq!(test.app.composer.text(), "hi\nx");
    }

    #[test]
    fn fullscreen_theme_uses_yolop_palette_not_tuika_default() {
        // Full-screen builds its own tuika Theme from yolop's palette (item 6),
        // rather than inheriting tuika's neutral toolkit default.
        let theme = fullscreen::yolop_theme();
        assert_eq!(theme.accent, ACCENT_BLUE);
        assert_eq!(theme.accent_alt, ACCENT_GOLD);
        assert_eq!(theme.surface, PANEL_BG);
        // tuika's default is a different (red) identity.
        assert_ne!(theme.accent, tuika::Theme::default().accent);
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn fullscreen_model_picker_is_a_windowed_selectlist() {
        let mut test = app_with_llmsim().await;
        // The model list renders as a windowed tuika SelectList (item 4 / PR J).
        test.app.setup = Some(SetupStep::PickModel {
            provider: "openai".to_string(),
            selected: 0,
            custom: None,
            error: None,
        });
        let picker = render::setup_picker(&test.app).expect("model list is a picker");
        assert_eq!(picker.viewport, Some(render::MAX_VISIBLE_MODEL_ROWS as u16));
        assert!(!picker.options.is_empty(), "model list has options");
        // The custom-id sub-mode is a text input, not a list, so it falls back to
        // the shared text panel path (not a picker).
        test.app.setup = Some(SetupStep::PickModel {
            provider: "openai".to_string(),
            selected: 0,
            custom: Some("my-model".to_string()),
            error: None,
        });
        assert!(
            render::setup_picker(&test.app).is_none(),
            "custom-id sub-mode is not a SelectList picker"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn fullscreen_setup_overlay_renders_via_tuika() {
        use ratatui::backend::TestBackend;
        let mut test = app_with_llmsim().await;
        test.app.set_render_mode(RenderMode::Fullscreen);
        // First-run setup overlay is present; it should composite as a tuika
        // overlay — a bordered panel with the setup content.
        assert!(test.app.setup.is_some(), "first run should offer setup");

        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).expect("terminal");
        terminal.draw(|f| draw(f, &mut test.app)).expect("draw");
        let buffer = terminal.backend().buffer();

        let text: String = (0..buffer.area.height)
            .map(|y| {
                (0..buffer.area.width)
                    .map(|x| buffer[(x, y)].symbol().to_string())
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n");
        assert!(
            text.contains("Set Up Yolop"),
            "setup overlay title should render:\n{text}"
        );
        // tuika's Boxed draws a rounded border — find one of its corners.
        let has_border = (0..buffer.area.height).any(|y| {
            (0..buffer.area.width).any(|x| matches!(buffer[(x, y)].symbol(), "" | "" | "" | ""))
        });
        assert!(has_border, "the tuika overlay panel should draw a border");
        // The provider list is a tuika SelectList (item 4): the selected row is
        // caret-marked and highlighted with the theme's selection background
        // (yolop's accent, via yolop_theme).
        let has_caret = (0..buffer.area.height)
            .any(|y| (0..buffer.area.width).any(|x| buffer[(x, y)].symbol() == ""));
        assert!(
            has_caret,
            "the SelectList should mark the selected row:\n{text}"
        );
        let has_selection_bg = (0..buffer.area.height)
            .any(|y| (0..buffer.area.width).any(|x| buffer[(x, y)].bg == ACCENT_BLUE));
        assert!(
            has_selection_bg,
            "the selected row should use the theme selection background"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn fullscreen_scroll_wheel_unsticks_from_bottom() {
        let mut test = app_with_llmsim().await;
        test.app.set_render_mode(RenderMode::Fullscreen);
        for i in 0..80 {
            test.app.push_user(format!("line {i}"));
        }
        // Draw once so scroll metrics reflect the tall transcript.
        let _ = render_app_lines(&mut test.app, 40, 12);
        assert!(test.app.scroll.is_stuck_to_bottom());
        // A wheel-up should be consumed and detach from the bottom.
        assert!(test.app.handle_fullscreen_scroll(MouseEventKind::ScrollUp));
        assert!(!test.app.scroll.is_stuck_to_bottom());
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn fullscreen_scroll_reveals_full_history() {
        let mut test = app_with_llmsim().await;
        test.app.setup = None;
        test.app.set_render_mode(RenderMode::Fullscreen);
        for i in 0..80 {
            test.app.push_user(format!("line {i}"));
        }
        // Bottom-stuck by default: the newest line is visible, the oldest is
        // scrolled off the top.
        let bottom = render_app_lines(&mut test.app, 40, 12).join("\n");
        assert!(
            bottom.contains("line 79"),
            "newest line should be visible at the bottom:\n{bottom}"
        );
        assert!(
            !bottom.contains("line 0"),
            "oldest line should be scrolled off:\n{bottom}"
        );
        // Scroll to the very top: the *full* history is reachable — the old
        // recent-tail mirror could never render "line 0". Startup lines now
        // precede it in the same transcript, so scan until chat begins.
        test.app.scroll.jump_to_top();
        let mut history = render_app_lines(&mut test.app, 40, 12).join("\n");
        for _ in 0..100 {
            if history.contains("line 0") {
                break;
            }
            test.app
                .handle_fullscreen_scroll(MouseEventKind::ScrollDown);
            history.push_str(&render_app_lines(&mut test.app, 40, 12).join("\n"));
        }
        assert!(
            history.contains("line 0"),
            "oldest chat line should be reachable after the startup transcript:\n{history}"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn fullscreen_wrap_cache_matches_full_rebuild() {
        let mut test = app_with_llmsim().await;
        test.app.setup = None;
        test.app.set_render_mode(RenderMode::Fullscreen);
        let width = 40;

        let text_of = |lines: &[Line<'static>]| -> Vec<String> {
            lines
                .iter()
                .map(|l| l.spans.iter().map(|s| s.content.to_string()).collect())
                .collect()
        };
        // A from-scratch reference: one full pass over the whole history.
        let full_rebuild = |app: &App, w: usize| -> Vec<Line<'static>> {
            let mut lines = Vec::new();
            append_transcript_range(&mut lines, &app.lines, 0, w, None);
            lines
        };

        // Prime the cache on an initial batch, then append more of a different
        // author (which exercises the inter-author gap across the resume
        // boundary) and read the cache again — the incrementally-built result
        // must match a full from-scratch rebuild exactly.
        for i in 0..30 {
            test.app.push_user(format!(
                "user message {i} long enough to wrap at width forty here"
            ));
        }
        let _ = test.app.full_transcript_lines_cached(width);
        for i in 0..30 {
            test.app.push_system(format!("system note {i}"));
        }
        let incremental = test.app.full_transcript_lines_cached(width);
        assert_eq!(
            text_of(&incremental),
            text_of(&full_rebuild(&test.app, width)),
            "incremental wrap cache drifted from a full rebuild"
        );

        // A width change must invalidate and rebuild rather than reuse the old
        // wrapping.
        let narrower = test.app.full_transcript_lines_cached(24);
        assert_eq!(
            text_of(&narrower),
            text_of(&full_rebuild(&test.app, 24)),
            "width change did not rebuild the wrap cache"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn trim_transcript_caps_fullscreen_history() {
        let mut test = app_with_llmsim().await;
        test.app.setup = None;
        test.app.set_render_mode(RenderMode::Fullscreen);
        for i in 0..(MAX_RETAINED_TRANSCRIPT_LINES + 100) {
            test.app.push_user(format!("l{i}"));
        }
        let gen_before = test.app.transcript_generation;
        test.app.trim_transcript();
        assert_eq!(
            test.app.lines.len(),
            MAX_RETAINED_TRANSCRIPT_LINES,
            "full-screen history should be capped at the retention window"
        );
        assert!(
            test.app.transcript_generation > gen_before,
            "trimming must invalidate the wrap cache"
        );
        // Newest lines survive; the oldest were dropped from the front.
        assert_eq!(test.app.lines.last().unwrap().text, "l50099");
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn trim_transcript_keeps_unflushed_inline_lines() {
        let mut test = app_with_llmsim().await;
        test.app.setup = None;
        // Inline mode (the default): lines past `printed_lines` have not been
        // flushed into native scrollback yet and must not be dropped.
        for i in 0..(MAX_RETAINED_TRANSCRIPT_LINES + 100) {
            test.app.push_user(format!("l{i}"));
        }
        let before = test.app.lines.len();
        test.app.trim_transcript();
        assert_eq!(
            test.app.lines.len(),
            before,
            "inline mode must not drop lines still awaiting flush"
        );
        // Once flushed, the flushed prefix can be trimmed down to the cap.
        test.app.printed_lines = test.app.lines.len();
        test.app.trim_transcript();
        assert_eq!(test.app.lines.len(), MAX_RETAINED_TRANSCRIPT_LINES);
        assert_eq!(test.app.printed_lines, MAX_RETAINED_TRANSCRIPT_LINES);
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn fullscreen_ctrl_click_resolves_visible_url() {
        let mut test = app_with_llmsim().await;
        test.app.setup = None;
        test.app.set_render_mode(RenderMode::Fullscreen);
        let area = Rect::new(2, 3, 40, 1);
        test.app.set_selection_area(area);
        let event = MouseEvent {
            kind: MouseEventKind::Up(MouseButton::Left),
            column: area.x + 10,
            row: area.y,
            modifiers: KeyModifiers::CONTROL,
        };
        assert!(test.app.handle_fullscreen_selection(event));
        let mut buffer = ratatui::buffer::Buffer::empty(Rect::new(0, 0, 50, 8));
        buffer.set_string(
            area.x,
            area.y,
            "see https://example.com/docs now",
            Style::default(),
        );
        test.app.resolve_link_click(&buffer);
        assert_eq!(
            test.app.take_pending_open_url().as_deref(),
            Some("https://example.com/docs")
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn fullscreen_mouse_drag_selects_and_copies_transcript() {
        let mut test = app_with_llmsim().await;
        test.app.setup = None;
        test.app.set_render_mode(RenderMode::Fullscreen);
        test.app.push_user("hello from user".to_string());

        // First draw records the transcript's selectable inner rect.
        let _ = render_app_lines(&mut test.app, 60, 12);
        let area = test.app.selection_area;
        assert!(
            area.width > 0 && area.height > 0,
            "the draw should record the transcript rect"
        );

        // Drag across the bottom transcript row (where the pushed line renders).
        let row = area.bottom() - 1;
        let ev = |kind, column| MouseEvent {
            kind,
            column,
            row,
            modifiers: KeyModifiers::empty(),
        };
        assert!(
            test.app
                .handle_fullscreen_selection(ev(MouseEventKind::Down(MouseButton::Left), area.x))
        );
        assert!(
            test.app.handle_fullscreen_selection(ev(
                MouseEventKind::Drag(MouseButton::Left),
                area.x + 5
            ))
        );
        assert!(test.app.handle_fullscreen_selection(ev(
            MouseEventKind::Up(MouseButton::Left),
            area.right() - 1
        )));

        let range = test
            .app
            .selection_range()
            .expect("a left-drag builds a selection");
        assert!(test.app.pending_copy, "releasing the drag arms the copy");

        // Second draw: highlights the selection and performs the deferred copy.
        let backend = TestBackend::new(60, 12);
        let mut terminal = Terminal::new(backend).expect("terminal");
        terminal.draw(|f| draw(f, &mut test.app)).expect("draw");
        assert!(!test.app.pending_copy, "the draw consumes the pending copy");

        let buffer = terminal.backend().buffer();
        let highlighted = (range.start.0..=range.end.0).any(|x| {
            buffer[(x, row)]
                .modifier
                .contains(ratatui::style::Modifier::REVERSED)
        });
        assert!(highlighted, "the selected row should be highlighted");
        let text = tuika::selected_text(buffer, test.app.selection_area, range);
        assert!(
            text.contains("hello"),
            "the selection should copy the transcript text, got {text:?}"
        );

        // Scrolling clears the stale selection.
        test.app.handle_fullscreen_scroll(MouseEventKind::ScrollUp);
        assert!(test.app.selection_range().is_none());
    }

    /// Render the same app state in regular and full-screen mode and return
    /// `(fullscreen_rows, regular_rows)`. Full-screen now routes through the
    /// shared presentation renderer (`render::draw_shared`), so the buffers
    /// must be byte-for-byte identical — this is the helper the
    /// unified-presentation parity tests build on.
    fn render_regular_and_fullscreen(
        app: &mut App,
        width: u16,
        height: u16,
    ) -> (Vec<String>, Vec<String>) {
        app.set_render_mode(RenderMode::Inline);
        let regular = render_app_lines(app, width, height);
        app.set_render_mode(RenderMode::Fullscreen);
        let fullscreen = render_app_lines(app, width, height);
        (fullscreen, regular)
    }

    /// `fullscreen_matches_regular_presentation` pins parity for the base
    /// transcript state; this widens that guard to the states most likely to
    /// tempt a mode-specific rendering fork — a busy turn with a token count, an
    /// extension-pushed status segment, an open setup overlay, an overflowing
    /// transcript, and an oversized paste in the composer. If any of these ever
    /// diverges between the two modes, the unified-presentation invariant has
    /// regressed.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn fullscreen_shares_regular_presentation_across_states() {
        type Mutate = fn(&mut App);
        // (name, state mutation, a substring the frame must contain — empty to
        // skip the content check, e.g. for the overlay case whose exact copy
        // lives elsewhere).
        let cases: &[(&str, Mutate, &str)] = &[
            (
                "busy turn with tokens",
                |app| {
                    app.busy = true;
                    app.session_tokens = Some(4096);
                    app.push_user("hello from user".to_string());
                },
                "hello from user",
            ),
            (
                "extension status segment",
                |app| {
                    app.extension_status
                        .insert("ext:lsp".to_string(), "indexing".to_string());
                    app.push_user("hello from user".to_string());
                },
                "hello from user",
            ),
            (
                "open setup overlay",
                |app| {
                    app.setup = Some(SetupStep::Provider { selected: 0 });
                },
                "",
            ),
            (
                "transcript taller than the viewport",
                |app| {
                    for i in 0..80 {
                        app.push_user(format!("line {i}"));
                    }
                },
                "",
            ),
            (
                "oversized paste in the composer",
                |app| {
                    let paste = (0..40)
                        .map(|i| format!("pasteline{i}"))
                        .collect::<Vec<_>>()
                        .join("\n");
                    app.composer.insert_str(&paste);
                },
                "",
            ),
        ];

        for (name, mutate, needle) in cases {
            let mut test = app_with_llmsim().await;
            // Start from a dismissed first-run overlay; cases that want it re-open
            // it themselves.
            test.app.setup = None;
            mutate(&mut test.app);

            let (fullscreen, regular) = render_regular_and_fullscreen(&mut test.app, 60, 20);

            // Visual equivalence (tuika full-screen vs inline): both render a
            // non-blank frame and, where checked, the same key content.
            assert!(
                fullscreen.iter().any(|row| !row.is_empty()),
                "state {name} should render a non-blank frame"
            );
            if !needle.is_empty() {
                let fs = fullscreen.join("\n");
                let reg = regular.join("\n");
                assert!(
                    fs.contains(needle),
                    "full-screen state {name} should render {needle:?}: {fs}"
                );
                assert!(
                    reg.contains(needle),
                    "inline state {name} should render {needle:?}: {reg}"
                );
            }
        }
    }

    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::config::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,
        }
    }

    #[tokio::test]
    async fn sandbox_approval_can_be_granted_for_the_session() {
        let mut test = app_with_llmsim().await;
        let (reply, answer) = oneshot::channel();
        test.app.pending_sandbox_approval = Some(PendingSandboxApproval { reply });

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

        assert_eq!(
            answer.await.unwrap(),
            crate::sandbox_approval::ApprovalDecision::ApproveForSession
        );
        assert!(test.app.pending_sandbox_approval.is_none());
        assert!(test.app.lines.iter().any(|line| {
            line.author == Author::System && line.text == "approved for this session"
        }));
    }

    /// 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 setup_picker_navigation_clamps_at_ends() {
        let mut test = app_with_llmsim().await;
        let app = &mut test.app;
        app.setup = Some(SetupStep::Provider { selected: 0 });

        fn provider_selected(app: &App) -> usize {
            match app.setup {
                Some(SetupStep::Provider { selected }) => selected,
                _ => panic!("expected the provider step"),
            }
        }

        // Up at the top holds at 0 — navigation clamps, it does not wrap.
        app.handle_setup_key(KeyEvent::new(KeyCode::Up, KeyModifiers::empty()))
            .await;
        assert_eq!(provider_selected(app), 0);

        // Down walks forward one row at a time and clamps at the last option
        // even when pressed past the end.
        let last = PROVIDER_OPTIONS.len() - 1;
        for _ in 0..last + 3 {
            app.handle_setup_key(KeyEvent::new(KeyCode::Down, KeyModifiers::empty()))
                .await;
        }
        assert_eq!(provider_selected(app), last);
    }

    #[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(crate::tui::session_tasks_view::BackgroundCounts {
                running: 1,
                scheduled: 0,
                total: 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 running, 0 scheduled"),
            "panel should summarize session tasks: {lines}"
        );
        assert!(
            lines.contains("[task_panel] background_tool running: write marker"),
            "panel should list the session task row: {lines}"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn presentation_state_exposes_sandbox_and_hard_approval_matrix() {
        let test = app_with_llmsim().await;
        test.app
            .settings
            .set_sandbox_mode(crate::config::SandboxMode::ReadOnly)
            .unwrap();
        test.app
            .settings
            .set_approval_policy(crate::config::ApprovalPolicy::Never)
            .unwrap();

        assert_eq!(
            test.app.presentation_state().approval_mode,
            "normal · read-only · never"
        );
    }

    #[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().await;
        }

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

        /// 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::ContextUsed(used)) => {
                            self.context_used_tokens = Some(used);
                        }
                        Ok(TurnEvent::Done) => {
                            self.finish_busy();
                            self.start_next_queued_turn();
                        }
                        Ok(TurnEvent::Failed(err)) => {
                            self.finish_busy();
                            self.push_system(format!("turn failed: {err}"));
                            self.start_next_queued_turn();
                        }
                        Err(mpsc::error::TryRecvError::Empty) => {}
                        Err(mpsc::error::TryRecvError::Disconnected) => {
                            self.finish_busy();
                            self.start_next_queued_turn();
                        }
                    }
                }
                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::config::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::config::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 undo_command_refreshes_visible_branch_and_restores_prompt() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = None;
        app.lines.clear();

        for prompt in ["first turn", "second turn"] {
            app.set_input_text(prompt.to_string());
            app.submit_input().await;
            app.pump_turn_until_idle_for_test().await;
        }

        let preview = app
            .session
            .execute_command("undo", None)
            .await
            .expect("preview undo");
        let token = preview
            .message
            .lines()
            .last()
            .and_then(|line| line.split('`').nth(1))
            .expect("confirmation token");
        let restored = app
            .session
            .execute_command("undo", Some(format!("confirm {token}")))
            .await
            .expect("confirm undo");
        app.refresh_after_checkpoint_restore(restored.message).await;

        assert!(
            app.lines
                .iter()
                .any(|line| { matches!(line.author, Author::User) && line.text == "first turn" })
        );
        assert!(
            !app.lines
                .iter()
                .any(|line| { matches!(line.author, Author::User) && line.text == "second turn" })
        );
        assert_eq!(app.input_text(), "second turn");

        let session_id = fixture.app.session.session_id();
        let workspace_root = fixture._workspace.path().to_path_buf();
        let sessions_root = fixture._sessions.path().to_path_buf();
        drop(fixture.app);
        let settings = std::sync::Arc::new(crate::config::SettingsStore::open(
            sessions_root.join("settings.toml"),
        ));
        let resumed = crate::runtime::build_with_options(
            workspace_root,
            crate::runtime::ProviderChoice::Sim,
            Some(session_id),
            sessions_root,
            settings,
            crate::runtime::BuildOptions::default(),
        )
        .await
        .expect("resume rewound session");
        let resumed_text = resumed
            .handles
            .runtime
            .messages(session_id)
            .await
            .expect("resumed messages")
            .into_iter()
            .filter_map(|message| message.text().map(str::to_string))
            .collect::<Vec<_>>();
        assert!(resumed_text.iter().any(|text| text == "first turn"));
        assert!(!resumed_text.iter().any(|text| text == "second turn"));
    }

    #[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().await;

        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().await;

        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::tui::input::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 inline_viewport_mirrors_session_system_notices_after_chat() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = None;
        app.lines.clear();
        app.push_user("first question".into());
        app.lines.push(ChatLine {
            author: Author::Assistant,
            text: "first answer".into(),
        });
        app.push_system("attached clipboard image #1 (640x480 PNG)".into());

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

        assert!(
            rows.iter()
                .any(|row| row.contains("attached clipboard image #1")),
            "session system notices should mirror above the composer: {rows:?}"
        );
    }

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

        let mut terminal = inline_terminal(100, 60);
        app.flush_transcript(&mut terminal)
            .expect("flush prior turn");
        app.push_system("attached clipboard image #1 (640x480 PNG)".into());
        app.flush_transcript(&mut terminal)
            .expect("flush image notice");
        terminal.draw(|f| draw(f, app)).expect("draw after notice");

        let inline_rows = inline_transcript_rows(&mut terminal);
        let notice_row = inline_rows
            .iter()
            .position(|row| row.contains("attached clipboard image #1"))
            .expect("image paste notice in inline viewport");

        assert!(
            notice_row + 1 >= inline_rows.len().saturating_sub(1),
            "incremental system notice should sit near the composer, not above a mirrored tail: inline={inline_rows:?}"
        );
    }

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

        let mut terminal = inline_terminal(100, 60);
        app.flush_transcript(&mut terminal)
            .expect("flush prior turn");
        app.push_system("turn failed: provider timeout".into());
        app.flush_transcript(&mut terminal)
            .expect("flush turn notice");
        terminal.draw(|f| draw(f, app)).expect("draw after notice");

        let inline_rows = inline_transcript_rows(&mut terminal);
        assert!(
            inline_rows
                .iter()
                .any(|row| row.contains("turn failed: provider timeout")),
            "turn-failed notice should mirror above the composer: {inline_rows:?}"
        );
    }

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

        let rendered = render_inline_composer(app, 100, 60, 1);

        assert_eq!(
            rendered.viewport_bottom, 60,
            "inline viewport should sit flush with the terminal bottom"
        );
        assert!(
            rendered.scrollback_height < 20,
            "cursor+resize anchoring should not push a tall blank band into scrollback (height={})",
            rendered.scrollback_height
        );
    }

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

        let rendered = render_inline_composer(app, 100, 60, 1);
        let answer_row = rendered
            .lines
            .iter()
            .position(|row| row.contains("Latest answer tail"))
            .expect("recent answer rendered");
        let separator_row = rendered
            .lines
            .iter()
            .position(|row| row.contains("Enter to send"))
            .expect("message separator rendered");

        assert_eq!(
            answer_row + 1,
            separator_row,
            "flushed transcript should stay adjacent to the composer chrome: {:?}",
            rendered.lines
        );
    }

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

        assert!(
            rows.iter().any(|row| row.contains("type /help")),
            "inline rendering should show the initial help message: {rows:?}"
        );
    }

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

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

        assert!(
            rows.iter().any(|row| row.contains("type /help")),
            "fullscreen should render the same initial help message: {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_mirrors_recent_tail_after_scrollback_flush() {
        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")),
            "recent user transcript should stay visible above the composer: {rows:?}"
        );
        assert!(
            rows.iter().any(|row| row.contains("Done.")),
            "recent assistant transcript should stay visible above the composer: {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::runtime::session_log::session_dir_path(sessions.path(), session_id);
        std::fs::create_dir_all(&session_dir).expect("session dir");
        let log_path = crate::runtime::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::config::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 busy_composer_queues_messages_for_fifo_delivery() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = None;
        app.lines.clear();

        app.set_input_text("first turn".into());
        app.submit_input().await;
        assert!(app.busy);

        for ch in "steer this way".chars() {
            app.handle_key(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::empty()))
                .await;
        }
        app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::empty()))
            .await;
        app.set_input_text("then verify it".into());
        app.submit_input().await;

        assert_eq!(app.queued_messages.len(), 2);
        assert!(app.input_text().is_empty());
        assert!(app.busy, "queueing must not interrupt the active turn");

        app.pump_turn_until_idle_for_test().await;

        assert!(app.queued_messages.is_empty());
        let user_lines = app
            .lines
            .iter()
            .filter(|line| line.author == Author::User)
            .map(|line| line.text.as_str())
            .collect::<Vec<_>>();
        assert_eq!(
            user_lines,
            ["first turn", "steer this way", "then verify it"]
        );
        let assistant_count = app
            .lines
            .iter()
            .filter(|line| line.author == Author::Assistant)
            .count();
        assert_eq!(assistant_count, 3, "each queued message must be delivered");
    }

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

        app.set_input_text("cancel this turn".into());
        app.submit_input().await;
        app.set_input_text("keep this steering".into());
        app.submit_input().await;

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

        assert_eq!(app.queued_messages.len(), 1);
        app.pump_turn_until_idle_for_test().await;

        assert!(app.queued_messages.is_empty());
        assert!(
            app.lines
                .iter()
                .any(|line| { line.author == Author::User && line.text == "keep this steering" })
        );
        assert!(app.lines.iter().any(|line| {
            line.author == Author::Assistant && line.text.contains("offline mode")
        }));
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn ctrl_c_clears_busy_composer_without_interrupting_turn() {
        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.set_input_text("unsent steering draft".into());

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

        assert!(app.input_text().is_empty());
        assert!(app.busy);
        assert!(cancel_rx.try_recv().is_err());
        assert!(!app.should_quit);
    }

    #[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 mcp_reload_applies_config_live_without_restart() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;

        // The workspace declares no servers at startup.
        assert!(!app.startup.mcp_server_names.iter().any(|n| n == "docs"));

        // Write a workspace `.mcp.json` after startup, then `/mcp reload`.
        std::fs::write(
            app.startup.workspace_root.join(".mcp.json"),
            serde_json::to_vec_pretty(&serde_json::json!({
                "mcpServers": { "docs": { "type": "http", "url": "https://example.com/mcp" } }
            }))
            .unwrap(),
        )
        .expect("write .mcp.json");
        app.lines.clear();
        app.dispatch_command_for_test("mcp reload").await;

        // The server is now live on the session and reported as active — and
        // the old "restart required" guidance is gone.
        assert!(app.startup.mcp_server_names.iter().any(|n| n == "docs"));
        assert!(
            app.lines
                .iter()
                .any(|line| line.text.contains("active MCP servers: docs")),
            "reload should report the active set: {:?}",
            app.lines
        );
        assert!(
            !app.lines.iter().any(|line| line.text.contains("restart")),
            "reload must not tell the user to restart: {:?}",
            app.lines
        );

        // Disabling via `/mcp` also applies live: the server drops out.
        app.lines.clear();
        app.dispatch_command_for_test("mcp disable docs workspace")
            .await;
        assert!(
            !app.startup.mcp_server_names.iter().any(|n| n == "docs"),
            "disabling a server removes it from the live set: {:?}",
            app.startup.mcp_server_names
        );
        assert!(
            app.lines
                .iter()
                .any(|line| line.text.contains("active MCP servers")),
            "disable should report the active set: {:?}",
            app.lines
        );
    }

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

        // Unknown server: guidance to add it first, no browser attempt.
        app.lines.clear();
        app.dispatch_command_for_test("mcp login ghost").await;
        assert!(
            app.lines
                .iter()
                .any(|line| line.text.contains("`ghost` is not configured")),
            "unknown server should be reported: {:?}",
            app.lines
        );

        // A stdio server is not eligible for OAuth login.
        std::fs::write(
            app.startup.workspace_root.join(".mcp.json"),
            serde_json::to_vec_pretty(&serde_json::json!({
                "mcpServers": { "fs": { "type": "stdio", "command": "true" } }
            }))
            .unwrap(),
        )
        .expect("write .mcp.json");
        app.lines.clear();
        app.dispatch_command_for_test("mcp login fs").await;
        assert!(
            app.lines
                .iter()
                .any(|line| line.text.contains("stdio server")
                    && line.text.contains("OAuth login only applies")),
            "stdio server should be rejected before any browser flow: {:?}",
            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 up_down_recall_previous_prompts() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = None;
        app.history.record("first");
        app.history.record("second");

        let up = || KeyEvent::new(KeyCode::Up, KeyModifiers::empty());
        let down = || KeyEvent::new(KeyCode::Down, KeyModifiers::empty());

        // Up from an empty composer recalls newest-first.
        app.handle_key(up()).await;
        assert_eq!(app.input_text(), "second");
        app.handle_key(up()).await;
        assert_eq!(app.input_text(), "first");
        // Already at the oldest entry: Up holds instead of clearing.
        app.handle_key(up()).await;
        assert_eq!(app.input_text(), "first");

        // Down walks back toward newer, then restores the (empty) draft.
        app.handle_key(down()).await;
        assert_eq!(app.input_text(), "second");
        app.handle_key(down()).await;
        assert_eq!(app.input_text(), "");
        assert!(!app.history.is_browsing());
    }

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

        // A non-empty, freshly-typed draft must not be clobbered by recall.
        for ch in ['h', 'i'] {
            app.handle_key(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::empty()))
                .await;
        }
        app.handle_key(KeyEvent::new(KeyCode::Up, KeyModifiers::empty()))
            .await;
        assert_eq!(app.input_text(), "hi");
        assert!(!app.history.is_browsing());
    }

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

        // `/cwd` is a client command: it records into history but starts no turn,
        // so the app stays idle and recall stays reachable.
        for ch in ['/', 'c', 'w', 'd'] {
            app.handle_key(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::empty()))
                .await;
        }
        app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::empty()))
            .await;

        assert_eq!(app.input_text(), "");
        app.handle_key(KeyEvent::new(KeyCode::Up, KeyModifiers::empty()))
            .await;
        assert_eq!(app.input_text(), "/cwd");
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn fullscreen_renders_at_mention_suggestions() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = None;
        app.set_render_mode(RenderMode::Fullscreen);
        let root = app.startup.workspace_root.clone();
        std::fs::write(root.join("hello.txt"), b"hi").expect("write file");

        for ch in ['@', 'h', 'e', 'l'] {
            app.handle_key(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::empty()))
                .await;
        }
        let rows = render_app_lines(app, 100, 24);
        assert!(
            rows.iter().any(|row| row.contains("@hello.txt")),
            "fullscreen should render the @file hint row: {rows:?}"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn fullscreen_renders_reverse_search_prompt() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = None;
        app.set_render_mode(RenderMode::Fullscreen);
        app.history.record("deploy prod");

        app.handle_key(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL))
            .await;
        let rows = render_app_lines(app, 100, 24);
        assert!(
            rows.iter().any(|row| row.contains("reverse-search")),
            "fullscreen should render the Ctrl+R search prompt: {rows:?}"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn at_mention_completes_workspace_files() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = None;
        let root = app.startup.workspace_root.clone();
        std::fs::write(root.join("hello.txt"), b"hi").expect("write file");

        // Type "@hel" — the suggestion row should offer the matching file.
        for ch in ['@', 'h', 'e', 'l'] {
            app.handle_key(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::empty()))
                .await;
        }
        let suggestions = app.suggestions();
        assert!(
            suggestions.iter().any(|s| s.label == "@hello.txt"),
            "expected @hello.txt among {suggestions:?}"
        );

        // Tab accepts the first suggestion, completing the mention in place.
        app.handle_key(KeyEvent::new(KeyCode::Tab, KeyModifiers::empty()))
            .await;
        assert_eq!(app.input_text(), "@hello.txt");
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn ctrl_r_reverse_search_matches_narrows_and_accepts() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = None;
        for entry in ["deploy staging", "run tests", "deploy prod"] {
            app.history.record(entry);
        }

        // Ctrl+R opens search and previews the newest entry.
        app.handle_key(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL))
            .await;
        assert!(app.history_search.is_some());
        assert_eq!(app.input_text(), "deploy prod");

        // Typing narrows to the newest entry containing the query.
        for ch in ['t', 'e', 's', 't'] {
            app.handle_key(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::empty()))
                .await;
        }
        assert_eq!(app.input_text(), "run tests");
        let view = app.history_search_view().expect("search active");
        assert_eq!(view.query, "test");
        assert!(view.matched);

        // Enter accepts the match into the composer and leaves search mode.
        app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::empty()))
            .await;
        assert!(app.history_search.is_none());
        assert_eq!(app.input_text(), "run tests");
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn ctrl_r_cycles_older_matches_then_reports_no_match() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = None;
        for entry in ["deploy staging", "run tests", "deploy prod"] {
            app.history.record(entry);
        }

        app.handle_key(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL))
            .await;
        for ch in ['d', 'e', 'p', 'l', 'o', 'y'] {
            app.handle_key(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::empty()))
                .await;
        }
        // Newest "deploy" match first.
        assert_eq!(app.input_text(), "deploy prod");
        // Ctrl+R again cycles to the older "deploy" entry.
        app.handle_key(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL))
            .await;
        assert_eq!(app.input_text(), "deploy staging");

        // A query with no match clears the preview and flags it in the view.
        app.handle_key(KeyEvent::new(KeyCode::Char('z'), KeyModifiers::empty()))
            .await;
        assert_eq!(app.input_text(), "");
        assert!(!app.history_search_view().unwrap().matched);
    }

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

        // Type a draft, then search, then cancel — the draft must come back.
        for ch in ['d', 'r', 'a', 'f', 't'] {
            app.handle_key(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::empty()))
                .await;
        }
        app.handle_key(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL))
            .await;
        assert_eq!(app.input_text(), "some old prompt");
        app.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::empty()))
            .await;
        assert!(app.history_search.is_none());
        assert_eq!(app.input_text(), "draft");
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn ctrl_r_with_empty_history_is_a_no_op() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        app.setup = None;
        app.handle_key(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL))
            .await;
        assert!(app.history_search.is_none());
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn shift_enter_inserts_newline_instead_of_submitting() {
        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::SHIFT))
            .await;
        app.handle_key(KeyEvent::new(KeyCode::Char('b'), KeyModifiers::empty()))
            .await;

        assert_eq!(app.input_text(), "a\nb");
        assert!(
            !app.lines
                .iter()
                .any(|line| matches!(line.author, Author::User))
        );
    }

    #[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.composer.newline();
            assert_eq!(app.input_height(80), expected);
        }
        app.composer.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.composer.line_count(),
            1,
            "composer stays one logical line"
        );
        let input_width = 10;
        let measured = app.input_height(input_width);
        assert!(
            measured >= 2,
            "soft-wrapped composer should grow past one row (got {measured})"
        );

        // `input_height` is the composer's own visual height, clamped to the
        // bound — the App delegates straight to the shared TextInputState.
        let expected = tuika::TextInputState::from_text(&app.input_text())
            .visual_height(input_width)
            .clamp(1, MAX_INPUT_HEIGHT);
        assert_eq!(
            measured, expected,
            "composer height should match TextInput 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("Codex Subscription")),
            "provider picker should use the title-cased Codex Subscription label: {rendered:?}"
        );
        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:?}"
        );
        assert!(
            !rows.iter().any(|line| line.contains("Enter to send")),
            "the composer must not render through the setup sheet: {rows:?}"
        );
        assert!(
            rows.first().is_some_and(String::is_empty) && rows.last().is_some_and(String::is_empty),
            "the centered panel should have clean margins without underlying chrome: {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::testing::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_device_login_wait_can_be_cancelled() {
        let mut fixture = app_with_llmsim().await;
        let app = &mut fixture.app;
        let task = tokio::spawn(std::future::pending());
        app.codex_login = Some(PendingCodexLogin { id: 7, task });
        app.setup = Some(SetupStep::CodexLogin {
            selected: 1,
            method: CodexLoginMethod::Device,
            device_code: Some(("https://example.test/device".into(), "ABCD-EFGH".into())),
        });

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

        assert!(app.codex_login.is_none());
        assert!(matches!(
            app.setup,
            Some(SetupStep::Credential {
                ref provider,
                selected: 1,
                error: Some(ref error),
            }) if provider == "codex" && error == "Codex sign-in canceled"
        ));
    }

    #[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::testing::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.6-sol"));
    }

    #[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.6-sol 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 third 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::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::testing::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 == 2
        ));
    }

    #[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.6-sol 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_while_busy() {
        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,
                queued_messages: 2,
                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("2 queued") && rows[0].contains("Enter to queue"),
            "busy separator should expose steering and its queue: {}",
            rows[0]
        );
    }

    #[test]
    fn chrome_busy_shows_live_elapsed_timer() {
        let state = ViewState {
            presentation: PresentationState {
                busy: true,
                turn_activity: Some("reading files".to_string()),
                turn_elapsed_secs: Some(75),
                ..presentation_state_idle()
            },
            busy_frame: 4,
            ..view_state_idle()
        };
        let rows = render_chrome_lines(&state, 80, 4);
        assert!(
            rows[0].contains("1m15s"),
            "busy separator should show the elapsed timer: {}",
            rows[0]
        );
    }

    #[test]
    fn format_elapsed_is_compact() {
        assert_eq!(format_elapsed(8), "8s");
        assert_eq!(format_elapsed(75), "1m15s");
        assert_eq!(format_elapsed(3725), "1h02m");
    }

    #[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
        );
    }
}