eclipse-cli 0.13.4

Command-line interface for eclipse
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
//! The full-screen interface: a scrolling transcript, a composer, a live readout, and
//! approvals in a modal instead of a y/N prompt on stderr.
//!
//! Shape of it: this thread owns the terminal and blocks on a channel; the input reader
//! is its own thread; every run is a task on the tokio runtime that reports through the
//! same channel. Nothing in here awaits, so a slow model can never stall a keypress —
//! the composer stays responsive while the transcript fills in.
//!
//! The REPL (`repl.rs`) is still what runs when stdout is not a terminal, and `--plain`
//! forces it on one. That keeps piping and scripting exactly as they were.

pub mod app;
pub mod view;

use crate::approve::{Choice, SessionAllows};
use crate::bang;
use crate::farewell;
use crate::loops_cli;
use app::{Action, Activity, App, Approval, Block, NoteKind};
use eclipse_core::approvals::{Decision, Pending};
use eclipse_core::cancel::Cancel;
use eclipse_core::loops::{Owner, State as LoopState};
use eclipse_core::runtime::{Agent, AgentEvent, RunOptions};
use eclipse_core::tools::{AllowAll, Approver};
use eclipse_core::Error;
use ratatui::crossterm::event::{
    self, DisableBracketedPaste, EnableBracketedPaste, KeyCode, KeyEvent, KeyEventKind,
    KeyModifiers,
};
use ratatui::crossterm::execute;
use ratatui::widgets::Widget as _;
use std::io::Write as _;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{RecvTimeoutError, Sender};
use std::sync::Arc;
use std::time::Duration;

/// Everything the loop can wake up for.
pub enum UiEvent {
    Key(KeyEvent),
    Paste(String),
    /// The reader thread is finished: no keystroke is ever going to arrive, so the interface must
    /// not keep drawing a prompt it cannot hear (`#413`).
    Quit,
    Agent(AgentEvent),
    /// A run ended: the session id, or a message for the transcript.
    Done(Result<String, String>),
    /// Where a successful run's answer came from: the hops it took, empty when it did not hop.
    /// Sent just before `Done`.
    Routed(Vec<eclipse_core::router::Hop>),
    /// The subagents a successful run started and what they cost. Sent just before `Done`.
    Delegated(Vec<eclipse_core::tools_delegate::ChildRun>),
    Approval {
        tool: String,
        summary: String,
        reply: tokio::sync::oneshot::Sender<Choice>,
    },
    /// What the endpoint behind `route` says it serves, and what went wrong if it said nothing.
    /// The route travels with the answer so the list can be attributed to the place it came from.
    Models(Option<String>, Result<Vec<String>, String>),
    /// A `!command` that has finished: what it printed and how it ended.
    Bang(crate::bang::Ran),
    /// The stored sessions, for `/resume`.
    Sessions(Result<Vec<app::Picked>, String>),
    /// A session that has been read back: its id, its transcript, and whether it was cut off
    /// mid-tool-call.
    Resumed(Result<(String, Vec<Block>, bool), String>),
    /// What the endpoint advertises for the model now in use, after a switch, and the rail
    /// derived from it. A window of `0` leaves the readout alone: a missing window is not a
    /// reason to invent one.
    Budget {
        window: usize,
        budget: usize,
    },
    /// A loop tick's own line (`#173`): skipped, ended, or the `--until` check's verdict. Sent
    /// after the record has been written, so what the screen says is what the file says.
    LoopNote(String),
    /// Nothing happened; exists so the spinner turns and the elapsed time moves.
    Tick,
}

/// Asks the user, from inside a run, and parks until the modal answers.
struct UiApprover {
    tx: Sender<UiEvent>,
    /// Tools already allowed for this session: answered without a modal.
    allows: SessionAllows,
}

#[async_trait::async_trait]
impl Approver for UiApprover {
    async fn decide(&self, call: &Pending) -> Decision {
        let (tool, summary) = (call.tool.as_str(), call.summary.as_str());
        if self.allows.contains(tool) {
            return Decision::Allow;
        }
        let (tx, rx) = tokio::sync::oneshot::channel();
        if self
            .tx
            .send(UiEvent::Approval {
                tool: tool.to_string(),
                summary: summary.to_string(),
                reply: tx,
            })
            .is_err()
        {
            // The interface is gone and nobody can answer it here: the run stops with the call
            // on record rather than denying something the user never saw.
            return Decision::Defer;
        }
        let choice = rx.await.unwrap_or(Choice::Deny);
        if choice == Choice::Session {
            self.allows.insert(tool);
        }
        match choice {
            Choice::Deny => Decision::Deny("declined in the panel".to_string()),
            _ => Decision::Allow,
        }
    }
}

/// Restores the terminal however this function is left, panics included.
struct Terminal;

/// The live region at the bottom of the screen. The transcript is not drawn in it: the transcript
/// is printed above it, into the terminal's own scrollback, the way a command's output is. So this
/// is only as tall as the turn still being written plus the two lines that belong to the reader.
pub const LIVE_HEIGHT: u16 = 10;

impl Terminal {
    fn enter() -> anyhow::Result<(Self, ratatui::DefaultTerminal)> {
        // A clean slate before the first line: `2J` clears the screen, `H` puts the cursor at the
        // top of it, and `3J` clears the scrollback the shell left behind. Without the third one the
        // banner starts under whatever the last command printed, and the two read as one document.
        // It is also the anchor the inline viewport wants: after a clear-home the cursor is at a
        // known row, so nothing has to be guessed from what was already on screen.
        let mut out = std::io::stdout();
        let _ = write!(out, "\x1b[2J\x1b[H\x1b[3J");
        let _ = out.flush();

        // No alternate screen, and no mouse reporting, which is what makes the wheel, the text
        // selection, the right-click menu and the clipboard the terminal's own — the same bargain
        // Hermes makes, and the one a reader already knows how to use. The transcript lives in the
        // ordinary buffer, so a wheel notch scrolls real history instead of a viewport this program
        // would have to invent.
        let terminal = ratatui::init_with_options(ratatui::TerminalOptions {
            viewport: ratatui::Viewport::Inline(LIVE_HEIGHT),
        });
        // Bracketed paste, because without it every newline inside a paste arrives as `Enter`,
        // and this interface reads `Enter` as "submit". A 2 kB paste became a dozen attempts to
        // start a run, each one refused with "a run is in flight".
        let _ = execute!(out, EnableBracketedPaste);
        Ok((Self, terminal))
    }
}

impl Drop for Terminal {
    fn drop(&mut self) {
        let mut out = std::io::stdout();
        // Before `restore()`: a terminal left in bracketed-paste mode pastes escape sequences
        // into the shell prompt after the interface has exited.
        let _ = execute!(out, DisableBracketedPaste);
        ratatui::restore();
    }
}

/// `(dial, what the route offers, the config file, the profile)` — one tuple because the four are
/// always set together by the caller that read the config, and never apart.
pub type ReasoningSetup = (
    eclipse_core::reasoning::Shared,
    Option<eclipse_core::provider::Reasoning>,
    Option<std::path::PathBuf>,
    Option<String>,
);

/// What the interface needs to open, gathered by the caller that read the config.
pub struct Setup {
    pub status: crate::status::Status,
    /// Advertised tools grouped by source, for the opening pane. Built where the registry is in
    /// hand rather than reconstructed here, so the pane and `eclipse tools list` cannot disagree.
    pub groups: Vec<(String, Vec<String>)>,
    /// Skills that loaded, grouped by source, from the same discovery the prompt index uses.
    pub skills: Vec<(String, Vec<String>)>,
    pub model: String,
    pub workspace: String,
    pub profile: Option<String>,
    pub session: Option<String>,
    /// The stored transcript of `session`, when one was named. `None` means the interface starts
    /// on the welcome pane; `Some` means it starts where the last conversation stopped, and the
    /// bool says whether that conversation was cut off mid-tool-call.
    pub history: Option<(Vec<Block>, bool)>,
    /// `/yolo`: whether the next turn answers every tool call itself. Shared with the caller (and
    /// with the spawner), read per turn — a mode the session can enter and leave.
    pub yolo: crate::yolo::Yolo,
    /// The config file this process read, for `/settings` and `/set`.
    pub config_path: Option<std::path::PathBuf>,
    /// Which profile, from which file, under which home, writing sessions where — filled once by
    /// the caller that read the config, so `/profile` cannot disagree with `eclipse doctor`.
    pub place: Option<eclipse_core::config::Where>,
    /// Where the update badge is read from, when there is anything to watch. A watch rather than
    /// a string: the badge lasts as long as the install is behind, so the interface asks again
    /// instead of printing a notice that scrolls away.
    pub update: Option<eclipse_core::update::Watch>,
    /// What the exit does to the screen: `[cli] clear_on_exit`.
    pub clear_on_exit: eclipse_core::config::ClearOnExit,
    /// Where `[hooks]` hooks put their one-line reports. The full-screen UI owns the terminal,
    /// so a line on stderr would garble the screen or be lost; these are shown as notes when
    /// the run that produced them is done.
    pub hook_notes: Arc<std::sync::Mutex<Vec<String>>>,
    /// What a `!command` runs under: the same `[tools] shell_isolate` the model's `shell` gets.
    /// Built by the caller, which has the config, so the two cannot disagree about the mode.
    pub sandbox: eclipse_core::sandbox::Sandbox,
    /// `/bg` and `/tasks`: the registry and the flags a background run inherits. `None` when this
    /// session has no state directory, and then both verbs say so instead of guessing.
    pub spawner: Option<crate::bg::Spawner>,
    /// `/reasoning`: the dial, the control the next request's route resolves to (as data, so this
    /// interface never has to borrow the agent it does not own), the config file `--global` writes,
    /// and the profile that file is overlaid on.
    pub reasoning: Option<ReasoningSetup>,
}

/// Set by the terminating-signal handler. An atomic because that is the whole of what a signal
/// handler may touch: no allocation, no lock, no `std::io`.
#[cfg(unix)]
static TERMINATING: AtomicBool = AtomicBool::new(false);

#[cfg(unix)]
extern "C" fn note_termination(_: libc::c_int) {
    // `SeqCst` on both sides: the store is what the loop's load is waiting for, and the cost of one
    // atomic per signal is not a cost.
    TERMINATING.store(true, Ordering::SeqCst);
}

/// Ask to be told about `SIGTERM`, `SIGHUP` and `SIGINT` instead of dying in the middle of a frame.
///
/// `#410`: `ratatui::init_with_options` puts the terminal in raw mode and turns bracketed paste on,
/// and the only thing that gives it back is `Drop`. A `kill` or a `systemctl stop` terminates the
/// process without running destructors, so the reader is left with echo off and `?2004h` set, in a
/// shell that looks broken until they run `reset`.
///
/// `SIGINT` is here for `kill -INT` and nothing else: the keyboard's Ctrl-C never becomes a signal,
/// because raw mode turns `ISIG` off and crossterm delivers it as a key event. Handling it costs
/// one comparison and closes the hole where a script or a supervisor signals with the wrong number
/// and gets the dirty terminal anyway.
#[cfg(unix)]
fn catch_termination() {
    // SAFETY: the handler only stores to a static atomic, which is async-signal-safe. The previous
    // handler is dropped deliberately: the default for both is "die now", and that is the thing
    // being replaced.
    unsafe {
        for signal in [libc::SIGTERM, libc::SIGHUP, libc::SIGINT] {
            libc::signal(signal, note_termination as *const () as libc::sighandler_t);
        }
    }
}

#[cfg(not(unix))]
fn catch_termination() {}

/// Whether a terminating signal has been caught since this process started.
fn terminating() -> bool {
    #[cfg(unix)]
    {
        TERMINATING.load(Ordering::SeqCst)
    }
    #[cfg(not(unix))]
    {
        false
    }
}

