leviath-cli 0.3.8

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

use crossterm::event::KeyCode;

use super::helpers::truncate;
use super::state::Dashboard;
use super::types::*;
use crate::runstate;
use leviath_core::interaction;

impl Dashboard {
    pub(super) fn handle_key(&mut self, key: crossterm::event::KeyEvent) {
        let key_code = key.code;
        // Ctrl-C quits from anywhere - dialogs, text inputs, every screen. It
        // is the one binding a user reaches for expecting it to always work.
        if key
            .modifiers
            .contains(crossterm::event::KeyModifiers::CONTROL)
            && key_code == KeyCode::Char('c')
        {
            self.should_quit = true;
            return;
        }

        // Help overlay: scrolls, and closes deliberately (Esc/q/?/Enter),
        // never by a key that would also act underneath.
        if self.show_help {
            if crate::tui::widgets::help::handle_help_key(&key, &self.help_scroll) {
                self.show_help = false;
            }
            return;
        }

        // A confirmation dialog owns the keys until answered.
        if self.pending_confirm.is_some() {
            self.handle_confirm_key(&key);
            return;
        }

        // MCP management screen is modal: it owns all keys while open.
        if self.mcp_screen {
            self.handle_mcp_screen_key(key_code);
            return;
        }

        // So is the new-run screen. It has to be: a task is typed here, so
        // every letter belongs to the editor rather than to a list command.
        if self.new_run_screen {
            self.handle_new_run_key(key);
            return;
        }

        // ── Detail view ─────────────────────────────────────────────────────
        if self.detail_view {
            if self.input_mode {
                self.handle_input_mode_key(key_code, key);
                return;
            }

            // Search mode: intercept all keys for query editing
            if self.search_mode {
                match key_code {
                    KeyCode::Esc | KeyCode::Enter => {
                        if key_code == KeyCode::Esc {
                            self.search_query.clear();
                            self.search_match_idx = 0;
                        }
                        self.search_mode = false;
                    }
                    KeyCode::Backspace => {
                        self.search_query.pop();
                        self.search_match_idx = 0;
                    }
                    KeyCode::Char(c) => {
                        self.search_query.push(c);
                        self.search_match_idx = 0;
                    }
                    _ => {}
                }
                return;
            }

            // Detail view - not in input mode
            self.handle_detail_view_key(key_code);
            return;
        }

        // ── Main agent list ──────────────────────────────────────────────────
        // ── Main list filter mode: intercept all keys for query editing ─────────
        if self.list_search_mode {
            match key_code {
                KeyCode::Esc => {
                    self.list_search_mode = false;
                    self.list_search_query.clear();
                    self.selected = 0;
                    self.update_display_indices();
                }
                KeyCode::Enter => {
                    self.list_search_mode = false;
                }
                KeyCode::Backspace => {
                    self.list_search_query.pop();
                    self.selected = 0;
                    self.update_display_indices();
                }
                KeyCode::Char(c) => {
                    self.list_search_query.push(c);
                    self.selected = 0;
                    self.update_display_indices();
                }
                _ => {}
            }
            return;
        }

        if self.main_focus == MainPane::LogPane {
            self.handle_log_pane_key(key_code);
            return;
        }
        self.handle_main_list_key(key_code);
    }

    /// Keys while a confirmation dialog is open: the dialog decides, then the
    /// confirmed action runs against the run id it was opened for.
    fn handle_confirm_key(&mut self, key: &crossterm::event::KeyEvent) {
        use crate::tui::widgets::confirm::ConfirmOutcome;
        let Some((action, mut dialog)) = self.pending_confirm.take() else {
            return;
        };
        match dialog.handle(key) {
            ConfirmOutcome::Pending => self.pending_confirm = Some((action, dialog)),
            ConfirmOutcome::No => self.add_log("Cancelled".to_string()),
            ConfirmOutcome::Yes => match action {
                ConfirmAction::Kill { run_ids } => {
                    for run_id in &run_ids {
                        // Un-mark first: a killed row stays in the list, and a
                        // mark that survived the kill would silently pull the
                        // run into the next group action.
                        self.marked.remove(run_id);
                        self.perform_kill(run_id);
                    }
                }
                ConfirmAction::Delete { run_ids } => {
                    for run_id in &run_ids {
                        self.marked.remove(run_id);
                        self.perform_delete(run_id);
                    }
                }
                ConfirmAction::McpRemove { name } => self.mcp_remove_named(&name),
                // The box is read off the dialog rather than carried in the
                // outcome: whether to ask again is a note about future
                // questions, not a third answer to this one.
                ConfirmAction::EnableYolo => self.accept_yolo_warning(dialog.remembered()),
            },
        }
    }

    /// Keys while the log panel holds focus: scroll history, End/G resumes
    /// tailing, Tab/Esc hand focus back to the run list.
    fn handle_log_pane_key(&mut self, key_code: KeyCode) {
        let len = self.log.len();
        let viewport = self.log_viewport.max(1);
        match key_code {
            KeyCode::Up | KeyCode::Char('k') => self.log_scroll.scroll_up(1, len, viewport),
            KeyCode::Down | KeyCode::Char('j') => self.log_scroll.scroll_down(1),
            KeyCode::PageUp => self.log_scroll.scroll_up(viewport, len, viewport),
            KeyCode::PageDown => self.log_scroll.scroll_down(viewport),
            KeyCode::Home | KeyCode::Char('g') => self.log_scroll.jump_to_top(len, viewport),
            KeyCode::End | KeyCode::Char('G') => self.log_scroll.jump_to_tail(),
            KeyCode::Tab | KeyCode::BackTab | KeyCode::Esc => {
                self.main_focus = MainPane::RunList;
            }
            KeyCode::Char('q') => self.should_quit = true,
            KeyCode::Char('?') | KeyCode::F(1) => self.show_help = true,
            _ => {}
        }
    }

    /// Seed the input textarea when entering input mode. For an `EditText`
    /// pending request the buffer is pre-filled with the request's `body` (the
    /// current document) so the user edits it in place; otherwise it starts empty.
    fn seed_input_textarea(&mut self) {
        use interaction::InteractionKind;
        let seed = self
            .selected_agent()
            .and_then(|a| a.pending_request.as_ref())
            .filter(|r| r.kind == InteractionKind::EditText)
            .and_then(|r| r.body.clone());
        self.input_textarea = match seed {
            Some(body) => {
                ratatui_textarea::TextArea::new(body.lines().map(|s| s.to_string()).collect())
            }
            None => ratatui_textarea::TextArea::default(),
        };
    }

    /// Whether the user is actively editing a document (an `EditText`
    /// interaction). When true the editable textarea is rendered inline in the
    /// content pane - where the current text is shown - rather than in the bottom
    /// input bar, so editing happens in place over the document being revised.
    pub(in crate::commands::dashboard) fn editing_document(&self) -> bool {
        use interaction::InteractionKind;
        self.input_mode
            && self
                .selected_agent()
                .and_then(|a| a.pending_request.as_ref())
                .is_some_and(|r| r.kind == InteractionKind::EditText)
    }

    /// The document to review for the selected agent's pending interaction - the
    /// current instance's plan/output, carried as the request `body`. Shown in
    /// the output pane in place of the full accumulated history. `None` while
    /// actively editing (the textarea takes the pane) or when there is no body.
    pub(in crate::commands::dashboard) fn reviewing_body(&self) -> Option<String> {
        if self.editing_document() {
            return None;
        }
        self.selected_agent()
            .and_then(|a| a.pending_request.as_ref())
            .and_then(|r| r.body.as_deref())
            .filter(|b| !b.trim().is_empty())
            .map(str::to_string)
    }

    /// Whether the separate review pane is **on screen right now**, and so is
    /// what a scroll gesture should move.
    ///
    /// This must mirror the condition the renderer uses, not merely ask whether
    /// a review body exists. The pane is suppressed in input mode (where the
    /// document is drawn in the content pane instead) and whenever the output
    /// pane is already showing the same body - and in both of those cases a
    /// scroll aimed at `review_scroll` moves a pane nobody can see. That is
    /// exactly what happened: with a plan open for approval, every scroll key
    /// updated state that was not being rendered, so the plan sat still.
    ///
    /// `EditText` also uses `body`, but for editing rather than scrolling, so
    /// it is excluded.
    fn scroll_target_is_review(&self) -> bool {
        let content_shows_body =
            self.stage_content_mode == StageContentMode::Output && self.reviewing_body().is_some();
        !self.input_mode && !content_shows_body && self.has_scrollable_document()
    }

    /// Whether there is a review document on screen *somewhere* - the review
    /// pane or the content pane.
    ///
    /// "Is there anything to scroll", as distinct from
    /// [`Self::scroll_target_is_review`]'s "which pane holds it". Conflating
    /// those two questions is what aimed the scroll keys at a pane that was not
    /// being rendered.
    fn has_scrollable_document(&self) -> bool {
        use interaction::InteractionKind;
        self.selected_agent()
            .and_then(|a| a.pending_request.as_ref())
            .filter(|r| r.kind != InteractionKind::EditText)
            .and_then(|r| r.body.as_deref())
            .map(|b| !b.is_empty())
            .unwrap_or(false)
    }

    /// Scroll whatever is scrollable right now by `lines` (positive scrolls
    /// back through the document, matching the existing `review_scroll` /
    /// `detail_scroll` convention).
    ///
    /// One place so the keyboard and the mouse wheel cannot disagree about
    /// which pane a gesture moves.
    ///
    /// Scrolling clears any mouse selection: the highlight is anchored to
    /// screen cells, so moving text under it would leave it over the wrong
    /// content.
    pub(crate) fn scroll_by(&mut self, lines: i32) {
        self.selection = None;
        let target = match self.scroll_target_is_review() {
            true => &mut self.review_scroll,
            false => &mut self.detail_scroll,
        };
        *target = match lines >= 0 {
            true => target.saturating_add(lines.unsigned_abs() as usize),
            false => target.saturating_sub(lines.unsigned_abs() as usize),
        };
    }

    fn handle_input_mode_key(&mut self, key_code: KeyCode, key: crossterm::event::KeyEvent) {
        use interaction::InteractionKind;
        let kind = self
            .selected_agent()
            .and_then(|a| a.pending_request.as_ref())
            .map(|r| r.kind.clone());
        let options_len = self
            .selected_agent()
            .and_then(|a| a.pending_request.as_ref())
            .map(|r| r.options.len())
            .unwrap_or(0);

        match &kind {
            Some(InteractionKind::FreeText) | Some(InteractionKind::EditText) | None => {
                match key_code {
                    KeyCode::Enter if key.modifiers.is_empty() => {
                        self.submit_input();
                    }
                    KeyCode::Esc => {
                        self.input_mode = false;
                        self.input_textarea = ratatui_textarea::TextArea::default();
                        self.choice_selected = 0;
                    }
                    KeyCode::PageUp if self.has_scrollable_document() => self.scroll_by(10),
                    KeyCode::PageDown if self.has_scrollable_document() => self.scroll_by(-10),
                    _ => {
                        self.input_textarea
                            .input(ratatui_textarea::Input::from(key));
                    }
                }
            }
            _ => match key_code {
                KeyCode::Esc => {
                    self.input_mode = false;
                    self.input_textarea = ratatui_textarea::TextArea::default();
                    self.choice_selected = 0;
                }
                KeyCode::Enter => {
                    self.submit_input();
                }
                KeyCode::Up => {
                    if self.choice_selected > 0 {
                        self.choice_selected -= 1;
                    }
                }
                KeyCode::Down if options_len > 0 && self.choice_selected < options_len - 1 => {
                    self.choice_selected += 1;
                }
                // Up/Down move the selection here, so the document gets its own
                // keys. Without these there was no way at all to read a plan
                // longer than the pane while its approval prompt was open -
                // which is exactly when you need to read it.
                KeyCode::PageUp => self.scroll_by(10),
                KeyCode::PageDown => self.scroll_by(-10),
                KeyCode::Home => self.scroll_by(i32::MAX),
                KeyCode::End => self.scroll_by(i32::MIN),
                _ => {}
            },
        }
    }

    /// Keys while the full-screen stage explorer is open.
    fn handle_explorer_key(&mut self, key_code: KeyCode) {
        let visits = self.selected_history().map(|h| h.visits.len()).unwrap_or(0);
        let Some(explorer) = self.stage_explorer.as_mut() else {
            return;
        };
        match key_code {
            KeyCode::Esc | KeyCode::Char('g') => self.stage_explorer = None,
            KeyCode::Tab | KeyCode::BackTab => {
                explorer.tab = match explorer.tab {
                    ExplorerTab::Graph => ExplorerTab::Timeline,
                    ExplorerTab::Timeline => ExplorerTab::Graph,
                };
            }
            KeyCode::Char('u') => explorer.show_unvisited = !explorer.show_unvisited,
            KeyCode::Up | KeyCode::Char('k') => match explorer.tab {
                ExplorerTab::Graph => explorer.scroll = explorer.scroll.saturating_sub(1),
                ExplorerTab::Timeline => {
                    explorer.timeline_selected = explorer.timeline_selected.saturating_sub(1);
                }
            },
            KeyCode::Down | KeyCode::Char('j') => match explorer.tab {
                ExplorerTab::Graph => explorer.scroll = explorer.scroll.saturating_add(1),
                ExplorerTab::Timeline => {
                    if visits > 0 && explorer.timeline_selected + 1 < visits {
                        explorer.timeline_selected += 1;
                    }
                }
            },
            KeyCode::Enter => {
                if explorer.tab == ExplorerTab::Timeline {
                    let selected = explorer.timeline_selected;
                    let point = self
                        .selected_history()
                        .and_then(|h| h.visits.get(selected))
                        .map(|v| v.first_point);
                    if let Some(point) = point {
                        self.stage_explorer = None;
                        self.jump_to_history_point(point);
                    }
                }
            }
            KeyCode::Char('?') | KeyCode::F(1) => self.show_help = true,
            _ => {}
        }
    }

    /// Enter/Space in the Context view: fold or unfold the row under the
    /// tree cursor.
    fn toggle_context_row(&mut self) {
        use super::context_tree::TreeRow;
        let rows = self.context_tree_rows();
        match rows.get(self.context_tree.cursor) {
            Some(TreeRow::RegionHeader { region }) => {
                let region = region.clone();
                if !self.context_tree.collapsed_regions.remove(&region) {
                    self.context_tree.collapsed_regions.insert(region);
                }
                // The cursor stays on the header it just folded; a stale
                // cursor from a shrunken snapshot resolves through
                // `rows.get()` returning `None` on the next keypress.
            }
            Some(TreeRow::EntryStub { region, index }) => {
                let key = (region.clone(), *index);
                if !self.context_tree.expanded_entries.remove(&key) {
                    self.context_tree.expanded_entries.insert(key);
                }
            }
            None => {}
        }
        self.context_tree.follow_cursor = true;
    }

    /// Move the Context view's tree cursor, clamped, and scroll to it.
    fn move_context_cursor(&mut self, delta: isize) {
        let len = self.context_tree_rows().len();
        if len == 0 {
            return;
        }
        self.context_tree.cursor = self
            .context_tree
            .cursor
            .saturating_add_signed(delta)
            .min(len - 1);
        self.context_tree.follow_cursor = true;
    }

    /// Jump the tree cursor to the previous/next region header.
    fn jump_context_region(&mut self, forward: bool) {
        let rows = self.context_tree_rows();
        if let Some(target) =
            super::context_tree::nearest_region_row(&rows, self.context_tree.cursor, forward)
        {
            self.context_tree.cursor = target;
            self.context_tree.follow_cursor = true;
        }
    }