/// Run the interface until the user quits. Blocking: call it from `block_in_place` (or a
/// thread of its own) on a multi-threaded runtime.
pub fn run(handle: tokio::runtime::Handle, agent: Agent, setup: Setup) -> anyhow::Result<()> {
    let Setup {
        status,
        groups,
        skills,
        mut model,
        workspace,
        profile,
        session,
        history,
        yolo,
        config_path,
        place,
        update,
        clear_on_exit,
        hook_notes,
        sandbox,
        spawner,
        reasoning,
    } = setup;
    // Before the terminal is touched, so there is no window where raw mode is on and the signal
    // that arrives is still the default one.
    catch_termination();
    let (tx, rx) = std::sync::mpsc::channel::<UiEvent>();
    spawn_input(tx.clone());

    let mut app = App::new(status, &model, &workspace, profile);
    if let Some((dial, control, config, at)) = &reasoning {
        app.reasoning_control = control.clone();
        app.reasoning = Some(crate::reasoning_cli::Live::new(
            std::sync::Arc::clone(dial),
            config.clone(),
            at.clone(),
        ));
    }
    match history {
        // Resuming: the transcript is the session, not an empty screen with an old id in the
        // header — which is what the first version of this did.
        Some((blocks, interrupted)) => {
            app.blocks = blocks;
            if interrupted {
                app.note(
                    NoteKind::Warn,
                    "the last turn was interrupted mid-tool-call; continuing answers that call \
                     with a placeholder, which the model will see",
                );
            }
            if app.blocks.is_empty() {
                app.note(NoteKind::Info, "this session has no messages yet");
            }
        }
        None => app.blocks.push(app::Block::Welcome(app::Welcome {
            version: env!("CARGO_PKG_VERSION").to_string(),
            model: model.clone(),
            endpoint: app.status.endpoint.clone(),
            profile: app.profile.clone(),
            workspace: app.workspace.clone(),
            groups,
            skills,
            approvals: yolo.on(),
        })),
    }
    // The badge comes from the disk, not from a line the caller was told: a run that is behind
    // stays behind, and the check that fills the cache may answer after this first frame.
    app.update_watch = update;
    app.update = app.update_watch.as_ref().and_then(|w| w.read());
    app.session = session;
    app.status.session = app.session.clone();
    app.config_path = config_path;
    app.place = place;
    // The readout reads the switch, not a value copied from it: `/yolo` has to be able to change
    // what the bar says while the session is running.
    app.yolo = yolo.clone();
    let agent = Arc::new(agent);
    // One set for the whole interface session: "allow shell for this session" has to answer
    // the next `shell` without a modal, including the one in the next turn.
    let l = Loop {
        handle: handle.clone(),
        tx: tx.clone(),
        agent: Arc::clone(&agent),
        allows: SessionAllows::new(),
        sandbox,
        spawner,
    };

    let (guard, mut terminal) = Terminal::enter()?;

    let mut running_cancel: Option<Cancel> = None;
    // `#173`: the tick that is running right now, with the root its record lives under. It is the
    // interface's own copy of "a tick of mine is in flight" — the file answers that question for
    // another process, and this answers it for this one, so the run's end is reported once.
    let mut ticking: Option<(std::path::PathBuf, LoopState)> = None;

    // The header is printed once, above the live region, and then scrolls away like any other
    // line: a fact about the session does not need repainting, and the readout still names the
    // model on every frame.
    let width = terminal.size()?.width as usize;
    let head = view::header_line(&app, width);
    terminal.insert_before(1, |buf| {
        ratatui::widgets::Paragraph::new(head).render(buf.area, buf);
    })?;

    // First paint before the first keystroke: an empty terminal is not an interface.
    paint(&mut terminal, &mut app)?;

    while !app.quit {
        // `#410`: a `kill` or a `systemctl stop` does not run `Drop`, so the terminal would keep
        // raw mode and bracketed paste — echo off and `?2004h` still set — until the reader typed
        // `reset`. The handler only records that the signal happened; leaving here is the same path
        // `q` takes: the guard restores the terminal and one line says what happened.
        if terminating() {
            break;
        }
        let event = rx.recv_timeout(Duration::from_millis(90));
        if terminating() {
            break;
        }
        let mut redraw = false;
        match event {
            // The reader thread died (`#413`). The sender clone this function holds keeps the
            // channel connected forever, so `Disconnected` never arrives and the old loop spun at
            // 90 ms a tick with no input and no way out; the thread says so instead.
            Ok(UiEvent::Quit) => break,
            Ok(UiEvent::LoopNote(said)) => {
                let kind = if said.starts_with("loop ended") || said.contains("skipped") {
                    NoteKind::Warn
                } else {
                    NoteKind::Info
                };
                app.note(kind, said);
                redraw = true;
            }
            Ok(UiEvent::Tick) => {
                app.ticks = app.ticks.wrapping_add(1);
                // The badge is read once a second rather than every tick: it changes about as
                // often as a release is cut, and an idle screen should stay idle. Reading it is
                // how an answer that lands mid-run reaches the row without anything waiting.
                if app.ticks.is_multiple_of(10) && app.reread_update() {
                    redraw = true;
                }
                // `#173`: a loop tick. Once a second rather than every 90 ms — the record is a
                // file, and a file read four times a second to answer "is it due" is a poll no
                // loop needs. The run is submitted exactly as typed input is, so the transcript,
                // the spinner and the approval modal take the same path they always take.
                if app.ticks.is_multiple_of(10) && !app.running && ticking.is_none() {
                    if let (Some(id), Some(root)) = (
                        app.session.clone(),
                        app.place.as_ref().and_then(|p| p.home.clone()),
                    ) {
                        let now = eclipse_core::session::now_ms() as i64;
                        if let Some(mut state) = loops_cli::due(&root, &id, now) {
                            match l.agent.loop_tick_begin(&root, &mut state, now) {
                                Ok(true) => {
                                    let prompt = state.prompt.clone();
                                    let n = state.fired + 1;
                                    app.note(
                                        NoteKind::Info,
                                        format!("loop tick {n} · {}", state.interval),
                                    );
                                    ticking = Some((root.clone(), state));
                                    submit(&l, &mut app, &mut running_cancel, prompt, &yolo);
                                }
                                Ok(false) => {
                                    app.note(
                                        NoteKind::Warn,
                                        "loop tick skipped: a run is in flight",
                                    );
                                }
                                Err(why) => app.note(NoteKind::Warn, format!("{why:#}")),
                            }
                        }
                    }
                }
                // Only worth a repaint when something is actually moving.
                redraw = redraw || app.busy() || app.approval.is_some();
            }
            Ok(UiEvent::Agent(e)) => {
                app.on_event(e);
                redraw = true;
            }
            Ok(UiEvent::Routed(hops)) => {
                app.on_routed(hops);
                redraw = true;
            }
            Ok(UiEvent::Delegated(children)) => {
                app.on_delegated(&children);
                redraw = true;
            }
            Ok(UiEvent::Done(outcome)) => {
                // The tick's record is written off the UI thread: the `--until` question is a
                // provider call, and a modal that cannot repaint while it waits is worse than a
                // note that arrives a moment later.
                if let Some((root, mut state)) = ticking.take() {
                    let agent = Arc::clone(&l.agent);
                    let tx = l.tx.clone();
                    let reply = app.last_reply();
                    let result = match &outcome {
                        Ok(_) => Ok(reply),
                        Err(why) => Err(why.clone()),
                    };
                    let now = eclipse_core::session::now_ms() as i64;
                    l.handle.spawn(async move {
                        if let Err(why) = agent.loop_tick_end(&root, &mut state, now, result).await
                        {
                            let _ = tx.send(UiEvent::LoopNote(format!(
                                "could not record the loop tick: {why:#}"
                            )));
                            return;
                        }
                        if let Some(said) = state.tick_note() {
                            let _ = tx.send(UiEvent::LoopNote(said));
                        }
                    });
                }
                app.on_done(outcome);
                // `#172`: a turn that just finished may owe the goal another one. The judge has
                // already run inside the runtime, so this only reads the row.
                if !app.running {
                    continue_goal(&l, &mut app, &mut running_cancel, &yolo);
                }
                let said: Vec<String> = hook_notes
                    .lock()
                    .map(|mut n| std::mem::take(&mut *n))
                    .unwrap_or_default();
                for line in said {
                    let line = line.strip_prefix("note: ").unwrap_or(&line);
                    app.note(NoteKind::Info, line.to_string());
                }
                running_cancel = None;
                redraw = true;
            }
            Ok(UiEvent::Approval {
                tool,
                summary,
                reply,
            }) => {
                app.approval = Some(Approval::new(tool, summary, reply));
                redraw = true;
            }
            Ok(UiEvent::Models(route, Ok(models))) => {
                app.listing_models = false;
                app.set_models_from(route, models);
                redraw = true;
            }
            Ok(UiEvent::Budget { window, budget }) => {
                app.set_context(window, budget);
                redraw = true;
            }
            Ok(UiEvent::Sessions(Ok(items))) => {
                app.set_sessions(items);
                redraw = true;
            }
            Ok(UiEvent::Sessions(Err(why))) => {
                app.note(NoteKind::Warn, format!("could not list sessions: {why}"));
                redraw = true;
            }
            Ok(UiEvent::Resumed(Ok((id, blocks, interrupted)))) => {
                app.apply_session(id, blocks, interrupted);
                redraw = true;
            }
            Ok(UiEvent::Resumed(Err(why))) => {
                app.note(
                    NoteKind::Warn,
                    format!("could not open that session: {why}"),
                );
                redraw = true;
            }
            Ok(UiEvent::Models(route, Err(why))) => {
                app.listing_models = false;
                app.note(
                    NoteKind::Warn,
                    match &route {
                        Some(name) => format!("could not list models from `{name}`: {why}"),
                        None => format!("could not list models: {why}"),
                    },
                );
                redraw = true;
            }
            Ok(UiEvent::Bang(ran)) => {
                // The output and the exit line, and nothing in the session: the store is what
                // separates a bang command from a turn.
                let mut said = ran.output.clone();
                if !said.is_empty() {
                    said.push('\n');
                }
                said.push_str(&ran.summary());
                let kind = if ran.refused.is_some() {
                    NoteKind::Warn
                } else {
                    NoteKind::Info
                };
                app.note(kind, said);
                redraw = true;
            }
            Ok(UiEvent::Paste(text)) => {
                app.take_paste(&text);
                redraw = true;
            }
            Ok(UiEvent::Key(key)) => {
                if key.kind == KeyEventKind::Release {
                    continue;
                }
                match act(&mut app, key) {
                    Action::None => redraw = true,
                    Action::Submit(text) => {
                        // A leading bang is a command for the shell, not a turn for the model:
                        // nothing about it reaches the store, so it costs no tokens and cannot
                        // disturb the conversation. `fix the bug!` is still a prompt.
                        if let bang::Line::Bang(b) = bang::parse(&text) {
                            if let Some(why) = bang::refusal(bang::Surface::Tui) {
                                app.note(NoteKind::Warn, why);
                            } else {
                                app.note(NoteKind::Info, format!("! {}", b.script));
                                let tx = l.tx.clone();
                                let workspace = std::path::PathBuf::from(app.workspace.clone());
                                let sandbox = l.sandbox.clone();
                                l.handle.spawn(async move {
                                    let ran = bang::run(&b.script, &workspace, &sandbox).await;
                                    let _ = tx.send(UiEvent::Bang(ran));
                                });
                            }
                        } else {
                            submit(&l, &mut app, &mut running_cancel, text, &yolo);
                        }
                        redraw = true;
                    }
                    Action::CancelRun => {
                        if let Some(c) = &running_cancel {
                            c.cancel();
                            app.note(NoteKind::Warn, "stopping…");
                        }
                        redraw = true;
                    }
                    Action::Resume(id) => {
                        let agent = Arc::clone(&l.agent);
                        let tx = l.tx.clone();
                        l.handle.spawn(async move {
                            let loaded = agent
                                .store()
                                .load_records(&id)
                                .map(|records| {
                                    let (blocks, interrupted) = app::blocks_from(&records);
                                    (id, blocks, interrupted)
                                })
                                .map_err(|e| format!("{e:#}"));
                            let _ = tx.send(UiEvent::Resumed(loaded));
                        });
                    }
                    Action::PickModel(name, route) => {
                        // The old name, so "did it change" is a real question: `apply_model`
                        // updates both copies on success.
                        let before = app.model.clone();
                        apply_model(&l, &mut app, name, route.as_deref(), &mut model);
                        if app.model != before {
                            reprobe_budget(&l);
                        }
                    }
                    Action::PickProvider(route) => {
                        ask_models_from(&l, &mut app, Some(route));
                    }
                    Action::Command(cmd) => {
                        match command(&mut app, &cmd) {
                            Command::Quit => app.quit = true,
                            Command::Keep | Command::Unknown => {}
                            Command::Ask(arg) => {
                                ask_models(&l, &mut app, &arg, &mut model);
                            }
                            Command::Sessions => ask_sessions(&l, &mut app),
                            Command::Retry => {
                                match crate::retry::target(l.agent.store(), app.session.as_deref())
                                {
                                    crate::retry::Retry::Refused(why) => {
                                        app.note(NoteKind::Warn, why);
                                    }
                                    crate::retry::Retry::Ask(text) => {
                                        // Not a question the transcript shows twice: the one on screen
                                        // is the one being answered again, and the note says so.
                                        app.note(NoteKind::Info, "retrying the last question");
                                        submit_as(
                                            &l,
                                            &mut app,
                                            &mut running_cancel,
                                            text,
                                            &yolo,
                                            Sent::Again,
                                        );
                                    }
                                }
                            }
                            Command::Bg(text) => match &l.spawner {
                                None => app.note(
                                    NoteKind::Warn,
                                    "this session has no state directory, so `/bg` has nowhere to \
                                     record a task",
                                ),
                                Some(spawner) => match spawner.spawn(&text, Some(app.model.as_str()))
                                {
                                    Ok(id) => app.note(
                                        NoteKind::Info,
                                        format!(
                                            "background {id} — `/tasks` lists it; it keeps running \
                                             whatever this prompt does"
                                        ),
                                    ),
                                    Err(why) => app.note(NoteKind::Warn, format!("{why:#}")),
                                },
                            },
                            Command::Goal(arg) => {
                                let id = app
                                    .session
                                    .clone()
                                    .unwrap_or_else(|| l.agent.store().new_id());
                                let now = eclipse_core::session::now_ms() as i64;
                                match eclipse_core::goals::manage(
                                    l.agent.store(),
                                    &id,
                                    &arg,
                                    now,
                                ) {
                                    Ok(said) => {
                                        app.session = Some(id);
                                        app.status.session = app.session.clone();
                                        app.note(NoteKind::Info, said);
                                    }
                                    Err(why) => app.note(NoteKind::Warn, format!("{why:#}")),
                                }
                                // Starting or resuming a goal owes a turn straight away; a
                                // `status` or `pause` owes none, and `goal_continuation` is the
                                // one place that decides.
                                if !app.running {
                                    continue_goal(&l, &mut app, &mut running_cancel, &yolo);
                                }
                            }
                            Command::Loop(arg) => {
                                match app.place.as_ref().and_then(|p| p.home.clone()) {
                                    None => app.note(
                                        NoteKind::Warn,
                                        "this interface was started without a state directory, \
                                         so a loop has nowhere to record itself",
                                    ),
                                    Some(root) => match app.session.clone() {
                                        Some(id) => {
                                            let now = eclipse_core::session::now_ms() as i64;
                                            match loops_cli::manage(
                                                &root,
                                                &id,
                                                &arg,
                                                Owner::Cli,
                                                now,
                                            ) {
                                                Ok(said) => app.note(NoteKind::Info, said),
                                                Err(why) => {
                                                    app.note(NoteKind::Warn, format!("{why:#}"))
                                                }
                                            }
                                        }
                                        // A loop needs a session to send its prompt back into, and
                                        // `/loop` is the one command that may make one: asking for
                                        // the status of nothing is the only verb that must not.
                                        None if loops_cli::starts(&arg) => {
                                            let id = l.agent.store().new_id();
                                            let now = eclipse_core::session::now_ms() as i64;
                                            match loops_cli::manage(
                                                &root,
                                                &id,
                                                &arg,
                                                Owner::Cli,
                                                now,
                                            ) {
                                                Ok(said) => {
                                                    app.session = Some(id.clone());
                                                    app.status.session = Some(id);
                                                    app.note(NoteKind::Info, said);
                                                }
                                                Err(why) => {
                                                    app.note(NoteKind::Warn, format!("{why:#}"))
                                                }
                                            }
                                        }
                                        None => app.note(
                                            NoteKind::Info,
                                            "no loop in this session — start one with \
                                             `/loop 2m <prompt>`",
                                        ),
                                    },
                                }
                            }
                            Command::Tasks => match &l.spawner {
                                None => app.note(
                                    NoteKind::Warn,
                                    "this session has no state directory, so there are no tasks to \
                                     list",
                                ),
                                Some(spawner) => app.set_tasks(spawner.registry.list()),
                            },
                            Command::Compress => {
                                l.agent.compress_now();
                                app.note(
                                    NoteKind::Info,
                                    "compacted: the next request keeps the first turn and the \
                                     newest turns and replaces the middle with the compiled \
                                     handoff; the transcript is unchanged"
                                        .to_string(),
                                );
                            }
                            Command::New => {
                                let welcome = app.blocks.iter().find_map(|b| match b {
                                    Block::Welcome(w) => Some(w.clone()),
                                    _ => None,
                                });
                                match welcome {
                                    // The pane is still the first block in a fresh session, so
                                    // it can be reused rather than rebuilt.
                                    Some(welcome) => app.start_new_session(Some(welcome)),
                                    None => app.start_new_session(None),
                                }
                                model = app.model.clone();
                                app.note(NoteKind::Info, "new session");
                            }
                        }
                        redraw = true;
                    }
                    Action::Quit => app.quit = true,
                }
            }
            Err(RecvTimeoutError::Timeout) => continue,
            Err(RecvTimeoutError::Disconnected) => break,
        }
        if redraw {
            paint(&mut terminal, &mut app)?;
        }
    }
    // The terminal is the reader's again — but its last frame is not, and a shell prompt under a
    // half-drawn screen reads exactly like a crash. So: give the terminal back (the guard's Drop
    // restores the cursor and paste mode), clear what this program drew — the scrollback stays
    // unless asked — and say one line about what happened.
    let farewell = farewell::line(&app.status);
    drop(terminal);
    drop(guard);
    farewell::print(clear_on_exit, &farewell);
    Ok(())
}

/// The handles a turn needs: the runtime, the event channel, the agent and the answers
/// allowed for this session. Bundled because every call site would otherwise repeat them.
#[derive(Clone)]
struct Loop {
    handle: tokio::runtime::Handle,
    tx: Sender<UiEvent>,
    agent: Arc<Agent>,
    allows: SessionAllows,
    /// For `!command`: the human types it, so the allowlist does not apply, but the sandbox does.
    sandbox: eclipse_core::sandbox::Sandbox,
    /// `/bg` starts a process; `/tasks` reads what those processes wrote. One struct holds both,
    /// because the registry and the spawner must be the same directory.
    spawner: Option<crate::bg::Spawner>,
}

/// `/resume`: ask the store for the recent sessions and hand them to the picker.
fn ask_sessions(l: &Loop, app: &mut App) {
    app.note(NoteKind::Info, "reading recent sessions…");
    let agent = Arc::clone(&l.agent);
    let tx = l.tx.clone();
    l.handle.spawn(async move {
        let listed = agent
            .store()
            .list()
            .map(|infos| {
                infos
                    .into_iter()
                    .map(|s| {
                        // A child shows what it is; the title still wins when there is one.
                        let preview = if s.subagent().is_some() {
                            s.tagged_label()
                        } else {
                            s.preview
                        };
                        app::Picked {
                            note: if s.pinned {
                                "pinned".to_string()
                            } else {
                                String::new()
                            },
                            id: s.id,
                            title: s.title,
                            ago: app::ago(s.updated_ms),
                            messages: s.messages,
                            preview,
                        }
                    })
                    .collect::<Vec<_>>()
            })
            .map_err(|e| format!("{e:#}"));
        let _ = tx.send(UiEvent::Sessions(listed));
    });
}

/// Use `name` from the next turn on. One implementation for the menu and for typing it, so the
/// two cannot disagree about what a switch does or what it says.
fn apply_model(l: &Loop, app: &mut App, name: String, route: Option<&str>, model: &mut String) {
    // The route first: setting the model before the route would validate the name against the
    // endpoint that is about to be left.
    if let Some(route) = route {
        if let Err(e) = l.agent.set_route(Some(route)) {
            app.note(NoteKind::Warn, format!("{e:#}"));
            return;
        }
    }
    if name == *model {
        // The route may still have changed, which is a real change even when the model name is
        // the same one the old endpoint served.
        app.note(
            NoteKind::Info,
            match route {
                Some(route) => format!("provider: {route}, model: {name} — already in use"),
                None => format!("model: {name} — already in use"),
            },
        );
        return;
    }
    match l.agent.set_model(Some(name.clone())) {
        Ok(()) => {
            *model = name.clone();
            app.set_model_name(&name);
            let where_ = match route {
                Some(route) => format!("provider: {route}, model: {name}"),
                None => format!("model: {name}"),
            };
            app.note(
                NoteKind::Info,
                format!("{where_} — this session only; the configuration file is unchanged"),
            );
        }
        Err(e) => app.note(NoteKind::Warn, format!("{e:#}")),
    }
}

/// `/model` and `/model <n|name>`: ask the endpoint, or switch to what it already told us.
fn ask_models(l: &Loop, app: &mut App, arg: &str, model: &mut String) {
    if arg.is_empty() {
        // Which endpoint to ask is only a question when the configuration has more than one. With
        // one, the old single-step `/model` is the whole answer.
        let routes = l.agent.route_infos();
        if routes.len() > 1 {
            let current = routes
                .iter()
                .find(|r| r.model == *model)
                .map(|r| r.name.clone());
            app.open_providers(&routes, current.as_deref());
            return;
        }
        ask_models_from(l, app, None);
        return;
    }
    let Some(name) = app.resolve_model(arg) else {
        app.note(
            NoteKind::Warn,
            format!(
                "`{arg}` is not in the list; /model with no argument opens it, and \
                 /model <number or name> picks from it"
            ),
        );
        return;
    };
    apply_model(l, app, name, None, model);
}

/// Ask one route what it serves, or the selected one when `route` is `None`.
fn ask_models_from(l: &Loop, app: &mut App, route: Option<String>) {
    app.note(
        NoteKind::Info,
        match &route {
            Some(name) => format!("asking `{name}` which models it serves…"),
            None => "asking the endpoint which models it serves…".to_string(),
        },
    );
    app.listing_models = true;
    let agent = Arc::clone(&l.agent);
    let tx = l.tx.clone();
    l.handle.spawn(async move {
        let listed = agent
            .list_models_for(route.as_deref())
            .await
            .map_err(|e| format!("{e:#}"));
        let _ = tx.send(UiEvent::Models(route, listed));
    });
}

/// Ask the endpoint what the model now in use can hold. A configured budget wins, so the
/// probe is skipped entirely then — the readout is not allowed to disagree with the config.
/// What the readout shows is the rail the loop will use, which is a share of that window.
fn reprobe_budget(l: &Loop) {
    if l.agent.context_budget_is_configured() {
        return;
    }
    let agent = Arc::clone(&l.agent);
    let tx = l.tx.clone();
    l.handle.spawn(async move {
        let window = agent
            .advertised_context_window(std::time::Duration::from_secs(2))
            .await;
        // A failed probe leaves the readout alone rather than inventing a window.
        let seen = window.map(|w| {
            agent.set_advertised_window(w);
            // `[context] window_tokens`, when it is set, is what this process will actually
            // use, so that is what the readout must show even when the endpoint said something
            // else.
            agent.context_window()
        });
        let _ = tx.send(UiEvent::Budget {
            window: seen.unwrap_or(0),
            budget: agent.context_budget(),
        });
    });
}

/// The reader thread: terminal events in, [`UiEvent`] out. Ends when the loop is gone.
fn spawn_input(tx: Sender<UiEvent>) {
    std::thread::spawn(move || loop {
        match event::poll(Duration::from_millis(90)) {
            Ok(true) => match event::read() {
                Ok(event::Event::Key(k)) => {
                    if tx.send(UiEvent::Key(k)).is_err() {
                        break;
                    }
                }
                Ok(event::Event::Paste(s)) => {
                    if tx.send(UiEvent::Paste(s)).is_err() {
                        break;
                    }
                }
                // A mouse report can still arrive — a terminal that re-enabled reporting itself,
                // say — and there is nothing for it to mean here: the pointer is the terminal's.
                // Resize is handled by the next draw: the layout is recomputed anyway.
                Ok(_) => {}
                // `#413`: crossterm failed, so this thread is done and no key will ever arrive
                // again. Tell the loop rather than leaving it to spin: it holds a sender of its
                // own, so it will never see `Disconnected`.
                Err(_) => {
                    let _ = tx.send(UiEvent::Quit);
                    break;
                }
            },
            Ok(false) => {
                if tx.send(UiEvent::Tick).is_err() {
                    break;
                }
            }
            Err(_) => {
                let _ = tx.send(UiEvent::Quit);
                break;
            }
        }
    });
}

/// One key, one decision. Anything that needs the loop (sending, cancelling) comes back
/// as an [`Action`] rather than being done here.
pub fn act(app: &mut App, key: KeyEvent) -> Action {
    let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);

    // An approval owns the keyboard while it is up: a stray key must not answer it. It comes
    // before the session list and the command list, and neither opens over it.
    if app.approval.is_some() {
        match key.code {
            KeyCode::Up | KeyCode::Char('k') | KeyCode::BackTab => {
                if let Some(a) = app.approval.as_mut() {
                    a.move_by(-1);
                }
                return Action::None;
            }
            KeyCode::Down | KeyCode::Char('j') | KeyCode::Tab => {
                if let Some(a) = app.approval.as_mut() {
                    a.move_by(1);
                }
                return Action::None;
            }
            KeyCode::Enter => {
                if let Some(choice) = app.pending_choice() {
                    app.answer_approval(choice);
                }
                return Action::None;
            }
            KeyCode::Char('1') => {
                app.answer_approval(Choice::Once);
                return Action::None;
            }
            KeyCode::Char('2') => {
                app.answer_approval(Choice::Session);
                return Action::None;
            }
            KeyCode::Char('3') => {
                app.answer_approval(Choice::Deny);
                return Action::None;
            }
            KeyCode::Char('y') | KeyCode::Char('Y') => {
                app.answer_approval(Choice::Once);
                return Action::None;
            }
            KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => {
                app.answer_approval(Choice::Deny);
                return Action::None;
            }
            _ => return Action::None,
        }
    }

    // The session list owns the keyboard while it is up, for the same reason an approval does:
    // a stray key must not switch the session out from under a person.
    //
    // Every printable key narrows the list, so `j` and `k` type rather than move — arrows and Tab
    // are the movement keys here, because a filter you cannot type "json" into is not a filter.
    if app.picker.is_some() {
        match key.code {
            KeyCode::Up | KeyCode::BackTab => {
                if let Some(p) = app.picker.as_mut() {
                    p.move_by(-1);
                }
                return Action::None;
            }
            KeyCode::Down | KeyCode::Tab => {
                if let Some(p) = app.picker.as_mut() {
                    p.move_by(1);
                }
                return Action::None;
            }
            // Shift is not a reason to refuse a character: it is how an uppercase letter arrives,
            // and some terminals report it on plain ones too. Control and Alt still belong to the
            // interface, so they fall through to the keys below.
            KeyCode::Char(c)
                if !c.is_control()
                    && !key
                        .modifiers
                        .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) =>
            {
                if let Some(p) = app.picker.as_mut() {
                    p.type_char(c);
                }
                return Action::None;
            }
            KeyCode::Backspace => {
                // Nothing left to delete closes the list, which is where a reader's finger takes
                // them after emptying a search box.
                let still_open = match app.picker.as_mut() {
                    Some(p) => p.backspace(),
                    None => false,
                };
                if !still_open {
                    app.picker = None;
                }
                return Action::None;
            }
            KeyCode::Enter => {
                let chosen = app
                    .picker
                    .as_ref()
                    .map(|p| (p.kind, p.current().cloned()))
                    .and_then(|(kind, item)| item.map(|i| (kind, i)));
                return match chosen {
                    // A task is a session: opening it reads that transcript, whether the run
                    // behind it is still writing or long finished.
                    Some((app::PickerKind::Sessions | app::PickerKind::Tasks, item)) => {
                        Action::Resume(item.id)
                    }
                    // The list closes here; switching the model is the loop's job, because it
                    // holds the agent.
                    // Step one: the route names the next list, so the menu closes and a request
                    // goes out for what that endpoint serves.
                    Some((app::PickerKind::Provider, item)) => {
                        app.picker = None;
                        Action::PickProvider(item.id)
                    }
                    Some((app::PickerKind::Model, item)) => {
                        // The route the list came from travels with the choice: `None` when there
                        // was only one to ask.
                        let route = app.picker.as_ref().and_then(|p| p.route.clone());
                        app.picker = None;
                        Action::PickModel(item.id, route)
                    }
                    None => Action::None,
                };
            }
            KeyCode::Esc => {
                // First press clears the query, second closes: undoing a typo should not throw
                // away the list you were reading.
                let cleared = app
                    .picker
                    .as_mut()
                    .map(|p| p.clear_query())
                    .unwrap_or(false);
                if !cleared {
                    app.picker = None;
                }
                return Action::None;
            }
            _ => return Action::None,
        }
    }

    // The command list takes only the keys that mean something to it. Everything else closes
    // it and goes on to the line, so it can never trap a key the editor would have handled.
    if app.menu.is_some() {
        match key.code {
            KeyCode::Up | KeyCode::Char('k') | KeyCode::BackTab => {
                if let Some(m) = app.menu.as_mut() {
                    m.move_by(-1);
                }
                return Action::None;
            }
            KeyCode::Down | KeyCode::Char('j') => {
                if let Some(m) = app.menu.as_mut() {
                    m.move_by(1);
                }
                return Action::None;
            }
            KeyCode::Tab => {
                app.accept_menu();
                return Action::None;
            }
            // Accept, then fall through to the Enter below: running it is exactly what typing
            // the command and pressing Enter does.
            KeyCode::Enter => app.accept_menu(),
            KeyCode::Esc => {
                // The one keystroke that means "I do not want this", and the only thing that
                // outlasts it is the line being committed or killed (#253).
                app.menu = None;
                app.menu_dismissed = true;
                return Action::None;
            }
            KeyCode::Char(ch) if !ctrl => {
                app.insert(ch);
                app.refilter_menu();
                return Action::None;
            }
            KeyCode::Backspace => {
                app.backspace();
                app.refilter_menu();
                return Action::None;
            }
            _ => app.menu = None,
        }
    }

    match key.code {
        KeyCode::Char('c') if ctrl => {
            if app.busy() {
                Action::CancelRun
            } else {
                app.kill_line();
                Action::None
            }
        }
        KeyCode::Char('d') if ctrl => {
            if app.input.is_empty() {
                Action::Quit
            } else {
                app.delete();
                Action::None
            }
        }
        KeyCode::Esc => {
            if app.busy() {
                Action::CancelRun
            } else {
                app.kill_line();
                Action::None
            }
        }
        KeyCode::Enter => {
            if app.busy() {
                app.note(NoteKind::Warn, "a run is in flight (esc to stop it)");
                return Action::None;
            }
            let text = app.take();
            let trimmed = text.trim().to_string();
            if trimmed.is_empty() {
                // A list that is still on its way is not a keystroke that did nothing.
                if app.listing_models {
                    app.note(
                        NoteKind::Info,
                        "still asking the endpoint which models it serves…",
                    );
                }
                return Action::None;
            }
            if let Some(cmd) = trimmed.strip_prefix('/') {
                let cmd = format!("/{cmd}");
                // Echo the command, the way a shell shows what it ran.
                app.blocks.push(Block::User(trimmed));
                return Action::Command(cmd);
            }
            Action::Submit(trimmed)
        }
        KeyCode::Char(ch) => {
            if ctrl {
                match ch {
                    'a' => app.home(),
                    'e' => app.end(),
                    'u' => app.kill_line(),
                    'k' => {
                        let keep: String = app.input.chars().take(app.cursor).collect();
                        app.input = keep;
                    }
                    'l' => app.clear_transcript(),
                    // Folding reasoning lives here because this is where the control keys are
                    // dispatched; an arm after this one would never be reached. When everything
                    // is already printed there is nothing to open in place, so the next paint
                    // prints the last folded block's reasoning again, below it (#217).
                    't' => {
                        let opening = !app.show_thinking;
                        app.toggle_thinking();
                        // Only on the way open, and only when nothing is left on screen to open:
                        // with a run in flight the block above is still being drawn, and `^T`
                        // can reach it.
                        app.echo = if opening && view::finished_blocks(app) == app.blocks.len() {
                            view::last_folded_printed_reasoning(app)
                        } else {
                            None
                        };
                    }
                    _ => {}
                }
                return Action::None;
            }
            app.insert(ch);
            // The menu is a function of the line: a `/` at the start opens it, every further
            // character filters it, and a line that stops being a command word closes it. That is
            // how a wrong letter stops being fatal (#253).
            app.refilter_menu();
            Action::None
        }
        KeyCode::Tab => {
            app.complete_command();
            Action::None
        }
        KeyCode::Backspace => {
            app.backspace();
            Action::None
        }
        KeyCode::Delete => {
            app.delete();
            Action::None
        }
        KeyCode::Left => {
            if ctrl {
                app.home()
            } else {
                app.move_left()
            }
            Action::None
        }
        KeyCode::Right => {
            if ctrl {
                app.end()
            } else {
                app.move_right()
            }
            Action::None
        }
        // Home and End belong to the line under the cursor. The transcript above has no viewport
        // to jump around in any more: it is the terminal's scrollback, and the terminal's own keys
        // move through it.
        KeyCode::Home => {
            app.home();
            Action::None
        }
        KeyCode::End => {
            app.end();
            Action::None
        }
        KeyCode::Up => {
            app.earlier();
            Action::None
        }
        KeyCode::Down => {
            app.later();
            Action::None
        }
        _ => Action::None,
    }
}