    fn handle_detail_view_key(&mut self, key_code: KeyCode) {
        if self.stage_explorer.is_some() {
            self.handle_explorer_key(key_code);
            return;
        }
        let in_context = self.stage_content_mode == StageContentMode::Context;
        match key_code {
            KeyCode::Esc => {
                if !self.search_query.is_empty() {
                    // First Esc clears the search; second exits detail view
                    self.search_query.clear();
                    self.search_match_idx = 0;
                } else {
                    self.detail_view = false;
                    self.detail_scroll = 0;
                    self.review_scroll = 0;
                    self.reset_context_history();
                }
            }
            // Stage tab navigation
            KeyCode::Left => {
                if self.selected_stage > 0 {
                    self.selected_stage -= 1;
                    self.detail_scroll = 0;
                    self.review_scroll = 0;
                    self.search_mode = false;
                    self.search_query.clear();
                    self.search_match_idx = 0;
                }
            }
            KeyCode::Right => {
                let max_stage = self
                    .selected_agent()
                    .map(|a| a.num_stages.saturating_sub(1))
                    .unwrap_or(0);
                if self.selected_stage < max_stage {
                    self.selected_stage += 1;
                    self.detail_scroll = 0;
                    self.review_scroll = 0;
                    self.search_mode = false;
                    self.search_query.clear();
                    self.search_match_idx = 0;
                }
            }
            // Number keys 1-9: jump to stage tab
            KeyCode::Char(c @ '1'..='9') => {
                let idx = (c as usize) - ('1' as usize);
                let max_stage = self
                    .selected_agent()
                    .map(|a| a.num_stages.saturating_sub(1))
                    .unwrap_or(0);
                if idx <= max_stage {
                    self.selected_stage = idx;
                    self.detail_scroll = 0;
                    self.review_scroll = 0;
                    self.search_mode = false;
                    self.search_query.clear();
                    self.search_match_idx = 0;
                }
            }
            // Content mode toggle
            KeyCode::Char('l') => {
                self.stage_content_mode = StageContentMode::Logs;
                self.detail_scroll = 0;
            }
            KeyCode::Char('o') => {
                self.stage_content_mode = StageContentMode::Output;
                self.detail_scroll = 0;
            }
            KeyCode::Char('c') => {
                self.stage_content_mode = StageContentMode::Context;
                self.detail_scroll = 0;
                // `c` shows the live current window; leave any history browsing.
                self.reset_context_history();
            }
            // Browse the run's archived context-window history in the Context
            // view: `,` = earlier point, `.` = later (past the newest → live).
            KeyCode::Char(',') => self.step_context_history(-1),
            KeyCode::Char('.') => self.step_context_history(1),
            KeyCode::Char('i') => {
                // Respond to a pending interaction, or send a mid-run message to
                // any active agent that accepts them - same key, same input area.
                if self.selected_stage_can_respond() || self.selected_agent_accepts_messages() {
                    self.input_mode = true;
                    self.choice_selected = 0;
                    self.seed_input_textarea();
                }
            }
            // In the Context view the up/down keys drive the tree cursor
            // (the view scrolls to follow it); elsewhere they scroll, through
            // `scroll_by` - the one place that decides which pane a gesture
            // moves.
            KeyCode::Up | KeyCode::Char('k') | KeyCode::Down | KeyCode::Char('j') if in_context => {
                let delta = if matches!(key_code, KeyCode::Up | KeyCode::Char('k')) {
                    -1
                } else {
                    1
                };
                self.move_context_cursor(delta);
            }
            KeyCode::Up | KeyCode::Char('k') => self.scroll_by(1),
            KeyCode::Down | KeyCode::Char('j') => self.scroll_by(-1),
            KeyCode::PageUp => self.scroll_by(10),
            KeyCode::PageDown => self.scroll_by(-10),
            // Fold / unfold the row under the Context tree's cursor.
            KeyCode::Enter | KeyCode::Char(' ') if in_context => self.toggle_context_row(),
            // Jump between region headers.
            KeyCode::Char('[') if in_context => self.jump_context_region(false),
            KeyCode::Char(']') if in_context => self.jump_context_region(true),
            // The full-screen stage explorer, for graph agents.
            KeyCode::Char('g') => {
                let target = self
                    .selected_agent()
                    .filter(|a| a.graph_info.is_some())
                    .map(|a| a.id.clone());
                match target {
                    Some(run_id) => {
                        self.ensure_history(&run_id);
                        self.stage_explorer = Some(ExplorerState::new());
                    }
                    None => self.toast(
                        "This agent is linear; there is no stage graph to explore",
                        ToastLevel::Info,
                    ),
                }
            }
            // Home/End are the documented jumps; b/e stay as the historical
            // aliases. (`detail_scroll` counts up from the bottom, so "top of
            // the document" is the maximum offset.)
            KeyCode::Char('b') | KeyCode::Home => {
                self.detail_scroll = usize::MAX;
                self.review_scroll = usize::MAX;
            }
            KeyCode::Char('e') | KeyCode::End => {
                self.detail_scroll = 0;
                self.review_scroll = 0;
            }
            KeyCode::Char('?') | KeyCode::F(1) => {
                self.show_help = true;
            }
            // Search: `/` enters search mode; `n`/`N` step through matches
            KeyCode::Char('/') => {
                self.search_mode = true;
                self.search_query.clear();
                self.search_match_idx = 0;
            }
            KeyCode::Char('n') => {
                if !self.search_query.is_empty() {
                    self.search_match_idx = self.search_match_idx.saturating_add(1);
                }
            }
            KeyCode::Char('N') => {
                if !self.search_query.is_empty() {
                    self.search_match_idx = self.search_match_idx.saturating_sub(1);
                }
            }
            // Yank: `y` copies the current stage content to clipboard
            KeyCode::Char('y') => {
                self.handle_yank();
            }
            // `x` kills, behind a real confirmation (`k` is unbound here: in a
            // view whose neighbors are l/o/c, a vim-reflex `k` killing the run
            // is exactly the accident this replaces).
            KeyCode::Char('x') => self.request_kill(),
            KeyCode::Char('p') => {
                self.handle_pause();
            }
            KeyCode::Char('r') => {
                self.handle_resume();
            }
            _ => {}
        }
    }

    fn handle_yank(&mut self) {
        self.handle_yank_with_fn(self.yank_fn);
    }

    fn handle_yank_with_fn(&mut self, yank_fn: fn(&str) -> bool) {
        if let Some(agent) = self.selected_agent() {
            let (content, label) = match self.stage_content_mode {
                StageContentMode::Output => (
                    runstate::tail_stage_output(&agent.id, self.selected_stage, 524_288),
                    "Output",
                ),
                StageContentMode::Logs => (
                    runstate::tail_stage_log(&agent.id, self.selected_stage, 524_288),
                    "Logs",
                ),
                StageContentMode::Context => {
                    let json = std::fs::read_to_string(
                        runstate::stage_dir(&agent.id, self.selected_stage).join("context.json"),
                    )
                    .unwrap_or_default();
                    (json, "Context JSON")
                }
            };
            if content.is_empty() {
                self.toasts.push(Toast {
                    message: format!("No {} content to yank", label),
                    remaining_ticks: 25,
                    level: ToastLevel::Warning,
                });
            } else if yank_fn(&content) {
                self.toasts.push(Toast {
                    message: format!("{} yanked to clipboard", label),
                    remaining_ticks: 25,
                    level: ToastLevel::Info,
                });
            } else {
                self.toasts.push(Toast {
                    message: "Clipboard unavailable (no pbcopy/xclip/OSC52)".to_string(),
                    remaining_ticks: 30,
                    level: ToastLevel::Error,
                });
            }
        }
    }

    /// Pause the selected agent (main list and detail view share this: unlike
    /// kill, there is no input state to reset). Gated on the states the daemon
    /// will actually pause, so an ineligible row sends nothing instead of
    /// producing a guaranteed refusal toast.
    fn handle_pause(&mut self) {
        if let Some(agent) = self.selected_agent()
            && matches!(
                agent.status,
                AgentDisplayStatus::Active | AgentDisplayStatus::Idle | AgentDisplayStatus::Stale
            )
        {
            let agent_id = agent.id.clone();
            let _ = self.cmd_tx.send(DaemonCommand::Pause {
                run_id: agent_id.clone(),
            });
            // See the comment in `handle_kill_from_detail` - the index is still
            // valid because the `cmd_tx.send` above does not touch
            // `display_indices`/`agents`/`selected`.
            let idx = self
                .selected_agent_raw_idx()
                .expect("selected_agent() returned Some above");
            let a = self
                .agents
                .get_mut(idx)
                .expect("index snapshotted from the still-unchanged display_indices/agents above");
            a.status = AgentDisplayStatus::Paused;
            self.add_log(format!("{}: pause requested", agent_id));
        }
    }

    /// Resume the selected agent if it is paused.
    fn handle_resume(&mut self) {
        if let Some(agent) = self.selected_agent()
            && agent.status == AgentDisplayStatus::Paused
        {
            let agent_id = agent.id.clone();
            let _ = self.cmd_tx.send(DaemonCommand::Resume {
                run_id: agent_id.clone(),
            });
            // See the comment in `handle_kill_from_detail` - the index is still
            // valid because the `cmd_tx.send` above does not touch
            // `display_indices`/`agents`/`selected`.
            let idx = self
                .selected_agent_raw_idx()
                .expect("selected_agent() returned Some above");
            let a = self
                .agents
                .get_mut(idx)
                .expect("index snapshotted from the still-unchanged display_indices/agents above");
            a.status = AgentDisplayStatus::Active;
            self.add_log(format!("{}: resume requested", agent_id));
        }
    }

    fn handle_main_list_key(&mut self, key_code: KeyCode) {
        match key_code {
            // Esc dismisses: the filter first, then the marks. It does not
            // quit - `q` quits, the same as every other Leviath TUI.
            KeyCode::Esc => {
                if !self.list_search_query.is_empty() {
                    self.list_search_query.clear();
                    self.selected = 0;
                    self.update_display_indices();
                } else if !self.marked.is_empty() {
                    self.marked.clear();
                }
            }
            // Space marks or unmarks the selected run for a group kill or
            // delete, then moves down one row so repeated presses sweep the
            // list.
            KeyCode::Char(' ') => {
                if let Some(agent) = self.selected_agent() {
                    let id = agent.id.clone();
                    if !self.marked.remove(&id) {
                        self.marked.insert(id);
                    }
                    if self.selected < self.display_indices.len() - 1 {
                        self.selected += 1;
                        self.table_state.select(Some(self.selected));
                    }
                }
            }
            KeyCode::Char('q') => self.should_quit = true,
            KeyCode::Up | KeyCode::Char('k') => {
                if !self.display_indices.is_empty() && self.selected > 0 {
                    self.selected -= 1;
                    self.table_state.select(Some(self.selected));
                }
            }
            KeyCode::Down | KeyCode::Char('j') => {
                if !self.display_indices.is_empty()
                    && self.selected < self.display_indices.len() - 1
                {
                    self.selected += 1;
                    self.table_state.select(Some(self.selected));
                }
            }
            KeyCode::Home | KeyCode::Char('g') => {
                if !self.display_indices.is_empty() {
                    self.selected = 0;
                    self.table_state.select(Some(0));
                }
            }
            KeyCode::End | KeyCode::Char('G') => {
                if !self.display_indices.is_empty() {
                    self.selected = self.display_indices.len() - 1;
                    self.table_state.select(Some(self.selected));
                }
            }
            KeyCode::Tab | KeyCode::BackTab => {
                self.main_focus = MainPane::LogPane;
            }
            KeyCode::Enter => {
                if !self.display_indices.is_empty() {
                    self.open_detail_view();
                }
            }
            KeyCode::Char('/') => {
                self.list_search_mode = true;
                self.list_search_query.clear();
                self.selected = 0;
                self.update_display_indices();
            }
            KeyCode::Char('s') => self.cycle_sort_mode(),
            KeyCode::Char('d') => self.request_delete(),
            // `x` kills, behind a real confirmation. `k` deliberately does
            // not: it is list navigation here, like everywhere else.
            KeyCode::Char('x') => self.request_kill(),
            KeyCode::Char('p') => {
                self.handle_pause();
            }
            KeyCode::Char('r') => {
                self.handle_resume();
            }
            KeyCode::Char('?') | KeyCode::F(1) => {
                self.show_help = true;
            }
            KeyCode::Char('m') => {
                // Open the MCP management screen; load the current servers.
                self.mcp_screen = true;
                self.mcp_selected = 0;
                self.refresh_mcp_rows();
            }
            KeyCode::Char('n') => self.open_new_run_screen(),
            _ => {}
        }
    }

    /// Keys handled while the MCP management screen is open.
    ///
    /// In add mode the line editor owns typing; otherwise the keys drive the
    /// server list (navigate, add, delete, login, test).
    fn handle_mcp_screen_key(&mut self, key_code: KeyCode) {
        if self.mcp_add_mode {
            match key_code {
                KeyCode::Esc => {
                    self.mcp_add_mode = false;
                    self.mcp_add_input.clear();
                }
                KeyCode::Enter => {
                    let line = std::mem::take(&mut self.mcp_add_input);
                    self.mcp_add_mode = false;
                    self.mcp_add_from_line(&line);
                }
                KeyCode::Backspace => {
                    self.mcp_add_input.pop();
                }
                KeyCode::Char(c) => {
                    self.mcp_add_input.push(c);
                }
                _ => {}
            }
            return;
        }

        match key_code {
            // Esc closes the screen (back); `q` quits the app, the same as
            // everywhere else.
            KeyCode::Esc => {
                self.mcp_screen = false;
            }
            KeyCode::Char('q') => self.should_quit = true,
            KeyCode::Char('?') | KeyCode::F(1) => self.show_help = true,
            KeyCode::Up | KeyCode::Char('k') => {
                self.mcp_selected = self.mcp_selected.saturating_sub(1);
            }
            KeyCode::Down | KeyCode::Char('j') => {
                if !self.mcp_rows.is_empty() && self.mcp_selected + 1 < self.mcp_rows.len() {
                    self.mcp_selected += 1;
                }
            }
            KeyCode::Char('a') => {
                self.mcp_add_mode = true;
                self.mcp_add_input.clear();
            }
            KeyCode::Char('d') => {
                self.mcp_request_remove();
            }
            KeyCode::Char('l') => {
                self.mcp_login_selected();
            }
            KeyCode::Char('t') => {
                self.mcp_test_selected();
            }
            KeyCode::Char('r') => {
                self.refresh_mcp_rows();
            }
            _ => {}
        }
    }

    pub(super) fn submit_input(&mut self) {
        use interaction::{ApprovalScope, InteractionKind, InteractionResponse};

        let (agent_id, req) = match self.selected_agent() {
            Some(a) => (a.id.clone(), a.pending_request.clone()),
            None => return,
        };

        let (resp, display) = match &req {
            Some(r) => match r.kind {
                InteractionKind::FreeText => {
                    let raw = self.input_textarea.lines().join("\n").trim().to_string();
                    let input = if raw == "/quit" || raw == "/exit" {
                        String::new()
                    } else {
                        raw
                    };
                    let d = if input.is_empty() {
                        "(end)".to_string()
                    } else {
                        truncate(&input, 40)
                    };
                    (InteractionResponse::text(&r.id, &input), d)
                }
                InteractionKind::EditText => {
                    // Preserve indentation / internal newlines - only trim the
                    // display label, not the submitted content.
                    let input = self.input_textarea.lines().join("\n");
                    let d = if input.trim().is_empty() {
                        "(no changes)".to_string()
                    } else {
                        truncate(input.trim(), 40)
                    };
                    (InteractionResponse::text(&r.id, &input), d)
                }
                InteractionKind::MultipleChoice => {
                    let idx = self.choice_selected;
                    let label = r.options.get(idx).cloned().unwrap_or(idx.to_string());
                    let d = truncate(&label, 40);
                    (InteractionResponse::choice(&r.id, idx), d)
                }
                InteractionKind::ToolApproval => {
                    let idx = self.choice_selected;
                    let label = r.options.get(idx).cloned().unwrap_or(idx.to_string());
                    let d = truncate(&label, 40);
                    // The index-to-scope mapping lives with the labels, so the
                    // two cannot drift; anything it does not recognise denies.
                    let (approved, scope) = match leviath_core::interaction::approval_choice(idx) {
                        Some(scope) => (true, scope),
                        None => (false, ApprovalScope::Once),
                    };
                    (InteractionResponse::approval(&r.id, approved, scope), d)
                }
                InteractionKind::Confirm => {
                    let approved = self.choice_selected == 0;
                    let label = if approved { "Yes" } else { "No" };
                    (
                        InteractionResponse::approval(&r.id, approved, ApprovalScope::Once),
                        label.to_string(),
                    )
                }
            },
            None => {
                let raw = self.input_textarea.lines().join("\n").trim().to_string();
                let input = if raw == "/quit" || raw == "/exit" {
                    String::new()
                } else {
                    raw
                };
                let d = if input.is_empty() {
                    "(end)".to_string()
                } else {
                    truncate(&input, 40)
                };
                (
                    InteractionResponse {
                        request_id: String::new(),
                        value: Some(input),
                        choice_index: None,
                        approved: None,
                        scope: None,
                    },
                    d,
                )
            }
        };

        self.input_mode = false;
        self.input_textarea = ratatui_textarea::TextArea::default();
        self.choice_selected = 0;

        let answered_id = resp.request_id.clone();
        // The index is still valid because nothing since the
        // `self.selected_agent()` lookup at the top of this function (which is
        // where `req`/`agent_id` came from) touches
        // `display_indices`/`agents`/`selected` - an `if let` guard here would
        // add an "index went stale" branch that can never actually be exercised.
        let idx = self
            .selected_agent_raw_idx()
            .expect("selected_agent() returned Some above");
        let a = self
            .agents
            .get_mut(idx)
            .expect("index snapshotted from the still-unchanged display_indices/agents above");
        a.last_answered_request_id = if answered_id.is_empty() {
            None
        } else {
            Some(answered_id)
        };
        a.waiting_prompt = None;
        a.pending_request = None;
        a.status = AgentDisplayStatus::Active;

        // A pending interaction is answered via the daemon's interaction hub;
        // free-typed input with no pending request is delivered as a mid-run
        // message to the agent.
        if req.is_some() {
            let _ = self.cmd_tx.send(DaemonCommand::Answer { response: resp });
            self.add_log(format!("Sent: {}", display));
        } else {
            let content = resp.value.clone().unwrap_or_default();
            let _ = self.cmd_tx.send(DaemonCommand::Message {
                agent_id: agent_id.clone(),
                content,
            });
            self.add_log(format!("💬 User: \"{}\"", display));
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crossterm::event::{KeyEvent, KeyModifiers};
    use tokio::sync::mpsc;

    use crate::commands::dashboard::test_support::make_test_dashboard;

    fn make_test_agent(id: &str, status: AgentDisplayStatus) -> DashboardAgent {
        DashboardAgent {
            id: id.to_string(),
            blueprint_name: "test-agent".to_string(),
            stage: "main".to_string(),
            stage_index: 0,
            num_stages: 2,
            status,
            tokens_in: 0,
            tokens_out: 0,
            cached_tokens: 0,
            iteration: 0,
            waiting_prompt: None,
            pending_request: None,
            last_answered_request_id: None,
            context_snapshot: None,
            stages: vec![],
            workdir: "/tmp".to_string(),
            task: "test".to_string(),
            title: None,
            model: None,
            parent_id: None,
            depth: 0,
            started_at: 1000,
            last_progress_at: None,
            active_until: None,
            waiting_secs: 0,
            graph_info: None,
            accepts_messages: true,
            taint_summary: vec![],
        }
    }

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

    // ── Status assertion helpers (both branches covered by #[should_panic] companions) ──

    fn assert_cancelled(status: &AgentDisplayStatus) {
        if !matches!(status, AgentDisplayStatus::Cancelled) {
            panic!("expected Cancelled, got {:?}", status);
        }
    }

    fn assert_complete(status: &AgentDisplayStatus) {
        if !matches!(status, AgentDisplayStatus::Complete) {
            panic!("expected Complete, got {:?}", status);
        }
    }

    #[test]
    #[should_panic(expected = "expected Cancelled")]
    fn assert_cancelled_helper_panics_on_wrong_status() {
        assert_cancelled(&AgentDisplayStatus::Active);
    }

    #[test]
    #[should_panic(expected = "expected Complete")]
    fn assert_complete_helper_panics_on_wrong_status() {
        assert_complete(&AgentDisplayStatus::Active);
    }

    #[test]
    fn q_quits_from_the_main_list_and_esc_does_not() {
        let mut dash = make_test_dashboard();
        dash.handle_key(key(KeyCode::Esc));
        assert!(!dash.should_quit, "Esc dismisses; it never quits");
        dash.handle_key(key(KeyCode::Char('q')));
        assert!(dash.should_quit);
    }

    #[test]
    fn ctrl_c_quits_from_anywhere() {
        for setup in [false, true] {
            let mut dash = make_test_dashboard();
            dash.detail_view = setup;
            dash.handle_key(crossterm::event::KeyEvent::new(
                KeyCode::Char('c'),
                crossterm::event::KeyModifiers::CONTROL,
            ));
            assert!(dash.should_quit, "detail={setup}");
        }
    }

    #[test]
    fn key_esc_clears_filter_first() {
        let mut dash = make_test_dashboard();
        dash.list_search_query = "test".to_string();
        dash.handle_key(key(KeyCode::Esc));
        assert!(!dash.should_quit);
        assert!(dash.list_search_query.is_empty());
    }

    #[test]
    fn key_enter_opens_detail_view() {
        let mut dash = make_test_dashboard();
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Active));
        dash.update_display_indices();
        dash.handle_key(key(KeyCode::Enter));
        assert!(dash.detail_view);
    }