/// Print what has finished, then draw the live region.
///
/// A terminal's scrollback is append-only, so nothing here may be printed twice and nothing may be
/// printed while it is still changing. `stable_line_count` says where the finished lines end, and
/// the watermark in `App` says where printing left off.
fn paint(terminal: &mut ratatui::DefaultTerminal, app: &mut App) -> anyhow::Result<()> {
    // Every repaint re-reads the dial (`#264`): `/reasoning high` has to reach the read-out on the
    // same frame it reaches the dial, and there is no other place every path goes through.
    app.refresh_effort();
    let width = terminal.size()?.width as usize;
    // What the pane may occupy above the window, with one row for the header printed under it. A
    // pane that asked for more would still be printed, and its top would scroll off the screen.
    let room = (terminal.size()?.height as usize)
        .saturating_sub(LIVE_HEIGHT as usize)
        .saturating_sub(1);
    // The watermark is a block count: `^T` and a resize both change how tall the printed part is,
    // and a line count would then point into a transcript rearranged around it — printing again
    // what is already in the scrollback, and later skipping lines nobody saw.
    let finished = view::finished_blocks(app);
    if finished > app.printed {
        let lines = view::transcript_lines(app, width, room);
        let from = view::line_offset_of(app, app.printed, width, room);
        let to = view::line_offset_of(app, finished, width, room);
        let chunk: Vec<_> = lines
            .into_iter()
            .skip(from)
            .take(to.saturating_sub(from))
            .collect();
        // Frozen at the fold state it is printed with, so the next frame cannot change its height.
        app.freeze_printed(finished);
        if !chunk.is_empty() {
            let height = chunk.len() as u16;
            terminal.insert_before(height, move |buf| {
                ratatui::widgets::Paragraph::new(ratatui::text::Text::from(chunk))
                    .render(buf.area, buf);
            })?;
        }
    }
    // `^T` for history: a block that is already in the scrollback cannot be opened in place, so
    // it is printed again below — a copy under a rule, appended, never an edit of what is above.
    if let Some(index) = app.echo.take() {
        let lines = view::reasoning_echo(app, index, width);
        if !lines.is_empty() {
            let height = lines.len() as u16;
            terminal.insert_before(height, move |buf| {
                ratatui::widgets::Paragraph::new(ratatui::text::Text::from(lines))
                    .render(buf.area, buf);
            })?;
        }
    }
    terminal.draw(|f| view::draw(f, app, app.printed, room))?;
    Ok(())
}

/// How this turn relates to the session: a question, or the last one sent again (#224).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Sent {
    /// Becomes a user row in the store and a question in the transcript.
    New,
    /// It is already both. The attempt adds only what it produces — which is what keeps the store
    /// holding one copy of the question however many times the answer was tried.
    Again,
}

fn submit(
    l: &Loop,
    app: &mut App,
    running_cancel: &mut Option<Cancel>,
    text: String,
    yolo: &crate::yolo::Yolo,
) {
    submit_as(l, app, running_cancel, text, yolo, Sent::New);
}

fn submit_as(
    l: &Loop,
    app: &mut App,
    running_cancel: &mut Option<Cancel>,
    text: String,
    yolo: &crate::yolo::Yolo,
    how: Sent,
) {
    // The line carried chips where the paste was; the model gets the paste. A retry's text comes
    // back from the store already expanded, and the chips it belonged to are long gone.
    let text = app.expand_pastes(&text);
    if how == Sent::New {
        app.pastes.clear();
        app.history.push(&text);
        app.blocks.push(Block::User(text.clone()));
    }
    app.running = true;
    app.activity = Activity::Requesting;
    app.ticks = 0;

    // Fix the id before the run so a failed first turn can be retried in the same session.
    let id = app
        .session
        .get_or_insert_with(|| l.agent.store().new_id())
        .clone();
    app.status.session = Some(id.clone());

    let cancel = Cancel::new();
    *running_cancel = Some(cancel.clone());

    let agent = Arc::clone(&l.agent);
    let tx = l.tx.clone();
    let allows = l.allows.clone();
    // The spawned task owns the switch: it is an `Arc` inside, so this is the same flag the
    // composer flips, not a copy of the value at submit time.
    let yolo = yolo.clone();
    let handle = l.handle.clone();
    handle.spawn(async move {
        let sink = {
            let tx = tx.clone();
            move |e: AgentEvent| {
                let _ = tx.send(UiEvent::Agent(e));
            }
        };
        // Two approvers, one call site: the runtime takes a trait object either way.
        let allow = AllowAll;
        let ask = UiApprover {
            tx: tx.clone(),
            allows,
        };
        // Read once, at the moment the turn starts: a `/yolo` typed while this turn is running
        // applies to the next one, which is exactly what "the next turn" means.
        let approver: &dyn Approver = if yolo.on() { &allow } else { &ask };
        // `resume` is the whole of the store's half: with it, no user row is appended and no
        // `run_start` hook fires, so the request is built from the history that already holds the
        // question. The attempt's own rows join that same question.
        let opts = RunOptions {
            resume: how == Sent::Again,
            ..RunOptions::default()
        };
        let result = agent
            .run_cancellable_with(Some(&id), &text, approver, &sink, &cancel, &opts)
            .await;
        let outcome = match result {
            Ok(run) => {
                let _ = tx.send(UiEvent::Routed(run.hops));
                let _ = tx.send(UiEvent::Delegated(run.children));
                Ok(run.session_id)
            }
            Err(Error::Cancelled) => Err("cancelled".to_string()),
            Err(e) => Err(format!("{e:#}")),
        };
        let _ = tx.send(UiEvent::Done(outcome));
    });
}

/// `#172`: give the session's goal its next turn, when it owes one.
///
/// Through the same `submit` a typed prompt takes, so the transcript, the spinner and the approval
/// modal are unchanged — a goal turn is a turn, not a second kind of run. The budget and the state
/// are on the row, so a paused, finished or blocked goal stops this immediately.
fn continue_goal(
    l: &Loop,
    app: &mut App,
    running_cancel: &mut Option<Cancel>,
    yolo: &crate::yolo::Yolo,
) {
    let Some(id) = app.session.clone() else {
        return;
    };
    match l.agent.goal_continuation(&id) {
        Ok(Some(prompt)) => {
            let readout = l
                .agent
                .store()
                .goal(&id)
                .ok()
                .flatten()
                .map(|g| g.readout())
                .unwrap_or_default();
            app.note(NoteKind::Info, format!("goal: {readout}"));
            submit(l, app, running_cancel, prompt, yolo);
        }
        Ok(None) => {}
        Err(why) => app.note(NoteKind::Warn, format!("could not read the goal: {why:#}")),
    }
}

/// What a slash command asks the loop to do on its behalf. The loop owns the handles; a
/// command handler that reached for them itself would be a second way to reach the agent.
#[derive(Debug, PartialEq, Eq)]
enum Command {
    Keep,
    Quit,
    /// `/model` with an optional argument: empty means "ask the endpoint".
    Ask(String),
    /// `/resume`: list the stored sessions.
    Sessions,
    /// `/new`: start a session that does not exist yet.
    New,
    /// `/compress`: compact this session from the next request on.
    Compress,
    /// `/retry`: the last question, again, against the same stored row (#224). The text is read in
    /// the loop, because the store is the loop's to reach for.
    Retry,
    /// `/bg <prompt>`: start it as a task the composer returns from at once (#225). The spawn is
    /// the loop's, because it holds the handles a child inherits.
    Bg(String),
    /// `/tasks`: list the background runs. Also the loop's: it reads the registry.
    Tasks,
    /// `/loop …` (`#173`): the words are answered by `loops_cli`, but the session id, the install
    /// root and the timer all belong to the loop.
    Loop(String),
    /// `/goal …` (`#172`): a row in the session store, plus the first turn it owes.
    Goal(String),
    /// Nothing ran: no such command here. The note saying so is already in the transcript.
    Unknown,
}

/// Keys the `/help` footer names; the commands above it come from `commands::help`.
const KEY_HINTS: &str =
    "keys: / menu · tab complete · ↑↓ choose · esc stop · the wheel scrolls your terminal · \
     ⌃U clear line · ⌃D quit";

/// The list and the write live in `settings_cli` so the REPL answers with the same words.
fn settings_table(app: &App) -> String {
    match &app.config_path {
        Some(path) => crate::settings_cli::table(path, app.profile.as_deref()),
        None => "this interface was started without a config file: nothing to list".to_string(),
    }
}

fn set_one(app: &App, key: &str, value: &str) -> Result<String, String> {
    let path = app
        .config_path
        .clone()
        .ok_or_else(|| "this interface was started without a config file".to_string())?;
    crate::settings_cli::set_one(&path, app.profile.as_deref(), key, value)
}

/// The words come from `commands::COMMANDS`; the `match` stays a `match` because the handlers
/// need the interface's own state, and the drift test below holds it to the table.
fn command(app: &mut App, cmd: &str) -> Command {
    use eclipse_core::commands::{self as table, Front, Parsed};
    let (command, arg) = match table::parse(cmd, Front::Tui) {
        Parsed::Run(command, arg) => (command, arg),
        Parsed::Elsewhere(command) => {
            app.note(NoteKind::Warn, command.unavailable_in(Front::Tui));
            return Command::Unknown;
        }
        Parsed::Unknown(line) => {
            app.note(NoteKind::Warn, format!("unknown command {line}; try /help"));
            return Command::Unknown;
        }
    };
    match command.name {
        "/exit" => return Command::Quit,
        "/help" => app.note(
            NoteKind::Info,
            format!("{}\n{KEY_HINTS}", table::help(Front::Tui)),
        ),
        "/new" => return Command::New,
        "/id" => {
            let id = app.session.clone().unwrap_or_else(|| "(none yet)".into());
            app.note(NoteKind::Info, id);
        }
        "/status" => {
            let mut detail = app.status.detail(&crate::ui::Style::plain());
            // `#227`: quiet while the effort matches the file; explicit when it does not. The
            // wording is the report's (`#264`, `#276`), so `/status` cannot describe the dial
            // differently from `/reasoning` or the read-out above the prompt.
            if let Some(report) = app.effort_report() {
                if report.session {
                    detail.push_str(&format!("\neffort: {}", report.in_force));
                }
            }
            app.note(NoteKind::Info, detail.trim_start().to_string());
        }
        "/settings" => app.note(NoteKind::Info, settings_table(app)),
        // `#228`: which profile, from which file, under which home. `list` is the same renderer
        // `eclipse profiles list` prints, and a name is refused because a profile is a config
        // file, a home and a store — none of which this transcript can change underneath itself.
        "/profile" => match (&app.place, arg.trim()) {
            (None, _) => app.note(
                NoteKind::Info,
                "this interface was started without a config file: nothing to report",
            ),
            (Some(place), "") => app.note(NoteKind::Info, crate::profiles_cli::one(place)),
            (Some(place), "list") => app.note(
                NoteKind::Info,
                crate::profiles_cli::list(place, &eclipse_core::config::process_env),
            ),
            (Some(_), name) => app.note(NoteKind::Warn, crate::profiles_cli::refusal(name)),
        },
        // `#229`: what the long-lived process is doing — read-only, and the same report the plain
        // REPL prints, from the same probe. `/platforms` adds the platform table, which has no
        // rows yet; the alias is told apart by the word that was typed, not by `command.name`.
        "/gateway" | "/platforms" => {
            let snapshot = crate::gateway_view::probe(
                &crate::gateway_view::System,
                &eclipse_core::config::process_env,
                app.place.as_ref(),
            );
            let typed = cmd.split_whitespace().next().unwrap_or_default();
            let report = if typed == "/platforms" {
                crate::gateway_view::platforms(&snapshot, app.place.as_ref())
            } else {
                crate::gateway_view::text(&snapshot, app.place.as_ref())
            };
            app.note(NoteKind::Info, report.trim_end().to_string());
        }
        // `#230`: the same table, the same two read verbs. `app.place.home` is the cron root — the
        // one directory both surfaces read — and `/cron run` blocks here for as long as the job
        // takes, because an exit code reported later in another pane is not a report.
        "/cron" => match app.place.as_ref().and_then(|p| p.home.clone()) {
            None => app.note(
                NoteKind::Warn,
                "this session has no state directory, so there are no jobs to show".to_string(),
            ),
            Some(root) => match crate::cron_cli::composer(
                app.place.as_ref(),
                &root,
                arg.trim(),
                &crate::ui::Style::plain(),
            ) {
                Ok(said) => app.note(NoteKind::Info, said),
                Err(why) => app.note(NoteKind::Warn, why.to_string()),
            },
        },
        // `#227`: effort for this session, and how much of it is drawn here. The display flags are
        // this screen's own — the plain REPL has no block to fold, and the dashboard keeps its
        // default because it is read on a different screen.
        "/reasoning" => {
            let control = app.reasoning_control.clone();
            let dial = app.reasoning.as_ref().map(|live| live.dial.clone());
            let said = match (&dial, app.reasoning.as_mut()) {
                (Some(dial), Some(live)) => {
                    // The report this call is about to change, read from the same dial the arm
                    // moves (`#276`): the route's declared default included, so `/reasoning` on a
                    // fresh install answers `medium` and not `not sent`.
                    let report = |dial: &std::sync::Arc<eclipse_core::reasoning::Dial>| {
                        eclipse_core::reasoning::report_for(dial, control.as_ref())
                    };
                    live.apply(
                        arg,
                        &|level| eclipse_core::reasoning::sentence(control.as_ref(), level),
                        &|| report(dial),
                    )
                }
                _ => Err(
                    "this interface was started without a config file: there is no dial to turn"
                        .to_string(),
                ),
            };
            match said {
                Ok(said) => app.note(NoteKind::Info, said),
                Err(why) => app.note(NoteKind::Warn, why),
            }
        }
        // `#226`: the same switch the plain REPL flips, on the same flag — the readout is where
        // this front says it is on, and it repaints on the next frame.
        "/yolo" => match app.yolo.apply(arg) {
            Ok(said) => app.note(NoteKind::Info, said),
            Err(why) => app.note(NoteKind::Warn, why),
        },
        "/set" => {
            let words: Vec<&str> = arg.split_whitespace().collect();
            match words.split_first() {
                Some((key, rest)) if !rest.is_empty() => match set_one(app, key, &rest.join(" ")) {
                    Ok(said) => app.note(NoteKind::Info, said),
                    Err(why) => app.note(NoteKind::Warn, why),
                },
                _ => app.note(
                    NoteKind::Warn,
                    "usage: /set <key> <value> — the keys are in /settings",
                ),
            }
        }
        // `#173`: the same parser, the same record and the same sentence as the plain REPL; what
        // this front adds is a timer that keeps ticking while nobody is typing.
        "/loop" => return Command::Loop(arg.to_string()),
        "/goal" => return Command::Goal(arg.to_string()),
        "/clear" => app.clear_transcript(),
        "/retry" => return Command::Retry,
        // The spawn and the registry read are the loop's: it owns the handles a child inherits,
        // and the same one `/tasks` reads back. A missing argument is said here, where the
        // composer can still be corrected.
        "/bg" => {
            if arg.trim().is_empty() {
                app.note(
                    NoteKind::Warn,
                    "usage: /bg <prompt> — the run continues after this prompt returns",
                );
                return Command::Keep;
            }
            return Command::Bg(arg.to_string());
        }
        "/tasks" => return Command::Tasks,
        "/compress" => return Command::Compress,
        // `#240`: the same three words the REPL answers, from the same renderer for `list`. The
        // store is opened for the one `UPDATE`; the interface holds no handle to it.
        "/archive" => match app.place.as_ref().and_then(|p| p.sessions.clone()) {
            None => app.note(
                NoteKind::Warn,
                "this session has no state directory, so there is nothing to file".to_string(),
            ),
            Some(dir) => match arg.trim() {
                "list" => match crate::archived_list(&dir, &crate::ui::Style::plain()) {
                    Ok(said) => app.note(NoteKind::Info, said),
                    Err(why) => app.note(NoteKind::Warn, why.to_string()),
                },
                "off" => match app.session.clone() {
                    None => app.note(
                        NoteKind::Warn,
                        "no session is open yet: there is nothing to put back".to_string(),
                    ),
                    Some(id) => {
                        match eclipse_core::session::SessionStore::new(dir).set_archived(&id, false) {
                            Ok(()) => app.note(
                                NoteKind::Info,
                                format!("unarchived {id} — back in the list, and a prune may take it again"),
                            ),
                            Err(why) => app.note(NoteKind::Warn, why.to_string()),
                        }
                    }
                },
                "" => match app.session.clone() {
                    None => app.note(
                        NoteKind::Warn,
                        "no session is open yet: the next message opens one".to_string(),
                    ),
                    Some(id) => {
                        match eclipse_core::session::SessionStore::new(dir).set_archived(&id, true)
                        {
                            Ok(()) => app.note(
                                NoteKind::Info,
                                format!(
                                    "archived {id} — out of `sessions list`, still in `sessions \
                                     search`; `/archive off` puts it back"
                                ),
                            ),
                            Err(why) => app.note(NoteKind::Warn, why.to_string()),
                        }
                    }
                },
                other => app.note(
                    NoteKind::Warn,
                    format!("/archive takes `list` or `off`, not {other:?}"),
                ),
            },
        },
        "/resume" => return Command::Sessions,
        "/model" => return Command::Ask(arg.to_string()),
        other => {
            app.note(
                NoteKind::Warn,
                format!("unknown command {other}; try /help"),
            );
            return Command::Unknown;
        }
    }
    Command::Keep
}

#[cfg(test)]
mod tests {
    /// `#413`'s premise, which is why the fix is a message and not a disconnect: `run` holds a
    /// sender of its own for the whole loop, so `Disconnected` never arrives. An input thread that
    /// died silently used to leave the interface spinning at 90 ms a tick, drawing a prompt that
    /// could not hear anything and offering no way out.
    #[test]
    fn a_sender_the_loop_still_holds_keeps_the_channel_connected() {
        use std::time::Duration as D;
        let (tx, rx) = std::sync::mpsc::channel::<UiEvent>();
        let held_by_the_loop = tx.clone();
        // The reader thread's own sender goes away, exactly as it does when that thread ends.
        drop(tx);
        assert!(
            matches!(
                rx.recv_timeout(D::from_millis(1)),
                Err(std::sync::mpsc::RecvTimeoutError::Timeout)
            ),
            "with the loop's sender alive there is no Disconnected to break on"
        );
        drop(held_by_the_loop);
        assert!(matches!(
            rx.recv_timeout(D::from_millis(1)),
            Err(std::sync::mpsc::RecvTimeoutError::Disconnected)
        ));
    }

    use super::*;
    use crate::status::Status;
    use eclipse_core::usage::TurnUsage;
    use ratatui::crossterm::event::KeyCode;

    fn app() -> App {
        App::new(Status::new("m", "h:1", 1000, "/w".into()), "m", "/w", None)
    }

    fn key(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }

    fn picked(id: &str, title: &str, preview: &str) -> app::Picked {
        app::Picked {
            id: id.into(),
            title: Some(title.into()),
            note: String::new(),
            ago: "1m".into(),
            messages: 2,
            preview: preview.into(),
        }
    }

    /// The path a terminal actually takes: a key event, through `act`, to the rows on screen.
    ///
    /// The picker's own tests call `type_char` directly, which is why a bug in the routing —
    /// a key that never reaches the filter — could survive them. This one types at the list the
    /// way a person does.
    #[test]
    fn typing_at_the_session_list_narrows_it() {
        let mut a = app();
        a.set_sessions(vec![
            picked("s1", "max horda", "we fixed the search"),
            picked("s2", "kitchen reno", "nothing about that word"),
            picked("s3", "eclipse release", "session search shipped"),
        ]);

        // One letter, through the key handler.
        assert_eq!(act(&mut a, key(KeyCode::Char('m'))), Action::None);
        let p = a.picker.as_ref().expect("the list stays up while typing");
        assert_eq!(p.query, "m", "a printable key is the filter's");
        assert_eq!(
            p.items.len(),
            1,
            "only \"max horda\" holds an m: {:?}",
            p.items
        );
        assert_eq!(p.all.len(), 3, "the whole list is kept for the count");

        // A second letter narrows further, and a letter no row has empties the list rather than
        // the list closing: "nothing matches" is an answer, not an exit.
        assert_eq!(act(&mut a, key(KeyCode::Char('x'))), Action::None);
        assert_eq!(a.picker.as_ref().unwrap().items.len(), 1);
        assert_eq!(act(&mut a, key(KeyCode::Char('z'))), Action::None);
        assert_eq!(a.picker.as_ref().unwrap().items.len(), 0);
        assert_eq!(a.picker.as_ref().unwrap().query, "mxz");

        // Backspace undoes it, and the cursor comes back to the top.
        for _ in 0..3 {
            assert_eq!(act(&mut a, key(KeyCode::Backspace)), Action::None);
        }
        let p = a.picker.as_ref().unwrap();
        assert_eq!(p.query, "");
        assert_eq!(p.items.len(), 3);

        // `j` types now: it is a letter in a filter, not a movement key.
        assert_eq!(act(&mut a, key(KeyCode::Char('j'))), Action::None);
        assert_eq!(a.picker.as_ref().unwrap().query, "j");
        // Arrows are the movement keys, and they leave the query alone.
        let before = a.picker.as_ref().unwrap().query.clone();
        assert_eq!(act(&mut a, key(KeyCode::Down)), Action::None);
        assert_eq!(a.picker.as_ref().unwrap().query, before);
        assert_eq!(act(&mut a, key(KeyCode::Up)), Action::None);

        // Esc clears the query first, and closes the list only on the second press.
        assert_eq!(act(&mut a, key(KeyCode::Esc)), Action::None);
        let p = a
            .picker
            .as_ref()
            .expect("a query is cleared before the list closes");
        assert_eq!(p.query, "");
        assert_eq!(p.items.len(), 3);
        assert_eq!(act(&mut a, key(KeyCode::Esc)), Action::None);
        assert!(a.picker.is_none(), "the second Esc closes the list");
    }

    /// Some terminals report Shift on a plain letter. That must not make the filter deaf, which
    /// is why the guard refuses only Control and Alt.
    #[test]
    fn a_shifted_letter_still_reaches_the_filter() {
        let mut a = app();
        a.set_sessions(vec![
            picked("s1", "max horda", "x"),
            picked("s2", "kitchen", "y"),
        ]);
        let shifted = KeyEvent::new(KeyCode::Char('m'), KeyModifiers::SHIFT);
        assert_eq!(act(&mut a, shifted), Action::None);
        assert_eq!(a.picker.as_ref().unwrap().query, "m");
        assert_eq!(a.picker.as_ref().unwrap().items.len(), 1);

        // Control still belongs to the interface: Ctrl-K must not type a `k`.
        let ctrl = KeyEvent::new(KeyCode::Char('k'), KeyModifiers::CONTROL);
        act(&mut a, ctrl);
        assert_eq!(
            a.picker.as_ref().unwrap().query,
            "m",
            "Ctrl-K is not a letter"
        );
    }

    #[test]
    fn enter_submits_and_a_slash_runs_a_command() {
        let mut a = app();
        for ch in "hello".chars() {
            act(&mut a, key(KeyCode::Char(ch)));
        }
        assert_eq!(
            act(&mut a, key(KeyCode::Enter)),
            Action::Submit("hello".into())
        );
        assert!(a.input.is_empty(), "the composer is emptied by submitting");

        for ch in "/status".chars() {
            act(&mut a, key(KeyCode::Char(ch)));
        }
        assert_eq!(
            act(&mut a, key(KeyCode::Enter)),
            Action::Command("/status".into())
        );
    }

    #[test]
    fn a_second_enter_while_running_is_refused_rather_than_queued() {
        let mut a = app();
        a.running = true;
        for ch in "more".chars() {
            act(&mut a, key(KeyCode::Char(ch)));
        }
        assert_eq!(act(&mut a, key(KeyCode::Enter)), Action::None);
        assert_eq!(a.input, "more", "the text is kept for after the run");
        assert!(matches!(
            a.blocks.last(),
            Some(Block::Note {
                kind: NoteKind::Warn,
                ..
            })
        ));
    }