    #[test]
    fn key_enter_no_effect_empty_list() {
        let mut dash = make_test_dashboard();
        dash.handle_key(key(KeyCode::Enter));
        assert!(!dash.detail_view);
    }

    #[test]
    fn key_up_down_moves_selection() {
        let mut dash = make_test_dashboard();
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Active));
        dash.agents
            .push(make_test_agent("run-2", AgentDisplayStatus::Active));
        dash.update_display_indices();
        assert_eq!(dash.selected, 0);
        dash.handle_key(key(KeyCode::Down));
        assert_eq!(dash.selected, 1);
        dash.handle_key(key(KeyCode::Up));
        assert_eq!(dash.selected, 0);
    }

    #[test]
    fn key_up_at_top_stays() {
        let mut dash = make_test_dashboard();
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Active));
        dash.update_display_indices();
        dash.handle_key(key(KeyCode::Up));
        assert_eq!(dash.selected, 0);
    }

    #[test]
    fn key_slash_enters_list_search() {
        let mut dash = make_test_dashboard();
        dash.handle_key(key(KeyCode::Char('/')));
        assert!(dash.list_search_mode);
    }

    #[test]
    fn key_question_shows_help() {
        let mut dash = make_test_dashboard();
        dash.handle_key(key(KeyCode::Char('?')));
        assert!(dash.show_help);
    }

    #[test]
    fn help_overlay_dismissed_only_deliberately() {
        let mut dash = make_test_dashboard();
        dash.show_help = true;
        // A stray key is ignored: it neither closes help nor acts underneath.
        dash.handle_key(key(KeyCode::Char('x')));
        assert!(dash.show_help);
        assert!(dash.pending_confirm.is_none(), "x did not open a dialog");
        dash.handle_key(key(KeyCode::Esc));
        assert!(!dash.show_help);
    }

    #[test]
    fn detail_view_esc_returns_to_list() {
        let mut dash = make_test_dashboard();
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Active));
        dash.update_display_indices();
        dash.detail_view = true;
        dash.handle_key(key(KeyCode::Esc));
        assert!(!dash.detail_view);
    }

    #[test]
    fn detail_view_esc_clears_search_first() {
        let mut dash = make_test_dashboard();
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Active));
        dash.update_display_indices();
        dash.detail_view = true;
        dash.search_query = "test".to_string();
        dash.handle_key(key(KeyCode::Esc));
        assert!(dash.detail_view); // still in detail view
        assert!(dash.search_query.is_empty());
    }

    #[test]
    fn detail_view_left_right_switches_stage() {
        let mut dash = make_test_dashboard();
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Active));
        dash.update_display_indices();
        dash.detail_view = true;
        dash.selected_stage = 0;
        dash.handle_key(key(KeyCode::Right));
        assert_eq!(dash.selected_stage, 1);
        dash.handle_key(key(KeyCode::Left));
        assert_eq!(dash.selected_stage, 0);
    }

    #[test]
    fn detail_view_content_mode_toggle() {
        let mut dash = make_test_dashboard();
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Active));
        dash.update_display_indices();
        dash.detail_view = true;
        dash.handle_key(key(KeyCode::Char('l')));
        assert_eq!(dash.stage_content_mode, StageContentMode::Logs);
        dash.handle_key(key(KeyCode::Char('o')));
        assert_eq!(dash.stage_content_mode, StageContentMode::Output);
        dash.handle_key(key(KeyCode::Char('c')));
        assert_eq!(dash.stage_content_mode, StageContentMode::Context);
    }

    #[test]
    fn detail_view_search_mode() {
        let mut dash = make_test_dashboard();
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Active));
        dash.update_display_indices();
        dash.detail_view = true;
        dash.handle_key(key(KeyCode::Char('/')));
        assert!(dash.search_mode);
        dash.handle_key(key(KeyCode::Char('t')));
        dash.handle_key(key(KeyCode::Char('e')));
        assert_eq!(dash.search_query, "te");
        dash.handle_key(key(KeyCode::Backspace));
        assert_eq!(dash.search_query, "t");
        dash.handle_key(key(KeyCode::Enter));
        assert!(!dash.search_mode);
        assert_eq!(dash.search_query, "t");
    }

    #[test]
    fn detail_view_search_esc_clears() {
        let mut dash = make_test_dashboard();
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Active));
        dash.update_display_indices();
        dash.detail_view = true;
        dash.search_mode = true;
        dash.search_query = "test".to_string();
        dash.handle_key(key(KeyCode::Esc));
        assert!(!dash.search_mode);
        assert!(dash.search_query.is_empty());
    }

    #[test]
    fn detail_view_scroll() {
        let mut dash = make_test_dashboard();
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Active));
        dash.update_display_indices();
        dash.detail_view = true;
        dash.handle_key(key(KeyCode::Up));
        assert_eq!(dash.detail_scroll, 1);
        dash.handle_key(key(KeyCode::Down));
        assert_eq!(dash.detail_scroll, 0);
    }

    #[test]
    fn detail_view_page_scroll() {
        let mut dash = make_test_dashboard();
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Active));
        dash.update_display_indices();
        dash.detail_view = true;
        dash.handle_key(key(KeyCode::PageUp));
        assert_eq!(dash.detail_scroll, 10);
        dash.handle_key(key(KeyCode::PageDown));
        assert_eq!(dash.detail_scroll, 0);
    }

    #[test]
    fn detail_view_begin_end() {
        let mut dash = make_test_dashboard();
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Active));
        dash.update_display_indices();
        dash.detail_view = true;
        dash.handle_key(key(KeyCode::Char('b')));
        assert_eq!(dash.detail_scroll, usize::MAX);
        dash.handle_key(key(KeyCode::Char('e')));
        assert_eq!(dash.detail_scroll, 0);
    }

    #[test]
    fn number_keys_jump_to_stage() {
        let mut dash = make_test_dashboard();
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Active);
        agent.num_stages = 5;
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;
        dash.handle_key(key(KeyCode::Char('3')));
        assert_eq!(dash.selected_stage, 2);
    }

    #[test]
    fn the_delete_dialog_confirms_with_y_and_deletes() {
        let mut dash = make_test_dashboard();
        dash.agents
            .push(make_test_agent("run-del", AgentDisplayStatus::Complete));
        dash.update_display_indices();
        dash.handle_key(key(KeyCode::Char('d')));
        assert!(dash.pending_confirm.is_some(), "d opens the dialog");

        dash.handle_key(key(KeyCode::Char('y')));
        assert!(dash.pending_confirm.is_none());
        assert!(
            dash.agents.is_empty(),
            "confirming removes the run from the list"
        );
    }

    #[test]
    fn the_delete_dialog_ignores_stray_keys_and_enter_declines() {
        let mut dash = make_test_dashboard();
        dash.agents
            .push(make_test_agent("run-keep", AgentDisplayStatus::Complete));
        dash.update_display_indices();
        dash.handle_key(key(KeyCode::Char('d')));

        // A stray key neither confirms nor dismisses.
        dash.handle_key(key(KeyCode::Char('z')));
        assert!(dash.pending_confirm.is_some());

        // Enter activates the focused button, which defaults to No.
        dash.handle_key(key(KeyCode::Enter));
        assert!(dash.pending_confirm.is_none());
        assert_eq!(dash.agents.len(), 1, "declining deletes nothing");
    }

    #[test]
    fn list_search_mode_typing() {
        let mut dash = make_test_dashboard();
        dash.list_search_mode = true;
        dash.handle_key(key(KeyCode::Char('a')));
        assert_eq!(dash.list_search_query, "a");
        dash.handle_key(key(KeyCode::Char('b')));
        assert_eq!(dash.list_search_query, "ab");
        dash.handle_key(key(KeyCode::Backspace));
        assert_eq!(dash.list_search_query, "a");
    }

    #[test]
    fn list_search_mode_esc_clears() {
        let mut dash = make_test_dashboard();
        dash.list_search_mode = true;
        dash.list_search_query = "test".to_string();
        dash.handle_key(key(KeyCode::Esc));
        assert!(!dash.list_search_mode);
        assert!(dash.list_search_query.is_empty());
    }

    #[test]
    fn list_search_mode_enter_confirms() {
        let mut dash = make_test_dashboard();
        dash.list_search_mode = true;
        dash.list_search_query = "test".to_string();
        dash.handle_key(key(KeyCode::Enter));
        assert!(!dash.list_search_mode);
        assert_eq!(dash.list_search_query, "test"); // preserved
    }

    #[test]
    fn list_search_mode_unhandled_key_is_noop() {
        let mut dash = make_test_dashboard();
        dash.list_search_mode = true;
        dash.list_search_query = "test".to_string();
        dash.handle_key(key(KeyCode::Left));
        assert!(dash.list_search_mode);
        assert_eq!(dash.list_search_query, "test");
    }

    #[test]
    fn detail_view_search_mode_unhandled_key_is_noop() {
        let mut dash = make_test_dashboard();
        let agent = make_test_agent("run-1", AgentDisplayStatus::Active);
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;
        dash.search_mode = true;
        dash.search_query = "test".to_string();
        dash.handle_key(key(KeyCode::Left));
        assert!(dash.search_mode);
        assert_eq!(dash.search_query, "test");
    }

    // ─── handle_input_mode_key for choice navigation ──────────────────────

    /// A plan approval is a multiple-choice prompt with the plan as its body.
    fn dashboard_awaiting_a_plan() -> Dashboard {
        let mut dash = make_test_dashboard();
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Waiting);
        let mut req = leviath_core::interaction::InteractionRequest::multiple_choice(
            "plan_approval",
            "Review the plan above. What would you like to do?",
            vec!["Approve".into(), "Revise".into()],
            "plan",
        );
        req.body = Some(format!("## Plan\n{}", "1. a step\n".repeat(200)));
        agent.pending_request = Some(req);
        agent.waiting_prompt = Some("Review the plan above.".to_string());
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;
        dash.input_mode = true;
        dash
    }

    /// Up/Down move the choice selection, so PageUp/PageDown/Home/End must
    /// scroll the document - without them a plan longer than the pane cannot
    /// be read while its approval prompt is open, which is the only time it is
    /// shown.
    #[test]
    fn a_plan_can_be_scrolled_while_its_approval_prompt_is_open() {
        let mut dash = dashboard_awaiting_a_plan();
        assert_eq!(dash.detail_scroll, 0);

        // In input mode the plan is drawn in the content pane - the separate
        // review pane is suppressed - so that is what has to move. Verified
        // against the real dashboard through a pty: the pane's own position
        // readout went 100% → 91% → 81% on two PageUps.
        dash.handle_key(key(KeyCode::PageUp));
        assert_eq!(dash.detail_scroll, 10, "PageUp scrolls the plan");
        assert_eq!(dash.review_scroll, 0, "and not a pane nobody can see");
        dash.handle_key(key(KeyCode::PageDown));
        assert_eq!(dash.detail_scroll, 0, "and PageDown comes back");

        // Down still selects rather than scrolling - the plan keys were added
        // beside the choice keys, not on top of them.
        dash.choice_selected = 0;
        dash.handle_key(key(KeyCode::Down));
        assert_eq!(dash.choice_selected, 1);
        assert_eq!(dash.detail_scroll, 0);

        // Home/End jump the length of the document without overflowing.
        dash.handle_key(key(KeyCode::Home));
        assert!(dash.detail_scroll > 0);
        dash.handle_key(key(KeyCode::End));
        assert_eq!(dash.detail_scroll, 0);
    }

    /// A free-text prompt can carry a document too (an agent asking a question
    /// about something it is showing you), so it gets the same scroll keys.
    /// `EditText` deliberately does not: there the body is what you are editing,
    /// and PageUp/PageDown belong to the text area.
    #[test]
    fn free_text_scrolls_a_review_but_edit_text_keeps_its_page_keys() {
        let mut dash = make_test_dashboard();
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Waiting);
        let mut req = leviath_core::interaction::InteractionRequest::free_text(
            "q1",
            "What next?",
            "plan",
            true,
        );
        req.body = Some("a line\n".repeat(200));
        agent.pending_request = Some(req);
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;
        dash.input_mode = true;

        dash.handle_key(key(KeyCode::PageUp));
        assert_eq!(dash.detail_scroll, 10, "the document scrolls");
        assert!(
            dash.input_textarea.lines().concat().is_empty(),
            "and the key did not land in the answer box"
        );
        dash.handle_key(key(KeyCode::PageDown));
        assert_eq!(dash.detail_scroll, 0);

        // EditText: the body is the thing being edited, so the guard is false
        // and the key goes to the text area instead.
        dash.agents[0].pending_request =
            Some(leviath_core::interaction::InteractionRequest::edit_text(
                "e1",
                "Edit the plan",
                "plan",
                "## Plan\n1. a step",
            ));
        dash.detail_scroll = 0;
        dash.handle_key(key(KeyCode::PageUp));
        assert_eq!(
            dash.detail_scroll, 0,
            "an edit target is not scrolled out from under the cursor"
        );
    }

    /// The wheel moves the same pane the keyboard does.
    #[test]
    fn the_mouse_wheel_scrolls_the_review_and_falls_back_to_the_detail_pane() {
        let mut dash = dashboard_awaiting_a_plan();
        dash.scroll_by(3);
        assert_eq!(dash.detail_scroll, 3);
        dash.scroll_by(-3);
        assert_eq!(dash.detail_scroll, 0);
        // Past the top it stops rather than wrapping.
        dash.scroll_by(-3);
        assert_eq!(dash.detail_scroll, 0);

        // Out of input mode and with the content pane on logs, the review pane
        // is what is rendered - and so what the wheel moves.
        dash.input_mode = false;
        dash.handle_key(key(KeyCode::Char('l')));
        dash.scroll_by(3);
        assert_eq!(dash.review_scroll, 3);
        assert_eq!(dash.detail_scroll, 0, "the content pane did not move");
    }

    #[test]
    fn input_mode_choice_up_down() {
        let mut dash = make_test_dashboard();
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Waiting);
        agent.pending_request = Some(
            leviath_core::interaction::InteractionRequest::multiple_choice(
                "mc1",
                "Pick one",
                vec!["A".into(), "B".into(), "C".into()],
                "main",
            ),
        );
        agent.waiting_prompt = Some("Pick one".to_string());
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;
        dash.input_mode = true;
        dash.choice_selected = 0;

        // Down
        dash.handle_key(key(KeyCode::Down));
        assert_eq!(dash.choice_selected, 1);
        dash.handle_key(key(KeyCode::Down));
        assert_eq!(dash.choice_selected, 2);
        // Down at bottom stays
        dash.handle_key(key(KeyCode::Down));
        assert_eq!(dash.choice_selected, 2);

        // Up
        dash.handle_key(key(KeyCode::Up));
        assert_eq!(dash.choice_selected, 1);
        dash.handle_key(key(KeyCode::Up));
        assert_eq!(dash.choice_selected, 0);
        // Up at top stays
        dash.handle_key(key(KeyCode::Up));
        assert_eq!(dash.choice_selected, 0);
    }

    #[test]
    fn input_mode_esc_exits() {
        let mut dash = make_test_dashboard();
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Waiting);
        agent.pending_request = Some(leviath_core::interaction::InteractionRequest::free_text(
            "ft1", "prompt", "main", true,
        ));
        agent.waiting_prompt = Some("prompt".to_string());
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;
        dash.input_mode = true;

        dash.handle_key(key(KeyCode::Esc));
        assert!(!dash.input_mode);
    }

    #[test]
    fn input_mode_free_text_typing_appends_to_textarea() {
        let mut dash = make_test_dashboard();
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Waiting);
        agent.pending_request = Some(leviath_core::interaction::InteractionRequest::free_text(
            "ft1", "prompt", "main", true,
        ));
        agent.waiting_prompt = Some("prompt".to_string());
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;
        dash.input_mode = true;

        dash.handle_key(key(KeyCode::Char('h')));
        dash.handle_key(key(KeyCode::Char('i')));
        assert_eq!(dash.input_textarea.lines(), vec!["hi".to_string()]);
    }

    #[test]
    fn input_mode_edit_text_typing_appends_to_textarea() {
        // EditText routes through the text-editing key arm just like FreeText.
        let mut dash = make_test_dashboard();
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Waiting);
        agent.pending_request = Some(leviath_core::interaction::InteractionRequest::edit_text(
            "et1", "Edit", "main", "seed",
        ));
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;
        dash.input_mode = true;

        dash.handle_key(key(KeyCode::Char('!')));
        assert_eq!(dash.input_textarea.lines(), vec!["!".to_string()]);
    }

    #[test]
    fn seed_input_textarea_prefills_edit_text_body() {
        let mut dash = make_test_dashboard();
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Waiting);
        agent.pending_request = Some(leviath_core::interaction::InteractionRequest::edit_text(
            "et1",
            "Edit",
            "main",
            "line A\nline B",
        ));
        dash.agents.push(agent);
        dash.update_display_indices();

        dash.seed_input_textarea();
        assert_eq!(
            dash.input_textarea.lines(),
            vec!["line A".to_string(), "line B".to_string()]
        );
    }

    #[test]
    fn editing_document_true_only_while_editing_an_edit_text() {
        let mut dash = make_test_dashboard();
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Waiting);
        agent.pending_request = Some(leviath_core::interaction::InteractionRequest::edit_text(
            "et1", "Edit", "main", "body",
        ));
        dash.agents.push(agent);
        dash.update_display_indices();

        // Pending EditText but not in input mode ⇒ not editing yet.
        assert!(!dash.editing_document());
        // Entering input mode over an EditText ⇒ editing inline.
        dash.input_mode = true;
        assert!(dash.editing_document());
        // While editing, the textarea owns the pane - no separate review body.
        assert!(dash.reviewing_body().is_none());
    }

    #[test]
    fn reviewing_body_returns_the_pending_document_or_none() {
        let mut dash = make_test_dashboard();
        // No agent / no pending ⇒ None.
        assert!(dash.reviewing_body().is_none());

        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Waiting);
        let mut req = leviath_core::interaction::InteractionRequest::multiple_choice(
            "mc1",
            "Approve?",
            vec!["Approve".to_string()],
            "plan_approval",
        );
        req.body = Some("## Plan\n1. write it".to_string());
        agent.pending_request = Some(req);
        dash.agents.push(agent);
        dash.update_display_indices();
        // A pending body is surfaced for review.
        assert_eq!(
            dash.reviewing_body().as_deref(),
            Some("## Plan\n1. write it")
        );

        // A blank body is not surfaced.
        dash.agents[0].pending_request.as_mut().unwrap().body = Some("   ".to_string());
        assert!(dash.reviewing_body().is_none());
    }

    #[test]
    fn editing_document_false_for_non_edit_text_prompt() {
        let mut dash = make_test_dashboard();
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Waiting);
        agent.pending_request = Some(leviath_core::interaction::InteractionRequest::free_text(
            "ft1", "Q?", "main", true,
        ));
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.input_mode = true;
        // FreeText input mode is a bottom-bar response, not a document edit.
        assert!(!dash.editing_document());
    }

    #[test]
    fn seed_input_textarea_empty_for_free_text() {
        let mut dash = make_test_dashboard();
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Waiting);
        agent.pending_request = Some(leviath_core::interaction::InteractionRequest::free_text(
            "ft1", "Q?", "main", true,
        ));
        dash.agents.push(agent);
        dash.update_display_indices();

        dash.input_textarea.insert_str("stale");
        dash.seed_input_textarea();
        // FreeText is not seeded from body → cleared to empty.
        assert_eq!(dash.input_textarea.lines(), vec!["".to_string()]);
    }

    #[test]
    fn submit_input_edit_text_preserves_newlines() {
        let (cmd_tx, mut cmd_rx) = mpsc::unbounded_channel();
        let mut dash = Dashboard::new(cmd_tx);
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Waiting);
        agent.pending_request = Some(interaction::InteractionRequest::edit_text(
            "et1", "Edit", "main", "old",
        ));
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;
        dash.input_mode = true;

        dash.input_textarea = ratatui_textarea::TextArea::new(vec![
            "  indented".to_string(),
            "second line".to_string(),
        ]);
        dash.submit_input();

        assert!(!dash.input_mode);
        assert!(dash.agents[0].pending_request.is_none());
        // The edited text is answered to the daemon with indentation + newline intact.
        let cmd = cmd_rx.try_recv().expect("an Answer command was queued");
        assert_eq!(
            cmd,
            DaemonCommand::Answer {
                response: interaction::InteractionResponse::text("et1", "  indented\nsecond line"),
            }
        );
    }

    #[test]
    fn submit_input_edit_text_empty_reports_no_changes() {
        // Covers the empty-edit display branch of the EditText submit arm.
        let (cmd_tx, mut cmd_rx) = mpsc::unbounded_channel();
        let mut dash = Dashboard::new(cmd_tx);
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Waiting);
        agent.pending_request = Some(interaction::InteractionRequest::edit_text(
            "et1", "Edit", "main", "old",
        ));
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;
        dash.input_mode = true;

        // Whitespace-only edit → trimmed empty → "(no changes)" display path.
        dash.input_textarea = ratatui_textarea::TextArea::new(vec!["   ".to_string()]);
        dash.submit_input();

        assert!(!dash.input_mode);
        let cmd = cmd_rx.try_recv().expect("an Answer command was queued");
        assert_eq!(
            cmd,
            DaemonCommand::Answer {
                response: interaction::InteractionResponse::text("et1", "   "),
            }
        );
    }

    #[test]
    fn input_mode_no_pending_request_typing_appends_to_textarea() {
        // kind resolves to None when there's no pending_request at all -
        // exercises the `Some(FreeText) | None` arm's None side.
        let mut dash = make_test_dashboard();
        let agent = make_test_agent("run-1", AgentDisplayStatus::Active);
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;
        dash.input_mode = true;

        dash.handle_key(key(KeyCode::Char('x')));
        assert_eq!(dash.input_textarea.lines(), vec!["x".to_string()]);
    }

    #[test]
    fn input_mode_esc_on_choice_resets() {
        let mut dash = make_test_dashboard();
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Waiting);
        agent.pending_request = Some(
            leviath_core::interaction::InteractionRequest::multiple_choice(
                "mc1",
                "Pick",
                vec!["A".into(), "B".into()],
                "main",
            ),
        );
        agent.waiting_prompt = Some("Pick".to_string());
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;
        dash.input_mode = true;
        dash.choice_selected = 1;

        dash.handle_key(key(KeyCode::Esc));
        assert!(!dash.input_mode);
        assert_eq!(dash.choice_selected, 0);
    }

    // ─── handle_pause / handle_resume ─────────────────────────────────────

    /// Every state the daemon will pause is pausable from the list, sends the
    /// command, and flips the row optimistically.
    #[test]
    fn pause_sends_command_for_each_pausable_state() {
        for status in [
            AgentDisplayStatus::Active,
            AgentDisplayStatus::Idle,
            AgentDisplayStatus::Stale,
        ] {
            let (cmd_tx, mut cmd_rx) = mpsc::unbounded_channel();
            let mut dash = Dashboard::new(cmd_tx);
            dash.agents.push(make_test_agent("run-1", status.clone()));
            dash.update_display_indices();
            dash.handle_key(key(KeyCode::Char('p')));
            assert_eq!(
                cmd_rx.try_recv().ok(),
                Some(DaemonCommand::Pause {
                    run_id: "run-1".to_string()
                }),
                "pause from {status:?} sends the command"
            );
            assert_eq!(dash.agents[0].status, AgentDisplayStatus::Paused);
        }
    }

    /// Waiting and finished runs are not pausable: nothing is sent, so the user
    /// never sees a guaranteed refusal toast.
    #[test]
    fn pause_is_a_no_op_for_unpausable_states() {
        for status in [
            AgentDisplayStatus::Waiting,
            AgentDisplayStatus::Paused,
            AgentDisplayStatus::Complete,
            AgentDisplayStatus::Cancelled,
        ] {
            let (cmd_tx, mut cmd_rx) = mpsc::unbounded_channel();
            let mut dash = Dashboard::new(cmd_tx);
            dash.agents.push(make_test_agent("run-1", status.clone()));
            dash.update_display_indices();
            dash.handle_key(key(KeyCode::Char('p')));
            assert!(
                cmd_rx.try_recv().is_err(),
                "pause from {status:?} sends nothing"
            );
            assert_eq!(dash.agents[0].status, status);
        }
    }

    #[test]
    fn resume_sends_command_for_a_paused_run_only() {
        let (cmd_tx, mut cmd_rx) = mpsc::unbounded_channel();
        let mut dash = Dashboard::new(cmd_tx);
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Paused));
        dash.update_display_indices();
        dash.handle_key(key(KeyCode::Char('r')));
        assert_eq!(
            cmd_rx.try_recv().ok(),
            Some(DaemonCommand::Resume {
                run_id: "run-1".to_string()
            })
        );
        assert_eq!(dash.agents[0].status, AgentDisplayStatus::Active);
    }

    #[test]
    fn resume_is_a_no_op_for_a_run_that_is_not_paused() {
        let (cmd_tx, mut cmd_rx) = mpsc::unbounded_channel();
        let mut dash = Dashboard::new(cmd_tx);
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Active));
        dash.update_display_indices();
        dash.handle_key(key(KeyCode::Char('r')));
        assert!(cmd_rx.try_recv().is_err());
        assert_eq!(dash.agents[0].status, AgentDisplayStatus::Active);
    }

    /// With no agents at all, both keys fall through the `selected_agent()`
    /// guard without panicking or sending.
    #[test]
    fn pause_and_resume_with_no_agents_do_nothing() {
        let (cmd_tx, mut cmd_rx) = mpsc::unbounded_channel();
        let mut dash = Dashboard::new(cmd_tx);
        dash.handle_key(key(KeyCode::Char('p')));
        dash.handle_key(key(KeyCode::Char('r')));
        assert!(cmd_rx.try_recv().is_err());
    }

    /// The detail view shares the same handlers via its own `p`/`r` bindings.
    #[test]
    fn pause_and_resume_work_from_the_detail_view() {
        let (cmd_tx, mut cmd_rx) = mpsc::unbounded_channel();
        let mut dash = Dashboard::new(cmd_tx);
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Active));
        dash.update_display_indices();
        dash.detail_view = true;

        dash.handle_key(key(KeyCode::Char('p')));
        assert_eq!(
            cmd_rx.try_recv().ok(),
            Some(DaemonCommand::Pause {
                run_id: "run-1".to_string()
            })
        );
        assert_eq!(dash.agents[0].status, AgentDisplayStatus::Paused);

        dash.handle_key(key(KeyCode::Char('r')));
        assert_eq!(
            cmd_rx.try_recv().ok(),
            Some(DaemonCommand::Resume {
                run_id: "run-1".to_string()
            })
        );
        assert_eq!(dash.agents[0].status, AgentDisplayStatus::Active);
    }

    // ─── kill via x + confirmation ────────────────────────────────────────

    /// `c` no longer cancels from the list (it was an unconfirmed kill by
    /// another name); it is simply unbound there.
    #[test]
    fn c_in_the_main_list_does_nothing() {
        let (cmd_tx, mut cmd_rx) = mpsc::unbounded_channel();
        let mut dash = Dashboard::new(cmd_tx);
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Active));
        dash.update_display_indices();
        dash.handle_key(key(KeyCode::Char('c')));
        assert_eq!(dash.agents[0].status, AgentDisplayStatus::Active);
        assert!(cmd_rx.try_recv().is_err());
    }

    /// `k` navigates; it must never kill. The kill key is `x`, behind a
    /// confirmation.
    #[test]
    fn k_in_the_main_list_moves_the_cursor_not_the_daemon() {
        let (cmd_tx, mut cmd_rx) = mpsc::unbounded_channel();
        let mut dash = Dashboard::new(cmd_tx);
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Active));
        dash.agents
            .push(make_test_agent("run-2", AgentDisplayStatus::Active));
        dash.update_display_indices();
        dash.selected = 1;
        dash.table_state.select(Some(1));
        dash.handle_key(key(KeyCode::Char('k')));
        assert_eq!(dash.selected, 0, "k moves up");
        assert_eq!(dash.agents[0].status, AgentDisplayStatus::Active);
        assert!(cmd_rx.try_recv().is_err(), "nothing was killed");
    }

    /// Every state that is not a finished one can be killed. A gate of only
    /// `Active | Waiting` would make a run showing IDLE or STALE - exactly the
    /// states a user reaches for the kill key in - unkillable.
    #[test]
    fn every_unfinished_state_can_be_killed_after_confirming() {
        for status in [
            AgentDisplayStatus::Active,
            AgentDisplayStatus::Waiting,
            AgentDisplayStatus::Idle,
            AgentDisplayStatus::Stale,
        ] {
            let (cmd_tx, mut cmd_rx) = mpsc::unbounded_channel();
            let mut dash = Dashboard::new(cmd_tx);
            dash.agents.push(make_test_agent("run-1", status.clone()));
            dash.update_display_indices();
            dash.handle_key(key(KeyCode::Char('x')));
            assert!(
                dash.pending_confirm.is_some(),
                "{status:?} must open the kill dialog"
            );
            dash.handle_key(key(KeyCode::Char('y')));

            assert_eq!(
                cmd_rx.try_recv().unwrap(),
                DaemonCommand::Cancel {
                    run_id: "run-1".to_string()
                },
                "{status:?} must be killable via x + confirm"
            );
        }
    }

    /// …and a finished run is left alone: `x` does not even open the dialog,
    /// so there is nothing to mis-confirm.
    #[test]
    fn a_finished_run_is_not_killed() {
        for status in [
            AgentDisplayStatus::Complete,
            AgentDisplayStatus::CompleteInteractive,
            AgentDisplayStatus::Cancelled,
            AgentDisplayStatus::Error("boom".to_string()),
        ] {
            let (cmd_tx, mut cmd_rx) = mpsc::unbounded_channel();
            let mut dash = Dashboard::new(cmd_tx);
            dash.agents.push(make_test_agent("run-1", status.clone()));
            dash.update_display_indices();
            dash.handle_key(key(KeyCode::Char('x')));

            assert!(dash.pending_confirm.is_none(), "{status:?}: no dialog");
            assert!(
                cmd_rx.try_recv().is_err(),
                "{status:?} must not be re-killed"
            );
        }
    }

    /// Declining the kill dialog leaves the run exactly as it was.
    #[test]
    fn declining_the_kill_dialog_kills_nothing() {
        let (cmd_tx, mut cmd_rx) = mpsc::unbounded_channel();
        let mut dash = Dashboard::new(cmd_tx);
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Active));
        dash.update_display_indices();
        dash.handle_key(key(KeyCode::Char('x')));
        dash.handle_key(key(KeyCode::Esc));

        assert!(dash.pending_confirm.is_none());
        assert_eq!(dash.agents[0].status, AgentDisplayStatus::Active);
        assert!(cmd_rx.try_recv().is_err());
    }

    #[test]
    fn confirmed_kill_clears_local_waiting_state_and_cancels() {
        let (cmd_tx, mut cmd_rx) = mpsc::unbounded_channel();
        let mut dash = Dashboard::new(cmd_tx);
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Waiting);
        agent.waiting_prompt = Some("?".to_string());
        agent.pending_request = Some(interaction::InteractionRequest::free_text(
            "q1", "?", "main", true,
        ));
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.handle_key(key(KeyCode::Char('x')));
        dash.handle_key(key(KeyCode::Char('y')));

        assert_cancelled(&dash.agents[0].status);
        assert!(dash.agents[0].pending_request.is_none());
        assert!(dash.agents[0].waiting_prompt.is_none());
        assert_eq!(
            cmd_rx.try_recv().unwrap(),
            DaemonCommand::Cancel {
                run_id: "run-1".to_string()
            }
        );
    }

    #[test]
    fn main_list_d_no_agent_selected_is_noop() {
        let mut dash = make_test_dashboard();
        dash.handle_key(key(KeyCode::Char('d')));
        assert!(dash.pending_confirm.is_none());
        assert!(dash.agents.is_empty());
    }

    #[test]
    fn x_with_no_agent_selected_is_a_noop() {
        let mut dash = make_test_dashboard();
        dash.handle_key(key(KeyCode::Char('x')));
        assert!(dash.pending_confirm.is_none());

        dash.detail_view = true;
        dash.handle_key(key(KeyCode::Char('x')));
        assert!(dash.pending_confirm.is_none());
    }

    #[test]
    fn tab_focuses_the_log_pane_and_its_keys_scroll() {
        let mut dash = make_test_dashboard();
        // The seeded log tail is shared test state; a known length makes the
        // scroll arithmetic below deterministic.
        dash.log.clear();
        for i in 0..50 {
            dash.log.push(LogEntry {
                timestamp: "12:00:00".to_string(),
                message: format!("line {i}"),
            });
        }
        dash.log_viewport = 10;
        dash.handle_key(key(KeyCode::Tab));
        assert_eq!(dash.main_focus, MainPane::LogPane);

        dash.handle_key(key(KeyCode::Up));
        dash.handle_key(key(KeyCode::Char('k')));
        assert_eq!(dash.log_scroll.offset_from_tail, 2);
        dash.handle_key(key(KeyCode::PageUp));
        assert_eq!(dash.log_scroll.offset_from_tail, 12);
        dash.handle_key(key(KeyCode::Down));
        dash.handle_key(key(KeyCode::Char('j')));
        dash.handle_key(key(KeyCode::PageDown));
        assert_eq!(dash.log_scroll.offset_from_tail, 0);

        dash.handle_key(key(KeyCode::Home));
        assert_eq!(dash.log_scroll.offset_from_tail, 40);
        dash.handle_key(key(KeyCode::End));
        assert!(dash.log_scroll.is_tailing());
        dash.handle_key(key(KeyCode::Char('g')));
        assert!(!dash.log_scroll.is_tailing());
        dash.handle_key(key(KeyCode::Char('G')));
        assert!(dash.log_scroll.is_tailing());

        // ? opens help from the log pane; a stray key is ignored.
        dash.handle_key(key(KeyCode::Char('?')));
        assert!(dash.show_help);
        dash.handle_key(key(KeyCode::Esc));
        assert!(!dash.show_help);
        dash.handle_key(key(KeyCode::Char('z')));

        // Esc hands focus back to the list; q quits from the pane.
        dash.handle_key(key(KeyCode::Esc));
        assert_eq!(dash.main_focus, MainPane::RunList);
        dash.handle_key(key(KeyCode::Tab));
        dash.handle_key(key(KeyCode::Char('q')));
        assert!(dash.should_quit);
    }

    #[test]
    fn home_end_and_enter_navigate_the_main_list() {
        let mut dash = make_test_dashboard();
        let mut a = make_test_agent("run-1", AgentDisplayStatus::Active);
        a.stage_index = 1;
        a.num_stages = 3;
        dash.agents.push(a);
        dash.agents
            .push(make_test_agent("run-2", AgentDisplayStatus::Active));
        dash.agents
            .push(make_test_agent("run-3", AgentDisplayStatus::Active));
        dash.update_display_indices();

        dash.handle_key(key(KeyCode::End));
        assert_eq!(dash.selected, 2);
        dash.handle_key(key(KeyCode::Home));
        assert_eq!(dash.selected, 0);
        dash.handle_key(key(KeyCode::Char('G')));
        assert_eq!(dash.selected, 2);
        dash.handle_key(key(KeyCode::Char('g')));
        assert_eq!(dash.selected, 0);

        // Enter opens the detail view at the selected run's current stage.
        dash.handle_key(key(KeyCode::Enter));
        assert!(dash.detail_view);
        assert_eq!(dash.selected_stage, 1);

        // With no rows at all, the same keys are no-ops.
        let mut empty = make_test_dashboard();
        for code in [KeyCode::Home, KeyCode::End, KeyCode::Enter] {
            empty.handle_key(key(code));
        }
        assert!(!empty.detail_view);
    }

    #[test]
    fn s_cycles_the_sort_mode_from_the_keyboard() {
        let mut dash = make_test_dashboard();
        assert_eq!(dash.sort_mode, SortMode::StartedAt);
        dash.handle_key(key(KeyCode::Char('s')));
        assert_eq!(dash.sort_mode, SortMode::RecentActivity);
    }

    #[test]
    fn the_confirm_handler_declines_to_act_without_a_dialog() {
        let mut dash = make_test_dashboard();
        dash.handle_confirm_key(&crossterm::event::KeyEvent::new(
            KeyCode::Enter,
            crossterm::event::KeyModifiers::empty(),
        ));
        assert!(dash.pending_confirm.is_none());
        assert!(!dash.should_quit);
    }

    #[test]
    fn question_mark_opens_help_on_the_mcp_screen() {
        let mut dash = make_test_dashboard();
        dash.mcp_screen = true;
        dash.handle_key(key(KeyCode::Char('?')));
        assert!(dash.show_help);
    }

    fn graph_agent(id: &str) -> DashboardAgent {
        use crate::commands::dashboard::graph::{GraphEdge, GraphTransitionInfo};
        let mut agent = make_test_agent(id, AgentDisplayStatus::Active);
        let mut edges = std::collections::HashMap::new();
        edges.insert(
            "plan".to_string(),
            vec![GraphEdge {
                target: "implement".to_string(),
                hint: Some("ready".to_string()),
                condition: "always".to_string(),
                transform: "direct".to_string(),
            }],
        );
        edges.insert(
            "review".to_string(),
            vec![GraphEdge {
                target: "implement".to_string(),
                hint: None,
                condition: "llm_choice".to_string(),
                transform: "direct".to_string(),
            }],
        );
        edges.insert(
            "implement".to_string(),
            vec![GraphEdge {
                target: "review".to_string(),
                hint: None,
                condition: "always".to_string(),
                transform: "direct".to_string(),
            }],
        );
        agent.graph_info = Some(GraphTransitionInfo {
            edges,
            entry_stage: "plan".to_string(),
            stage_names: vec![
                "plan".to_string(),
                "implement".to_string(),
                "review".to_string(),
            ],
        });
        agent.stage = "implement".to_string();
        agent
    }

    fn seeded_points(stages: &[(&str, i64)]) -> Vec<leviath_core::run_archive::RunPoint> {
        stages
            .iter()
            .map(|(stage, at)| {
                let mut meta = leviath_core::run_meta::RunMeta::new(
                    "run-1".to_string(),
                    "a".to_string(),
                    "/p".to_string(),
                    "t".to_string(),
                    None,
                    "/w".to_string(),
                    3,
                );
                meta.current_stage = stage.to_string();
                meta.iteration = 1;
                leviath_core::run_archive::RunPoint {
                    meta,
                    context: leviath_core::run_meta::ContextSnapshot {
                        stage_name: stage.to_string(),
                        total_tokens: 0,
                        max_tokens: 100,
                        regions: vec![],
                    },
                    at: *at,
                }
            })
            .collect()
    }

    fn seed_cache(dash: &mut Dashboard, points: Vec<leviath_core::run_archive::RunPoint>) {
        dash.history = Some(crate::commands::dashboard::history::RunHistoryCache {
            run_id: "run-1".to_string(),
            visits: crate::commands::dashboard::history::derive_visits(&points),
            points,
            loaded_at_tick: u64::MAX,
        });
    }

    #[test]
    fn g_opens_the_explorer_for_graph_agents_and_toasts_for_linear() {
        let mut dash = make_test_dashboard();
        dash.agents
            .push(make_test_agent("run-linear", AgentDisplayStatus::Active));
        dash.update_display_indices();
        dash.detail_view = true;
        dash.handle_key(key(KeyCode::Char('g')));
        assert!(dash.stage_explorer.is_none());
        assert!(dash.toasts.iter().any(|t| t.message.contains("linear")));

        let mut dash = make_test_dashboard();
        dash.agents.push(graph_agent("run-1"));
        dash.update_display_indices();
        dash.detail_view = true;
        dash.handle_key(key(KeyCode::Char('g')));
        assert!(dash.stage_explorer.is_some());
        // g again closes it.
        dash.handle_key(key(KeyCode::Char('g')));
        assert!(dash.stage_explorer.is_none());
    }

    #[test]
    fn the_explorer_tabs_scrolls_toggles_and_jumps_to_a_visit() {
        let mut dash = make_test_dashboard();
        dash.agents.push(graph_agent("run-1"));
        dash.update_display_indices();
        dash.detail_view = true;
        seed_cache(
            &mut dash,
            seeded_points(&[
                ("plan", 10),
                ("implement", 20),
                ("review", 30),
                ("implement", 40),
            ]),
        );
        dash.handle_key(key(KeyCode::Char('g')));
        assert!(dash.stage_explorer.is_some());

        // Graph tab: scroll down/up, toggle unvisited, help opens.
        dash.handle_key(key(KeyCode::Down));
        dash.handle_key(key(KeyCode::Char('j')));
        assert_eq!(dash.stage_explorer.as_ref().unwrap().scroll, 2);
        dash.handle_key(key(KeyCode::Up));
        dash.handle_key(key(KeyCode::Char('k')));
        assert_eq!(dash.stage_explorer.as_ref().unwrap().scroll, 0);
        dash.handle_key(key(KeyCode::Char('u')));
        assert!(!dash.stage_explorer.as_ref().unwrap().show_unvisited);
        dash.handle_key(key(KeyCode::Char('?')));
        assert!(dash.show_help);
        dash.handle_key(key(KeyCode::Esc));

        // Enter on the graph tab does nothing; on the timeline it jumps.
        dash.handle_key(key(KeyCode::Enter));
        assert!(dash.stage_explorer.is_some());
        dash.handle_key(key(KeyCode::Tab));
        assert_eq!(
            dash.stage_explorer.as_ref().unwrap().tab,
            ExplorerTab::Timeline
        );
        // Move to the last visit (the implement revisit) and jump.
        dash.handle_key(key(KeyCode::Down));
        dash.handle_key(key(KeyCode::Down));
        dash.handle_key(key(KeyCode::Down));
        dash.handle_key(key(KeyCode::Down)); // clamped at the last visit
        assert_eq!(dash.stage_explorer.as_ref().unwrap().timeline_selected, 3);
        dash.handle_key(key(KeyCode::Enter));
        assert!(
            dash.stage_explorer.is_none(),
            "the jump closes the explorer"
        );
        assert_eq!(
            dash.context_history_idx,
            Some(3),
            "jumped to the revisit's first point"
        );
        assert_eq!(dash.stage_content_mode, StageContentMode::Context);

        // Esc closes from either tab; Tab cycles back to the graph; the
        // timeline's Up key and `?` work; unmapped keys are ignored.
        dash.handle_key(key(KeyCode::Char('g')));
        dash.handle_key(key(KeyCode::Tab));
        dash.handle_key(key(KeyCode::Down));
        dash.handle_key(key(KeyCode::Up));
        dash.handle_key(key(KeyCode::Char('k')));
        assert_eq!(dash.stage_explorer.as_ref().unwrap().timeline_selected, 0);
        dash.handle_key(key(KeyCode::Char('?')));
        assert!(dash.show_help);
        dash.handle_key(key(KeyCode::Esc)); // closes help
        dash.handle_key(key(KeyCode::Char('z'))); // ignored
        dash.handle_key(key(KeyCode::Tab));
        assert_eq!(
            dash.stage_explorer.as_ref().unwrap().tab,
            ExplorerTab::Graph
        );
        dash.handle_key(key(KeyCode::Esc));
        assert!(dash.stage_explorer.is_none());
    }

    #[test]
    fn explorer_guards_hold_when_driven_directly_or_without_visits() {
        let mut dash = make_test_dashboard();
        // No explorer open: the handler declines to act.
        dash.handle_explorer_key(KeyCode::Enter);
        assert!(dash.stage_explorer.is_none());

        // Timeline Enter with no archived visits is a no-op.
        dash.agents.push(graph_agent("run-1"));
        dash.update_display_indices();
        dash.detail_view = true;
        dash.handle_key(key(KeyCode::Char('g')));
        dash.handle_key(key(KeyCode::Tab));
        dash.handle_key(key(KeyCode::Enter));
        assert!(dash.stage_explorer.is_some(), "nothing to jump to");
        assert_eq!(dash.context_history_idx, None);
    }

    #[test]
    fn g_with_no_agent_selected_toasts_instead_of_opening() {
        let mut dash = make_test_dashboard();
        dash.detail_view = true;
        dash.handle_key(key(KeyCode::Char('g')));
        assert!(dash.stage_explorer.is_none());
        assert!(dash.toasts.iter().any(|t| t.message.contains("linear")));
    }

    fn context_agent(id: &str) -> DashboardAgent {
        let mut agent = make_test_agent(id, AgentDisplayStatus::Active);
        let entry = |content: &str| leviath_core::run_meta::RegionEntrySnapshot {
            content: content.to_string(),
            tokens: 5,
            kind: Default::default(),
            metadata: None,
            key: None,
            taint: Default::default(),
        };
        agent.context_snapshot = Some(std::sync::Arc::new(crate::runstate::ContextSnapshot {
            stage_name: "main".to_string(),
            total_tokens: 20,
            max_tokens: 100,
            regions: vec![
                crate::runstate::RegionSnapshot {
                    name: "system".to_string(),
                    kind: "pinned".to_string(),
                    current_tokens: 10,
                    max_tokens: 50,
                    entries: vec![entry("alpha"), entry("beta")],
                },
                crate::runstate::RegionSnapshot {
                    name: "conversation".to_string(),
                    kind: "sliding".to_string(),
                    current_tokens: 10,
                    max_tokens: 50,
                    entries: vec![entry("gamma")],
                },
            ],
        }));
        agent
    }

    #[test]
    fn the_context_tree_cursor_folds_and_jumps() {
        use crate::commands::dashboard::context_tree::TreeRow;
        let mut dash = make_test_dashboard();
        dash.agents.push(context_agent("run-ctx"));
        dash.update_display_indices();
        dash.detail_view = true;
        dash.handle_key(key(KeyCode::Char('c')));
        assert_eq!(dash.stage_content_mode, StageContentMode::Context);

        // 5 rows: system, its 2 stubs, conversation, its stub.
        assert_eq!(dash.context_tree_rows().len(), 5);

        // j/k move the cursor and clamp.
        dash.handle_key(key(KeyCode::Char('j')));
        assert_eq!(dash.context_tree.cursor, 1);
        dash.handle_key(key(KeyCode::Up));
        dash.handle_key(key(KeyCode::Char('k')));
        assert_eq!(dash.context_tree.cursor, 0);

        // ] and [ jump between region headers.
        dash.handle_key(key(KeyCode::Char(']')));
        assert_eq!(
            dash.context_tree_rows()[dash.context_tree.cursor],
            TreeRow::RegionHeader {
                region: "conversation".to_string()
            }
        );
        assert_eq!(dash.context_tree.cursor, 3);
        dash.handle_key(key(KeyCode::Char('[')));
        assert_eq!(dash.context_tree.cursor, 0);

        // Space on an entry stub expands it; again collapses.
        dash.handle_key(key(KeyCode::Char('j')));
        dash.handle_key(key(KeyCode::Char(' ')));
        assert!(
            dash.context_tree
                .expanded_entries
                .contains(&("system".to_string(), 0))
        );
        dash.handle_key(key(KeyCode::Enter));
        assert!(dash.context_tree.expanded_entries.is_empty());

        // Enter on a header folds the region: its stubs leave the row list.
        dash.handle_key(key(KeyCode::Char('k')));
        dash.handle_key(key(KeyCode::Enter));
        assert!(dash.context_tree.collapsed_regions.contains("system"));
        assert_eq!(dash.context_tree_rows().len(), 3);
        // …and unfolds.
        dash.handle_key(key(KeyCode::Enter));
        assert_eq!(dash.context_tree_rows().len(), 5);

        // A cursor stranded past the end after a fold gets clamped.
        dash.handle_key(key(KeyCode::Char(']')));
        dash.handle_key(key(KeyCode::Char('j')));
        assert_eq!(dash.context_tree.cursor, 4);
        dash.handle_key(key(KeyCode::Char('[')));
        dash.handle_key(key(KeyCode::Enter)); // fold conversation? no - cursor on header 0?
    }

    #[test]
    fn context_keys_are_inert_outside_context_mode_and_without_rows() {
        let mut dash = make_test_dashboard();
        dash.agents
            .push(make_test_agent("run-plain", AgentDisplayStatus::Active));
        dash.update_display_indices();
        dash.detail_view = true;

        // Output mode: j/k scroll, Enter/Space/brackets do nothing.
        dash.handle_key(key(KeyCode::Char('k')));
        assert_eq!(dash.detail_scroll, 1);
        dash.handle_key(key(KeyCode::Char('j')));
        assert_eq!(dash.detail_scroll, 0, "j scrolls back down outside context");
        dash.handle_key(key(KeyCode::Up));
        dash.handle_key(key(KeyCode::Down));
        assert_eq!(dash.detail_scroll, 0);
        dash.handle_key(key(KeyCode::Enter));
        dash.handle_key(key(KeyCode::Char(' ')));
        assert!(dash.context_tree.expanded_entries.is_empty());

        // Context mode with no snapshot: cursor keys are safe no-ops.
        dash.handle_key(key(KeyCode::Char('c')));
        dash.handle_key(key(KeyCode::Char('j')));
        dash.handle_key(key(KeyCode::Enter));
        dash.handle_key(key(KeyCode::Char('[')));
        dash.handle_key(key(KeyCode::Char(']')));
        assert_eq!(dash.context_tree.cursor, 0);
    }

    #[test]
    fn main_list_unhandled_key_is_noop() {
        let mut dash = make_test_dashboard();
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Active));
        dash.update_display_indices();
        let selected_before = dash.selected;
        dash.handle_key(key(KeyCode::Char('z')));
        assert_eq!(dash.selected, selected_before);
    }

    #[test]
    fn submit_input_no_agent_selected_returns_early() {
        let mut dash = make_test_dashboard();
        dash.input_mode = true;
        // No agents at all - selected_agent() is None.
        dash.submit_input();
        assert!(dash.agents.is_empty());
    }

    // ─── kill from the detail view ────────────────────────────────────────

    #[test]
    fn kill_from_detail_active_agent() {
        let mut dash = make_test_dashboard();
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Active));
        dash.update_display_indices();
        dash.detail_view = true;
        dash.handle_key(key(KeyCode::Char('x')));
        dash.handle_key(key(KeyCode::Char('y')));
        assert_cancelled(&dash.agents[0].status);
    }

    #[test]
    fn kill_from_detail_complete_agent_no_op() {
        let mut dash = make_test_dashboard();
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Complete));
        dash.update_display_indices();
        dash.detail_view = true;
        dash.handle_key(key(KeyCode::Char('x')));
        assert!(dash.pending_confirm.is_none());
        assert_complete(&dash.agents[0].status);
    }

    #[test]
    fn confirmed_kill_from_detail_resets_input_state() {
        let (cmd_tx, mut cmd_rx) = mpsc::unbounded_channel();
        let mut dash = Dashboard::new(cmd_tx);
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Waiting);
        agent.waiting_prompt = Some("?".to_string());
        agent.pending_request = Some(interaction::InteractionRequest::free_text(
            "q1", "?", "main", true,
        ));
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;
        dash.handle_key(key(KeyCode::Char('x')));
        dash.handle_key(key(KeyCode::Char('y')));

        assert_cancelled(&dash.agents[0].status);
        assert!(dash.agents[0].pending_request.is_none());
        assert!(!dash.input_mode);
        assert_eq!(
            cmd_rx.try_recv().unwrap(),
            DaemonCommand::Cancel {
                run_id: "run-1".to_string()
            }
        );
    }

    // ─── detail view: search n/N ──────────────────────────────────────────

    #[test]
    fn detail_view_search_n_increments_match() {
        let mut dash = make_test_dashboard();
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Active));
        dash.update_display_indices();
        dash.detail_view = true;
        dash.search_query = "test".to_string();
        dash.search_match_idx = 0;
        dash.handle_key(key(KeyCode::Char('n')));
        assert_eq!(dash.search_match_idx, 1);
        dash.handle_key(key(KeyCode::Char('n')));
        assert_eq!(dash.search_match_idx, 2);
    }

    #[test]
    fn detail_view_search_shift_n_decrements_match() {
        let mut dash = make_test_dashboard();
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Active));
        dash.update_display_indices();
        dash.detail_view = true;
        dash.search_query = "test".to_string();
        dash.search_match_idx = 5;
        dash.handle_key(key(KeyCode::Char('N')));
        assert_eq!(dash.search_match_idx, 4);
    }

    #[test]
    fn detail_view_search_n_no_query_no_op() {
        let mut dash = make_test_dashboard();
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Active));
        dash.update_display_indices();
        dash.detail_view = true;
        dash.search_query.clear();
        dash.search_match_idx = 0;
        dash.handle_key(key(KeyCode::Char('n')));
        assert_eq!(dash.search_match_idx, 0);
    }

    // ─── detail view: unified i key (respond + mid-run message) ───────────

    #[test]
    fn detail_view_i_enters_input_when_can_respond() {
        let mut dash = make_test_dashboard();
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Waiting);
        agent.waiting_prompt = Some("prompt".to_string());
        agent.pending_request = Some(leviath_core::interaction::InteractionRequest::free_text(
            "ft1", "prompt", "main", true,
        ));
        agent.stage_index = 0;
        agent.stages = vec![crate::runstate::StageRecord::new("main".to_string(), 0)];
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;
        dash.selected_stage = 0;

        dash.handle_key(key(KeyCode::Char('i')));
        assert!(dash.input_mode);
    }

    #[test]
    fn detail_view_i_enters_input_for_active_accepting_agent() {
        let mut dash = make_test_dashboard();
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Active);
        agent.accepts_messages = true;
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;

        dash.handle_key(key(KeyCode::Char('i')));
        assert!(dash.input_mode);
    }

    #[test]
    fn detail_view_i_no_effect_when_not_accepting_and_cannot_respond() {
        let mut dash = make_test_dashboard();
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Active);
        agent.accepts_messages = false;
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;

        dash.handle_key(key(KeyCode::Char('i')));
        assert!(!dash.input_mode);
    }

    #[test]
    fn detail_view_m_key_no_longer_bound() {
        // The message keybinding is 'i', not 'm'. Pressing 'm' must not enter
        // input mode.
        let mut dash = make_test_dashboard();
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Active);
        agent.accepts_messages = true;
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;

        dash.handle_key(key(KeyCode::Char('m')));
        assert!(!dash.input_mode);
    }

    // ─── detail view: d key for delete ────────────────────────────────────

    #[test]
    fn main_list_d_opens_confirm_delete() {
        let mut dash = make_test_dashboard();
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Active));
        dash.update_display_indices();
        dash.handle_key(key(KeyCode::Char('d')));
        assert!(dash.pending_confirm.is_some());
    }

    // ─── detail view: review scroll ───────────────────────────────────────

    #[test]
    fn detail_view_scroll_with_review_body() {
        let mut dash = make_test_dashboard();
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Waiting);
        agent.pending_request = Some(leviath_core::interaction::InteractionRequest::review(
            "rev1",
            "Review",
            "# Long markdown body\n\nSome content here.",
            "main",
        ));
        agent.waiting_prompt = Some("Review".to_string());
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;

        // In the default Output mode the content pane is already showing the
        // body, so the separate review pane is suppressed and the content pane
        // is what a scroll must move. Asserting `review_scroll` here - a pane
        // that is not on screen - is precisely how a plan sits still while
        // every scroll key "works" and this test stays green.
        dash.handle_key(key(KeyCode::Up));
        assert_eq!(dash.detail_scroll, 1);
        assert_eq!(dash.review_scroll, 0);

        dash.handle_key(key(KeyCode::Down));
        assert_eq!(dash.detail_scroll, 0);

        dash.handle_key(key(KeyCode::PageUp));
        assert_eq!(dash.detail_scroll, 10);

        dash.handle_key(key(KeyCode::PageDown));
        assert_eq!(dash.detail_scroll, 0);

        // Switch the content pane to logs and the review pane *is* rendered, so
        // now the same keys move it instead.
        dash.handle_key(key(KeyCode::Char('l')));
        dash.handle_key(key(KeyCode::PageUp));
        assert_eq!(dash.review_scroll, 10, "the review pane is on screen now");
        assert_eq!(dash.detail_scroll, 0);
    }

    // ─── handle_input_mode_key for ToolApproval ──────────────────────────

    #[test]
    fn input_mode_tool_approval_up_down() {
        let mut dash = make_test_dashboard();
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Waiting);
        agent.pending_request = Some(
            leviath_core::interaction::InteractionRequest::tool_approval(
                "ta1",
                "bash",
                serde_json::json!({"cmd": "ls"}),
                "main",
                &[],
            ),
        );
        agent.waiting_prompt = Some("Allow tool?".to_string());
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;
        dash.input_mode = true;
        dash.choice_selected = 0;

        // Down through once / stage / run / deny
        for expected in 1..=3 {
            dash.handle_key(key(KeyCode::Down));
            assert_eq!(dash.choice_selected, expected);
        }
        // Can't go past last
        dash.handle_key(key(KeyCode::Down));
        assert_eq!(dash.choice_selected, 3);

        // Up back
        dash.handle_key(key(KeyCode::Up));
        assert_eq!(dash.choice_selected, 2);
    }

    #[test]
    fn input_mode_tool_approval_esc_resets() {
        let mut dash = make_test_dashboard();
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Waiting);
        agent.pending_request = Some(
            leviath_core::interaction::InteractionRequest::tool_approval(
                "ta1",
                "bash",
                serde_json::json!({"cmd": "ls"}),
                "main",
                &[],
            ),
        );
        agent.waiting_prompt = Some("Allow tool?".to_string());
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;
        dash.input_mode = true;
        dash.choice_selected = 2;

        dash.handle_key(key(KeyCode::Esc));
        assert!(!dash.input_mode);
        assert_eq!(dash.choice_selected, 0);
    }

    // ─── submit_input for FreeText ───────────────────────────────────────

    #[test]
    fn submit_input_free_text() {
        let (cmd_tx, _cmd_rx) = mpsc::unbounded_channel();
        let mut dash = Dashboard::new(cmd_tx);
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Waiting);
        agent.pending_request = Some(leviath_core::interaction::InteractionRequest::free_text(
            "ft1", "What?", "main", true,
        ));
        agent.waiting_prompt = Some("What?".to_string());
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;
        dash.input_mode = true;

        // Type something into the textarea
        dash.input_textarea.insert_str("my answer");

        dash.submit_input();

        assert!(!dash.input_mode);
        assert!(dash.agents[0].pending_request.is_none());
        assert!(dash.agents[0].waiting_prompt.is_none());
        assert_eq!(dash.agents[0].status, AgentDisplayStatus::Active);
    }

    // ─── submit_input for FreeText with /quit ─────────────────────────────

    #[test]
    fn submit_input_free_text_quit() {
        let (cmd_tx, _cmd_rx) = mpsc::unbounded_channel();
        let mut dash = Dashboard::new(cmd_tx);
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Waiting);
        agent.pending_request = Some(leviath_core::interaction::InteractionRequest::free_text(
            "ft1", "What?", "main", true,
        ));
        agent.waiting_prompt = Some("What?".to_string());
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;
        dash.input_mode = true;

        dash.input_textarea.insert_str("/quit");

        dash.submit_input();

        assert!(!dash.input_mode);
        // Agent status should be Active (resumed)
        assert_eq!(dash.agents[0].status, AgentDisplayStatus::Active);
    }

    // ─── submit_input for MultipleChoice ──────────────────────────────────

    #[test]
    fn submit_input_multiple_choice() {
        let (cmd_tx, _cmd_rx) = mpsc::unbounded_channel();
        let mut dash = Dashboard::new(cmd_tx);
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Waiting);
        agent.pending_request = Some(
            leviath_core::interaction::InteractionRequest::multiple_choice(
                "mc1",
                "Pick",
                vec!["A".into(), "B".into(), "C".into()],
                "main",
            ),
        );
        agent.waiting_prompt = Some("Pick".to_string());
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;
        dash.input_mode = true;
        dash.choice_selected = 1; // Select "B"

        dash.submit_input();

        assert!(!dash.input_mode);
        assert_eq!(dash.choice_selected, 0); // reset
        assert!(dash.agents[0].pending_request.is_none());
    }

    // ─── submit_input for ToolApproval with different indices ─────────────

    /// Every option position, end to end: the index the user landed on has to
    /// become the scope the daemon is told about, or a person choosing "for this
    /// stage" silently gets something else.
    #[test]
    fn submit_input_tool_approval_sends_the_scope_the_option_named() {
        let cases = [
            (0, true, interaction::ApprovalScope::Once),
            (1, true, interaction::ApprovalScope::Stage),
            (2, true, interaction::ApprovalScope::Run),
            (3, false, interaction::ApprovalScope::Once),
        ];
        for (index, approved, scope) in cases {
            let (cmd_tx, mut cmd_rx) = mpsc::unbounded_channel();
            let mut dash = Dashboard::new(cmd_tx);
            let mut agent = make_test_agent("run-1", AgentDisplayStatus::Waiting);
            agent.pending_request = Some(
                leviath_core::interaction::InteractionRequest::tool_approval(
                    "ta1",
                    "bash",
                    serde_json::json!({"cmd": "ls"}),
                    "main",
                    &["shell:ls".to_string()],
                ),
            );
            agent.waiting_prompt = Some("Allow tool?".to_string());
            dash.agents.push(agent);
            dash.update_display_indices();
            dash.detail_view = true;
            dash.input_mode = true;
            dash.choice_selected = index;

            dash.submit_input();
            assert!(!dash.input_mode);
            assert!(dash.agents[0].pending_request.is_none());
            let cmd = cmd_rx.try_recv().expect("an Answer command was queued");
            assert_eq!(
                cmd,
                DaemonCommand::Answer {
                    response: interaction::InteractionResponse::approval("ta1", approved, scope),
                },
                "option {index}"
            );
        }
    }

    // ─── submit_input for Confirm ─────────────────────────────────────────

    #[test]
    fn submit_input_confirm_yes() {
        let (cmd_tx, _cmd_rx) = mpsc::unbounded_channel();
        let mut dash = Dashboard::new(cmd_tx);
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Waiting);
        agent.pending_request = Some(leviath_core::interaction::InteractionRequest::confirm(
            "c1", "Proceed?", "main",
        ));
        agent.waiting_prompt = Some("Proceed?".to_string());
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;
        dash.input_mode = true;
        dash.choice_selected = 0; // "Yes"

        dash.submit_input();
        assert!(!dash.input_mode);
        assert!(dash.agents[0].pending_request.is_none());
    }

    #[test]
    fn submit_input_confirm_no() {
        let (cmd_tx, _cmd_rx) = mpsc::unbounded_channel();
        let mut dash = Dashboard::new(cmd_tx);
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Waiting);
        agent.pending_request = Some(leviath_core::interaction::InteractionRequest::confirm(
            "c1", "Proceed?", "main",
        ));
        agent.waiting_prompt = Some("Proceed?".to_string());
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;
        dash.input_mode = true;
        dash.choice_selected = 1; // "No"

        dash.submit_input();
        assert!(!dash.input_mode);
        assert!(dash.agents[0].pending_request.is_none());
    }

    // ─── submit_input for in-process agent (cmd_tx path) ──────────────────

    #[test]
    fn submit_input_in_process_agent() {
        let (cmd_tx, mut cmd_rx) = mpsc::unbounded_channel();
        let mut dash = Dashboard::new(cmd_tx);
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Waiting);
        agent.pending_request = Some(leviath_core::interaction::InteractionRequest::free_text(
            "ft1", "What?", "main", true,
        ));
        agent.waiting_prompt = Some("What?".to_string());
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;
        dash.input_mode = true;

        dash.input_textarea.insert_str("in-process answer");

        dash.submit_input();

        assert!(!dash.input_mode);
        // Should have sent EngineCommand::SendInput
        let cmd = cmd_rx.try_recv();
        assert!(cmd.is_ok());
    }

    // ─── submit_input with no pending request (mid-run message) ───────────

    #[test]
    fn submit_input_no_pending_request() {
        let (cmd_tx, _cmd_rx) = mpsc::unbounded_channel();
        let mut dash = Dashboard::new(cmd_tx);
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Active);
        agent.pending_request = None;
        agent.waiting_prompt = None;
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;
        dash.input_mode = true;

        dash.input_textarea.insert_str("hello mid-run");

        dash.submit_input();

        assert!(!dash.input_mode);
    }

    // ─── submit_input with no pending request /exit ───────────────────────

    #[test]
    fn submit_input_no_pending_request_exit() {
        let (cmd_tx, _cmd_rx) = mpsc::unbounded_channel();
        let mut dash = Dashboard::new(cmd_tx);
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Active);
        agent.pending_request = None;
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;
        dash.input_mode = true;

        dash.input_textarea.insert_str("/exit");
        dash.submit_input();

        assert!(!dash.input_mode);
    }

    // ─── handle_kill_from_detail for in-process agent ─────────────────────

    #[test]
    fn kill_from_detail_in_process_agent_sends_command() {
        let (cmd_tx, mut cmd_rx) = mpsc::unbounded_channel();
        let mut dash = Dashboard::new(cmd_tx);
        let agent = make_test_agent("run-1", AgentDisplayStatus::Active);
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;

        dash.handle_key(key(KeyCode::Char('x')));
        dash.handle_key(key(KeyCode::Char('y')));

        assert_eq!(dash.agents[0].status, AgentDisplayStatus::Cancelled);

        // Should have sent CancelAgent command
        let cmd = cmd_rx.try_recv();
        assert!(cmd.is_ok());
    }

    // ─── x + confirm from the list for in-process agent ───────────────────

    #[test]
    fn kill_from_list_in_process_agent_sends_command() {
        let (cmd_tx, mut cmd_rx) = mpsc::unbounded_channel();
        let mut dash = Dashboard::new(cmd_tx);
        let agent = make_test_agent("run-1", AgentDisplayStatus::Active);
        dash.agents.push(agent);
        dash.update_display_indices();

        dash.handle_key(key(KeyCode::Char('x')));
        dash.handle_key(key(KeyCode::Char('y')));

        assert_eq!(dash.agents[0].status, AgentDisplayStatus::Cancelled);

        let cmd = cmd_rx.try_recv();
        assert!(cmd.is_ok());
    }

    // ─── handle_yank generates toast for run-state agent ──────────────────

    #[test]
    fn yank_generates_toast_for_empty_content() {
        let mut dash = make_test_dashboard();
        let agent = make_test_agent("run-1", AgentDisplayStatus::Active);
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;
        dash.stage_content_mode = StageContentMode::Output;

        dash.handle_key(key(KeyCode::Char('y')));

        // Should have generated a toast (either "No Output content" or clipboard result)
        assert!(!dash.toasts.is_empty());
    }

    #[test]
    fn yank_logs_mode_empty_content_toast() {
        let mut dash = make_test_dashboard();
        let agent = make_test_agent("run-yank-logs", AgentDisplayStatus::Active);
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;
        dash.stage_content_mode = StageContentMode::Logs;

        dash.handle_key(key(KeyCode::Char('y')));

        assert!(!dash.toasts.is_empty());
    }

    #[test]
    fn yank_context_mode_empty_content_toast() {
        let mut dash = make_test_dashboard();
        let agent = make_test_agent("run-yank-context", AgentDisplayStatus::Active);
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;
        dash.stage_content_mode = StageContentMode::Context;

        dash.handle_key(key(KeyCode::Char('y')));

        assert!(!dash.toasts.is_empty());
    }

    #[test]
    fn yank_with_real_content_reports_success() {
        // Uses `handle_yank_with_fn` with an injected always-succeeds clipboard
        // fn for a deterministic toast assertion. (`handle_yank` itself uses
        // the dashboard's injected `yank_fn`, which is a no-op under
        // `make_test_dashboard`; the native-tool-vs-OSC52 branches live in
        // `helpers::yank_to_clipboard_via`'s own tests, and the real OSC52
        // write in `leviath_sys::tty`.)
        crate::runstate::with_isolated_runs_dir("yank_with_real_content_reports_success", |_d| {
            let run_id = "test-yank-real-content";
            crate::runstate::append_stage_output(run_id, 0, "some real output");

            let mut dash = make_test_dashboard();
            let agent = make_test_agent(run_id, AgentDisplayStatus::Active);
            dash.agents.push(agent);
            dash.update_display_indices();
            dash.detail_view = true;
            dash.stage_content_mode = StageContentMode::Output;

            dash.handle_yank_with_fn(|_| true);

            assert!(
                dash.toasts
                    .iter()
                    .any(|t| t.message.contains("yanked to clipboard"))
            );

            let _ = std::fs::remove_dir_all(crate::runstate::run_dir(run_id));
        });
    }

    #[test]
    fn detail_view_question_mark_shows_help() {
        let mut dash = make_test_dashboard();
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Active));
        dash.update_display_indices();
        dash.detail_view = true;
        dash.handle_key(key(KeyCode::Char('?')));
        assert!(dash.show_help);
    }

    // ─── d key from main list for non-run-state agent ─────────────────────

    // ─── input_mode_key: FreeText Enter submits ───────────────────────────

    #[test]
    fn input_mode_free_text_enter_submits() {
        let mut dash = make_test_dashboard();
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Waiting);
        agent.pending_request = Some(leviath_core::interaction::InteractionRequest::free_text(
            "ft1", "prompt", "main", true,
        ));
        agent.waiting_prompt = Some("prompt".to_string());
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;
        dash.input_mode = true;

        dash.input_textarea.insert_str("answer");

        // Enter with no modifiers should submit
        dash.handle_key(key(KeyCode::Enter));
        assert!(!dash.input_mode);
    }

    // ─── input_mode_key: MultipleChoice Enter submits ─────────────────────

    #[test]
    fn input_mode_multiple_choice_enter_submits() {
        crate::runstate::with_isolated_runs_dir("input_mode_multiple_choice_enter_submits", |_d| {
            let run_id = format!("test-mc-enter-{}", std::process::id());
            let mut dash = make_test_dashboard();
            let mut agent = make_test_agent(&run_id, AgentDisplayStatus::Waiting);
            agent.pending_request = Some(
                leviath_core::interaction::InteractionRequest::multiple_choice(
                    "mc1",
                    "Pick",
                    vec!["A".into(), "B".into()],
                    "main",
                ),
            );
            agent.waiting_prompt = Some("Pick".to_string());
            dash.agents.push(agent);
            dash.update_display_indices();
            dash.detail_view = true;
            dash.input_mode = true;
            dash.choice_selected = 0;

            // Ensure the run directory exists so write_response succeeds
            let _ = std::fs::create_dir_all(crate::runstate::run_dir(&run_id));

            dash.handle_key(key(KeyCode::Enter));
            assert!(!dash.input_mode);
            assert!(dash.log.iter().any(|e| e.message.contains("A")));

            let _ = std::fs::remove_dir_all(crate::runstate::run_dir(&run_id));
        });
    }

    // ─── Multiple events processed in sequence ────────────────────────────

    // ─── submit_input last_answered_request_id tracking ───────────────────

    #[test]
    fn submit_input_tracks_last_answered_request_id() {
        let mut dash = make_test_dashboard();
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Waiting);
        agent.pending_request = Some(leviath_core::interaction::InteractionRequest::free_text(
            "req-42", "What?", "main", true,
        ));
        agent.waiting_prompt = Some("What?".to_string());
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;
        dash.input_mode = true;

        dash.input_textarea.insert_str("answer");
        dash.submit_input();

        assert_eq!(
            dash.agents[0].last_answered_request_id.as_deref(),
            Some("req-42")
        );
    }

    // ─── detail view: Left/Right stage navigation ─────────────────────────

    #[test]
    fn detail_view_left_when_selected_stage_greater_than_zero() {
        // Exercises lines 164-171: the body of `if self.selected_stage > 0`
        // for the Left key in handle_detail_view_key.
        let mut dash = make_test_dashboard();
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Active);
        agent.num_stages = 3;
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;
        dash.selected_stage = 2;
        dash.detail_scroll = 5;
        dash.review_scroll = 3;
        // search_mode must be FALSE so search mode doesn't intercept the Left key.
        // The handler still clears search_query and search_match_idx.
        dash.search_mode = false;
        dash.search_query = "foo".to_string();
        dash.search_match_idx = 4;

        dash.handle_key(key(KeyCode::Left));

        assert_eq!(dash.selected_stage, 1);
        assert_eq!(dash.detail_scroll, 0);
        assert_eq!(dash.review_scroll, 0);
        assert!(!dash.search_mode);
        assert!(dash.search_query.is_empty());
        assert_eq!(dash.search_match_idx, 0);
    }

    #[test]
    fn detail_view_left_when_selected_stage_is_zero_no_op() {
        // Exercises the false branch of `if self.selected_stage > 0` (line 164).
        let mut dash = make_test_dashboard();
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Active));
        dash.update_display_indices();
        dash.detail_view = true;
        dash.selected_stage = 0;

        dash.handle_key(key(KeyCode::Left));

        assert_eq!(dash.selected_stage, 0);
    }

    #[test]
    fn detail_view_right_advances_stage_when_below_max() {
        // Exercises lines 178-185: the body of `if self.selected_stage < max_stage`
        // for the Right key in handle_detail_view_key.
        let mut dash = make_test_dashboard();
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Active);
        agent.num_stages = 3; // max_stage = 2
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;
        dash.selected_stage = 0;
        dash.detail_scroll = 5;
        dash.review_scroll = 3;
        // search_mode must be FALSE so search mode doesn't intercept the Right key.
        dash.search_mode = false;
        dash.search_query = "bar".to_string();
        dash.search_match_idx = 7;

        dash.handle_key(key(KeyCode::Right));

        assert_eq!(dash.selected_stage, 1);
        assert_eq!(dash.detail_scroll, 0);
        assert_eq!(dash.review_scroll, 0);
        assert!(!dash.search_mode);
        assert!(dash.search_query.is_empty());
        assert_eq!(dash.search_match_idx, 0);
    }

    #[test]
    fn detail_view_right_at_max_stage_no_op() {
        // Exercises the false branch of `if self.selected_stage < max_stage`.
        let mut dash = make_test_dashboard();
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Active);
        agent.num_stages = 2; // max_stage = 1
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;
        dash.selected_stage = 1; // already at max

        dash.handle_key(key(KeyCode::Right));

        assert_eq!(dash.selected_stage, 1);
    }

    // ─── detail view: number key stage jump ──────────────────────────────

    #[test]
    fn detail_view_number_key_jumps_to_valid_stage() {
        // Exercises lines 194-201: the body of `if idx <= max_stage` in the
        // Char('1'..='9') arm of handle_detail_view_key.
        let mut dash = make_test_dashboard();
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Active);
        agent.num_stages = 3; // max_stage=2; '3' => idx=2 which is <= 2
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;
        dash.selected_stage = 0;
        dash.detail_scroll = 10;
        dash.review_scroll = 5;
        // search_mode must be FALSE - in search mode, Char('3') is treated as a
        // search character rather than a stage-jump key.
        dash.search_mode = false;
        dash.search_query = "xyz".to_string();
        dash.search_match_idx = 3;

        dash.handle_key(key(KeyCode::Char('3')));

        assert_eq!(dash.selected_stage, 2);
        assert_eq!(dash.detail_scroll, 0);
        assert_eq!(dash.review_scroll, 0);
        assert!(!dash.search_mode);
        assert!(dash.search_query.is_empty());
        assert_eq!(dash.search_match_idx, 0);
    }

    /// A dashboard in detail view that is browsing a (fake) history point, for
    /// the reset-to-live key tests.
    fn browsing_detail_dashboard() -> Dashboard {
        let mut dash = make_test_dashboard();
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Active));
        dash.update_display_indices();
        dash.detail_view = true;
        let points = vec![leviath_core::run_archive::RunPoint {
            meta: leviath_core::run_meta::RunMeta::new(
                "run-1".to_string(),
                "a".to_string(),
                "/p".to_string(),
                "t".to_string(),
                None,
                "/w".to_string(),
                1,
            ),
            context: leviath_core::run_meta::ContextSnapshot {
                stage_name: "s".to_string(),
                total_tokens: 0,
                max_tokens: 100,
                regions: vec![],
            },
            at: 0,
        }];
        dash.history = Some(crate::commands::dashboard::history::RunHistoryCache {
            run_id: "run-1".to_string(),
            visits: crate::commands::dashboard::history::derive_visits(&points),
            points,
            loaded_at_tick: u64::MAX,
        });
        dash.context_history_idx = Some(0);
        dash
    }

    #[test]
    fn detail_view_comma_and_period_route_to_history_step() {
        // With no archive on disk, stepping is a no-op - this exercises the
        // `,`/`.` routing arms without needing a run.lvr fixture.
        let mut dash = make_test_dashboard();
        dash.agents.push(make_test_agent(
            "run-no-archive",
            AgentDisplayStatus::Active,
        ));
        dash.update_display_indices();
        dash.detail_view = true;
        dash.handle_key(key(KeyCode::Char(',')));
        dash.handle_key(key(KeyCode::Char('.')));
        assert_eq!(dash.context_history_idx, None);
    }

    #[test]
    fn detail_view_c_returns_to_live_context() {
        let mut dash = browsing_detail_dashboard();
        dash.handle_key(key(KeyCode::Char('c')));
        assert_eq!(dash.stage_content_mode, StageContentMode::Context);
        assert_eq!(dash.context_history_idx, None); // back to live
    }

    #[test]
    fn detail_view_esc_resets_context_history() {
        let mut dash = browsing_detail_dashboard();
        dash.handle_key(key(KeyCode::Esc));
        assert!(!dash.detail_view);
        assert_eq!(dash.context_history_idx, None);
    }

    #[test]
    fn detail_view_number_key_out_of_range_no_op() {
        // Exercises the false branch of `if idx <= max_stage`: pressing '9'
        // when there are only 2 stages (max_stage=1) leaves selected_stage unchanged.
        let mut dash = make_test_dashboard();
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Active);
        agent.num_stages = 2; // max_stage=1; '9' => idx=8 which is > 1
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;
        dash.selected_stage = 0;

        dash.handle_key(key(KeyCode::Char('9')));

        assert_eq!(dash.selected_stage, 0);
    }

    // ─── detail view: 'N' search when query is empty (no-op) ──────────────

    #[test]
    fn detail_view_shift_n_no_query_no_op() {
        // Exercises the false branch of `if !self.search_query.is_empty()` in
        // the Char('N') arm (line 301), ensuring search_match_idx stays at 0.
        let mut dash = make_test_dashboard();
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Active));
        dash.update_display_indices();
        dash.detail_view = true;
        dash.search_query.clear();
        dash.search_match_idx = 0;
        dash.handle_key(key(KeyCode::Char('N')));
        assert_eq!(dash.search_match_idx, 0);
    }

    // ─── handle_yank: no agent, is_run_state=false ────────────────────────

    #[test]
    fn yank_no_agent_is_noop() {
        // Exercises the `else` branch of `if let Some(agent) = self.selected_agent()`
        // (line 359) in handle_yank: no agent means nothing happens.
        let mut dash = make_test_dashboard();
        dash.detail_view = true;
        // No agents at all
        dash.handle_key(key(KeyCode::Char('y')));
        assert!(dash.toasts.is_empty());
    }

    // ─── main list: Down key - three agents to confirm can-move path ──────

    #[test]
    fn main_list_down_advances_through_multiple_agents() {
        // Exercises lines 421-424: the body of the Down key's inner if-block
        // in handle_main_list_key when selected < display_indices.len() - 1.
        let mut dash = make_test_dashboard();
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Active));
        dash.agents
            .push(make_test_agent("run-2", AgentDisplayStatus::Active));
        dash.agents
            .push(make_test_agent("run-3", AgentDisplayStatus::Active));
        dash.update_display_indices();
        assert_eq!(dash.selected, 0);

        dash.handle_key(key(KeyCode::Down));
        assert_eq!(dash.selected, 1);

        dash.handle_key(key(KeyCode::Down));
        assert_eq!(dash.selected, 2);

        // At bottom - cannot go further
        dash.handle_key(key(KeyCode::Down));
        assert_eq!(dash.selected, 2);
    }

    // ─── confirmed kill clears pending_request (list and detail) ──────────

    #[test]
    fn kill_from_list_run_state_agent_clears_pending_request() {
        let mut dash = make_test_dashboard();
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Active);
        agent.pending_request = Some(leviath_core::interaction::InteractionRequest::free_text(
            "r1", "?", "main", true,
        ));
        dash.agents.push(agent);
        dash.update_display_indices();

        dash.handle_key(key(KeyCode::Char('x')));
        dash.handle_key(key(KeyCode::Char('y')));

        assert!(dash.agents[0].pending_request.is_none());
        assert_cancelled(&dash.agents[0].status);
    }

    #[test]
    fn kill_from_detail_run_state_agent_clears_pending_request() {
        let mut dash = make_test_dashboard();
        let mut agent = make_test_agent("run-1", AgentDisplayStatus::Active);
        agent.pending_request = Some(leviath_core::interaction::InteractionRequest::free_text(
            "r1", "?", "main", true,
        ));
        dash.agents.push(agent);
        dash.update_display_indices();
        dash.detail_view = true;

        dash.handle_key(key(KeyCode::Char('x')));
        dash.handle_key(key(KeyCode::Char('y')));

        assert!(dash.agents[0].pending_request.is_none());
        assert_cancelled(&dash.agents[0].status);
    }

    // ─── handle_yank_with_fn: clipboard-unavailable branch ───────────────────

    #[test]
    fn yank_clipboard_unavailable_shows_error_toast() {
        crate::runstate::with_isolated_runs_dir(
            "yank_clipboard_unavailable_shows_error_toast",
            |_d| {
                use crate::runstate;
                let run_id = "test-yank-clipboard-unavailable-x7z9";
                let stage_path = runstate::stage_dir(run_id, 0);
                std::fs::create_dir_all(&stage_path).ok();
                std::fs::write(stage_path.join("context.json"), r#"{"test":true}"#).ok();

                let mut dash = make_test_dashboard();
                let agent = make_test_agent(run_id, AgentDisplayStatus::Active);
                dash.agents.push(agent);
                dash.update_display_indices();
                dash.detail_view = true;
                dash.stage_content_mode = StageContentMode::Context;
                dash.selected_stage = 0;

                dash.handle_yank_with_fn(|_| false);

                assert!(
                    dash.toasts
                        .iter()
                        .any(|t| t.message.contains("Clipboard unavailable"))
                );

                let _ = std::fs::remove_dir_all(runstate::run_dir(run_id));
            },
        );
    }

    // ─── MCP management screen keys ───────────────────────────────────────

    /// A dashboard whose MCP context points at a temp dir.
    fn mcp_dash(dir: &std::path::Path) -> Dashboard {
        let mut dash = make_test_dashboard();
        dash.mcp_ctx.config_path = dir.join("config.toml");
        dash.mcp_ctx.store_path = dir.join("mcp-auth.json");
        dash
    }

    #[test]
    fn m_opens_the_mcp_screen() {
        let dir = tempfile::tempdir().unwrap();
        let mut dash = mcp_dash(dir.path());
        dash.handle_key(key(KeyCode::Char('m')));
        assert!(dash.mcp_screen);
    }

    #[test]
    fn esc_closes_the_mcp_screen_and_q_quits_the_app() {
        let dir = tempfile::tempdir().unwrap();
        let mut dash = mcp_dash(dir.path());
        dash.mcp_screen = true;
        dash.handle_key(key(KeyCode::Esc));
        assert!(!dash.mcp_screen);
        assert!(!dash.should_quit);

        dash.mcp_screen = true;
        dash.handle_key(key(KeyCode::Char('q')));
        assert!(dash.should_quit, "q means quit here like everywhere else");
    }

    #[test]
    fn arrows_navigate_the_mcp_list() {
        let dir = tempfile::tempdir().unwrap();
        let mut dash = mcp_dash(dir.path());
        dash.mcp_add_from_line("a npx");
        dash.mcp_add_from_line("b npx");
        dash.refresh_mcp_rows();
        dash.mcp_screen = true;
        dash.mcp_selected = 0;

        dash.handle_key(key(KeyCode::Down));
        assert_eq!(dash.mcp_selected, 1);
        dash.handle_key(key(KeyCode::Down)); // clamped at last
        assert_eq!(dash.mcp_selected, 1);
        dash.handle_key(key(KeyCode::Up));
        assert_eq!(dash.mcp_selected, 0);
        dash.handle_key(key(KeyCode::Up)); // clamped at 0
        assert_eq!(dash.mcp_selected, 0);
    }

    #[test]
    fn a_opens_the_add_editor_and_enter_adds() {
        let dir = tempfile::tempdir().unwrap();
        let mut dash = mcp_dash(dir.path());
        dash.mcp_screen = true;

        dash.handle_key(key(KeyCode::Char('a')));
        assert!(dash.mcp_add_mode);
        // Type "srv npx".
        for c in "srv npx".chars() {
            dash.handle_key(key(KeyCode::Char(c)));
        }
        // A backspace then retype to cover Backspace.
        dash.handle_key(key(KeyCode::Backspace));
        dash.handle_key(key(KeyCode::Char('x')));
        dash.handle_key(key(KeyCode::Enter));
        assert!(!dash.mcp_add_mode);

        let config =
            crate::config::Config::load_from_path_public(&dash.mcp_ctx.config_path).unwrap();
        assert_eq!(config.mcp_servers.len(), 1);
        assert_eq!(config.mcp_servers[0].command.as_deref(), Some("npx")); // "np" + "x"
    }

    #[test]
    fn esc_cancels_the_add_editor() {
        let dir = tempfile::tempdir().unwrap();
        let mut dash = mcp_dash(dir.path());
        dash.mcp_screen = true;
        dash.mcp_add_mode = true;
        dash.mcp_add_input = "half typed".to_string();
        dash.handle_key(key(KeyCode::Esc));
        assert!(!dash.mcp_add_mode);
        assert!(dash.mcp_add_input.is_empty());
    }

    #[test]
    fn add_editor_ignores_non_text_keys() {
        let dir = tempfile::tempdir().unwrap();
        let mut dash = mcp_dash(dir.path());
        dash.mcp_screen = true;
        dash.mcp_add_mode = true;
        // A key with no meaning in the editor is a no-op.
        dash.handle_key(key(KeyCode::Down));
        assert!(dash.mcp_add_mode);
        assert!(dash.mcp_add_input.is_empty());
    }

    #[test]
    fn d_removes_the_selected_server_after_confirming() {
        let dir = tempfile::tempdir().unwrap();
        let mut dash = mcp_dash(dir.path());
        dash.mcp_add_from_line("gone npx");
        dash.refresh_mcp_rows();
        dash.mcp_screen = true;
        dash.mcp_selected = 0;
        dash.handle_key(key(KeyCode::Char('d')));
        assert!(dash.pending_confirm.is_some(), "d asks first");
        assert_eq!(dash.mcp_rows.len(), 1, "nothing removed yet");
        dash.handle_key(key(KeyCode::Char('y')));
        assert!(dash.mcp_rows.is_empty());
    }

    #[test]
    fn l_and_t_dispatch_login_and_test() {
        let dir = tempfile::tempdir().unwrap();
        let mut dash = mcp_dash(dir.path());
        dash.mcp_add_from_line("remote https://e.com/mcp");
        dash.refresh_mcp_rows();
        dash.mcp_screen = true;
        dash.mcp_selected = 0;
        dash.handle_key(key(KeyCode::Char('l')));
        dash.handle_key(key(KeyCode::Char('t')));
        assert!(dash.mcp_cmd_rx_for_test().try_recv().is_ok());
        assert!(dash.mcp_cmd_rx_for_test().try_recv().is_ok());
    }

    #[test]
    fn r_refreshes_the_list() {
        let dir = tempfile::tempdir().unwrap();
        let mut dash = mcp_dash(dir.path());
        dash.mcp_screen = true;
        // Add a server on disk behind the screen's back, then refresh.
        let mut config = crate::config::Config::default();
        config
            .mcp_servers
            .push(leviath_mcp::MCPServerConfig::stdio("x", "npx", vec![]));
        config
            .save_to_path_public(&dash.mcp_ctx.config_path)
            .unwrap();
        assert!(dash.mcp_rows.is_empty());
        dash.handle_key(key(KeyCode::Char('r')));
        assert_eq!(dash.mcp_rows.len(), 1);
    }

    #[test]
    fn unbound_mcp_screen_keys_are_ignored() {
        let dir = tempfile::tempdir().unwrap();
        let mut dash = mcp_dash(dir.path());
        dash.mcp_screen = true;
        dash.handle_key(key(KeyCode::Char('z')));
        assert!(dash.mcp_screen, "an unbound key does nothing");
    }

    // ─── the new-run screen ───────────────────────────────────────────────

    /// A dashboard whose new-run screen reads from an empty temp tree, so `n`
    /// never scans the real agents directory or working directory.
    fn new_run_dash(dir: &std::path::Path) -> Dashboard {
        let mut dash = make_test_dashboard();
        dash.new_run_ctx = NewRunContext {
            agents_dir: dir.join("agents"),
            config_path: dir.join("config.toml"),
            workdir: dir.join("work"),
        };
        dash
    }

    #[test]
    fn n_opens_the_new_run_screen() {
        let dir = tempfile::tempdir().unwrap();
        let mut dash = new_run_dash(dir.path());
        dash.handle_key(key(KeyCode::Char('n')));
        assert!(dash.new_run_screen);
    }

    #[test]
    fn the_new_run_screen_owns_the_keys_while_open() {
        let dir = tempfile::tempdir().unwrap();
        let mut dash = new_run_dash(dir.path());
        dash.handle_key(key(KeyCode::Char('n')));
        // `q` would quit from the main list; here it is filter text, because a
        // task is typed on this screen.
        dash.handle_key(key(KeyCode::Char('q')));
        assert!(!dash.should_quit);
        assert_eq!(dash.new_run_filter, "q");

        dash.handle_key(key(KeyCode::Esc));
        dash.handle_key(key(KeyCode::Esc));
        assert!(!dash.new_run_screen);
    }

    // ─── where you end up after starting a run ───────────────────────────────

    /// The whole path: list → new run → the run's own page → back to the list.
    ///
    /// The last step is the one worth pinning. The new-run screen closes at submit
    /// rather than staying behind the detail view, so Esc from the run lands on
    /// the list and not back in a form that has already been filled in.
    #[test]
    fn starting_a_run_opens_its_page_and_esc_returns_to_the_list() {
        let mut dash = make_test_dashboard();
        dash.handle_key(key(KeyCode::Char('n')));
        assert!(dash.new_run_screen, "n opens the screen");

        // The run is dispatched; the daemon has not reported it yet.
        dash.close_new_run_screen();
        dash.inject_spawn_outcome_for_test(SpawnOutcome {
            message: "Started run-7".to_string(),
            ok: true,
            run_id: Some("run-7".to_string()),
        });
        dash.drain_spawn_outcomes();
        dash.open_pending_run();
        assert!(
            !dash.detail_view,
            "nothing to open until the run reaches the list"
        );

        // It arrives on a later sync.
        dash.agents
            .push(make_test_agent("run-7", AgentDisplayStatus::Active));
        dash.update_display_indices();
        dash.open_pending_run();
        assert!(dash.detail_view, "the run's page opens by itself");
        assert_eq!(
            dash.selected_agent().map(|a| a.id.as_str()),
            Some("run-7"),
            "and it is the run that was started, not whatever was selected"
        );

        // Back goes to the list, not to the screen the run was started from.
        dash.handle_key(key(KeyCode::Esc));
        assert!(!dash.detail_view);
        assert!(!dash.new_run_screen, "the form is not on the back stack");
    }

    /// A run that never appears is given up on rather than opening a page minutes
    /// later, under whatever the user has moved on to.
    #[test]
    fn a_run_that_never_arrives_is_dropped() {
        let mut dash = make_test_dashboard();
        dash.inject_spawn_outcome_for_test(SpawnOutcome {
            message: "Started ghost".to_string(),
            ok: true,
            run_id: Some("ghost".to_string()),
        });
        dash.drain_spawn_outcomes();
        for _ in 0..crate::commands::dashboard::new_run::OPEN_RUN_TICKS + 1 {
            dash.open_pending_run();
        }
        assert!(dash.pending_open_run.is_none(), "it stopped waiting");
        assert!(!dash.detail_view);
    }

    /// Somewhere else means the user went there themselves.
    #[test]
    fn a_pending_run_does_not_yank_you_out_of_another_screen() {
        let mut dash = make_test_dashboard();
        dash.inject_spawn_outcome_for_test(SpawnOutcome {
            message: "Started run-7".to_string(),
            ok: true,
            run_id: Some("run-7".to_string()),
        });
        dash.drain_spawn_outcomes();
        dash.agents
            .push(make_test_agent("run-7", AgentDisplayStatus::Active));
        dash.update_display_indices();

        dash.mcp_screen = true;
        dash.open_pending_run();
        assert!(!dash.detail_view, "it waits rather than interrupting");
        assert!(dash.mcp_screen);
    }

    /// A spawn that failed has no page to open.
    #[test]
    fn a_refused_run_opens_nothing() {
        let mut dash = make_test_dashboard();
        dash.inject_spawn_outcome_for_test(SpawnOutcome {
            message: "The daemon refused the run: nope".to_string(),
            ok: false,
            run_id: None,
        });
        dash.drain_spawn_outcomes();
        assert!(dash.pending_open_run.is_none());
        dash.open_pending_run();
        assert!(!dash.detail_view);
    }

    // ── Marking runs with Space for group kill / delete ──────────────────

    #[test]
    fn space_marks_the_selected_run_and_advances() {
        let mut dash = make_test_dashboard();
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Active));
        dash.agents
            .push(make_test_agent("run-2", AgentDisplayStatus::Active));
        dash.update_display_indices();
        let first_id = dash.selected_agent().unwrap().id.clone();
        dash.handle_key(key(KeyCode::Char(' ')));
        assert!(dash.marked.contains(&first_id));
        assert_eq!(dash.selected, 1, "space moves down like the Down key");
    }

    #[test]
    fn space_on_a_marked_run_unmarks_it() {
        let mut dash = make_test_dashboard();
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Active));
        dash.agents
            .push(make_test_agent("run-2", AgentDisplayStatus::Active));
        dash.update_display_indices();
        dash.handle_key(key(KeyCode::Char(' ')));
        dash.handle_key(key(KeyCode::Up));
        dash.handle_key(key(KeyCode::Char(' ')));
        assert!(dash.marked.is_empty(), "the second press toggles it off");
    }

    #[test]
    fn space_on_the_last_row_keeps_the_selection() {
        let mut dash = make_test_dashboard();
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Active));
        dash.update_display_indices();
        dash.handle_key(key(KeyCode::Char(' ')));
        assert_eq!(dash.marked.len(), 1);
        assert_eq!(dash.selected, 0, "nothing below to advance to");
    }

    #[test]
    fn space_with_no_runs_is_a_noop() {
        let mut dash = make_test_dashboard();
        dash.handle_key(key(KeyCode::Char(' ')));
        assert!(dash.marked.is_empty());
    }

    #[test]
    fn esc_clears_marks_when_no_filter_is_set() {
        let mut dash = make_test_dashboard();
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Active));
        dash.update_display_indices();
        dash.handle_key(key(KeyCode::Char(' ')));
        assert_eq!(dash.marked.len(), 1);
        dash.handle_key(key(KeyCode::Esc));
        assert!(dash.marked.is_empty());
        assert!(!dash.should_quit);
    }

    #[test]
    fn esc_clears_the_filter_before_the_marks() {
        let mut dash = make_test_dashboard();
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Active));
        dash.update_display_indices();
        dash.handle_key(key(KeyCode::Char(' ')));
        dash.list_search_query = "test".to_string();
        dash.handle_key(key(KeyCode::Esc));
        assert!(dash.list_search_query.is_empty());
        assert_eq!(dash.marked.len(), 1, "the first Esc only drops the filter");
        dash.handle_key(key(KeyCode::Esc));
        assert!(dash.marked.is_empty());
    }

    #[test]
    fn marked_delete_confirm_carries_all_ids_and_removes_them() {
        let mut dash = make_test_dashboard();
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Complete));
        dash.agents
            .push(make_test_agent("run-2", AgentDisplayStatus::Complete));
        dash.agents
            .push(make_test_agent("run-3", AgentDisplayStatus::Complete));
        dash.update_display_indices();
        dash.marked.insert("run-1".to_string());
        dash.marked.insert("run-2".to_string());
        dash.handle_key(key(KeyCode::Char('d')));

        let (action, dialog) = dash.pending_confirm.clone().expect("d opens the dialog");
        assert_eq!(
            action,
            ConfirmAction::Delete {
                run_ids: vec!["run-1".to_string(), "run-2".to_string()],
            }
        );
        assert!(
            format!("{:?}", dialog.body).contains("Delete 2 runs"),
            "the body states the count: {:?}",
            dialog.body
        );

        dash.handle_key(key(KeyCode::Char('y')));
        assert_eq!(dash.agents.len(), 1, "both marked runs are gone");
        assert_eq!(dash.agents[0].id, "run-3");
        assert!(dash.marked.is_empty(), "acted-on ids leave the mark set");
    }

    #[test]
    fn marked_delete_of_one_run_uses_the_singular_noun() {
        let mut dash = make_test_dashboard();
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Complete));
        dash.update_display_indices();
        dash.marked.insert("run-1".to_string());
        dash.handle_key(key(KeyCode::Char('d')));
        let (_, dialog) = dash.pending_confirm.clone().expect("d opens the dialog");
        assert!(
            format!("{:?}", dialog.body).contains("Delete 1 run and its"),
            "{:?}",
            dialog.body
        );
    }

    #[test]
    fn marked_kill_skips_finished_runs_and_unmarks_only_the_killed() {
        let (cmd_tx, mut cmd_rx) = mpsc::unbounded_channel();
        let mut dash = Dashboard::new(cmd_tx);
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Active));
        dash.agents
            .push(make_test_agent("run-2", AgentDisplayStatus::Complete));
        dash.update_display_indices();
        dash.marked.insert("run-1".to_string());
        dash.marked.insert("run-2".to_string());
        dash.handle_key(key(KeyCode::Char('x')));

        let (action, dialog) = dash.pending_confirm.clone().expect("x opens the dialog");
        assert_eq!(
            action,
            ConfirmAction::Kill {
                run_ids: vec!["run-1".to_string()],
            },
            "the finished run is not on the kill list"
        );
        assert!(
            format!("{:?}", dialog.body).contains("Cancel 1 run?"),
            "{:?}",
            dialog.body
        );

        dash.handle_key(key(KeyCode::Char('y')));
        assert_cancelled(&dash.agents[0].status);
        assert_eq!(
            cmd_rx.try_recv().unwrap(),
            DaemonCommand::Cancel {
                run_id: "run-1".to_string()
            }
        );
        assert!(cmd_rx.try_recv().is_err(), "run-2 was never cancelled");
        assert!(!dash.marked.contains("run-1"), "the killed run is unmarked");
        assert!(
            dash.marked.contains("run-2"),
            "the skipped run stays marked"
        );
    }

    #[test]
    fn marked_kill_of_several_runs_cancels_each() {
        let (cmd_tx, mut cmd_rx) = mpsc::unbounded_channel();
        let mut dash = Dashboard::new(cmd_tx);
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Active));
        dash.agents
            .push(make_test_agent("run-2", AgentDisplayStatus::Waiting));
        dash.update_display_indices();
        dash.marked.insert("run-1".to_string());
        dash.marked.insert("run-2".to_string());
        dash.handle_key(key(KeyCode::Char('x')));

        let (_, dialog) = dash.pending_confirm.clone().expect("x opens the dialog");
        assert!(
            format!("{:?}", dialog.body).contains("Cancel 2 runs?"),
            "{:?}",
            dialog.body
        );

        dash.handle_key(key(KeyCode::Char('y')));
        assert_cancelled(&dash.agents[0].status);
        assert_cancelled(&dash.agents[1].status);
        assert!(cmd_rx.try_recv().is_ok());
        assert!(cmd_rx.try_recv().is_ok());
        assert!(dash.marked.is_empty());
    }

    #[test]
    fn marked_kill_with_only_finished_runs_opens_no_dialog() {
        let mut dash = make_test_dashboard();
        dash.agents
            .push(make_test_agent("run-1", AgentDisplayStatus::Complete));
        dash.update_display_indices();
        dash.marked.insert("run-1".to_string());
        dash.handle_key(key(KeyCode::Char('x')));
        assert!(dash.pending_confirm.is_none());
    }
}