    #[test]
    fn escape_stops_a_run_but_only_clears_the_line_when_idle() {
        let mut a = app();
        a.insert_str("draft");
        assert_eq!(act(&mut a, key(KeyCode::Esc)), Action::None);
        assert!(a.input.is_empty());

        a.running = true;
        assert_eq!(act(&mut a, key(KeyCode::Esc)), Action::CancelRun);
        let ctrl_c = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL);
        assert_eq!(act(&mut a, ctrl_c), Action::CancelRun);
    }

    #[test]
    fn ctrl_d_quits_only_on_an_empty_line() {
        let mut a = app();
        let ctrl_d = KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL);
        a.insert_str("x");
        a.end();
        assert_eq!(act(&mut a, ctrl_d), Action::None);
        assert_eq!(
            a.input, "x",
            "at the end of the line there is nothing to delete"
        );
        a.home();
        assert_eq!(act(&mut a, ctrl_d), Action::None);
        assert!(a.input.is_empty(), "it deletes forward");
        assert_eq!(act(&mut a, ctrl_d), Action::Quit);
    }

    #[test]
    fn an_approval_owns_the_keyboard() {
        let mut a = app();
        let (tx, mut rx) = tokio::sync::oneshot::channel();
        a.approval = Some(Approval::new("shell".into(), "rm -rf".into(), tx));
        // A normal character is swallowed, not typed into the composer.
        assert_eq!(act(&mut a, key(KeyCode::Char('x'))), Action::None);
        assert!(a.input.is_empty());
        assert!(a.approval.is_some());
        // `y` answers and clears the modal.
        assert_eq!(act(&mut a, key(KeyCode::Char('y'))), Action::None);
        assert!(a.approval.is_none());
        assert_eq!(rx.try_recv(), Ok(Choice::Once));
    }

    #[test]
    fn the_cursor_rests_on_deny_and_the_arrows_move_it() {
        let mut a = app();
        let (tx, mut rx) = tokio::sync::oneshot::channel();
        a.approval = Some(Approval::new("shell".into(), "date".into(), tx));
        assert_eq!(a.pending_choice(), Some(Choice::Deny), "safe by default");

        // One press of enter must not run a command.
        assert_eq!(act(&mut a, key(KeyCode::Enter)), Action::None);
        assert_eq!(rx.try_recv(), Ok(Choice::Deny));

        // ...but one arrow up makes it easy to say yes on purpose.
        let (tx, mut rx) = tokio::sync::oneshot::channel();
        a.approval = Some(Approval::new("shell".into(), "date".into(), tx));
        assert_eq!(act(&mut a, key(KeyCode::Up)), Action::None);
        assert_eq!(a.pending_choice(), Some(Choice::Session));
        assert_eq!(act(&mut a, key(KeyCode::Up)), Action::None);
        assert_eq!(a.pending_choice(), Some(Choice::Once));
        // It wraps, so holding down never leaves the menu.
        assert_eq!(act(&mut a, key(KeyCode::Up)), Action::None);
        assert_eq!(a.pending_choice(), Some(Choice::Deny));
        assert_eq!(act(&mut a, key(KeyCode::Down)), Action::None);
        assert_eq!(a.pending_choice(), Some(Choice::Once));
        assert_eq!(act(&mut a, key(KeyCode::Enter)), Action::None);
        assert_eq!(rx.try_recv(), Ok(Choice::Once));
    }

    #[test]
    fn the_second_answer_is_the_one_that_lasts() {
        let mut a = app();
        let (tx, mut rx) = tokio::sync::oneshot::channel();
        a.approval = Some(Approval::new("shell".into(), "date".into(), tx));
        // `2` is the session answer, reachable without counting arrows.
        assert_eq!(act(&mut a, key(KeyCode::Char('2'))), Action::None);
        assert_eq!(rx.try_recv(), Ok(Choice::Session));
    }

    /// `/retry` is a loop action, not a note: the text comes from the store, so the command has to
    /// leave the app's hands (#224).
    #[test]
    fn retry_is_a_command_the_loop_answers() {
        let mut a = app();
        assert_eq!(command(&mut a, "/retry"), Command::Retry);
        assert!(
            a.blocks.is_empty(),
            "it says nothing by itself: the loop has the store"
        );
    }

    #[test]
    fn status_reaches_the_transcript_through_a_command() {
        let mut a = app();
        a.status.record(TurnUsage {
            prompt_tokens: Some(1200),
            cached_tokens: Some(1000),
            completion_tokens: Some(40),
            latency_ms: 900,
            ..TurnUsage::default()
        });
        assert_eq!(command(&mut a, "/status"), Command::Keep);
        let text = match a.blocks.last() {
            Some(Block::Note { text, .. }) => text.clone(),
            other => panic!("expected a note, got {other:?}"),
        };
        assert!(text.contains("1200"), "{text}");
        assert!(text.contains("cache 83%"), "{text}");
    }

    #[test]
    fn new_session_starts_empty_and_forgets_the_id() {
        let mut a = app();
        a.session = Some("s1".into());
        a.blocks.push(Block::User("hi".into()));
        a.printed = 40; // a long previous session, already in the scrollback
                        // The command only asks; the loop owns the switch, because clearing the screen is a
                        // decision the loop makes once rather than something a key handler does behind its back.
        assert_eq!(command(&mut a, "/new"), Command::New);
        a.start_new_session(Some(welcome()));
        assert!(a.session.is_none(), "the id goes");
        assert!(a.status.session.is_none(), "and the readout agrees");
        assert_eq!(
            a.blocks.len(),
            1,
            "the pane, and nothing from the old session"
        );
        assert!(matches!(a.blocks[0], Block::Welcome(_)));
        assert_eq!(
            a.printed, 0,
            "the watermark belongs to the session it counted"
        );
    }

    /// The watermark counts lines of *this* transcript. Kept across a switch, it hides the new
    /// one: the painter would skip the first N lines of a list that no longer has them.
    #[test]
    fn a_cleared_transcript_prints_the_next_one_from_its_first_line() {
        let mut a = app();
        a.blocks.push(Block::User("old".into()));
        a.printed = 7; // what the printer had already handed to the scrollback

        assert_eq!(command(&mut a, "/clear"), Command::Keep);
        assert_eq!(a.printed, 0, "a cleared screen has nothing printed");
        assert!(a.blocks.is_empty());

        a.blocks.push(Block::User("new".into()));
        let skip = view::line_offset_of(&a, a.printed, 80, 24);
        let printed = view::transcript_lines(&a, 80, 24)
            .into_iter()
            .skip(skip)
            .count();
        assert!(
            printed > 0,
            "the first line after a clear has to reach the screen"
        );
    }

    /// Ctrl+L is the same clear by another door, and it went through the same non-reset.
    #[test]
    fn ctrl_l_clears_the_screen_and_the_watermark_with_it() {
        let mut a = app();
        a.blocks.push(Block::User("old".into()));
        a.printed = 7;
        assert_eq!(
            act(
                &mut a,
                KeyEvent::new(KeyCode::Char('l'), KeyModifiers::CONTROL)
            ),
            Action::None
        );
        assert!(a.blocks.is_empty());
        assert_eq!(a.printed, 0);
    }

    /// The watermark is a block boundary, so `^T` after a finished run prints nothing.
    ///
    /// This is the bug it replaces: unfolding a block that sits *above* the watermark made the
    /// printed part taller, `paint` printed from a line number the rearranged transcript no
    /// longer meant, and the answer appeared twice. Folding it back then made the count *shorter*
    /// than the watermark, and every later frame silently dropped lines.
    #[test]
    fn unfolding_a_printed_block_prints_nothing_and_loses_nothing() {
        let mut a = app();
        a.blocks.push(Block::User("ask me something".into()));
        a.blocks.push(Block::Reasoning {
            text: (1..=30).map(|i| format!("thought {i}\n")).collect(),
            done: true,
        });
        a.blocks.push(Block::Reply {
            text: "the answer".into(),
            done: true,
        });

        // The printer hands everything finished to the scrollback and freezes its fold state.
        let printed = view::stable_line_count(&a, 80, 24);
        a.freeze_printed(view::finished_blocks(&a));
        assert_eq!(a.printed, 3, "every block is printed");

        for _ in 0..2 {
            a.toggle_thinking();
            assert_eq!(
                view::stable_line_count(&a, 80, 24),
                printed,
                "a printed block keeps the height it was printed at, whatever ^T does now"
            );
            assert_eq!(
                view::line_offset_of(&a, a.printed, 80, 24),
                printed,
                "so the next frame would print nothing"
            );
        }
    }

    /// `^T` after a finished run has nothing on screen to open, so it asks for the echo — and
    /// still does not move the watermark (#217).
    #[test]
    fn a_toggle_on_a_finished_run_asks_for_the_echo() {
        let mut a = app();
        a.blocks.push(Block::Reasoning {
            text: (1..=30).map(|i| format!("thought {i}\n")).collect(),
            done: true,
        });
        a.blocks.push(Block::Reply {
            text: "the answer".into(),
            done: true,
        });
        a.freeze_printed(view::finished_blocks(&a));
        let printed = view::line_offset_of(&a, a.printed, 80, 24);

        act(
            &mut a,
            KeyEvent::new(KeyCode::Char('t'), KeyModifiers::CONTROL),
        );
        assert!(a.show_thinking, "the toggle still flips the flag");
        assert_eq!(a.echo, Some(0), "and asks the paint to print block 0 again");
        assert_eq!(
            view::line_offset_of(&a, a.printed, 80, 24),
            printed,
            "which is a copy below, not a reprint of what is above"
        );

        // Folding back asks for nothing: there is nothing to show.
        act(
            &mut a,
            KeyEvent::new(KeyCode::Char('t'), KeyModifiers::CONTROL),
        );
        assert_eq!(a.echo, None);
    }

    /// What `^T` does govern: the tail, which has not been printed yet.
    #[test]
    fn a_toggle_still_opens_the_block_that_has_not_been_printed() {
        let mut a = app();
        a.blocks.push(Block::User("ask".into()));
        a.blocks.push(Block::Reasoning {
            text: (1..=30).map(|i| format!("old {i}\n")).collect(),
            done: true,
        });
        a.freeze_printed(view::finished_blocks(&a));
        let printed = view::stable_line_count(&a, 80, 24);

        a.blocks.push(Block::Reasoning {
            text: (1..=30).map(|i| format!("new {i}\n")).collect(),
            done: false,
        });
        let folded = view::transcript_lines(&a, 80, 24).len();
        a.toggle_thinking();
        let open = view::transcript_lines(&a, 80, 24).len();

        assert!(
            open > folded,
            "the unprinted block grew: {folded} -> {open}"
        );
        assert_eq!(
            view::line_offset_of(&a, a.printed, 80, 24),
            printed,
            "and the printed part did not"
        );
        assert_eq!(a.printed, 2, "the new block is not printed yet");
    }

    /// A narrower window rewraps everything, including what is behind the watermark. The boundary
    /// is still the same block, so the pane starts where it started — not N lines into a list that
    /// happens to have moved.
    #[test]
    fn a_reflow_moves_the_printed_part_without_reprinting_it() {
        let mut a = app();
        a.blocks.push(Block::User(
            "a question long enough to wrap somewhere".into(),
        ));
        a.blocks.push(Block::Reply {
            text: "the answer, also long enough that a narrow window wraps it".into(),
            done: true,
        });
        a.freeze_printed(view::finished_blocks(&a));

        let text_of = |lines: Vec<ratatui::text::Line<'static>>| -> String {
            lines
                .iter()
                .map(|l| {
                    l.spans
                        .iter()
                        .map(|s| s.content.as_ref())
                        .collect::<String>()
                })
                .collect::<Vec<_>>()
                .join("\n")
        };
        for width in [100usize, 40, 72] {
            let all = view::transcript_lines(&a, width, 24);
            let skip = view::line_offset_of(&a, a.printed, width, 24);
            let tail = text_of(all.into_iter().skip(skip).collect());
            assert!(
                !tail.contains("a question long enough"),
                "at {width}: the pane must not start before the watermark: {tail}"
            );
        }
    }

    /// `/resume` replaces the transcript too: the loaded conversation has to start on screen, not
    /// after however many lines the previous one happened to print.
    #[test]
    fn a_resumed_session_is_shown_from_its_first_line() {
        let mut a = app();
        a.printed = 120;
        a.apply_session(
            "s1".into(),
            vec![Block::User("one".into()), Block::User("two".into())],
            false,
        );
        assert_eq!(a.printed, 0);
        assert_eq!(a.blocks.len(), 2);
    }

    #[test]
    fn resume_asks_the_loop_for_the_list() {
        let mut a = app();
        assert_eq!(command(&mut a, "/resume"), Command::Sessions);
        assert_eq!(command(&mut a, "/sessions"), Command::Sessions);
    }

    fn typed(a: &mut App, text: &str) {
        for ch in text.chars() {
            assert_eq!(act(a, key(KeyCode::Char(ch))), Action::None);
        }
    }

    fn menu_names(a: &App) -> Vec<&'static str> {
        a.menu
            .as_ref()
            .map(|m| m.items.iter().map(|c| c.name).collect())
            .unwrap_or_default()
    }

    #[test]
    fn a_slash_opens_the_menu_with_every_command_the_interface_has() {
        let mut a = app();
        typed(&mut a, "/");
        assert_eq!(
            menu_names(&a),
            [
                "/new",
                "/resume",
                "/retry",
                "/bg",
                "/tasks",
                "/model",
                "/id",
                "/profile",
                "/gateway",
                "/goal",
                "/loop",
                "/cron",
                "/reasoning",
                "/settings",
                "/set",
                "/yolo",
                "/status",
                "/compress",
                "/archive",
                "/clear",
                "/help",
                "/exit"
            ]
        );
        assert_eq!(a.menu.as_ref().map(|m| m.cursor), Some(0));
        assert_eq!(a.input, "/");
    }

    #[test]
    fn the_arrows_move_the_highlight_and_stop_at_the_ends() {
        let mut a = app();
        typed(&mut a, "/");
        assert_eq!(act(&mut a, key(KeyCode::Up)), Action::None);
        assert_eq!(a.menu.as_ref().map(|m| m.cursor), Some(0));
        assert_eq!(act(&mut a, key(KeyCode::Down)), Action::None);
        assert_eq!(act(&mut a, key(KeyCode::Char('j'))), Action::None);
        assert_eq!(
            a.menu.as_ref().and_then(|m| m.current()).map(|c| c.name),
            Some("/retry"),
            "down, then j: /new, /resume, /retry"
        );
        assert_eq!(act(&mut a, key(KeyCode::Char('k'))), Action::None);
        assert_eq!(act(&mut a, key(KeyCode::BackTab)), Action::None);
        assert_eq!(a.menu.as_ref().map(|m| m.cursor), Some(0));
        // One more press than there are commands: the cursor stops at the last one rather than
        // wrapping, so the count only has to be at least the length of the list.
        for _ in 0..30 {
            act(&mut a, key(KeyCode::Down));
        }
        assert_eq!(
            a.menu.as_ref().and_then(|m| m.current()).map(|c| c.name),
            Some("/exit")
        );
        assert_eq!(a.input, "/", "moving never touches the line");
    }

    #[test]
    fn tab_in_the_menu_fills_the_highlighted_command_without_running_it() {
        let mut a = app();
        typed(&mut a, "/");
        act(&mut a, key(KeyCode::Down));
        assert_eq!(act(&mut a, key(KeyCode::Tab)), Action::None);
        assert_eq!(a.input, "/resume");
        assert_eq!(a.cursor, 7);
        assert!(a.menu.is_none(), "accepting closes it");
        assert!(a.blocks.is_empty(), "and nothing ran");
    }

    #[test]
    fn enter_in_the_menu_runs_the_highlighted_command_like_typing_it() {
        let mut a = app();
        typed(&mut a, "/");
        act(&mut a, key(KeyCode::Down));
        assert_eq!(
            act(&mut a, key(KeyCode::Enter)),
            Action::Command("/resume".into())
        );
        assert!(a.menu.is_none() && a.input.is_empty());
        assert!(matches!(a.blocks.last(), Some(Block::User(t)) if t == "/resume"));

        // A command with an argument runs bare, as `/model` typed by hand does.
        typed(&mut a, "/mo");
        assert_eq!(
            act(&mut a, key(KeyCode::Enter)),
            Action::Command("/model".into())
        );
    }

    #[test]
    fn escape_closes_the_menu_and_leaves_the_text_alone() {
        let mut a = app();
        typed(&mut a, "/s");
        assert!(a.menu.is_some());
        assert_eq!(act(&mut a, key(KeyCode::Esc)), Action::None);
        assert!(a.menu.is_none());
        assert_eq!(a.input, "/s");
    }

    #[test]
    fn a_typed_letter_refilters_and_no_match_closes_the_menu() {
        let mut a = app();
        typed(&mut a, "/s");
        assert_eq!(menu_names(&a), ["/resume", "/settings", "/set", "/status"]);
        typed(&mut a, "t");
        assert_eq!(menu_names(&a), ["/status"], "`/st` matches one command");
        act(&mut a, key(KeyCode::Backspace));
        assert_eq!(menu_names(&a), ["/resume", "/settings", "/set", "/status"]);
        act(&mut a, key(KeyCode::Backspace));
        // 21 now, not 20: `/loop` joined the table (`#173`), and this asserts the menu shows
        // every command the interface has rather than a number that happens to be right.
        assert_eq!(menu_names(&a).len(), 22, "back to the bare slash");
        act(&mut a, key(KeyCode::Backspace));
        assert!(a.menu.is_none(), "an empty line has no menu");
    }

    /// `#253`: the menu belongs to the line, not to the keystroke that opened it. A wrong letter
    /// used to consume it — `refilter_menu` took the menu and returned — so nothing brought it back
    /// but clearing the line.
    #[test]
    fn a_wrong_letter_says_so_and_backspace_brings_the_list_back() {
        let mut a = app();
        typed(&mut a, "/s");
        typed(&mut a, "z");
        assert_eq!(a.input, "/sz");
        assert!(a.menu.is_some(), "the menu stays up to say it has nothing");
        assert!(menu_names(&a).is_empty(), "and offers nothing");

        // The same keystroke that dropped it for good now puts the list back.
        act(&mut a, key(KeyCode::Backspace));
        assert_eq!(menu_names(&a), ["/resume", "/settings", "/set", "/status"]);
        act(&mut a, key(KeyCode::Backspace));
        assert_eq!(a.input, "/");
        assert_eq!(
            menu_names(&a).len(),
            22,
            "and all the way back to everything"
        );

        // Backspacing through a real command filters out the way typing it filtered in.
        let mut a = app();
        typed(&mut a, "/cron");
        assert_eq!(menu_names(&a), ["/cron"]);
        act(&mut a, key(KeyCode::Backspace));
        assert_eq!(menu_names(&a), ["/cron"]);
        act(&mut a, key(KeyCode::Backspace));
        assert!(menu_names(&a).contains(&"/cron"));
        for _ in 0..2 {
            act(&mut a, key(KeyCode::Backspace));
        }
        assert_eq!(a.input, "/");
        // 21: `/loop` is in the table now (`#173`).
        assert_eq!(menu_names(&a).len(), 22);
        act(&mut a, key(KeyCode::Backspace));
        assert!(a.menu.is_none(), "deleting the `/` closes it");
    }

    /// Esc still wins for the rest of the line, and Tab is the one thing that outranks it.
    #[test]
    fn esc_keeps_the_menu_shut_until_a_line_is_finished_or_tab_asks() {
        let mut a = app();
        typed(&mut a, "/s");
        act(&mut a, key(KeyCode::Esc));
        assert!(a.menu.is_none());
        // Neither more typing nor a backspace brings it back.
        typed(&mut a, "e");
        assert!(a.menu.is_none(), "the next keystroke must not undo esc");
        assert_eq!(a.input, "/se");
        act(&mut a, key(KeyCode::Backspace));
        assert!(a.menu.is_none());
        // Tab is an explicit ask, and it opens it again.
        act(&mut a, key(KeyCode::Tab));
        assert!(a.menu.is_some(), "tab outranks the earlier esc");
        // And once the line is committed, the next one starts clean.
        act(&mut a, key(KeyCode::Enter));
        typed(&mut a, "/");
        assert!(a.menu.is_some(), "a new line is not the dismissed one");
    }

    #[test]
    fn a_space_ends_the_command_word_and_closes_the_menu() {
        let mut a = app();
        typed(&mut a, "/model");
        assert!(a.menu.is_some());
        typed(&mut a, " ");
        assert!(a.menu.is_none());
        typed(&mut a, "gem");
        assert_eq!(a.input, "/model gem");
        assert!(a.menu.is_none(), "arguments are not completed");
    }

    #[test]
    fn a_key_the_menu_does_not_use_closes_it_and_does_its_usual_job() {
        let mut a = app();
        typed(&mut a, "/s");
        assert_eq!(act(&mut a, key(KeyCode::Left)), Action::None);
        assert!(a.menu.is_none());
        assert_eq!(a.cursor, 1, "the arrow moved the cursor as it always does");
        // Ctrl-U clears the line: the menu does not keep it.
        typed(&mut a, "/");
        let ctrl_u = KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL);
        act(&mut a, ctrl_u);
        assert!(a.menu.is_none() && a.input.is_empty());
    }

    #[test]
    fn tab_fills_a_unique_prefix_and_opens_the_menu_for_several() {
        let mut a = app();
        typed(&mut a, "/ne");
        assert_eq!(act(&mut a, key(KeyCode::Tab)), Action::None);
        assert_eq!(a.input, "/new");
        assert!(a.menu.is_none());

        let mut a = app();
        typed(&mut a, "/mo");
        act(&mut a, key(KeyCode::Tab));
        assert_eq!(
            a.input, "/model ",
            "a command with an argument gets a space"
        );

        let mut a = app();
        typed(&mut a, "/s");
        act(&mut a, key(KeyCode::Esc));
        assert!(a.menu.is_none());
        act(&mut a, key(KeyCode::Tab));
        assert_eq!(menu_names(&a), ["/resume", "/settings", "/set", "/status"]);
        assert_eq!(a.input, "/s", "opening it does not touch the line");
    }

    #[test]
    fn tab_does_nothing_where_there_is_no_command_to_complete() {
        for line in ["hello", "/zzz", "/new now", "x /ne"] {
            let mut a = app();
            a.insert_str(line);
            assert_eq!(act(&mut a, key(KeyCode::Tab)), Action::None);
            assert_eq!(a.input, line);
            assert!(a.menu.is_none(), "{line:?}");
        }
        // Not at the end of the line either: completing there would strand the tail.
        let mut a = app();
        a.insert_str("/ne");
        a.move_left();
        act(&mut a, key(KeyCode::Tab));
        assert_eq!(a.input, "/ne");
    }

    #[test]
    fn prose_never_opens_the_menu_and_a_paste_does_not_either() {
        let mut a = app();
        typed(&mut a, "hello /");
        assert!(a.menu.is_none(), "a slash inside prose is just a slash");
        let mut a = app();
        a.insert_str("/");
        assert!(
            a.menu.is_none(),
            "a paste goes to the line and nothing else"
        );
        assert_eq!(a.input, "/");
    }

    #[test]
    fn the_menu_stays_shut_while_an_approval_or_a_picker_is_up() {
        let mut a = app();
        let (tx, _rx) = tokio::sync::oneshot::channel();
        a.approval = Some(Approval::new("shell".into(), "date".into(), tx));
        typed(&mut a, "/");
        assert!(a.menu.is_none());
        assert!(a.input.is_empty(), "the approval swallowed the key");

        let mut a = app();
        a.set_sessions(vec![app::Picked {
            note: String::new(),
            id: "a".into(),
            title: None,
            ago: "now".into(),
            messages: 1,
            preview: "hi".into(),
        }]);
        typed(&mut a, "/");
        assert!(a.menu.is_none() && a.input.is_empty());
        // Tab with a typed prefix cannot open it behind the picker either.
        a.input = "/s".into();
        a.cursor = 2;
        act(&mut a, key(KeyCode::Tab));
        assert!(a.menu.is_none());
    }

    #[test]
    fn help_lists_every_command_the_interface_has_and_the_new_keys() {
        let mut a = app();
        command(&mut a, "/help");
        let text = match a.blocks.last() {
            Some(Block::Note { text, .. }) => text.clone(),
            other => panic!("expected a note, got {other:?}"),
        };
        for c in eclipse_core::commands::COMMANDS {
            assert!(text.contains(c.name), "{} missing from\n{text}", c.name);
        }
        assert!(text.contains("tab") && text.contains("↑↓"), "{text}");
    }

    /// #225: `/tasks` is a list of sessions, so `enter` does what `enter` does on any list — and a
    /// `/bg` with no question is said here, where the composer can still be corrected.
    #[test]
    fn tasks_opens_a_list_whose_enter_resumes_the_session_and_bg_needs_a_prompt() {
        let mut a = app();
        let mut live =
            eclipse_core::tasks::Task::begun("1700000000000-1-0", "summarise the issues");
        live.pid = std::process::id();
        live.last = "tool read_file".into();
        a.set_tasks(vec![live]);

        let picker = a.picker.as_ref().expect("the list is up");
        assert_eq!(picker.kind, app::PickerKind::Tasks);
        assert_eq!(picker.title, "task");
        assert_eq!(picker.count_label(), "1 tasks");
        assert_eq!(picker.items[0].id, "1700000000000-1-0");
        assert!(
            picker.items[0].note.contains("running"),
            "the state is beside the row: {:?}",
            picker.items[0].note
        );
        assert!(
            picker.items[0]
                .preview
                .contains(&format!("pid {}", std::process::id())),
            "a live task prints the pid that stops it: {:?}",
            picker.items[0].preview
        );
        assert_eq!(
            act(&mut a, key(KeyCode::Enter)),
            Action::Resume("1700000000000-1-0".into())
        );

        // Nothing registered: a note, and no list.
        let mut empty = app();
        empty.set_tasks(Vec::new());
        assert!(empty.picker.is_none());
        assert!(matches!(
            empty.blocks.last(),
            Some(Block::Note {
                kind: NoteKind::Info,
                ..
            })
        ));

        // `/bg` with nothing after it, and with a question.
        let mut a = app();
        assert_eq!(command(&mut a, "/bg"), Command::Keep);
        assert!(matches!(
            a.blocks.last(),
            Some(Block::Note {
                kind: NoteKind::Warn,
                ..
            })
        ));
        assert_eq!(
            command(&mut a, "/bg summarise the issues"),
            Command::Bg("summarise the issues".into())
        );
        assert_eq!(command(&mut a, "/tasks"), Command::Tasks);
    }

    #[test]
    fn every_command_the_table_gives_the_interface_is_handled_here() {
        use eclipse_core::commands::{Front, COMMANDS};
        for c in COMMANDS {
            for word in std::iter::once(c.name).chain(c.aliases.iter().copied()) {
                let mut a = app();
                let got = command(&mut a, word);
                if c.serves(Front::Tui) {
                    assert_ne!(
                        got,
                        Command::Unknown,
                        "{word} is in the table but not handled"
                    );
                } else {
                    assert_eq!(got, Command::Unknown, "{word} is not for this interface");
                }
            }
        }
    }

    #[test]
    fn the_interface_handles_nothing_the_table_does_not_list() {
        // Near-misses of real commands, and words only a hand-written `match` would know.
        for word in [
            "/",
            "/ne",
            "/news",
            "/NEW",
            "/stat",
            "/statuses",
            "/clea",
            "/exi",
            "/h",
            "/models",
            "/session",
            "/q",
            "/mod",
            "new",
            "//new",
            "/new now",
            "/id 1",
            "/exit now",
        ] {
            let mut a = app();
            assert_eq!(command(&mut a, word), Command::Unknown, "{word:?} ran");
            assert!(
                matches!(
                    a.blocks.last(),
                    Some(Block::Note {
                        kind: NoteKind::Warn,
                        ..
                    })
                ),
                "{word:?} gave no warning"
            );
        }
    }

    fn welcome() -> app::Welcome {
        app::Welcome {
            approvals: false,
            version: "0.1.0".into(),
            model: "m".into(),
            endpoint: "127.0.0.1:1".into(),
            profile: None,
            workspace: "/w".into(),
            groups: Vec::new(),
            skills: Vec::new(),
        }
    }

    #[test]
    fn the_model_menu_switches_with_the_arrow_keys_and_closes_on_escape() {
        let mut a = app();
        a.set_models_from(None, vec!["alpha".into(), "beta".into(), "gamma".into()]);
        assert!(
            a.picker.is_some(),
            "an arrowless listing would be the old behaviour"
        );
        // `act` is the key path the terminal actually takes, not a helper that mimics it.
        act(&mut a, key(KeyCode::Down));
        match act(&mut a, key(KeyCode::Enter)) {
            Action::PickModel(name, route) => {
                assert_eq!(name, "beta");
                assert_eq!(
                    route, None,
                    "one route: the model step is the whole of /model"
                );
            }
            other => panic!("enter on a model must pick it, got {other:?}"),
        }
        assert!(a.picker.is_none(), "the list closes on a choice");

        let mut a = app();
        a.set_models_from(None, vec!["alpha".into(), "beta".into()]);
        act(&mut a, key(KeyCode::Down));
        act(&mut a, key(KeyCode::Esc));
        assert!(a.picker.is_none(), "escape closes without choosing");
        assert_eq!(a.model, "m", "and changes nothing");

        // An empty answer is not an empty menu: it says so and shows no list.
        let mut a = app();
        a.set_models_from(None, vec![]);
        assert!(a.picker.is_none());
    }

    #[test]
    fn enter_while_the_model_list_is_on_its_way_says_so() {
        let mut a = app();
        a.listing_models = true;
        // Enter with nothing typed: the old behaviour was silence, which reads as a lost key.
        assert!(matches!(act(&mut a, key(KeyCode::Enter)), Action::None));
        assert!(
            matches!(a.blocks.last(), Some(Block::Note { text, .. }) if text.contains("still asking")),
            "the wait is named: {:?}",
            a.blocks.last()
        );
        // Once the answer is in, silence is back to meaning "nothing to send".
        a.listing_models = false;
        let before = a.blocks.len();
        act(&mut a, key(KeyCode::Enter));
        assert_eq!(a.blocks.len(), before);
    }

    #[test]
    fn the_provider_step_comes_first_and_the_route_travels_with_the_model() {
        let routes = vec![
            eclipse_core::router::RouteInfo {
                name: "local".into(),
                model: "inkling-2-mini".into(),
                endpoint: "127.0.0.1:18045/v1".into(),
            },
            eclipse_core::router::RouteInfo {
                name: "cloud".into(),
                model: "big".into(),
                endpoint: "ollama.example:443/v1".into(),
            },
        ];
        let mut a = app();
        a.open_providers(&routes, Some("local"));
        let picker = a.picker.as_ref().expect("a menu, not a printed list");
        assert_eq!(picker.kind, app::PickerKind::Provider);
        assert_eq!(
            picker.cursor_name(),
            Some("local"),
            "the cursor starts where you are"
        );
        assert_eq!(
            picker.items[1].preview, "ollama.example:443/v1",
            "the endpoint is the detail line: two routes can be the same box"
        );

        // Down, Enter: that is a request for the second endpoint's models, not a choice yet.
        act(&mut a, key(KeyCode::Down));
        match act(&mut a, key(KeyCode::Enter)) {
            Action::PickProvider(name) => assert_eq!(name, "cloud"),
            other => panic!("enter on a provider must ask it, got {other:?}"),
        }
        assert!(
            a.picker.is_none(),
            "asking is not choosing: the menu closes"
        );

        // The answer opens the model list, remembering whose answer it was.
        a.set_models_from(Some("cloud".into()), vec!["big".into(), "small".into()]);
        let picker = a.picker.as_ref().expect("the model list");
        assert_eq!(picker.kind, app::PickerKind::Model);
        assert_eq!(picker.route.as_deref(), Some("cloud"));
        match act(&mut a, key(KeyCode::Enter)) {
            Action::PickModel(name, route) => {
                assert_eq!(name, "big");
                assert_eq!(
                    route.as_deref(),
                    Some("cloud"),
                    "the model is set on that route"
                );
            }
            other => panic!("enter on a model must pick it, got {other:?}"),
        }
        // `/model 2` still resolves against the list that was just shown.
        let mut b = app();
        b.set_models_from(Some("cloud".into()), vec!["big".into(), "small".into()]);
        assert_eq!(b.resolve_model("2").as_deref(), Some("small"));
    }

    #[test]
    fn typing_a_number_still_picks_from_the_last_list() {
        // `/model 2` is kept for a name that is hard to type; the menu did not remove it.
        let mut a = app();
        a.set_models_from(None, vec!["alpha".into(), "beta".into()]);
        assert_eq!(a.resolve_model("2").as_deref(), Some("beta"));
        assert_eq!(a.resolve_model("beta").as_deref(), Some("beta"));
        assert_eq!(a.resolve_model("9"), None);
    }
}

#[cfg(test)]
mod wheel_and_paste_tests {
    use super::*;
    use crate::tui::app::{App, PASTE_INLINE_LIMIT};

    fn app() -> App {
        let mut app = App::new(
            crate::status::Status::new("a-model", "http://localhost:1", 1000, "/tmp/ws".into()),
            "a-model",
            "/tmp/ws",
            None,
        );
        // Enough transcript that scrolling means something.
        for i in 0..100 {
            app.blocks.push(app::Block::Note {
                kind: app::NoteKind::Info,
                text: format!("line {i}"),
            });
        }
        app
    }

    fn key(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }

    /// The one mode `ratatui::init()` does not set, and the modes that must never be set.
    ///
    /// Without `?2004h` a pasted newline arrives as `Enter`, and `Enter` submits. The mouse modes
    /// are the absence being pinned here: any one of them takes the terminal's own selection, its
    /// own menu and its own copy and hands them to this program, which is precisely the trade that
    /// ended in "copied via osc 52" on a machine with no clipboard tool to fall back on.
    #[test]
    fn the_terminal_is_told_about_pastes_and_about_nothing_else() {
        use ratatui::crossterm::execute;
        let mut on = Vec::new();
        execute!(on, EnableBracketedPaste).unwrap();
        let on = String::from_utf8(on).unwrap();
        assert!(
            on.contains("\x1b[?2004h"),
            "bracketed paste is not enabled: {on:?}"
        );

        let mut off = Vec::new();
        execute!(off, DisableBracketedPaste).unwrap();
        let off = String::from_utf8(off).unwrap();
        assert!(
            off.contains("\x1b[?2004l"),
            "bracketed paste would outlive the interface: {off:?}"
        );

        // The five mouse modes crossterm knows: clicks, drags, motion, and the two encodings.
        for mouse in ["1000", "1002", "1003", "1006", "1015"] {
            let mode = format!("?{mouse}");
            assert!(
                !on.contains(&mode) && !off.contains(&mode),
                "the pointer was taken back from the terminal: {on:?} / {off:?}"
            );
        }
    }

    /// `↑`/`↓` walk the prompt history. There is no view for them to move: the transcript is the
    /// terminal's scrollback, so a key in this program cannot scroll it.
    #[test]
    fn the_arrows_walk_the_prompt_history() {
        let mut app = app();
        app.history.push("first");
        app.history.push("second");

        act(&mut app, key(KeyCode::Up));
        assert_eq!(app.input, "second", "older");
        act(&mut app, key(KeyCode::Up));
        assert_eq!(app.input, "first");
        act(&mut app, key(KeyCode::Down));
        assert_eq!(app.input, "second", "newer");

        // A shifted arrow is the arrow: there is no viewport for the modifier to reach for.
        act(&mut app, KeyEvent::new(KeyCode::Up, KeyModifiers::SHIFT));
        assert_eq!(
            app.input, "first",
            "shift does not change what an arrow means"
        );
        // And a key that used to page a viewport now does nothing at all.
        act(&mut app, key(KeyCode::PageUp));
        assert_eq!(app.input, "first");
    }

    /// The keys that used to reach a clipboard tool or write OSC 52 are only keys now. There is no
    /// menu of this program's to open either — `App` has no field to hold one — so what is left to
    /// assert is that these keys stay quiet: no note about a clipboard, and nothing that could be
    /// mistaken for a menu.
    #[test]
    fn no_key_reaches_for_a_menu_or_a_clipboard() {
        let shift_ctrl = KeyModifiers::CONTROL | KeyModifiers::SHIFT;
        for (code, modifiers) in [
            (KeyCode::Char('c'), shift_ctrl),
            (KeyCode::Char('C'), shift_ctrl),
            (KeyCode::Char('v'), shift_ctrl),
            (KeyCode::Char('v'), KeyModifiers::CONTROL),
            (KeyCode::Char('V'), KeyModifiers::CONTROL),
            (KeyCode::Insert, KeyModifiers::NONE),
            (KeyCode::Insert, KeyModifiers::SHIFT),
        ] {
            let mut app = app();
            let blocks = app.blocks.len();
            assert_eq!(
                act(&mut app, KeyEvent::new(code, modifiers)),
                Action::None,
                "{code:?}"
            );
            assert_eq!(app.blocks.len(), blocks, "{code:?} said something");
            assert!(
                app.menu.is_none() && app.picker.is_none(),
                "{code:?} opened a list"
            );
        }
    }

    #[test]
    fn ctrl_t_folds_reasoning_and_unfolds_it_again() {
        let mut app = app();
        assert!(
            !app.show_thinking,
            "folded is the default: a page of dim text is not the answer"
        );
        let k = KeyEvent::new(KeyCode::Char('t'), KeyModifiers::CONTROL);
        assert_eq!(act(&mut app, k), Action::None);
        assert!(app.show_thinking);
        act(&mut app, k);
        assert!(!app.show_thinking);
        // A bare `t` is still a letter: the fold key must not eat the composer.
        act(
            &mut app,
            KeyEvent::new(KeyCode::Char('t'), KeyModifiers::NONE),
        );
        assert_eq!(app.input, "t");
        assert!(!app.show_thinking);
    }

    #[test]
    fn home_and_end_are_the_line_and_ctrl_does_not_reach_for_a_view() {
        let mut app = app();
        app.input = "hello".into();
        app.cursor = 0;
        act(&mut app, KeyEvent::new(KeyCode::End, KeyModifiers::NONE));
        assert_eq!(app.cursor, 5);
        act(&mut app, KeyEvent::new(KeyCode::Home, KeyModifiers::NONE));
        assert_eq!(app.cursor, 0);

        // With ctrl they are the same keys: the transcript above has no viewport to jump to.
        act(
            &mut app,
            KeyEvent::new(KeyCode::Home, KeyModifiers::CONTROL),
        );
        assert_eq!(app.cursor, 0);
        act(&mut app, KeyEvent::new(KeyCode::End, KeyModifiers::NONE));
        assert_eq!(app.cursor, 5);
    }

    #[test]
    fn a_folded_reasoning_block_shows_a_preview_and_a_count() {
        let mut app = app();
        app.blocks.clear();
        // Exactly forty lines, no trailing newline: the count under test is 40 - 5.
        let long: String = (0..40)
            .map(|i| format!("reasoning line {i}"))
            .collect::<Vec<_>>()
            .join("\n");
        app.blocks.push(Block::Reasoning {
            text: long.clone(),
            done: false,
        });
        let lines = view::lines_for_test(&app, 80, 24);
        let text: Vec<String> = lines.iter().map(|l| format!("{l:?}")).collect();
        let joined = text.join("\n");
        assert!(
            joined.contains("reasoning line 0"),
            "the first lines are shown"
        );
        assert!(
            !joined.contains("reasoning line 39"),
            "and the rest is folded away"
        );
        assert!(
            joined.contains("+35 line(s)"),
            "the count says how much: {joined}"
        );
        assert!(joined.contains("thinking"), "and that it is still going");
        assert!(joined.contains("^T"), "and says how to see the rest");

        // Unfolded, everything is there and the count is gone.
        app.toggle_thinking();
        let all = view::lines_for_test(&app, 80, 24)
            .iter()
            .map(|l| format!("{l:?}"))
            .collect::<Vec<_>>()
            .join("\n");
        assert!(all.contains("reasoning line 39"));
        assert!(
            !all.contains("+35 line(s)"),
            "nothing is hidden, so nothing is counted"
        );
        assert!(!all.contains("^T"), "and there is nothing left to open");
    }

    #[test]
    fn a_short_paste_goes_straight_into_the_line() {
        let mut app = app();
        app.take_paste("crates/eclipse-cli/src/tui/mod.rs");
        assert_eq!(app.input, "crates/eclipse-cli/src/tui/mod.rs");
        assert!(app.pastes.is_empty());
        assert_eq!(app.expand_pastes(&app.input), app.input);
    }

    #[test]
    fn a_paste_with_a_newline_is_a_chip_even_when_it_is_short() {
        // This is the one that broke: two short lines arrived as two `Enter`s and each one tried
        // to start a run, so the screen filled with "a run is in flight".
        let mut app = app();
        app.take_paste("first line\nsecond line");
        assert!(app.input.starts_with("[Pasted #1:"), "{}", app.input);
        assert!(
            !app.input.contains('\n'),
            "a newline must never reach the line"
        );
        assert_eq!(app.pastes.len(), 1);
        assert_eq!(
            app.expand_pastes(&app.input),
            "first line\nsecond line",
            "the model gets the paste, not the chip"
        );
    }

    #[test]
    fn a_long_single_line_paste_is_a_chip_and_keeps_every_character() {
        let mut app = app();
        let long = "x".repeat(PASTE_INLINE_LIMIT + 1);
        app.take_paste(&long);
        assert!(app.input.starts_with("[Pasted #1:"), "{}", app.input);
        assert_eq!(app.expand_pastes(&app.input), long);
    }

    #[test]
    fn two_pastes_are_two_chips_and_both_come_back_where_they_were() {
        let mut app = app();
        app.take_paste("a\nb");
        app.insert_str(" and ");
        app.take_paste("c\nd");
        let expanded = app.expand_pastes(&app.input);
        assert_eq!(expanded, "a\nb and c\nd", "{}", app.input);
    }

    #[test]
    fn backspace_removes_a_chip_whole_and_takes_its_text_with_it() {
        let mut app = app();
        app.take_paste("a\nb");
        let chip = app.input.clone();
        app.backspace();
        assert!(app.input.is_empty(), "{}", app.input);
        assert!(app.pastes.is_empty(), "the text went with the chip");
        assert_eq!(
            app.expand_pastes(&chip),
            chip,
            "with nothing behind it a chip expands to itself, not to a paste nobody asked for"
        );

        // A chip deleted as a unit cannot come back through a later expansion.
        app.insert_str("x");
        assert_eq!(app.expand_pastes(&app.input), "x");
    }

    #[test]
    fn a_typed_character_is_still_one_character() {
        let mut app = app();
        app.insert_str("abc");
        app.backspace();
        assert_eq!(app.input, "ab");
        assert!(app.pastes.is_empty());
    }
}