railwayapp 5.54.1

Interact with Railway via CLI
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
//! State and key handling for the `railway ca` TUI.
//!
//! Deliberately free of rendering and of I/O: every key produces state changes
//! plus at most one [`Effect`] for the event loop to carry out. That keeps the
//! navigation model — which is most of the behaviour worth getting right —
//! testable without a terminal or a network.
//!
//! The tree is workspace → project → environment → agent. Structure comes from
//! one `UserProjects` call; agents arrive from one `myCloudAgents` call, which
//! answers for the whole account at once. Against a backboard that predates
//! that field, agents are per environment and load only when an environment is
//! expanded, because `cloudAgents` takes one environment at a time and a
//! workspace can hold dozens.

use std::collections::HashMap;

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

use super::session;
use super::theme::Theme;

/// Harnesses the launcher can put a session on, in cycle order. `railway`
/// leads the list — and so is the default pick with nothing configured —
/// since it is the one exception needing no credential of its own: no
/// carry-a-local-sign-in step, just the VM's own integrated Railway
/// credentials. `shell` closes it: not a harness at all, just the VM's login
/// shell, so it takes no prompt and sits after every real agent.
pub const HARNESSES: &[&str] = &[
    "railway",
    "grok",
    "codex",
    "claude",
    "opencode",
    "opencode2",
    "shell",
];

/// A single OpenCode row can switch editions without adding a second picker row.
pub fn opencode_alternate(index: usize) -> Option<usize> {
    let slug = match *HARNESSES.get(index)? {
        "opencode" => "opencode2",
        "opencode2" => "opencode",
        _ => return None,
    };
    HARNESSES.iter().position(|candidate| *candidate == slug)
}

pub fn harness_picker_indices(cursor: usize) -> Vec<usize> {
    let hidden = if HARNESSES.get(cursor) == Some(&"opencode2") {
        "opencode"
    } else {
        "opencode2"
    };
    HARNESSES
        .iter()
        .enumerate()
        .filter_map(|(i, slug)| (*slug != hidden).then_some(i))
        .collect()
}

pub fn harness_label(slug: &str) -> &str {
    match slug {
        "opencode" => "OpenCode",
        "opencode2" => "OpenCode2 [Beta]",
        _ => slug,
    }
}

/// The slice of [`HARNESSES`] that can be saved as the default agent —
/// everything but `shell`, which starts no harness and so makes no sense as
/// a standing default. What the setup wizard and settings offer.
pub fn default_harnesses() -> &'static [&'static str] {
    &HARNESSES[..HARNESSES.len() - 1]
}

/// Everything the Manage screen responds to, grouped for the `?` overlay. The
/// footer shows two or three of these; this is where the rest lives, so the
/// screen is not a permanent wall of key names.
pub const KEY_HELP: &[(&str, &[(&str, &str)])] = &[
    (
        "move",
        &[
            ("↑ ↓", "up and down"),
            ("→ ←", "open and close"),
            ("enter", "open · connect to a session"),
            (
                "click / drag",
                "select · double-click connects · resize divider",
            ),
        ],
    ),
    (
        "sessions",
        &[
            ("enter", "connect and type in it"),
            ("⌥f", "give it the whole screen · again to restore"),
            ("⌥enter / f", "leave the TUI and connect full screen"),
            ("⌥⇧[ ⌥⇧]", "previous / next session"),
            ("⌥esc", "stop typing in it"),
            ("wheel", "scroll its output"),
            ("click a link", "open it in your browser"),
            ("shift+pgup/pgdn", "scroll without the mouse"),
            ("x / X", "delete conversation / end shell"),
            ("r", "reconnect a pane whose connection dropped"),
        ],
    ),
    (
        "agents",
        &[
            ("⌥o", "open an SSH shell outside the TUI"),
            ("c", "copy an SSH shell command"),
            ("⌥b / b", "project bootstraps · save selected VM"),
            ("n", "new agent — pick its harness first"),
            ("⌥n", "new session on this VM · choose its agent"),
            (
                "⌥p",
                "new session from a prompt, on the selected row's agent",
            ),
            ("s / w", "sleep / wake"),
            ("d", "delete, with a confirmation"),
            ("⌥r", "refresh everything, from anywhere"),
            ("r", "refresh this environment"),
            ("shift+r", "look for agents in every project"),
        ],
    ),
    (
        "elsewhere",
        &[
            ("⌥t / t", "change project / use highlighted target"),
            ("esc", "step back — clear the draft, then home"),
            ("q", "quit, from home"),
            ("^c", "quit"),
        ],
    ),
];

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Agent {
    pub id: String,
    pub name: String,
    /// Already lowercased for display: `running`, `sleeping`, `starting`…
    pub status: String,
    /// Shell and exec sessions running on the agent's VM, which the platform
    /// tracks and which can be reattached to by name. Loaded when the agent row
    /// is expanded.
    pub sessions: LoadSessions,
    pub expanded: bool,
}

/// One reattachable session on an agent's VM.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ConsoleSession {
    /// The durable name the relay reattaches by.
    pub name: String,
    /// `SHELL` for an interactive session, `EXEC` for a one-shot command.
    pub kind: String,
    pub command: Option<String>,
    pub running: bool,
    pub attached: bool,
    /// When the platform says it began — what breaks ties when a pane has to
    /// be matched to a listed session (see [`App::adopt_pane_sessions`]).
    pub created_at: Option<chrono::DateTime<chrono::Utc>>,
    /// What the harness inside this session last reported it was doing —
    /// joined to the session by its durable name at fetch time. `None` when
    /// the harness never reported (a plain shell, or a report that predates
    /// name attribution).
    pub snapshot: Option<ThreadSnapshot>,
}

/// The reported state of one coding-agent run, from `CloudAgent.sessions` —
/// the same snapshot the dashboard's session cards render. Display-only.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ThreadSnapshot {
    /// Which harness reported: claude, codex, grok, railway-agent…
    pub harness: String,
    /// The harness's own session id — for `railway-agent`, the conversation
    /// the in-VM daemon addresses over the gate WebSocket.
    pub session_id: String,
    /// One of: unknown, working, waiting, idle, failed, done.
    pub state: String,
    /// Truncated first prompt of the run.
    pub prompt: Option<String>,
    /// Truncated most recent prompt of the run.
    pub latest_prompt: Option<String>,
    /// What the agent last said: the newest assistant text of the
    /// conversation, read from the daemon's catchup transcript over the
    /// harness gate. Only railway-agent threads have a daemon to ask, so this
    /// is None for every other harness — their responses exist only inside
    /// the VM (the hook pipeline deliberately never carries assistant text).
    pub last_reply: Option<String>,
    /// The VM's clock at the last report — orders snapshots per session.
    pub updated_at: String,
}

/// The env prologue every launch prepends. Everything before it is plumbing —
/// PATH, the GitHub token, the Claude env file — and none of it says what the
/// session is doing.
const LAUNCH_PROLOGUE: &str = "export RAILWAY_CODE_AUTOSTARTED=1; ";

impl ConsoleSession {
    pub(super) fn client_thread(
        agent_id: &str,
        harness: &str,
        thread: Option<&super::super::client_sessions::Thread>,
    ) -> Self {
        Self {
            name: super::super::client_sessions::name(
                harness,
                agent_id,
                thread.map(|t| t.id.as_str()),
            ),
            kind: "THREAD".into(),
            command: Some(harness.into()),
            running: true,
            attached: false,
            created_at: thread.and_then(|t| t.created_at),
            snapshot: thread.map(|thread| ThreadSnapshot {
                harness: harness.into(),
                session_id: thread.id.clone(),
                state: thread.state.clone(),
                prompt: Some(thread.title.clone()),
                latest_prompt: None,
                last_reply: None,
                updated_at: thread.updated_at.clone(),
            }),
        }
    }
    /// Is this worth showing?
    ///
    /// Provider threads remain resumable after the harness exits; transport
    /// rows are reserved for live interactive shells directly on the VM.
    pub fn is_interesting(&self) -> bool {
        self.running && (self.kind == "THREAD" || self.is_shell())
    }

    pub(super) fn is_shell(&self) -> bool {
        if self.kind != "SHELL" || self.snapshot.is_some() || self.harness_slug().is_some() {
            return false;
        }
        let Some(command) = self
            .command
            .as_deref()
            .map(str::trim)
            .filter(|c| !c.is_empty())
        else {
            return true;
        };
        let command = command
            .trim_end_matches(';')
            .rsplit("; ")
            .next()
            .unwrap_or(command)
            .trim_start_matches("exec ");
        let words = shlex::split(command).unwrap_or_default();
        if words
            .iter()
            .skip(1)
            .any(|word| word.starts_with('-') && !word.starts_with("--") && word.contains('c'))
        {
            return false;
        }
        matches!(
            command
                .split_whitespace()
                .next()
                .unwrap_or("")
                .rsplit('/')
                .next(),
            Some("bash" | "sh" | "zsh" | "fish" | "-bash" | "-sh" | "-zsh")
        )
    }

    /// The session's name, folded short and led by its harness:
    /// `merry-daisy-ld9` running railway becomes `railway-ld9` — a petname
    /// says nothing its random suffix doesn't, and a minted `railway-x2k9qm`
    /// already leads with its harness. The plain name when the harness is
    /// unknowable.
    pub fn short_name(&self) -> String {
        if super::super::client_sessions::is_client(&self.name) {
            return self
                .snapshot
                .as_ref()
                .and_then(|s| s.prompt.clone())
                .filter(|title| !title.trim().is_empty())
                .unwrap_or_else(|| super::super::client_sessions::NEW_THREAD.into());
        }
        match self.harness_slug() {
            Some(slug) if !self.name.starts_with(&format!("{slug}-")) => {
                let segments: Vec<&str> = self.name.split('-').collect();
                let short = match segments.as_slice() {
                    [.., suffix] if segments.len() >= 3 => suffix,
                    _ => self.name.as_str(),
                };
                format!("{slug}-{short}")
            }
            _ => self.name.clone(),
        }
    }

    /// The native title names a thread throughout its lifecycle. Only direct
    /// VM shells use a transport name and the `[S]` marker. Keep the full title;
    /// the renderer truncates it to the current sidebar width.
    pub fn thread_label(&self) -> String {
        if super::super::client_sessions::is_client(&self.name) {
            return self
                .short_name()
                .split_whitespace()
                .collect::<Vec<_>>()
                .join(" ");
        }
        if let Some(snapshot) = &self.snapshot {
            fn clean(text: Option<&str>) -> Option<&str> {
                text.map(str::trim).filter(|text| !text.is_empty())
            }
            let prompt = clean(
                snapshot
                    .latest_prompt
                    .as_deref()
                    .or(snapshot.prompt.as_deref()),
            );
            let reply = clean(snapshot.last_reply.as_deref());
            let text = if snapshot.state == "working" {
                prompt.or(reply)
            } else {
                reply.or(prompt)
            };
            if let Some(text) = text {
                return text.split_whitespace().collect::<Vec<_>>().join(" ");
            }
        }
        if self.is_shell() {
            format!("[S] {}", self.short_name())
        } else {
            super::super::client_sessions::NEW_THREAD.into()
        }
    }

    /// The harness this session runs, read off its launch line's binary.
    pub(super) fn harness_slug(&self) -> Option<&'static str> {
        let summary = self.command_summary();
        if summary == self.name {
            return None;
        }
        let binary = summary.split_whitespace().next()?;
        let base = binary.rsplit('/').next().unwrap_or(binary);
        match base {
            "railway-agent-tui" | "railway-agent" => Some("railway"),
            "claude" => Some("claude"),
            "codex" => Some("codex"),
            "opencode" => Some("opencode"),
            "opencode2" => Some("opencode2"),
            "grok" => Some("grok"),
            _ => None,
        }
    }

    /// The command, cleaned up for the detail pane: the harness invocation
    /// lifted out of the launch line's plumbing.
    pub fn command_summary(&self) -> String {
        let Some(command) = self
            .command
            .as_deref()
            .map(str::trim)
            .filter(|c| !c.is_empty())
        else {
            return self.name.clone();
        };
        let meaningful = match command.split_once(LAUNCH_PROLOGUE) {
            Some((_, rest)) => rest.split(';').next().unwrap_or(rest).trim(),
            None => command.lines().next().unwrap_or(command).trim(),
        };
        if meaningful.is_empty() {
            return self.name.clone();
        }
        truncate(meaningful, 160)
    }
}

/// Trim to `max` characters on a character boundary, with an ellipsis.
fn truncate(text: &str, max: usize) -> String {
    if text.chars().count() <= max {
        return text.to_string();
    }
    let kept: String = text.chars().take(max.saturating_sub(1)).collect();
    format!("{}", kept.trim_end())
}

impl LaunchRequest {
    /// Should this open a session of its own?
    ///
    /// A prompt is a new piece of work — submitting a second one must start a
    /// second agent session, not drop you back into the first. Only a plain
    /// "connect to that agent" reuses what is already open.
    pub fn wants_new_session(&self) -> bool {
        self.session_name.is_none() && (self.new_session || self.prompt.is_some() || self.force_new)
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LoadSessions {
    NotLoaded,
    Loading,
    Loaded(Vec<ConsoleSession>),
    Failed(String),
}

/// Per-environment agent list. `Failed` is kept rather than collapsed into an
/// empty list so a network blip reads as a network blip instead of "you have no
/// agents here", which would invite creating a duplicate.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Load {
    NotLoaded,
    Loading,
    Loaded(Vec<Agent>),
    Failed(String),
}

#[derive(Clone, Debug)]
pub struct EnvNode {
    pub id: String,
    pub name: String,
    pub expanded: bool,
    pub agents: Load,
}

#[derive(Clone, Debug)]
pub struct ProjectNode {
    pub id: String,
    pub name: String,
    pub expanded: bool,
    pub envs: Vec<EnvNode>,
}

#[derive(Clone, Debug)]
pub struct WorkspaceNode {
    pub id: String,
    pub name: String,
    pub expanded: bool,
    pub projects: Vec<ProjectNode>,
}

/// Where the prompt lands, and what a bare "Launch" acts on.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Target {
    pub project_id: String,
    pub project_name: String,
    pub environment_id: String,
    pub environment_name: String,
}

impl Target {
    pub fn label(&self) -> String {
        format!("{}/{}", self.project_name, self.environment_name)
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Screen {
    BootstrapPick,
    BootstrapSetup,
    /// First-run setup, over the tree.
    Setup,
    /// The ⌥s settings card, over the tree: every preference setup collects,
    /// changeable after the fact.
    Settings,
    /// Choosing where the prompt lands, over the tree. The same card list the
    /// setup flow asks with — picking a target is the same question, so it
    /// should not send anyone through the whole management tree to answer it.
    TargetPick,
    /// ⌥n on Manage: choosing which agent a new session runs, over the tree.
    HarnessPick,
    /// ⌥p on Manage: composing a prompt for a new session, over the tree —
    /// the launcher's prompt box, without the walk back to the New Session
    /// row.
    ManagePrompt,
    Manage,
}

/// A short confirmation in the bottom corner.
///
/// For the things that happen without a screen of their own — a drag that put
/// text on the clipboard is the case that needs it, because the only other
/// evidence is the clipboard itself, which you cannot see. It fades on its own;
/// nothing has to be dismissed.
/// An agent that has been told to wake or sleep and has not got there yet.
///
/// Waking returns the moment the platform accepts it; the VM then boots on its
/// own time, and the list keeps reporting `sleeping` until it does. Dropping
/// the pending label when the mutation returned made that look like the wake
/// had failed and rolled back — it hadn't, which is why launching onto the
/// agent worked seconds later.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AgentWatch {
    /// The status this is heading for.
    pub want: &'static str,
    pub environment_id: String,
    pub until: std::time::Instant,
}

/// How long to keep asking. A cold VM can take a while to boot, and giving up
/// early puts the wrong state back on the screen — the failure this whole
/// mechanism exists to avoid.
pub const WAKE_PATIENCE: std::time::Duration = std::time::Duration::from_secs(180);
/// Sleeping is a request the platform acts on quickly.
pub const SLEEP_PATIENCE: std::time::Duration = std::time::Duration::from_secs(60);
/// How often to ask again while waiting.
pub const WATCH_TICK: std::time::Duration = std::time::Duration::from_millis(1500);

/// How many background attaches may be in flight at once. Startup wants the
/// whole tree green, but each attach is a relay ssh, a reader thread, and a
/// scrollback replay — a fleet's worth at once is a thundering herd.
const AUTO_CONNECT_INFLIGHT: usize = 3;

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Toast {
    pub text: String,
    pub at: std::time::Instant,
    /// A tick or a cross; a failure that looks like a success is worse than no
    /// toast at all.
    pub ok: bool,
}

/// Long enough to read four words, short enough not to sit on the screen.
pub const TOAST_LIFETIME: std::time::Duration = std::time::Duration::from_millis(1800);

impl Toast {
    /// Errors carry things to read — a failure reason, sometimes a recipe —
    /// and stay up long enough to read them. A confirmation needs a glance.
    fn lifetime(&self) -> std::time::Duration {
        if self.ok {
            TOAST_LIFETIME
        } else {
            TOAST_LIFETIME * 5
        }
    }

    pub fn expired(&self) -> bool {
        self.at.elapsed() >= self.lifetime()
    }

    /// Time until this toast has had its moment.
    pub fn remaining(&self) -> std::time::Duration {
        self.lifetime().saturating_sub(self.at.elapsed())
    }
}

/// The target chooser: the setup flow's project card, on its own.
pub struct TargetPicker {
    pub options: Vec<Target>,
    pub cursor: usize,
}

impl TargetPicker {
    /// Every environment in the tree, the default project's first — one row per
    /// place an agent can actually live, since that is what is being chosen.
    pub fn new(
        tree: &[WorkspaceNode],
        default_project: Option<&str>,
        current: Option<&Target>,
    ) -> Self {
        let mut options: Vec<Target> = Vec::new();
        for ws in tree {
            for p in sorted_projects(ws, default_project) {
                let project = &ws.projects[p];
                for env in &project.envs {
                    options.push(Target {
                        project_id: project.id.clone(),
                        project_name: project.name.clone(),
                        environment_id: env.id.clone(),
                        environment_name: env.name.clone(),
                    });
                }
            }
        }
        // Open on the current target, so Enter twice is a no-op rather than a
        // surprise change.
        let cursor = current
            .and_then(|t| {
                options
                    .iter()
                    .position(|o| o.environment_id == t.environment_id)
            })
            .unwrap_or(0);
        Self { options, cursor }
    }

    /// The rows to draw: (label, note).
    pub fn rows(&self, default_project: Option<&str>) -> Vec<(String, String)> {
        self.options
            .iter()
            .map(|t| {
                let note = if Some(t.project_id.as_str()) == default_project {
                    "default".to_string()
                } else {
                    String::new()
                };
                (format!("{} ({})", t.project_name, t.environment_name), note)
            })
            .collect()
    }
}

/// A rectangle recorded by the renderer so mouse events can be mapped back to
/// the pane that drew it. Plain numbers rather than a ratatui `Rect` so the app
/// stays free of the drawing layer.
#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)]
pub struct PaneBox {
    pub x: u16,
    pub y: u16,
    pub w: u16,
    pub h: u16,
}

impl PaneBox {
    pub fn contains(&self, col: u16, row: u16) -> bool {
        self.w > 0
            && self.h > 0
            && col >= self.x
            && row >= self.y
            && col < self.x + self.w
            && row < self.y + self.h
    }
}

/// Where each pane last drew itself. Recorded every frame; read by the mouse.
///
/// Two rectangles per pane: the whole block, which is what a click has to hit
/// (nobody aims for the inside of a border), and the interior, which is what a
/// selection may cover.
#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)]
pub struct PaneRects {
    pub sidebar_divider: PaneBox,
    pub tree: PaneBox,
    pub session: PaneBox,
    pub tree_outer: PaneBox,
    pub session_outer: PaneBox,
    /// The new-session prompt box, borders included.
    pub prompt: PaneBox,
    pub bootstrap: PaneBox,
    pub bootstrap_card: PaneBox,
    pub bootstrap_fields: [PaneBox; 5],
    pub bootstrap_list: PaneBox,
    pub bootstrap_list_offset: usize,
    pub harness_list: PaneBox,
    pub harness_bootstrap: PaneBox,
    pub harness_use_bootstrap: PaneBox,
    /// The header's session tabs, drawn only while the pane is maximized. A
    /// fixed array so this stays `Copy`; sessions past the cap keep their
    /// ⌥⇧[ ⌥⇧] keys but aren't clickable.
    pub tabs: [PaneBox; MAX_TABS],
}

/// How many maximized-header tabs get a clickable box.
pub const MAX_TABS: usize = 8;

#[derive(Clone, Copy)]
struct SidebarDrag {
    start_column: u16,
    start_row: u16,
    start_width: u16,
    original: Option<u16>,
    moved: bool,
}

/// A drag in progress, confined to one pane. Copying out of the session must
/// not pick up tree rows sitting at the same screen rows.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Selection {
    pub pane: ManageFocus,
    pub anchor: (u16, u16),
    pub cursor: (u16, u16),
}

impl Selection {
    /// Start and end in reading order, so dragging up or backwards selects the
    /// same text as dragging down or forwards.
    fn ordered(&self) -> ((u16, u16), (u16, u16)) {
        let (ax, ay) = self.anchor;
        let (cx, cy) = self.cursor;
        if (ay, ax) <= (cy, cx) {
            ((ax, ay), (cx, cy))
        } else {
            ((cx, cy), (ax, ay))
        }
    }

    /// The selected cells, as one inclusive column range per row.
    ///
    /// Line-wise, the way a terminal selects: from the anchor to the end of its
    /// line, whole lines through the middle, and the start of the last line up
    /// to the cursor. A rectangle would be right for a column of numbers and
    /// wrong for everything else — selecting three lines of agent output would
    /// clip every one of them to the same columns.
    pub fn spans(&self, bounds: PaneBox) -> Vec<(u16, u16, u16)> {
        if bounds.w == 0 || bounds.h == 0 {
            return Vec::new();
        }
        let left = bounds.x;
        let right = bounds.x + bounds.w - 1;
        let ((sx, sy), (ex, ey)) = self.ordered();
        let (sy, ey) = (sy.max(bounds.y), ey.min(bounds.y + bounds.h - 1));
        if sy > ey {
            return Vec::new();
        }
        (sy..=ey)
            .map(|y| {
                let x0 = if y == sy { sx.max(left) } else { left };
                let x1 = if y == ey { ex.min(right) } else { right };
                (y, x0, x1)
            })
            .filter(|(_, x0, x1)| x0 <= x1)
            .collect()
    }

    pub fn is_empty(&self) -> bool {
        self.anchor == self.cursor
    }
}

/// What the keyboard is driving on the Manage screen.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ManageFocus {
    Tree,
    /// The session pane — keystrokes go to the agent.
    Session,
}

/// A row in the flattened tree. Indices point back into [`App::tree`].
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum RowKind {
    /// The pinned first row: standing on it puts the keyboard in the prompt
    /// and the session pane shows the launcher — the way a new session
    /// starts, without a separate screen to come from.
    NewSession,
    Workspace(usize),
    Project(usize, usize),
    Environment(usize, usize, usize),
    Agent(usize, usize, usize, usize),
    /// A reattachable session on an agent's VM.
    Session(usize, usize, usize, usize, usize),
    /// A non-selectable line under an environment: loading, empty, or failed.
    Note(usize, usize, usize),
    /// The collapsible tail of projects with no agents — where `n` goes to
    /// start somewhere new.
    OtherProjects,
    /// A non-selectable line that belongs to no environment: the empty state.
    Hint,
    /// A rule between the agent groups and the projects tail.
    Separator,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Row {
    pub depth: usize,
    pub kind: RowKind,
    pub label: String,
    /// Right-hand annotation: agent count, status, workspace marker.
    pub note: String,
    /// `Some` for agents, driving the status glyph and its colour.
    pub status: Option<String>,
    pub expanded: Option<bool>,
    /// Drawn de-emphasised: there is nothing here yet.
    pub dimmed: bool,
}

impl Row {
    pub fn selectable(&self) -> bool {
        !matches!(
            self.kind,
            RowKind::Note(..) | RowKind::Hint | RowKind::Separator
        )
    }
}

/// A lifecycle action on one agent.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum AgentOp {
    Sleep,
    Wake,
    Delete,
}

impl AgentOp {
    /// The optimistic label shown against the row while it runs. Present tense
    /// on purpose: the row is claiming what is happening, not what happened.
    pub fn pending_label(self) -> &'static str {
        match self {
            AgentOp::Sleep => "sleeping…",
            AgentOp::Wake => "waking…",
            AgentOp::Delete => "deleting…",
        }
    }
}

/// An action held back for a `y`/`n`. Only the ones that lose work need it.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct PendingConfirm {
    pub op: AgentOp,
    pub agent_id: String,
    pub agent_name: String,
    pub environment_id: String,
}

impl PendingConfirm {
    pub fn question(&self) -> String {
        match self.op {
            AgentOp::Delete => format!(
                "Delete {} and its disk? This cannot be undone.  y / n",
                self.agent_name
            ),
            AgentOp::Sleep => format!("Sleep {}?  y / n", self.agent_name),
            AgentOp::Wake => format!("Wake {}?  y / n", self.agent_name),
        }
    }
}

/// What the startup check learned about the user's SSH key. Connecting to an
/// agent rides SSH and the relay only answers registered keys, so a connect
/// while unregistered is held behind [`SshGate`] rather than sent to fail —
/// or worse, to the relay's interactive signup screen.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum SshKeyState {
    /// The check hasn't answered, or couldn't. Connects proceed; the launch
    /// pipeline re-checks and produces the error if there is one.
    #[default]
    Unknown,
    /// A local key is registered with Railway.
    Ready,
    /// A local key exists but Railway doesn't know it yet.
    NeedsRegistration(SshKeyOffer),
    /// Nothing in the SSH agent or ~/.ssh to register.
    NoLocalKeys,
}

/// The local key the gate offers to register.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SshKeyOffer {
    pub name: String,
    pub fingerprint: String,
    pub public_key: String,
}

/// A connect held back until the SSH key question is answered.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum HeldConnect {
    Bootstrap(super::bootstrap_setup::Request),
    Launch(LaunchRequest),
    OpenShell {
        agent_id: String,
        agent_name: String,
    },
    Reattach {
        agent_id: String,
        agent_name: String,
        environment_id: String,
        session_name: String,
    },
}

impl HeldConnect {
    /// Back into the effect it was before the gate held it.
    pub fn into_effect(self) -> Effect {
        match self {
            HeldConnect::Launch(req) => Effect::Launch(req),
            HeldConnect::Bootstrap(req) => Effect::CreateBootstrap(req),
            HeldConnect::OpenShell {
                agent_id,
                agent_name,
            } => Effect::OpenShell {
                agent_id,
                agent_name,
            },
            HeldConnect::Reattach {
                agent_id,
                agent_name,
                environment_id,
                session_name,
            } => Effect::Reattach {
                agent_id,
                agent_name,
                environment_id,
                session_name,
            },
        }
    }
}

/// The register-your-key question, floated over whatever raised it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SshGate {
    pub offer: SshKeyOffer,
    /// Resumed after a successful registration. `None` when the gate came
    /// from setup rather than a connect: declining just ends the question.
    pub then: Option<HeldConnect>,
}

/// What the loading screen is showing.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Loading {
    /// A launch is in flight; the session pane shows its progress. Kept as a
    /// pane state rather than a screen so the tree stays visible and usable
    /// while an agent boots.
    pub active: bool,
    /// Where this is going, e.g. `devtools/production`.
    pub target: String,
    pub harness: String,
    /// The task typed into the prompt, echoed back so the wait has context.
    pub prompt: Option<String>,
    /// Steps reported by the launch pipeline, oldest first.
    pub steps: Vec<String>,
    /// Advanced by the loop's tick; drives the spinner so a slow step still
    /// looks alive.
    pub tick: usize,
}

/// The mouse gestures the TUI reacts to.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum MouseAction {
    Down,
    Drag,
    Up,
    ScrollUp,
    ScrollDown,
}

/// What the event loop must do after a key. At most one per keystroke.
#[derive(Clone, Debug, PartialEq)]
pub enum Effect {
    SaveSidebarWidth(u16),
    CreateBootstrap(super::bootstrap_setup::Request),
    LoadBootstraps {
        environment_id: String,
    },
    SelectBootstrap {
        environment_id: String,
        id: Option<String>,
    },
    /// Fetch this environment's agents; the result comes back via
    /// [`App::agents_loaded`].
    LoadAgents {
        environment_id: String,
        path: (usize, usize, usize),
    },
    /// Fetch the reattachable sessions on one agent, along with the harness
    /// snapshots that label them (which need the environment id).
    LoadSessions {
        agent_id: String,
        environment_id: String,
        path: (usize, usize, usize, usize),
    },
    Launch(LaunchRequest),
    /// Close one session (by index) and sleep its agent.
    CloseSession {
        index: usize,
    },
    /// End a session on the agent. Its pane, if we have one, goes with it.
    KillSession {
        agent_id: String,
        environment_id: String,
        session_name: String,
    },
    DeleteThread {
        agent_id: String,
        environment_id: String,
        session_name: String,
    },
    /// Reconnect to an existing session on a running agent — no provisioning,
    /// no credential work, just ssh with the session's name.
    Reattach {
        agent_id: String,
        agent_name: String,
        environment_id: String,
        session_name: String,
    },
    /// Create the default project the wizard asked for, in this workspace.
    CreateDefaultProject(String),
    /// Persist what first-run setup collected.
    SaveSetup(Box<super::wizard::Outcome>),
    /// Persist a change made on the settings card. The same snapshot shape as
    /// setup, but merged over the file on disk rather than replacing it.
    SaveSettings(Box<super::wizard::Outcome>),
    /// Remember the default project chosen from the target card.
    SaveDefaultProject(Box<Target>),
    /// Open a link that was double-clicked in a session.
    OpenUrl(String),
    /// Look for agents in every project, on request. See
    /// [`App::scan_environments`].
    ScanEverywhere,
    /// Ask the platform for everything again: one account-wide agent query,
    /// plus the sessions of the agents someone is actually looking at. Raised
    /// by ⌥r, by the auto-refresh tick, and on re-entry after the TUI has
    /// handed the terminal back. See [`super::start_refresh`].
    RefreshAll,
    /// Put an SSH shell command for this VM on the clipboard.
    CopySsh {
        agent_id: String,
        environment_id: String,
    },
    /// Leave the TUI for a new shell on an existing VM, keeping its panes.
    OpenShell {
        agent_id: String,
        agent_name: String,
    },
    /// Leave the TUI and give the whole terminal to one session.
    FullScreen {
        agent_id: String,
        session_name: String,
        agent_name: String,
    },
    /// Run a lifecycle action, then refresh the environment it lives in.
    Agent {
        op: AgentOp,
        agent_id: String,
        environment_id: String,
    },
    /// Register the gate's key with Railway, then resume the held connect.
    RegisterSshKey {
        offer: SshKeyOffer,
        then: Option<HeldConnect>,
    },
    /// Leave the TUI for the Claude mint's manual-paste fallback; the caller
    /// re-enters with the same request. Raised only after the hidden mint
    /// already ran and failed under the frame.
    StepOutForMint(LaunchRequest),
    Quit,
}

/// One session the background auto-connect should attach — everything a
/// reattach needs, lifted out of the tree so the loop can spawn the ssh work
/// without holding a borrow on it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AutoConnect {
    pub agent_id: String,
    pub agent_name: String,
    pub environment_id: String,
    pub session_name: String,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LaunchRequest {
    pub project_id: String,
    pub environment_id: String,
    /// `Some` connects to this specific agent; `None` reuses or creates one.
    pub agent_id: Option<String>,
    /// Reattach to this durable session instead of starting the harness.
    pub session_name: Option<String>,
    /// Always create a fresh agent, even when one exists.
    pub force_new: bool,
    /// Open another session on the agent this request names, rather than
    /// reusing the one already open.
    pub new_session: bool,
    pub harness: String,
    pub prompt: Option<String>,
    /// Human-facing description of where this is going, for the handoff line.
    pub label: String,
    /// The command-line flags this launch started from, when a command line
    /// started it. The fields above overwrite the target, harness, agent and
    /// prompt; everything else — `--name`, `--variable`, `--env-file`,
    /// `--refresh-auth` — rides along from here, because nothing in the TUI
    /// asks for those and dropping them would quietly ignore what was typed.
    /// Default for launches the TUI starts itself.
    ///
    /// Boxed because a `LaunchRequest` is the largest thing several enums
    /// carry — `Effect`, `HeldConnect`, `Outcome`, `Message` — and inlining
    /// another 200 bytes of flags widens every one of them for a field only
    /// the command line ever fills.
    pub base: Box<crate::commands::code::LaunchArgs>,
}

struct DeletedThread {
    environment: String,
    agent_id: String,
    order: Vec<String>,
    row: ConsoleSession,
}

pub struct App {
    pub(super) activity: super::activity::Activity,
    pub(super) thread_cache: Option<super::cache::Cache>,
    /// Discovery is a startup/user gesture, never a consequence of cache age.
    discovered: std::collections::HashSet<String>,
    /// The project new agents go to: the linked directory's project, or the
    /// preferences file when this directory has no link. Sorted to the top of
    /// the tree and separated from the rest.
    pub default_project: Option<String>,
    /// Whether preferences exist yet. Decides whether first run offers the
    /// setup wizard or leaves changing things to the ⌥s settings card.
    pub configured: bool,
    /// Environments this machine has launched an agent in, from the CLI's own
    /// records. Loaded eagerly, because an agent you made is one you expect to
    /// find without hunting for it.
    pub known_environments: Vec<String>,
    /// The target chooser, while it is open.
    pub target_pick: Option<TargetPicker>,
    pub bootstrap_form: Option<super::bootstrap_setup::Form>,
    pub bootstrap_picker: Option<super::bootstrap_setup::Picker>,
    pub bootstrap_defaults:
        std::collections::BTreeMap<String, super::bootstrap_setup::DefaultState>,
    /// The VM selected for an Option+n session; None creates a fresh VM.
    pub harness_pick_agent: Option<String>,
    pub harness_pick_connect: bool,
    /// VM-specific discovery, never the user's default coding agent.
    pub primary_harnesses: HashMap<String, String>,
    pending_agent_connect: Option<String>,
    /// ⌥n's picker cursor while [`Screen::HarnessPick`] is up.
    pub harness_pick: Option<usize>,
    pub harness_pick_target: Option<Target>,
    pub harness_bootstrap: super::bootstrap_setup::LaunchChoice,
    pub harness_use_bootstrap: bool,
    /// ⌥p's draft while [`Screen::ManagePrompt`] is up.
    pub manage_prompt: Option<String>,
    /// The session pane has the whole screen: no tree, no detail column.
    pub maximized: bool,
    /// A launch to start as soon as the first frame is up, and then forget.
    ///
    /// How `railway code` opens: it has already answered where and which
    /// harness, so there is nothing to browse for — the TUI is here to hold
    /// the session, not to ask a question. Taken by the loop and fed through
    /// the same path a keypress would, so the ssh-key gate and the Claude
    /// mint still get their say.
    pub autostart: Option<LaunchRequest>,
    pub(crate) autostart_client: Option<super::ClientPane>,
    /// Like `autostart`, but the pipeline is already running — started beside
    /// the tree load because its gates were verified up front. The loop adopts
    /// it on frame one instead of dispatching.
    pub autostart_inflight: Option<super::InflightLaunch>,
    /// Leave the TUI when the last session pane closes on its own.
    ///
    /// `railway code` came for one session; when the harness exits (ctrl-c
    /// included), the person is done, and the right place to land is their
    /// local prompt — not a browser they never opened. Bare `railway ca`
    /// keeps its tree instead.
    pub quit_when_done: bool,
    /// One line for the caller to print after the terminal is restored — how
    /// a quit that closed a session says the agent is still running (and
    /// billing) now that the frame it would have said it in is gone.
    pub exit_note: Option<String>,
    /// This gesture belongs to the application in the session, not to us.
    pointer_to_app: bool,
    /// A short confirmation in the corner, and when it was raised.
    pub toast: Option<Toast>,
    pub theme: &'static Theme,
    pub screen: Screen,
    /// Open sessions, in the order they were opened. Several can run at once;
    /// the pane renders whichever is active and the rest keep working.
    pub sessions: Vec<super::session::Session>,
    /// Index into `sessions` of the one being rendered.
    pub active: Option<usize>,
    pub focus: ManageFocus,
    /// The task being prepared, and the steps reported so far.
    pub loading: Loading,
    /// After a launch, select this agent once its environment has loaded.
    pub pending_select: Option<String>,
    /// After the next load, expand this agent.
    pub pending_expand: Option<String>,
    /// After sessions load, put the cursor on this durable name.
    pub pending_select_session: Option<String>,
    /// Where the panes were drawn last frame, for hit-testing the mouse.
    pub panes: PaneRects,
    /// Sessions we have asked to end. Hidden from the tree the moment the kill
    /// is sent: the agent takes a second or two to reap the processes, and a
    /// row that reads "running" in the meantime looks like the key did nothing.
    /// A name leaves this set when a refresh no longer lists it.
    pub ending: std::collections::HashSet<String>,
    // Keep tombstones after acknowledgements to reject late inventories/events.
    pub(super) deleted_threads: std::collections::HashSet<String>,
    deleting_threads: HashMap<String, DeletedThread>,
    pub(super) deletion_tx: tokio::sync::mpsc::UnboundedSender<(String, Option<String>)>,
    pub(super) deletion_rx: tokio::sync::mpsc::UnboundedReceiver<(String, Option<String>)>,
    /// Session names whose attach is in flight — the row wears a spinner
    /// instead of the branch marker until the pane opens or the attempt fails.
    pub connecting: std::collections::HashSet<String>,
    /// Session names auto-connect has already tried this run. One attempt
    /// each: a failed relay path must not be retried in a loop, and a pane
    /// closed with `x` must stay closed rather than reopening on the next
    /// sweep. A name lands here when its attempt starts and whenever a pane
    /// attaches by any path.
    auto_attempted: std::collections::HashSet<String>,
    /// Session names whose dropped connection has already pulled the keyboard
    /// to its pane — once per drop, so Esc-ing away sticks. Cleared when the
    /// name reattaches, so a second drop announces itself the same way.
    drop_seen: std::collections::HashSet<String>,
    /// First-run setup, when there are no preferences yet.
    pub wizard: Option<super::wizard::Wizard>,
    /// The ⌥s settings card, while it is open.
    pub settings: Option<super::settings::Settings>,
    /// Which local directory skills would come from, if any.
    pub skills_source: Option<String>,
    /// Whether the skills preference is on, mirrored from the file so the
    /// settings card opens showing the truth.
    pub skills_enabled: bool,
    /// Hide the maximized layout's header tabs (⌥s settings): ⌥⇧[ ⌥⇧] stay
    /// the way between sessions, and the header keeps its status line.
    pub hide_tabs: bool,
    pub sidebar_width: Option<u16>,
    sidebar_drag: Option<SidebarDrag>,
    /// The key overlay is open.
    pub keys_open: bool,
    /// A drag in progress or a completed selection.
    pub selection: Option<Selection>,
    /// Where and when the last click landed, for spotting a double click.
    last_click: Option<((u16, u16), std::time::Instant)>,
    /// A selection whose text should be lifted out of the next frame. The
    /// rendered buffer is the only place the session pane's text exists in
    /// screen coordinates, and it can only be read from inside a draw.
    pub pending_copy: Option<Selection>,
    /// An action waiting on a `y`/`n`.
    pub confirm: Option<PendingConfirm>,
    /// What the startup check learned about the user's SSH key.
    pub ssh_key: SshKeyState,
    /// A register-your-key question holding a connect, when one is up.
    pub ssh_gate: Option<SshGate>,
    /// Agent id → what is happening to it right now. Shown immediately so a
    /// slow mutation looks like an action rather than a frozen key.
    pub ops: std::collections::HashMap<String, &'static str>,
    /// Agents whose state is still on its way. See [`AgentWatch`].
    pub watching: std::collections::HashMap<String, AgentWatch>,
    /// Round-robin cursor so a slow operation cannot monopolize watch polling.
    last_watched_environment: Option<String>,
    /// A refresh is in flight. Coalescing: a held ⌥r, or several actions
    /// finishing at once, must not stack account-wide queries.
    pub refreshing: bool,
    /// Refreshing is paused until this passes, because the API said so. A 429
    /// answered by polling harder is how a rate limit becomes a longer rate
    /// limit.
    pub refresh_paused_until: Option<std::time::Instant>,
    /// Agents whose fast thread poll is still in flight, so a slow reply (the
    /// gate transcript dials can take seconds) is never stacked under a
    /// second ask for the same agent.
    pub thread_polls: std::collections::HashSet<String>,
    /// Someone pressed a key for the refresh in flight, so its result is worth
    /// a line when it lands. See [`App::refreshed`].
    pub refresh_announce: bool,
    /// Environment id → minimum request-start time of an acceptable snapshot.
    /// Advanced by applied snapshots and successful mutations. This orders local
    /// requests, not FactoryVM generations or the backend's projection freshness.
    pub agent_snapshot_floor: std::collections::HashMap<String, std::time::Instant>,
    /// `myCloudAgents` is not available to this caller, so a refresh has to ask
    /// per environment. True for a workspace-scoped `RAILWAY_TOKEN` — the field
    /// requires an authenticated user — and for a backboard old enough not to
    /// have the field at all. Learned from the first failure, so the fallback
    /// costs one wasted request per run rather than being guessed at.
    pub account_query_unavailable: bool,
    /// Whether the New Session row's prompt has the keyboard. True whenever
    /// the cursor arrives on the row; Esc there sets it false — the "home"
    /// state, where letters are keys again and `q` quits.
    pub prompt_focused: bool,
    pub prompt: String,
    /// Where the next character lands in `prompt`, as a char offset — ←/→
    /// move it, so a typo mid-sentence is fixable in place.
    pub prompt_cursor: usize,
    pub harness: usize,
    pub target: Option<Target>,
    pub tree: Vec<WorkspaceNode>,
    pub cursor: usize,
    /// Whether the projects tail is open. `None` decides automatically: open
    /// while there are no agents to show — the tail is the whole tree then —
    /// and folded away once agent groups exist to lead with.
    pub others_expanded: Option<bool>,
    /// Transient one-line message shown in the header.
    pub status: String,
}

impl App {
    pub(super) fn restore_cached_threads(&mut self) {
        let Some(cache) = &self.thread_cache else {
            return;
        };
        for ws in &mut self.tree {
            for project in &mut ws.projects {
                for env in &mut project.envs {
                    let Load::Loaded(agents) = &mut env.agents else {
                        continue;
                    };
                    for agent in agents {
                        if agent.sessions == LoadSessions::NotLoaded
                            && let Some(mut rows) = cache.read(&env.id, &agent.id)
                        {
                            rows.retain(|row| !self.deleted_threads.contains(&row.name));
                            agent.sessions = LoadSessions::Loaded(rows);
                        }
                    }
                }
            }
        }
        self.adopt_pane_sessions();
    }

    pub(super) fn persist_threads(&self, agent_id: &str) {
        let Some(cache) = &self.thread_cache else {
            return;
        };
        for ws in &self.tree {
            for project in &ws.projects {
                for env in &project.envs {
                    if let Some(agent) = env.agents_vec().iter().find(|a| a.id == agent_id)
                        && let LoadSessions::Loaded(rows) = &agent.sessions
                    {
                        let _ = cache.save(&env.id, agent_id, rows);
                        return;
                    }
                }
            }
        }
    }

    pub fn new(
        tree: Vec<WorkspaceNode>,
        target: Option<Target>,
        harness: Option<&str>,
        theme: Option<&str>,
        default_project: Option<String>,
        configured: bool,
    ) -> Self {
        let (deletion_tx, deletion_rx) = tokio::sync::mpsc::unbounded_channel();
        let harness = harness
            .and_then(|h| HARNESSES.iter().position(|x| *x == h))
            .unwrap_or(0);
        let mut app = Self {
            default_project,
            configured,
            known_environments: Vec::new(),
            target_pick: None,
            bootstrap_form: None,
            bootstrap_picker: None,
            bootstrap_defaults: Default::default(),
            harness_pick: None,
            harness_pick_target: None,
            harness_bootstrap: Default::default(),
            harness_use_bootstrap: true,
            harness_pick_agent: None,
            harness_pick_connect: false,
            primary_harnesses: HashMap::new(),
            pending_agent_connect: None,
            manage_prompt: None,
            maximized: false,
            autostart: None,
            autostart_client: None,
            autostart_inflight: None,
            quit_when_done: false,
            exit_note: None,
            pointer_to_app: false,
            toast: None,
            theme: Theme::from_slug(theme),
            screen: Screen::Manage,
            sessions: Vec::new(),
            active: None,
            focus: ManageFocus::Tree,
            loading: Loading::default(),
            pending_select: None,
            pending_expand: None,
            pending_select_session: None,
            panes: PaneRects::default(),
            ending: std::collections::HashSet::new(),
            deleted_threads: Default::default(),
            deleting_threads: Default::default(),
            deletion_tx,
            deletion_rx,
            connecting: std::collections::HashSet::new(),
            auto_attempted: std::collections::HashSet::new(),
            drop_seen: std::collections::HashSet::new(),
            wizard: None,
            settings: None,
            skills_source: None,
            skills_enabled: false,
            hide_tabs: false,
            sidebar_width: None,
            sidebar_drag: None,
            keys_open: false,
            selection: None,
            last_click: None,
            pending_copy: None,
            confirm: None,
            ssh_key: SshKeyState::default(),
            ssh_gate: None,
            ops: std::collections::HashMap::new(),
            watching: std::collections::HashMap::new(),
            last_watched_environment: None,
            refreshing: false,
            thread_cache: None,
            activity: Default::default(),
            discovered: Default::default(),
            refresh_paused_until: None,
            thread_polls: std::collections::HashSet::new(),
            refresh_announce: false,
            agent_snapshot_floor: std::collections::HashMap::new(),
            account_query_unavailable: false,
            prompt_focused: true,
            prompt: String::new(),
            prompt_cursor: 0,
            harness,
            target,
            tree,
            cursor: 0,
            others_expanded: None,
            status: String::new(),
        };
        // Open the first workspace so the projects tail is never a wall of
        // collapsed rows on a multi-workspace account.
        if let Some(ws) = app.tree.first_mut() {
            ws.expanded = true;
        }
        app.clamp_cursor();
        // The tree can lead with an unselectable hint; the cursor belongs on
        // the first row a key can act on.
        if app.selected_row().is_some_and(|row| !row.selectable()) {
            app.move_cursor_inner(1);
        }
        app
    }

    /// Adopt a harness slug, ignoring one we don't know — the preferences file
    /// is user-editable and a typo there should not change the selection.
    pub fn set_harness(&mut self, slug: Option<&str>) {
        if let Some(i) = slug.and_then(|s| HARNESSES.iter().position(|x| *x == s)) {
            self.harness = i;
        }
    }

    /// A project action uses that row's environment, never an unrelated prompt target.
    pub fn bootstrap_target(&self) -> Option<Target> {
        let kind = self.selected_row()?.kind;
        if let RowKind::Project(w, p) = kind {
            let project = self.tree.get(w)?.projects.get(p)?;
            let e = self
                .target
                .as_ref()
                .filter(|t| t.project_id == project.id)
                .and_then(|t| project.envs.iter().position(|e| e.id == t.environment_id))
                .or_else(|| project.envs.iter().position(|e| e.name == "production"))
                .or_else(|| (!project.envs.is_empty()).then_some(0))?;
            return self.target_at((w, p, e));
        }
        if let Some(path) = self.env_of(kind) {
            return self.target_at(path);
        }
        if kind == RowKind::NewSession {
            return self.target.clone();
        }
        None
    }

    pub fn start_bootstrap_setup(&mut self) {
        if self.loading.active {
            return;
        }
        if let Some(target) = self.bootstrap_target() {
            let mut form = super::bootstrap_setup::Form::new(target, self.harness);
            form.return_to_prompt = self.launcher_selected();
            self.bootstrap_form = Some(form);
            self.screen = Screen::BootstrapSetup;
        }
    }

    pub fn start_bootstrap_picker(&mut self) -> Option<Effect> {
        if self.loading.active {
            return None;
        }
        let target = self.bootstrap_target()?;
        let env = target.environment_id.clone();
        self.bootstrap_picker = Some(super::bootstrap_setup::Picker::new(
            target,
            self.launcher_selected(),
        ));
        self.screen = Screen::BootstrapPick;
        Some(Effect::LoadBootstraps {
            environment_id: env,
        })
    }

    fn save_vm_bootstrap(&mut self, w: usize, p: usize, e: usize, a: usize) -> Option<Effect> {
        let env = &self.tree[w].projects[p].envs[e];
        let agent = env.agents_vec().get(a)?;
        if agent.status != "running" {
            self.status = "Wake the VM before saving a bootstrap".into();
            return None;
        }
        let mut form = super::bootstrap_setup::Form::new(self.target_at((w, p, e))?, self.harness);
        form.snapshot = Some(super::bootstrap_setup::Snapshot {
            agent_id: agent.id.clone(),
            agent_name: agent.name.clone(),
        });
        form.return_to_prompt = false;
        form.defaults_loading = true;
        let environment_id = env.id.clone();
        self.bootstrap_form = Some(form);
        self.screen = Screen::BootstrapSetup;
        Some(Effect::LoadBootstraps { environment_id })
    }

    fn open_bootstraps(&mut self) -> Option<Effect> {
        if self.loading.active {
            return None;
        }
        if self.focus == ManageFocus::Session
            && self.screen == Screen::Manage
            && self.active.is_some()
        {
            let id = self.active_session()?.agent_id.clone();
            let path = self.tree.iter().enumerate().find_map(|(w, ws)| {
                ws.projects.iter().enumerate().find_map(|(p, project)| {
                    project.envs.iter().enumerate().find_map(|(e, env)| {
                        env.agents_vec()
                            .iter()
                            .position(|agent| agent.id == id)
                            .map(|a| (w, p, e, a))
                    })
                })
            });
            if let Some((w, p, e, a)) = path {
                return self.save_vm_bootstrap(w, p, e, a);
            }
            self.toast_error("The VM's project is unavailable. Refresh the tree and try again.");
            return None;
        }
        if let Some(RowKind::Agent(w, p, e, a) | RowKind::Session(w, p, e, a, _)) =
            self.selected_row().map(|row| row.kind)
        {
            return self.save_vm_bootstrap(w, p, e, a);
        }
        if self.launcher_selected()
            && self.target.as_ref().is_some_and(|t| {
                matches!(
                    self.bootstrap_defaults.get(&t.environment_id),
                    Some(super::bootstrap_setup::DefaultState::Missing)
                )
            })
        {
            self.start_bootstrap_setup();
            None
        } else {
            self.start_bootstrap_picker()
        }
    }

    fn choose_bootstrap(&mut self) -> Option<Effect> {
        use super::bootstrap_setup::LaunchChoice;
        let picker = self.bootstrap_picker.as_mut()?;
        if picker.loading || picker.saving {
            return None;
        }
        let none = picker.cursor == picker.no_default_index();
        if picker.for_launch {
            self.harness_bootstrap = if picker.cursor == 0 {
                LaunchChoice::Default
            } else if none {
                LaunchChoice::None
            } else {
                let b = picker.entry_at(picker.cursor)?;
                if let Err(error) = b.require_ready() {
                    picker.error = Some(error.to_string());
                    return None;
                }
                LaunchChoice::Named(b.name.clone())
            };
            self.harness_use_bootstrap = !matches!(self.harness_bootstrap, LaunchChoice::None);
            self.bootstrap_picker = None;
            self.screen = Screen::HarnessPick;
            return None;
        }
        if picker.cursor == picker.create_index() {
            let mut form = super::bootstrap_setup::Form::new(picker.target.clone(), self.harness);
            form.return_to_prompt = picker.return_to_prompt;
            form.back_to_picker = true;
            self.bootstrap_form = Some(form);
            self.screen = Screen::BootstrapSetup;
            return None;
        }
        let id = if none {
            None
        } else {
            let b = picker.entry_at(picker.cursor)?;
            if let Err(error) = b.require_ready() {
                picker.error = Some(error.to_string());
                return None;
            }
            Some(b.id.clone())
        };
        picker.saving = true;
        picker.error = None;
        Some(Effect::SelectBootstrap {
            environment_id: picker.target.environment_id.clone(),
            id,
        })
    }

    fn open_launch_bootstraps(&mut self) -> Option<Effect> {
        if self.harness_pick_agent.is_some() {
            return None;
        }
        let target = self.harness_pick_target.clone()?;
        let env = target.environment_id.clone();
        let mut picker = super::bootstrap_setup::Picker::new(target, false);
        picker.for_launch = true;
        self.bootstrap_picker = Some(picker);
        self.screen = Screen::BootstrapPick;
        Some(Effect::LoadBootstraps {
            environment_id: env,
        })
    }

    fn on_key_bootstrap_picker(&mut self, key: KeyEvent) -> Option<Effect> {
        let picker = self.bootstrap_picker.as_mut()?;
        if picker.saving {
            return None;
        }
        match key.code {
            KeyCode::Esc => {
                self.screen = if picker.for_launch {
                    Screen::HarnessPick
                } else {
                    Screen::Manage
                };
                self.bootstrap_picker = None;
            }
            KeyCode::Char('n') if !picker.for_launch => {
                let target = picker.target.clone();
                self.bootstrap_picker = None;
                self.begin_harness_pick(target, None);
            }
            KeyCode::Down | KeyCode::Char('j') if !picker.loading => {
                picker.cursor = (picker.cursor + 1) % (picker.entries.len() + 2);
            }
            KeyCode::Up | KeyCode::Char('k') if !picker.loading => {
                picker.cursor =
                    (picker.cursor + picker.entries.len() + 1) % (picker.entries.len() + 2);
            }
            KeyCode::Char('r') if !picker.loading => {
                picker.loading = true;
                picker.error = None;
                return Some(Effect::LoadBootstraps {
                    environment_id: picker.target.environment_id.clone(),
                });
            }
            KeyCode::Enter => return self.choose_bootstrap(),
            _ => {}
        }
        None
    }

    fn on_key_bootstrap_setup(&mut self, key: KeyEvent) -> Option<Effect> {
        use super::bootstrap_setup::Action;
        match self.bootstrap_form.as_mut()?.on_key(key) {
            Action::None => None,
            Action::Close => {
                let form = self.bootstrap_form.take()?;
                if form.back_to_picker && !form.finished {
                    self.screen = Screen::BootstrapPick;
                } else {
                    self.bootstrap_picker = None;
                    self.screen = Screen::Manage;
                }
                None
            }
            Action::Submit(req) => Some(Effect::CreateBootstrap(*req)),
        }
    }

    /// Open the target chooser over the tree.
    pub fn start_target_pick(&mut self) {
        self.target_pick = Some(TargetPicker::new(
            &self.tree,
            self.default_project.as_deref(),
            self.target.as_ref(),
        ));
        self.screen = Screen::TargetPick;
    }

    fn on_key_target_pick(&mut self, key: KeyEvent) -> Option<Effect> {
        let picker = self.target_pick.as_mut()?;
        match key.code {
            KeyCode::Up | KeyCode::Char('k') => {
                picker.cursor = picker.cursor.saturating_sub(1);
            }
            KeyCode::Down | KeyCode::Char('j') => {
                picker.cursor = (picker.cursor + 1).min(picker.options.len().saturating_sub(1));
            }
            KeyCode::Enter => {
                let picked = picker.options.get(picker.cursor).cloned();
                self.target_pick = None;
                self.screen = Screen::Manage;
                // This card is where the default project is set, not just where
                // this run is pointed: it is the same question setup asks, and
                // answering it twice — once here, once in setup — would be a
                // way to end up with two different answers.
                if let Some(target) = picked {
                    self.status = format!("Default project set to {}", target.label());
                    self.default_project = Some(target.project_id.clone());
                    self.target = Some(target.clone());
                    return Some(Effect::SaveDefaultProject(Box::new(target)));
                }
            }
            KeyCode::Esc => {
                self.target_pick = None;
                self.screen = Screen::Manage;
            }
            _ => {}
        }
        None
    }

    /// Close the pane's window on the world along with the pane: a maximized
    /// layout with no session in it is an empty screen.
    fn unmaximize_without_a_session(&mut self) {
        if self.maximized && self.active.is_none() {
            self.maximized = false;
        }
    }

    /// Is the right-hand pane taking the whole screen — no tree, no detail
    /// column?
    ///
    /// The layout and the terminal emulator both have to agree on this, or a
    /// remote TUI wraps at the wrong column, so both ask here rather than
    /// reading `maximized` and re-deriving the rest. A launch in flight counts:
    /// `railway code` collapses the tree from the first frame, and the loading
    /// screen is what stands in for the session until there is one. A
    /// maximized flag with neither is not a full pane — it is a blank screen,
    /// which is what happens between a failed launch and the next key.
    pub fn pane_is_full(&self) -> bool {
        self.maximized && (self.active.is_some() || self.loading.active)
    }

    /// Open setup over the tree.
    ///
    /// `ask_first` puts the "set up cloud agents?" question in front of it,
    /// which is right when nobody asked for setup — a first run — and wrong
    /// when they asked for it themselves and have already answered it.
    pub fn start_wizard(&mut self, ask_first: bool) {
        let mut wizard = super::wizard::Wizard::new(
            &self.tree,
            Some(self.harness_name()),
            self.theme,
            self.skills_source.clone(),
            self.hide_tabs,
        );
        if !ask_first {
            wizard.skip_intro();
        }
        self.wizard = Some(wizard);
        self.screen = Screen::Setup;
    }

    /// Close it, whatever the reason.
    pub fn end_wizard(&mut self) {
        self.wizard = None;
        self.screen = Screen::Manage;
    }

    /// Open the ⌥s settings card over the tree, seeded with what is saved.
    ///
    /// The default project's names come from the target, which holds the
    /// saved default whenever one exists — the tree would only have the id.
    pub fn start_settings(&mut self) {
        let project = self
            .default_project
            .as_ref()
            .and(self.target.as_ref())
            .map(|t| super::wizard::ProjectOption {
                project_id: t.project_id.clone(),
                project_name: t.project_name.clone(),
                environment_id: t.environment_id.clone(),
                environment_name: t.environment_name.clone(),
            });
        // The settings card is over the saved default, whose index space is
        // `default_harnesses()` — a live shell selection has no row there and
        // falls back to the first entry rather than clamping onto the last
        // real agent.
        let agent = default_harnesses()
            .iter()
            .position(|slug| *slug == self.harness_name())
            .unwrap_or(0);
        self.settings = Some(super::settings::Settings::new(
            &self.tree,
            project,
            agent,
            self.skills_enabled,
            self.skills_source.clone(),
            self.theme,
            self.hide_tabs,
        ));
        self.screen = Screen::Settings;
    }

    /// Close it; every change was already saved on the way.
    pub fn end_settings(&mut self) {
        self.settings = None;
        self.screen = Screen::Manage;
    }

    /// Adopt a theme slug; an unknown one leaves the current theme alone.
    pub fn set_theme(&mut self, slug: Option<&str>) {
        if slug.is_some() {
            self.theme = Theme::from_slug(slug);
        }
    }

    pub fn harness_name(&self) -> &'static str {
        HARNESSES[self.harness.min(HARNESSES.len() - 1)]
    }

    /// Is the shell option selected? It launches no harness, so the prompt
    /// boxes go inert while it is: there is nothing to hand a prompt to.
    pub fn shell_selected(&self) -> bool {
        self.harness_name() == "shell"
    }

    /// The flattened, currently-visible tree: agent groups first, then the
    /// projects tail.
    ///
    /// Agents are what this screen is about, so every environment that has
    /// any is promoted to a top-level group — always open, never a level to
    /// expand. The containers survive as context rather than navigation: the
    /// group is labelled with its project (and environment, when that adds
    /// something), and projects with nothing in them wait in a collapsible
    /// tail at the bottom, which is where `n` goes to start an agent
    /// somewhere new.
    pub fn rows(&self) -> Vec<Row> {
        let mut rows = Vec::new();
        // The launcher, pinned first: where the cursor starts, and where it
        // goes back to for the next task. Standing here puts the keyboard in
        // the prompt and the launcher in the session pane.
        rows.push(Row {
            depth: 0,
            kind: RowKind::NewSession,
            label: "New Agent".into(),
            note: String::new(),
            status: None,
            expanded: None,
            dimmed: false,
        });
        // Ruled off from the list below it: the launcher is an action, and
        // without the line it reads as the first thread.
        rows.push(separator_row());
        let groups = self.agent_groups();
        for &(w, p, e) in &groups {
            self.push_thread_rows(&mut rows, w, p, e);
        }
        if groups.is_empty() {
            // "None yet" is a definitive claim, so it waits until every
            // environment has actually answered; anything still on its way
            // reads as searching, and a failure says so rather than passing
            // itself off as an empty account.
            let mut envs = self
                .tree
                .iter()
                .flat_map(|ws| ws.projects.iter())
                .flat_map(|project| project.envs.iter());
            let searching = envs
                .clone()
                .any(|env| matches!(env.agents, Load::NotLoaded | Load::Loading));
            let failed = envs.any(|env| matches!(env.agents, Load::Failed(_)));
            rows.push(Row {
                depth: 0,
                kind: RowKind::Hint,
                label: if searching {
                    "looking for cloud agents…".into()
                } else if failed {
                    "couldn't check every environment — r retries".into()
                } else {
                    "no threads yet — the prompt above starts one".into()
                },
                note: String::new(),
                status: None,
                expanded: None,
                dimmed: false,
            });
        }
        self.push_project_tail(&mut rows, &groups);
        rows
    }

    /// One environment's threads, flat: every running session is an entry of
    /// its own — an agent thread — and an agent with no sessions keeps a row
    /// so it stays reachable (to wake, connect to, or start a thread on).
    /// The containers are context, not levels: the project rides along as the
    /// row's note, and the whole story lives in the detail pane.
    fn push_thread_rows(&self, rows: &mut Vec<Row>, w: usize, p: usize, e: usize) {
        let proj = &self.tree[w].projects[p];
        let env = &proj.envs[e];
        let agents = env.agents_vec();
        let attached = self.agents_with_live_panes();
        for a in sorted_agents(agents, &attached) {
            let agent = &agents[a];
            let pending = self.ops.get(agent.id.as_str()).copied();
            let status = displayed_status(agent, &attached);
            // The threads this agent carries: what the platform says is
            // running in there, which outlives our connections and can be
            // rejoined by name.
            let live: Vec<(usize, &ConsoleSession)> = match &agent.sessions {
                LoadSessions::Loaded(sessions) => sessions
                    .iter()
                    .enumerate()
                    .filter(|(_, session)| {
                        session.is_interesting() && !self.ending.contains(&session.name)
                    })
                    .collect(),
                _ => Vec::new(),
            };
            // The agent heads its threads: always on the list, so a sleeping
            // or freshly created agent is reachable too — and an emptied one
            // still says what it is once its last session closes.
            rows.push(Row {
                depth: 0,
                kind: RowKind::Agent(w, p, e, a),
                label: agent.name.clone(),
                // No status tag: the orb's colour is the status, pending
                // states included.
                note: String::new(),
                status: Some(pending.unwrap_or(status).to_string()),
                expanded: Some(agent.expanded),
                dimmed: false,
            });
            // The agent's orb is green only when its effective status says
            // running — and its sessions never look better than it does: a
            // pane held open onto a sleeping agent is not "connected" in any
            // way that matters.
            let agent_live = pending.unwrap_or(status) == "running";
            for (i, session) in live {
                // Each thread leads with what is happening in it — the latest
                // prompt while the harness works, its last reply once done —
                // falling back to `[S] name` for a session nothing has
                // reported from. `connected` is whether THIS UI is attached;
                // the platform's own `attached` flag counts other clients
                // too, which is why it flickered.
                let connected = self.pane_for(&session.name).is_some();
                let connecting = self.connecting.contains(&session.name);
                let reported = session.snapshot.as_ref().map(|s| s.state.as_str());
                rows.push(Row {
                    depth: 1,
                    kind: RowKind::Session(w, p, e, a, i),
                    label: session.thread_label(),
                    note: String::new(),
                    status: if connected && agent_live {
                        Some("connected".to_string())
                    } else if connecting && agent_live {
                        Some("connecting".to_string())
                    } else if agent_live && let Some(state @ ("working" | "waiting")) = reported {
                        // The harness's own state, when it is worth a glyph:
                        // a spinner while it works, a hollow mark when it
                        // waits on a human.
                        Some(state.to_string())
                    } else {
                        None
                    },
                    expanded: None,
                    dimmed: false,
                });
            }
        }
    }

    /// The projects with agent-less environments, folded under one heading at
    /// the bottom.
    ///
    /// This is the browse-to-create surface the groups can't be: selecting a
    /// project or environment here and pressing `n` is how the first agent
    /// gets somewhere new. A project appears whenever it has an environment
    /// that is not a group above — usually because it has no agents at all,
    /// but also when its staging sits empty next to an occupied production;
    /// every environment stays reachable for `n`, `t`, and `r`. Workspaces
    /// appear as a level only when there is more than one to tell apart.
    fn push_project_tail(&self, rows: &mut Vec<Row>, groups: &[(usize, usize, usize)]) {
        let default_project = self.default_project.as_deref();
        let tails: Vec<(usize, Vec<usize>)> = self
            .tree
            .iter()
            .enumerate()
            .map(|(w, ws)| {
                let order = sorted_projects(ws, default_project)
                    .into_iter()
                    .filter(|&p| {
                        ws.projects[p]
                            .envs
                            .iter()
                            .any(|env| env.agents_vec().is_empty())
                    })
                    .collect();
                (w, order)
            })
            .collect();
        let total: usize = tails.iter().map(|(_, order)| order.len()).sum();
        if total == 0 {
            return;
        }
        if !groups.is_empty() {
            rows.push(separator_row());
        }
        let open = self.others_expanded.unwrap_or(groups.is_empty());
        rows.push(Row {
            depth: 0,
            kind: RowKind::OtherProjects,
            // "Other" is relative to the groups; without any there is nothing
            // for these to be other than.
            label: if groups.is_empty() {
                "projects".into()
            } else {
                "other projects".into()
            },
            note: format!("({total})"),
            status: None,
            expanded: Some(open),
            dimmed: false,
        });
        if !open {
            return;
        }
        let multi_workspace = self.tree.len() > 1;
        for (w, order) in tails {
            if order.is_empty() {
                continue;
            }
            let ws = &self.tree[w];
            let base = if multi_workspace {
                rows.push(Row {
                    depth: 1,
                    kind: RowKind::Workspace(w),
                    label: ws.name.clone(),
                    note: "workspace".into(),
                    status: None,
                    expanded: Some(ws.expanded),
                    dimmed: false,
                });
                if !ws.expanded {
                    continue;
                }
                2
            } else {
                1
            };
            for p in order {
                let proj = &ws.projects[p];
                let is_default = Some(proj.id.as_str()) == default_project;
                rows.push(Row {
                    depth: base,
                    kind: RowKind::Project(w, p),
                    label: proj.name.clone(),
                    note: if is_default {
                        "(default)".to_string()
                    } else {
                        String::new()
                    },
                    status: None,
                    expanded: Some(proj.expanded),
                    // Everything here is empty, so everything recedes — except
                    // the default, which is where agents go and has to be
                    // findable even while empty.
                    dimmed: !is_default,
                });
                if !proj.expanded {
                    continue;
                }
                for (e, env) in proj.envs.iter().enumerate() {
                    // An environment with agents is a group above; repeating
                    // it down here would be the same thing twice.
                    if !env.agents_vec().is_empty() {
                        continue;
                    }
                    let note = match &env.agents {
                        Load::Loading => "".into(),
                        Load::Failed(_) => "!".into(),
                        // Everything left here is empty, and a marker against
                        // every empty environment would be noise.
                        _ => String::new(),
                    };
                    rows.push(Row {
                        depth: base + 1,
                        kind: RowKind::Environment(w, p, e),
                        label: env.name.clone(),
                        note,
                        status: None,
                        expanded: Some(env.expanded),
                        dimmed: false,
                    });
                    if !env.expanded {
                        continue;
                    }
                    match &env.agents {
                        Load::Loaded(agents) if agents.is_empty() => {
                            rows.push(note_row(w, p, e, base + 2, "no agents here"));
                        }
                        Load::Loading => rows.push(note_row(w, p, e, base + 2, "loading…")),
                        Load::Failed(err) => {
                            rows.push(note_row(
                                w,
                                p,
                                e,
                                base + 2,
                                &format!("couldn't load: {err}"),
                            ));
                        }
                        // Loaded and non-empty lives in the groups; nothing to
                        // add under it here.
                        Load::Loaded(_) | Load::NotLoaded => {}
                    }
                }
            }
        }
    }

    /// Every environment with agents, as `(workspace, project, environment)`
    /// paths in display order: the groups with something running first, then
    /// the default project, then by name.
    ///
    /// Indices rather than references, so `RowKind` keeps pointing at the same
    /// environment as statuses change and the order shifts under it — the
    /// cursor is restored by identity, not by position.
    fn agent_groups(&self) -> Vec<(usize, usize, usize)> {
        let mut groups = Vec::new();
        for (w, ws) in self.tree.iter().enumerate() {
            for (p, proj) in ws.projects.iter().enumerate() {
                for (e, env) in proj.envs.iter().enumerate() {
                    if !env.agents_vec().is_empty() {
                        groups.push((w, p, e));
                    }
                }
            }
        }
        let default = self.default_project.as_deref();
        let running = |(w, p, e): &(usize, usize, usize)| {
            self.tree[*w].projects[*p].envs[*e]
                .agents_vec()
                .iter()
                .any(|agent| agent.status == "running")
        };
        groups.sort_by(|a, b| {
            let (pa, pb) = (&self.tree[a.0].projects[a.1], &self.tree[b.0].projects[b.1]);
            let is_default = |p: &ProjectNode| Some(p.id.as_str()) == default;
            running(b)
                .cmp(&running(a))
                .then_with(|| is_default(pb).cmp(&is_default(pa)))
                .then_with(|| pa.name.to_lowercase().cmp(&pb.name.to_lowercase()))
                .then_with(|| a.2.cmp(&b.2))
        });
        groups
    }

    pub fn selected_row(&self) -> Option<Row> {
        self.rows().into_iter().nth(self.cursor)
    }

    /// The environment a row belongs to, whatever kind of row it is — so `t`
    /// and `n` work with the cursor on an agent, not just on its environment.
    fn env_of(&self, kind: RowKind) -> Option<(usize, usize, usize)> {
        match kind {
            RowKind::Environment(w, p, e)
            | RowKind::Agent(w, p, e, _)
            | RowKind::Session(w, p, e, _, _)
            | RowKind::Note(w, p, e) => Some((w, p, e)),
            _ => None,
        }
    }

    fn target_at(&self, path: (usize, usize, usize)) -> Option<Target> {
        let (w, p, e) = path;
        let proj = self.tree.get(w)?.projects.get(p)?;
        let env = proj.envs.get(e)?;
        Some(Target {
            project_id: proj.id.clone(),
            project_name: proj.name.clone(),
            environment_id: env.id.clone(),
            environment_name: env.name.clone(),
        })
    }

    fn clamp_cursor(&mut self) {
        let len = self.rows().len();
        if len == 0 {
            self.cursor = 0;
        } else if self.cursor >= len {
            self.cursor = len - 1;
        }
    }

    /// Move by `delta`, skipping non-selectable note rows, and bring the pane
    /// along when the new row is a session.
    fn move_cursor(&mut self, delta: isize) -> Option<Effect> {
        self.move_cursor_inner(delta);
        // Arriving on the launcher puts the keyboard in its prompt; only Esc
        // there sets it down again.
        if self.cursor == 0 {
            self.prompt_focused = true;
        }
        self.sync_active_to_cursor();
        self.auto_expand_agent()
    }

    /// Selecting a machine refreshes its cached history in place.
    fn auto_expand_agent(&mut self) -> Option<Effect> {
        let row = self.selected_row()?;
        let RowKind::Agent(w, p, e, a) = row.kind else {
            return None;
        };
        let Load::Loaded(agents) = &self.tree.get(w)?.projects.get(p)?.envs.get(e)?.agents else {
            return None;
        };
        let agent = agents.get(a)?;
        let id = agent.id.clone();
        if agent.sessions == LoadSessions::NotLoaded {
            self.set_agent_expanded((w, p, e, a), true)
        } else {
            self.refresh_agent_sessions(&id)
        }
    }

    fn move_cursor_inner(&mut self, delta: isize) {
        let rows = self.rows();
        if rows.is_empty() {
            return;
        }
        let mut i = self.cursor as isize;
        loop {
            i += delta;
            if i < 0 || i as usize >= rows.len() {
                return; // ran off the end: leave the cursor where it was
            }
            if rows[i as usize].selectable() {
                self.cursor = i as usize;
                return;
            }
        }
    }

    /// Apply a scoped response only to its original environment, and only if
    /// the request follows the latest applied snapshot or mutation acceptance.
    pub fn agents_loaded_at(
        &mut self,
        path: (usize, usize, usize),
        environment_id: &str,
        result: Result<Vec<Agent>, String>,
        asked_at: std::time::Instant,
    ) {
        let (w, p, e) = path;
        if self
            .tree
            .get(w)
            .and_then(|ws| ws.projects.get(p))
            .and_then(|project| project.envs.get(e))
            .is_none_or(|env| env.id != environment_id)
            || self
                .agent_snapshot_floor
                .get(environment_id)
                .is_some_and(|at| *at > asked_at)
        {
            return;
        }
        // A load can change the order — a project that gains its first agent
        // moves up — so the cursor is put back by row identity rather than
        // left on whatever index it was.
        let anchor = self.selected_row().map(|row| row.kind);
        let mut refresh_failed = None;
        let mut answered = None;
        if let Some(env) = self
            .tree
            .get_mut(w)
            .and_then(|ws| ws.projects.get_mut(p))
            .and_then(|proj| proj.envs.get_mut(e))
        {
            let previous = std::mem::replace(&mut env.agents, Load::NotLoaded);
            env.agents = match (result, previous) {
                // Merged, not replaced: a fetch describes the platform's
                // agents, and whether a row is open and what is running on it
                // is ours. See [`merge_agents`].
                (Ok(agents), Load::Loaded(previous)) => {
                    answered = Some(env.id.clone());
                    Load::Loaded(merge_agents(previous, agents))
                }
                (Ok(agents), _) => {
                    answered = Some(env.id.clone());
                    Load::Loaded(agents)
                }
                // A refresh that fails must not take the agents with it:
                // stale beats gone, and the status line carries the reason.
                (Err(err), Load::Loaded(agents)) => {
                    refresh_failed = Some(err);
                    Load::Loaded(agents)
                }
                (Err(err), _) => Load::Failed(err),
            };
        }
        // Request time, not response time: a newer overlapping request can
        // still deliver a newer observation after this reply arrives.
        if let Some(id) = &answered {
            self.agent_snapshot_floor.insert(id.clone(), asked_at);
        }
        if let Some(err) = refresh_failed {
            self.toast_error(format!("Couldn't refresh: {err}"));
        }
        self.collapse_if_empty(w, p);
        if let Some(id) = answered {
            self.settle_watched_agents(&[id]);
        }
        self.restore_cursor(anchor);
        self.select_pending();
        // A just-launched agent arrives here before its sessions can be
        // asked about; the pane already attached to it is proof enough.
        self.adopt_pane_sessions();
    }

    /// Synchronous fixture loads represent a fresh request for the current tree.
    #[cfg(test)]
    fn agents_loaded(&mut self, path: (usize, usize, usize), result: Result<Vec<Agent>, String>) {
        let (w, p, e) = path;
        let Some(environment_id) = self
            .tree
            .get(w)
            .and_then(|ws| ws.projects.get(p))
            .and_then(|project| project.envs.get(e))
            .map(|env| env.id.clone())
        else {
            return;
        };
        self.agents_loaded_at(path, &environment_id, result, std::time::Instant::now());
    }

    /// The whole account's agents arrived in one `myCloudAgents` request.
    ///
    /// Every unanswered environment becomes loaded: one absent from the
    /// response holds no agents of the caller's, and saying so is what lets
    /// the tree show counts everywhere without a request per environment. An
    /// environment that already had a list gets the snapshot instead — that is
    /// what makes this a refresh rather than a first fill, and it is the only
    /// thing that can tell the tree an agent was created or deleted somewhere
    /// else. (Skipping environments that already had a list is why `shift+r`
    /// used to report "already loaded" and change nothing.)
    ///
    /// A snapshot may not overwrite a newer request's answer or settle a
    /// mutation accepted after the request began. Both fetch paths compare
    /// request-start times with [`Self::agent_snapshot_floor`]. Environments
    /// still `Loading` await their dedicated reply.
    pub fn my_agents_loaded(&mut self, agents: Vec<(String, Agent)>, asked_at: std::time::Instant) {
        let anchor = self.selected_row().map(|row| row.kind);
        let mut by_env: HashMap<String, Vec<Agent>> = HashMap::new();
        for (environment_id, agent) in agents {
            by_env.entry(environment_id).or_default().push(agent);
        }
        let mut answered = Vec::new();
        for ws in &mut self.tree {
            for project in &mut ws.projects {
                for env in &mut project.envs {
                    if self
                        .agent_snapshot_floor
                        .get(&env.id)
                        .is_some_and(|at| *at > asked_at)
                    {
                        continue;
                    }
                    let fresh = match &env.agents {
                        Load::NotLoaded | Load::Failed(_) => by_env.remove(&env.id),
                        Load::Loaded(previous) => Some(merge_agents(
                            previous.clone(),
                            by_env.remove(&env.id).unwrap_or_default(),
                        )),
                        Load::Loading => continue,
                    };
                    env.agents = Load::Loaded(fresh.unwrap_or_default());
                    answered.push(env.id.clone());
                }
            }
        }
        for id in &answered {
            self.agent_snapshot_floor.insert(id.clone(), asked_at);
        }
        self.settle_watched_agents(&answered);
        self.restore_cursor(anchor);
        self.select_pending();
        self.adopt_pane_sessions();
    }

    /// Fold up a project whose last agent has gone.
    ///
    /// After a delete the tree would otherwise sit open on an empty
    /// environment under an empty project, holding space for nothing. Only when
    /// every environment has answered — collapsing one that is still loading
    /// would hide agents that are about to appear.
    fn collapse_if_empty(&mut self, w: usize, p: usize) {
        let Some(project) = self.tree.get_mut(w).and_then(|ws| ws.projects.get_mut(p)) else {
            return;
        };
        let all_answered = project
            .envs
            .iter()
            .all(|env| matches!(env.agents, Load::Loaded(_)));
        let empty = project.envs.iter().all(|env| match &env.agents {
            Load::Loaded(agents) => agents.is_empty(),
            _ => true,
        });
        if !all_answered || !empty {
            return;
        }
        project.expanded = false;
        for env in project.envs.iter_mut() {
            env.expanded = false;
        }
    }

    /// Put the cursor back on the row it was on, wherever that row now sits.
    ///
    /// A row can be gone entirely — a load can fold the projects tail the
    /// cursor was in — and then the nearest selectable row is the best that
    /// can be done.
    fn restore_cursor(&mut self, anchor: Option<RowKind>) {
        if let Some(kind) = anchor {
            let rows = self.rows();
            if let Some(index) = rows.iter().position(|row| row.kind == kind) {
                self.cursor = index;
            }
        }
        self.clamp_cursor();
        if self.selected_row().is_some_and(|row| !row.selectable()) {
            self.move_cursor_inner(1);
        }
        if self.selected_row().is_some_and(|row| !row.selectable()) {
            self.move_cursor_inner(-1);
        }
    }

    /// Expand or collapse an agent, fetching its sessions the first time.
    fn set_agent_expanded(
        &mut self,
        path: (usize, usize, usize, usize),
        open: bool,
    ) -> Option<Effect> {
        let (w, p, e, a) = path;
        let env = self.tree.get_mut(w)?.projects.get_mut(p)?.envs.get_mut(e)?;
        let environment_id = env.id.clone();
        let Load::Loaded(agents) = &mut env.agents else {
            return None;
        };
        let agent = agents.get_mut(a)?;
        agent.expanded = open;
        if !open || agent.status != "running" {
            return None;
        }
        if self.thread_polls.contains(&agent.id) {
            return None;
        }
        // Loaded rows remain visible while the on-demand request is in flight.
        if !matches!(agent.sessions, LoadSessions::Loaded(_)) {
            agent.sessions = LoadSessions::Loading;
        }
        Some(Effect::LoadSessions {
            agent_id: agent.id.clone(),
            environment_id,
            path,
        })
    }

    /// A partial discovery failure keeps the affected harness's previous rows.
    pub(super) fn preserve_failed_threads(
        &self,
        agent_id: &str,
        failed: &[String],
        rows: &mut Vec<ConsoleSession>,
    ) {
        if failed.is_empty() {
            return;
        }
        for ws in &self.tree {
            for project in &ws.projects {
                for env in &project.envs {
                    let Load::Loaded(agents) = &env.agents else {
                        continue;
                    };
                    let Some(agent) = agents.iter().find(|a| a.id == agent_id) else {
                        continue;
                    };
                    let LoadSessions::Loaded(previous) = &agent.sessions else {
                        continue;
                    };
                    for row in previous {
                        if super::super::client_sessions::parse_name(&row.name)
                            .is_some_and(|(h, _, _)| failed.iter().any(|f| f == h))
                            && !rows.iter().any(|r| r.name == row.name)
                        {
                            rows.push(row.clone());
                        }
                    }
                }
            }
        }
    }

    /// Adopt only an exact, unambiguous live-process/console association. Two
    /// Grok dashboard tabs can share one PID; their order is not a focus signal.
    pub(super) fn remote_threads_loaded(
        &mut self,
        agent_id: &str,
        threads: &[super::super::remote_threads::RemoteThread],
    ) {
        for pane in &mut self.sessions {
            pane.sync_console_name();
        }
        let mut updates = Vec::new();
        for (index, pane) in self.sessions.iter().enumerate() {
            if pane.agent_id != agent_id
                || pane.ended()
                || pane.client_bridge.is_some()
                || pane.opencode_bridge.is_some()
            {
                continue;
            }
            let matches: Vec<_> = threads
                .iter()
                .filter(|row| {
                    (row.pane_id.is_some() && row.pane_id == pane.client_id)
                        || row.console_name.as_ref().is_some_and(|name| {
                            pane.console_name.as_ref() == Some(name) || &pane.durable_name == name
                        })
                })
                .collect();
            if let [row] = matches.as_slice() {
                updates.push((index, (*row).clone()));
            }
        }
        for (index, row) in updates {
            self.sessions[index].harness = row.harness;
            if row.console_name.is_some() {
                self.sessions[index].console_name = row.console_name;
            }
            self.adopt_thread(index, row.thread);
        }
    }

    /// Record a finished session fetch.
    pub fn sessions_loaded(
        &mut self,
        path: (usize, usize, usize, usize),
        agent_id: &str,
        result: Result<Vec<ConsoleSession>, String>,
    ) {
        let result = result.map(|mut rows| {
            rows.retain(|row| !self.deleted_threads.contains(&row.name));
            rows
        });
        let selected = self.selected_row().and_then(|row| {
            let RowKind::Session(w, p, e, a, i) = row.kind else {
                return None;
            };
            let session = self.console_session(w, p, e, a, i)?;
            Some(session.name.clone())
        });
        let open: std::collections::HashSet<_> = self
            .sessions
            .iter()
            .filter(|pane| !pane.ended() && pane.agent_id == agent_id)
            .map(|pane| pane.durable_name.clone())
            .collect();
        // Whatever this reply says, its discovery is no longer in flight.
        self.thread_polls.remove(agent_id);
        self.discovered.insert(agent_id.into());
        let (w, p, e, _) = path;
        // Resolved by id rather than trusting the index the request went out
        // with: the environment can be refetched while sessions are in
        // flight, and a new agent shifting the list would otherwise attach
        // these sessions to whoever now sits at that index.
        let a = match self
            .tree
            .get(w)
            .and_then(|ws| ws.projects.get(p))
            .and_then(|proj| proj.envs.get(e))
            .map(|env| &env.agents)
        {
            Some(Load::Loaded(agents)) => {
                match agents.iter().position(|agent| agent.id == agent_id) {
                    Some(a) => a,
                    // The agent is gone (deleted, or the refetch dropped it);
                    // its sessions have nowhere to belong.
                    None => return,
                }
            }
            _ => return,
        };
        let mut refresh_failed = None;
        if let Some(Load::Loaded(agents)) = self
            .tree
            .get_mut(w)
            .and_then(|ws| ws.projects.get_mut(p))
            .and_then(|proj| proj.envs.get_mut(e))
            .map(|env| &mut env.agents)
            && let Some(agent) = agents.get_mut(a)
        {
            let previous = std::mem::replace(&mut agent.sessions, LoadSessions::NotLoaded);
            agent.sessions = match (result, previous) {
                (Ok(mut sessions), LoadSessions::Loaded(previous)) => {
                    // A slow discovery must not roll back a newer live event.
                    for row in &mut sessions {
                        if open.contains(&row.name)
                            && let Some(old) = previous.iter().find(|old| old.name == row.name)
                            && old.snapshot.as_ref().map(|s| &s.updated_at)
                                > row.snapshot.as_ref().map(|s| &s.updated_at)
                        {
                            *row = old.clone();
                        }
                    }
                    // Open drafts may not exist in the provider index yet.
                    // Keep their slot across refreshes, alongside saved rows.
                    for row in &previous {
                        if super::super::client_sessions::is_client(&row.name)
                            && open.contains(&row.name)
                            && !sessions.iter().any(|s| s.name == row.name)
                        {
                            sessions.push(row.clone());
                        }
                    }
                    // Provider recency and title updates change row content,
                    // never its position while someone is navigating the list.
                    let positions: HashMap<_, _> = previous
                        .iter()
                        .enumerate()
                        .map(|(i, s)| (&s.name, i))
                        .collect();
                    sessions.sort_by_key(|s| positions.get(&s.name).copied().unwrap_or(usize::MAX));
                    LoadSessions::Loaded(sessions)
                }
                (Ok(sessions), _) => LoadSessions::Loaded(sessions),
                // The same rule the agent list follows: a refresh that fails
                // keeps what it had rather than replacing a good list with an
                // error. The reason goes to the status line, not a toast — a
                // background refresh must not raise one per tick while the
                // network is out.
                (Err(err), LoadSessions::Loaded(sessions)) => {
                    refresh_failed = Some(err);
                    LoadSessions::Loaded(sessions)
                }
                (Err(err), _) => LoadSessions::Failed(err),
            };
        }
        if let Some(err) = refresh_failed {
            self.status = format!("Couldn't refresh sessions: {err}");
        }
        // Anything we hid that the agent no longer reports has actually gone;
        // stop tracking it. One that is still listed stays hidden until it is.
        if let Some(LoadSessions::Loaded(sessions)) = self
            .tree
            .get(w)
            .and_then(|ws| ws.projects.get(p))
            .and_then(|proj| proj.envs.get(e))
            .and_then(|env| match &env.agents {
                Load::Loaded(agents) => agents.get(a).map(|agent| &agent.sessions),
                _ => None,
            })
        {
            let live: std::collections::HashSet<&str> = sessions
                .iter()
                .filter(|s| s.is_interesting())
                .map(|s| s.name.as_str())
                .collect();
            self.ending.retain(|name| live.contains(name.as_str()));
        }
        if self.pending_select_session.is_none() {
            self.pending_select_session = selected;
        }
        self.clamp_cursor();
        // The platform's list may still be missing sessions we are attached
        // to (the relay registers them a moment after ssh connects); fold
        // those back in rather than letting the reply hide them.
        self.adopt_pane_sessions();
        self.persist_threads(agent_id);
    }

    /// Expand an environment, loading its agents the first time.
    fn expand_env(&mut self, path: (usize, usize, usize)) -> Option<Effect> {
        let (w, p, e) = path;
        let env = self.tree.get_mut(w)?.projects.get_mut(p)?.envs.get_mut(e)?;
        env.expanded = true;
        if env.agents == Load::NotLoaded {
            env.agents = Load::Loading;
            return Some(Effect::LoadAgents {
                environment_id: env.id.clone(),
                path,
            });
        }
        None
    }

    /// The agent the tree cursor is pointing at, directly or via one of its
    /// sessions. A prompt submitted while an agent is selected belongs to that
    /// agent — the alternative is silently starting work somewhere else.
    fn launch(&self, agent_id: Option<String>, force_new: bool) -> Option<Effect> {
        // A shell session takes no prompt; a draft left over from cycling
        // through the agents must not ride along.
        let draft = (!self.shell_selected() && !self.prompt.trim().is_empty())
            .then(|| self.prompt.trim().to_string());
        self.launch_prompted(agent_id, force_new, draft)
    }

    /// [`Self::launch`], with the prompt supplied by the caller instead of
    /// read from the launcher's box — what the ⌥p composer sends.
    fn launch_prompted(
        &self,
        agent_id: Option<String>,
        force_new: bool,
        prompt: Option<String>,
    ) -> Option<Effect> {
        let target = self.target.clone()?;
        Some(Effect::Launch(LaunchRequest {
            project_id: target.project_id.clone(),
            environment_id: target.environment_id.clone(),
            agent_id,
            session_name: None,
            force_new,
            new_session: false,
            harness: self.harness_name().to_string(),
            prompt,
            label: target.label(),
            base: Default::default(),
        }))
    }

    pub fn on_key(&mut self, key: KeyEvent) -> Option<Effect> {
        if key.code == KeyCode::Esc
            && let Some(drag) = self.sidebar_drag.take()
        {
            self.sidebar_width = drag.original;
            return None;
        }

        // The SSH gate owns the keyboard until its question is answered.
        // Anything other than yes cancels: a mistyped key must never register
        // a credential on the account.
        if let Some(gate) = self.ssh_gate.take() {
            return match key.code {
                KeyCode::Char('y') | KeyCode::Char('Y') => Some(Effect::RegisterSshKey {
                    offer: gate.offer,
                    then: gate.then,
                }),
                _ => {
                    if matches!(&gate.then, Some(HeldConnect::Bootstrap(_)))
                        && let Some(form) = self.bootstrap_form.as_mut()
                    {
                        form.running = false;
                        form.error = Some(
                            "Setup cancelled before creating a VM: an SSH key must be registered."
                                .into(),
                        );
                    }
                    if gate.then.is_some() {
                        self.toast_error("Cancelled — connecting needs a registered SSH key");
                    }
                    None
                }
            };
        }

        // Creation owns the screen until checkpoint capture and VM cleanup finish.
        if self.screen == Screen::BootstrapSetup {
            return self.on_key_bootstrap_setup(key);
        }
        if self.screen == Screen::BootstrapPick {
            return self.on_key_bootstrap_picker(key);
        }
        if self.screen == Screen::Manage
            && self.focus == ManageFocus::Tree
            && key.modifiers.contains(KeyModifiers::CONTROL)
            && matches!(key.code, KeyCode::Char('b') | KeyCode::Char('B'))
        {
            return self.open_bootstraps();
        }

        // A focused session owns the keyboard: Ctrl-C must interrupt the agent,
        // Esc must reach its editor, and ⌥/^ chords belong to whatever is
        // running in there, apart from the app shortcuts handled below.
        //
        // Only while the session is the frontmost thing, though. A card
        // floated over it — the ⌥n picker, the ⌥p composer — is what the
        // keyboard is for while it is up, and focus stays on the session
        // underneath so closing the card returns to typing in it.
        if self.focus == ManageFocus::Session && self.screen == Screen::Manage {
            // Four ways out, because terminals disagree about what they will
            // report. `^]` is the classic escape chord and works everywhere,
            // and `^o` stays for anyone who learned it. Both modified Escapes
            // are taken because only one of them can be typed on a stock macOS
            // terminal: Option is a compose key there unless it is mapped to
            // Meta, and every other ⌥ chord survives that by arriving as the
            // character it composes to (⌥f as `ƒ`, ⌥[ as a curly quote — see
            // `alt_chord`). Escape composes to nothing, so ⌥esc arrives as a
            // bare Escape that belongs to the agent, with no modifier left to
            // tell the two apart. Shift is never composed, and the kitty
            // protocol reports a shifted Escape as `CSI 27;2u`, so ⇧esc is the
            // one that survives a terminal nobody has configured.
            let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
            let modified_esc = key.code == KeyCode::Esc
                && key
                    .modifiers
                    .intersects(KeyModifiers::ALT | KeyModifiers::SHIFT);
            let ctrl_bracket = ctrl && key.code == KeyCode::Char(']');
            let ctrl_o = ctrl && matches!(key.code, KeyCode::Char('o') | KeyCode::Char('O'));
            if modified_esc || ctrl_bracket || ctrl_o {
                self.focus = ManageFocus::Tree;
                // Releasing means "show me the tree" — a maximized pane has
                // it folded away, so give it back rather than handing focus
                // to something invisible.
                self.maximized = false;
                return None;
            }
            // A few chords are taken from the agent, all because the moment
            // you want them is while you are using it: ⌥f for room, ⌥⇧] and
            // ⌥⇧[ (with their unshifted aliases) to move between panes, ⌥n
            // and ⌥p to start more work — the thought "this needs its own
            // session" arrives while reading one, and going out to the tree
            // first to act on it is the friction they exist to remove. ⌥r
            // joins them for the same reason: a refresh that only worked with
            // the tree focused would be a chord that silently does nothing
            // half the time you press it. The costs, all in a shell: ⌥f is
            // Meta-f (forward-word), ⌥n and ⌥p are Meta-n / Meta-p (the
            // non-incremental history searches, which few people bind and
            // both harnesses ignore), and ⌥r is Meta-r (revert-line). ⌥b
            // saves this VM as a bootstrap; ⌥o opens its SSH shell, and ⌥t
            // selects a target project for new work.
            // Readline leaves Meta-] and Meta-[ unbound, bash binds Meta-{
            // only to the rarely-reached complete-into-braces, and `^]`
            // (character-search) is untouched because only the Meta forms are
            // claimed. Nothing else is intercepted — ⌥s still reaches the
            // agent from here.
            if let Some(chord) = alt_chord(&key)
                && matches!(chord, 'b' | 'o' | 't' | 'f' | 'n' | 'p' | 'r' | ']' | '[')
            {
                return self.alt_action(chord);
            }
            // Focusing an unconnected thread's card does not attach it or
            // give another open session the keyboard. Enter is an explicit
            // connect; Escape and Tab return to browsing.
            if self.active.is_none() {
                return match key.code {
                    KeyCode::Esc | KeyCode::Tab => {
                        self.focus = ManageFocus::Tree;
                        None
                    }
                    KeyCode::Enter => self.on_key_manage(key),
                    KeyCode::Char('c') | KeyCode::Char('C') if ctrl => Some(Effect::Quit),
                    _ => None,
                };
            }
            // Scrollback, before the agent sees the key. Shifted so an
            // unshifted PageUp still belongs to whatever is running.
            let shift = key.modifiers.contains(KeyModifiers::SHIFT);
            let scroll = match key.code {
                KeyCode::PageUp if shift => Some(true),
                KeyCode::PageDown if shift => Some(false),
                _ => None,
            };
            if let Some(i) = self.active {
                // A pane whose connection is gone answers with recovery
                // instead of typing: bytes sent to a dead pty vanish, which
                // used to make "session ended" a wall with no door. Scrollback
                // stays live — reading what the connection said on its way
                // out is half the point of keeping the screen.
                let dead = self
                    .sessions
                    .get(i)
                    .is_some_and(|s| s.ended() || s.stalled());
                if dead && scroll.is_none() {
                    return self.dead_pane_key(i, key);
                }
                // Every bare Escape belongs to the harness — including two in
                // a row. There used to be a double-tap release here, but the
                // first tap always went through, and in Claude Code a single
                // Esc cancels the running turn: the release gesture cost the
                // user their work on its way out. ⌥⇧esc (and ⇧esc, ^], ^o)
                // release without sending anything.
                if let Some(session) = self.sessions.get_mut(i) {
                    match scroll {
                        // No pointer for a keyboard scroll; report it over the
                        // middle of the pane.
                        Some(up) => session.scroll(up, 10, (1, 1)),
                        None => session.send_key(key),
                    }
                }
            }
            return None;
        }

        // Ctrl-C always quits, on every screen and in every focus.
        if key.modifiers.contains(KeyModifiers::CONTROL)
            && matches!(key.code, KeyCode::Char('c') | KeyCode::Char('C'))
        {
            return Some(Effect::Quit);
        }
        // Ctrl-T remains an alias for Option+T. Deliberately not plain `t`: the
        // prompt has focus by default, where `t` is a letter someone is typing.
        if key.modifiers.contains(KeyModifiers::CONTROL)
            && matches!(key.code, KeyCode::Char('t') | KeyCode::Char('T'))
        {
            self.start_target_pick();
            return None;
        }
        // Alt-chords work from every screen and both focuses — including the
        // prompt, where a bare letter is text someone is typing. macOS sends
        // Option+letter as a composed character unless the terminal maps Option
        // to Meta, so the handful that are not dead keys are accepted too.
        if let Some(action) = alt_chord(&key) {
            return self.alt_action(action);
        }
        self.status.clear();
        match self.screen {
            Screen::BootstrapSetup => self.on_key_bootstrap_setup(key),
            Screen::BootstrapPick => self.on_key_bootstrap_picker(key),
            Screen::Setup => self.on_key_wizard(key),
            Screen::Settings => self.on_key_settings(key),
            Screen::TargetPick => self.on_key_target_pick(key),
            Screen::HarnessPick => self.on_key_harness_pick(key),
            Screen::ManagePrompt => self.on_key_manage_prompt(key),
            Screen::Manage => self.on_key_manage(key),
        }
    }

    /// Pasted text — a ⌘v, or a dictation tool like Wispr Flow, which inserts
    /// into a terminal the same way. It goes where typing would go: a focused
    /// session gets it as a paste, a prompt box gets it as text. Anywhere
    /// else it is dropped whole — fed through `on_key` it would spray across
    /// hotkeys, and a stray paste must never trigger an action.
    pub fn on_paste(&mut self, text: String) -> Option<Effect> {
        // The SSH gate is a y/N question; pasted text is not an answer.
        if self.ssh_gate.is_some() {
            return None;
        }
        if self.focus == ManageFocus::Session && self.screen == Screen::Manage {
            if let Some(i) = self.active {
                // A dead pane's keys mean recovery, but a paste is not a
                // command — bytes to a dead pty vanish, so drop it.
                let dead = self
                    .sessions
                    .get(i)
                    .is_some_and(|s| s.ended() || s.stalled());
                if !dead && let Some(session) = self.sessions.get_mut(i) {
                    session.send_paste(&text);
                }
            }
            return None;
        }
        // A pasted newline stays a newline — the prompt boxes hold
        // paragraphs, and ⇧enter types the same character — but it is never
        // taken as Enter: pasting must not launch. Other control characters
        // have no business in a draft at all.
        let text: String = text
            .replace("\r\n", "\n")
            .chars()
            .map(|c| if c == '\r' { '\n' } else { c })
            .filter(|c| *c == '\n' || !c.is_control())
            .collect();
        match self.screen {
            Screen::BootstrapSetup => {
                if let Some(form) = self.bootstrap_form.as_mut() {
                    form.paste(&text);
                }
            }
            Screen::Manage if self.new_session_selected() && !self.shell_selected() => {
                self.prompt_insert_str(&text);
            }
            Screen::ManagePrompt if !self.shell_selected() => {
                if let Some(draft) = self.manage_prompt.as_mut() {
                    draft.push_str(&text);
                }
            }
            _ => {}
        }
        None
    }

    fn on_key_wizard(&mut self, key: KeyEvent) -> Option<Effect> {
        use super::wizard::Action;
        let wizard = self.wizard.as_mut()?;
        // A step doing work owns the keyboard until it is done.
        if wizard.busy.is_some() {
            return None;
        }
        let action = match key.code {
            KeyCode::Up | KeyCode::Char('k') => {
                wizard.up();
                Action::Redraw
            }
            KeyCode::Down | KeyCode::Char('j') => {
                wizard.down();
                Action::Redraw
            }
            KeyCode::Enter => wizard.select(),
            KeyCode::Esc => wizard.back(),
            _ => Action::None,
        };
        // The theme previews as the cursor moves, so the whole screen follows.
        self.theme = self
            .wizard
            .as_ref()
            .map(|w| w.previewed_theme())
            .unwrap_or(self.theme);
        match action {
            Action::None | Action::Redraw => None,
            Action::CreateProject(workspace_id) => Some(Effect::CreateDefaultProject(workspace_id)),
            Action::Cancel => {
                self.end_wizard();
                None
            }
            Action::Finish(outcome) => {
                // There are preferences now, so the next start skips the
                // wizard and the answers move to the ⌥s settings card.
                self.configured = true;
                self.end_wizard();
                Some(Effect::SaveSetup(outcome))
            }
        }
    }

    fn on_key_settings(&mut self, key: KeyEvent) -> Option<Effect> {
        use super::settings::Action;
        let settings = self.settings.as_mut()?;
        // The picker creating a project owns the keyboard until it is done.
        if settings.busy.is_some() {
            return None;
        }
        let action = match key.code {
            KeyCode::Up | KeyCode::Char('k') => {
                settings.up();
                Action::Redraw
            }
            KeyCode::Down | KeyCode::Char('j') => {
                settings.down();
                Action::Redraw
            }
            KeyCode::Left | KeyCode::Char('h') => settings.left(),
            KeyCode::Right | KeyCode::Char('l') => settings.right(),
            KeyCode::Enter => settings.select(),
            KeyCode::Esc => settings.back(),
            _ => Action::None,
        };
        // The theme applies as it cycles, so the whole screen follows.
        self.theme = self
            .settings
            .as_ref()
            .map(|s| s.current_theme())
            .unwrap_or(self.theme);
        match action {
            Action::None | Action::Redraw => None,
            Action::Save(outcome) => Some(Effect::SaveSettings(outcome)),
            Action::CreateProject(workspace_id) => Some(Effect::CreateDefaultProject(workspace_id)),
            Action::RunSetup => {
                self.settings = None;
                self.start_wizard(false);
                None
            }
            Action::Close => {
                self.end_settings();
                None
            }
        }
    }

    /// Hand a pointer event to the application, in the pane's own coordinates.
    /// Reports whether it wanted it.
    fn send_pointer(&mut self, kind: session::Pointer, col: u16, row: u16) -> bool {
        let pane = self.panes.session;
        if !pane.contains(col, row) {
            return false;
        }
        let at = (
            col.saturating_sub(pane.x) + 1,
            row.saturating_sub(pane.y) + 1,
        );
        let Some(index) = self.active else {
            return false;
        };
        match self.sessions.get_mut(index) {
            Some(session) => session.pointer(kind, at),
            None => false,
        }
    }

    /// The link under a screen position, in the open session.
    fn url_at(&self, col: u16, row: u16) -> Option<String> {
        let pane = self.panes.session;
        if !pane.contains(col, row) {
            return None;
        }
        self.active_session()?.url_at(row - pane.y, col - pane.x)
    }

    /// Which pane a screen position belongs to, borders included — a click
    /// anywhere on a panel selects it, which is also how the keyboard is taken
    /// back from a focused session.
    fn pane_at(&self, col: u16, row: u16) -> Option<ManageFocus> {
        if self.panes.session_outer.contains(col, row) {
            Some(ManageFocus::Session)
        } else if self.panes.tree_outer.contains(col, row) {
            Some(ManageFocus::Tree)
        } else {
            None
        }
    }

    /// Move focus onto the content already displayed in a panel. A thread
    /// without a local connection stays a detail card, even if another VM
    /// has a session open in the background.
    fn focus_panel(&mut self, pane: ManageFocus) {
        if pane == ManageFocus::Session && self.focus == ManageFocus::Tree && !self.pane_is_full() {
            let selected = self.selected_row().map(|row| row.kind);
            // The launcher's input belongs to the tree's prompt handler.
            if selected == Some(RowKind::NewSession) {
                return;
            }
            self.active = selected.and_then(|kind| match kind {
                RowKind::Session(..) => self.pane_for_row(kind),
                _ => None,
            });
        }
        self.focus = pane;
    }

    /// Handle a mouse event, returning any work it implies — expanding a row
    /// can need its children fetched, the same as the keyboard.
    ///
    /// A finished drag arms `pending_copy`; the text itself is lifted out of
    /// the next frame, since that is the only place the pane's contents exist
    /// in screen coordinates.
    #[cfg(test)]
    pub fn on_mouse(&mut self, kind: MouseAction, col: u16, row: u16) -> Option<Effect> {
        self.on_mouse_shifted(kind, col, row, false)
    }

    /// The same, told whether shift was held.
    ///
    /// Shift is the terminal's own convention for "this click is mine, not the
    /// application's" — it is how you select text in a program that has taken
    /// the mouse, and it means the same thing here.
    pub fn on_mouse_shifted(
        &mut self,
        kind: MouseAction,
        col: u16,
        row: u16,
        shift: bool,
    ) -> Option<Effect> {
        if let Some(drag) = self.sidebar_drag {
            match kind {
                // A fresh press or wheel gesture means the previous release
                // was lost (for example outside the window). Cancel that
                // unfinished resize and let the event reach its panel.
                MouseAction::Down | MouseAction::ScrollUp | MouseAction::ScrollDown => {
                    self.sidebar_drag = None;
                    self.sidebar_width = drag.original;
                }
                MouseAction::Drag => {
                    self.drag_sidebar_to(col);
                    return None;
                }
                MouseAction::Up => {
                    self.drag_sidebar_to(col);
                    let drag = self.sidebar_drag.take()?;
                    if !drag.moved
                        && row == drag.start_row
                        && self.screen == Screen::Manage
                        && let Some(pane) = self.pane_at(col, row)
                    {
                        self.focus_panel(pane);
                    }
                    if self.sidebar_width != drag.original {
                        return self.sidebar_width.map(Effect::SaveSidebarWidth);
                    }
                    return None;
                }
            }
        }
        if self.ssh_gate.is_some() {
            return None;
        }
        if kind == MouseAction::Down
            && !shift
            && !self.keys_open
            && self.confirm.is_none()
            && matches!(
                self.screen,
                Screen::Manage
                    | Screen::BootstrapSetup
                    | Screen::BootstrapPick
                    | Screen::HarnessPick
            )
            && self.panes.sidebar_divider.contains(col, row)
        {
            self.sidebar_drag = Some(SidebarDrag {
                start_column: col,
                start_row: row,
                start_width: self.panes.tree_outer.w,
                original: self.sidebar_width,
                moved: false,
            });
            self.selection = None;
            self.pending_copy = None;
            self.last_click = None;
            return None;
        }
        if self.screen == Screen::HarnessPick {
            if kind == MouseAction::Down {
                if self.panes.harness_use_bootstrap.contains(col, row) {
                    self.toggle_launch_bootstrap();
                } else if self.panes.harness_bootstrap.contains(col, row) {
                    return self.open_launch_bootstraps();
                } else if self.panes.harness_list.contains(col, row) {
                    let visible = harness_picker_indices(self.harness_pick?);
                    if let Some(index) = visible.get((row - self.panes.harness_list.y) as usize) {
                        self.harness_pick = Some(*index);
                    }
                }
            }
            return None;
        }
        if self.screen == Screen::BootstrapSetup {
            let form = self.bootstrap_form.as_mut()?;
            if form.running {
                return None;
            }
            if form.finished {
                if kind == MouseAction::Down && self.panes.bootstrap_fields[0].contains(col, row) {
                    return self
                        .on_key_bootstrap_setup(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
                }
                return None;
            }
            if kind == MouseAction::Down {
                if let Some(index) = self
                    .panes
                    .bootstrap_fields
                    .iter()
                    .position(|r| r.contains(col, row))
                {
                    form.field = index;
                    if index == form.default_field() || index == form.submit_field() {
                        return self.on_key_bootstrap_setup(KeyEvent::new(
                            KeyCode::Enter,
                            KeyModifiers::NONE,
                        ));
                    }
                    if index == 2 && form.snapshot.is_none() {
                        return self.on_key_bootstrap_setup(KeyEvent::new(
                            KeyCode::Right,
                            KeyModifiers::NONE,
                        ));
                    }
                    let field_box = self.panes.bootstrap_fields[index];
                    if let Some((value, cursor)) = form.text() {
                        let width = field_box.w.saturating_sub(4) as usize;
                        let start = super::bootstrap_setup::text_start(value, *cursor, width);
                        let clicked = col.saturating_sub(field_box.x + 2) as usize;
                        let mut used = 0;
                        *cursor = value.len();
                        for (i, c) in value[start..].char_indices() {
                            used += console::measure_text_width(&c.to_string());
                            if used > clicked {
                                *cursor = start + i;
                                break;
                            }
                        }
                    }
                }
            }
            return None;
        }
        if self.screen == Screen::BootstrapPick {
            let picker = self.bootstrap_picker.as_mut()?;
            if picker.loading || picker.saving {
                return None;
            }
            if self.panes.bootstrap_list.contains(col, row) {
                match kind {
                    MouseAction::Down => {
                        let index = self.panes.bootstrap_list_offset
                            + (row - self.panes.bootstrap_list.y) as usize;
                        if index < picker.entries.len() + 2 {
                            picker.cursor = index;
                            return self.choose_bootstrap();
                        }
                    }
                    MouseAction::ScrollUp => picker.cursor = picker.cursor.saturating_sub(1),
                    MouseAction::ScrollDown => {
                        picker.cursor = (picker.cursor + 1).min(picker.entries.len() + 1)
                    }
                    _ => {}
                }
            }
            return None;
        }
        if self.screen != Screen::Manage {
            return None;
        }
        match kind {
            // The wheel scrolls whichever pane it is over, without taking
            // focus: looking back through output is not the same as wanting to
            // type into it.
            MouseAction::ScrollUp | MouseAction::ScrollDown => {
                let up = kind == MouseAction::ScrollUp;
                if self.panes.session_outer.contains(col, row)
                    && let Some(index) = self.displayed_session_index()
                {
                    // Where the pointer is, in the pane's own coordinates —
                    // a wheel report carries a position, and an application
                    // may well care which pane region it is over.
                    let at = (
                        col.saturating_sub(self.panes.session.x) + 1,
                        row.saturating_sub(self.panes.session.y) + 1,
                    );
                    if let Some(session) = self.sessions.get_mut(index) {
                        session.scroll(up, 3, at);
                    }
                } else if self.panes.tree_outer.contains(col, row) {
                    self.move_cursor(if up { -1 } else { 1 });
                }
                None
            }
            MouseAction::Down => {
                if self.panes.bootstrap.contains(col, row) {
                    return self.open_bootstraps();
                }
                // A click clears the status line, the same as a keypress
                // (see on_key): the message answered the previous gesture,
                // and whatever this click means sets a fresh one — clicking
                // a disconnected session must not leave "not connected"
                // standing once the cursor is on a connected one.
                self.status.clear();
                // The maximized header's tabs: a click switches the pane.
                if self.pane_is_full()
                    && let Some(i) = (0..self.sessions.len().min(MAX_TABS))
                        .find(|&i| self.panes.tabs[i].contains(col, row))
                {
                    self.active = Some(i);
                    self.select_row_for_active();
                    return None;
                }
                // The prompt box is drawn in the session pane, but clicking it
                // means "let me type the task" — the keyboard for that lives
                // with the tree's New Session row, not with a session.
                if self.panes.prompt.contains(col, row) {
                    self.cursor = 0;
                    self.focus = ManageFocus::Tree;
                    self.prompt_focused = true;
                    return None;
                }
                let pane = self.pane_at(col, row)?;
                // An agent with clickable output — "click here to copy", a menu
                // you can point at — turns mouse reporting on and waits for the
                // events. Forward them, on three conditions: the pane already
                // has the keyboard, so the click that focuses it is still ours;
                // shift is not held, which is the terminal's own "this one is
                // mine"; and there is no plain link under the pointer, because
                // opening that is more useful than anything the app will do
                // with the click.
                if pane == ManageFocus::Session
                    && self.focus == ManageFocus::Session
                    && !shift
                    && self.url_at(col, row).is_none()
                    && self.send_pointer(session::Pointer::Press, col, row)
                {
                    self.pointer_to_app = true;
                    self.selection = None;
                    return None;
                }
                // Focus the displayed content. A disconnected thread's card
                // can take focus without opening a connection.
                let double = self.is_double_click(col, row);
                self.focus_panel(pane);
                let effect = (pane == ManageFocus::Tree && self.panes.tree.contains(col, row))
                    .then(|| self.click_tree_row(row, double))
                    .flatten();
                self.selection = Some(Selection {
                    pane,
                    anchor: (col, row),
                    cursor: (col, row),
                });
                effect
            }
            MouseAction::Drag => {
                if self.pointer_to_app {
                    self.send_pointer(session::Pointer::Drag, col, row);
                    return None;
                }
                let selection = self.selection.as_mut()?;
                // A drag stays in the pane it started in; leaving the pane
                // clamps rather than selecting across the divider.
                let pane = selection.pane;
                let bounds = match pane {
                    ManageFocus::Tree => self.panes.tree,
                    ManageFocus::Session => self.panes.session,
                };
                let col = col.clamp(bounds.x, bounds.x + bounds.w.saturating_sub(1));
                let row = row.clamp(bounds.y, bounds.y + bounds.h.saturating_sub(1));
                selection.cursor = (col, row);
                None
            }
            MouseAction::Up => {
                if self.pointer_to_app {
                    self.pointer_to_app = false;
                    self.send_pointer(session::Pointer::Release, col, row);
                    return None;
                }
                let click = self.selection.filter(|selection| selection.is_empty());
                match self.selection {
                    Some(selection) if !selection.is_empty() => {
                        self.pending_copy = Some(selection);
                    }
                    // A plain click is not a selection; drop it so the
                    // highlight does not linger over a single cell.
                    _ => self.selection = None,
                }
                // A click that went nowhere, on a link, opens it. On release
                // rather than on press, so that dragging *from* a link still
                // selects it — copying a URL and opening it are both things
                // people do, and the pointer moving is what tells them apart.
                let (col, row) = click?.anchor;
                let url = self.url_at(col, row)?;
                Some(Effect::OpenUrl(url))
            }
        }
    }

    pub fn resizing_sidebar(&self) -> bool {
        self.sidebar_drag.is_some()
    }

    fn drag_sidebar_to(&mut self, column: u16) {
        let Some(drag) = self.sidebar_drag else {
            return;
        };
        if column != drag.start_column
            && let Some(drag) = self.sidebar_drag.as_mut()
        {
            drag.moved = true;
        }
        if column == drag.start_column && self.sidebar_width == drag.original {
            return;
        }
        let requested = (i32::from(drag.start_width) + i32::from(column)
            - i32::from(drag.start_column))
        .clamp(0, i32::from(u16::MAX)) as u16;
        let available = self
            .panes
            .tree_outer
            .w
            .saturating_add(self.panes.session_outer.w);
        self.sidebar_width = Some(super::ui::sidebar_width(available, Some(requested)));
    }

    /// Two clicks on the same row inside the double-click window.
    fn is_double_click(&mut self, col: u16, row: u16) -> bool {
        const WINDOW: std::time::Duration = std::time::Duration::from_millis(400);
        let now = std::time::Instant::now();
        let double = self
            .last_click
            .is_some_and(|(at, when)| at == (col, row) && now.duration_since(when) < WINDOW);
        self.last_click = Some(((col, row), now));
        double
    }

    /// Move the tree cursor to the row that was clicked.
    ///
    /// A single click keeps the keyboard in the tree and shows the selected
    /// session. A double click focuses an open session or connects a
    /// disconnected one, the same as enter.
    fn click_tree_row(&mut self, row: u16, double: bool) -> Option<Effect> {
        if !self.click_tree_row_inner(row) {
            return None;
        }
        self.sync_active_to_cursor();
        let clicked = self.selected_row()?;
        // Clicking the launcher row is clicking the prompt.
        if matches!(clicked.kind, RowKind::NewSession) {
            self.prompt_focused = true;
            return None;
        }
        // A single click on an agent thread selects it (and asks for its
        // sessions, the same as arriving with the keyboard); a double click
        // connects, the same as enter.
        if let RowKind::Agent(w, p, e, a) = clicked.kind {
            if double {
                return self.connect_agent_row(w, p, e, a);
            }
            return self.auto_expand_agent();
        }
        // Anything with children toggles: clicking a folder to open it is the
        // one gesture every tree has.
        if let Some(expanded) = clicked.expanded {
            return self.set_expanded(clicked.kind, !expanded);
        }
        if let RowKind::Session(w, p, e, a, i) = clicked.kind {
            match self
                .console_session(w, p, e, a, i)
                .map(|s| s.name.clone())
                .and_then(|name| self.pane_for(&name))
            {
                // One click only selects — with the sidebar listing threads,
                // most rows are connected sessions, and a single click that handed the
                // keyboard over made the tree impossible to browse from a
                // focused pane. A double click (or enter) steps in.
                Some(index) => {
                    self.active = Some(index);
                    self.focus = if double {
                        ManageFocus::Session
                    } else {
                        ManageFocus::Tree
                    };
                }
                None if double => return self.reattach_row(clicked.kind),
                // No pane to focus: say how to get one, and re-ask the
                // platform while the hint is up — a row the agent no longer
                // reports validates away instead of inviting a reattach to
                // nothing.
                None => {
                    self.status = "Double-click (or enter) to connect".into();
                    let id = self.tree[w].projects[p].envs[e]
                        .agents_vec()
                        .get(a)?
                        .id
                        .clone();
                    return self.refresh_agent_sessions(&id);
                }
            }
        }
        None
    }

    /// Connect to an agent thread: enter on its row, or a double click.
    ///
    /// Connecting also retargets: the place you just opened is almost
    /// certainly where the next prompt should go.
    fn connect_agent_row(&mut self, w: usize, p: usize, e: usize, a: usize) -> Option<Effect> {
        let agent = self.tree[w].projects[p].envs[e].agents_vec().get(a)?;
        let id = agent.id.clone();
        if agent.status != "running" {
            self.status = format!(
                "{} is {} — press w to wake it first",
                agent.name, agent.status
            );
            return None;
        }
        let target = self.target_at((w, p, e))?;
        if matches!(
            agent.sessions,
            LoadSessions::NotLoaded | LoadSessions::Loading
        ) || self.thread_polls.contains(&id)
        {
            let fetching =
                matches!(agent.sessions, LoadSessions::Loading) || self.thread_polls.contains(&id);
            self.pending_agent_connect = Some(id.clone());
            self.status = "Finding this VM's coding agent…".into();
            if !fetching {
                self.thread_polls.insert(id.clone());
                if let Load::Loaded(agents) = &mut self.tree[w].projects[p].envs[e].agents {
                    agents[a].sessions = LoadSessions::Loading;
                }
                return Some(Effect::LoadSessions {
                    agent_id: id,
                    environment_id: target.environment_id,
                    path: (w, p, e, a),
                });
            }
            return None;
        }
        let primary = self
            .primary_harnesses
            .get(&id)
            .filter(|h| HARNESSES.contains(&h.as_str()))
            .cloned()
            .or_else(|| {
                let mut candidates: Vec<_> = self
                    .sessions
                    .iter()
                    .filter(|s| s.agent_id == id && s.harness != "shell")
                    .map(|s| s.harness.clone())
                    .collect();
                if let LoadSessions::Loaded(rows) = &agent.sessions {
                    candidates.extend(
                        rows.iter()
                            .filter_map(ConsoleSession::harness_slug)
                            .map(str::to_owned),
                    );
                }
                candidates.retain(|h| HARNESSES.contains(&h.as_str()));
                candidates.sort_unstable();
                candidates.dedup();
                (candidates.len() == 1).then(|| candidates[0].to_owned())
            });
        self.target = Some(target.clone());
        self.status.clear();
        let Some(primary) = primary else {
            self.begin_harness_pick(target, Some(id));
            self.harness_pick_connect = true;
            self.harness_pick = Some(0);
            return None;
        };
        self.connect_primary_agent(w, p, e, a, primary)
    }

    fn connect_primary_agent(
        &mut self,
        w: usize,
        p: usize,
        e: usize,
        a: usize,
        primary: String,
    ) -> Option<Effect> {
        let id = self.tree[w].projects[p].envs[e]
            .agents_vec()
            .get(a)?
            .id
            .clone();
        let target = self.target_at((w, p, e))?;
        if let Some(index) = self
            .sessions
            .iter()
            .position(|s| s.agent_id == id && s.harness == primary && !s.ended())
        {
            self.active = Some(index);
            self.focus = ManageFocus::Session;
            self.status = "Switched to the open session".into();
            return None;
        }
        if let Some(i) = self.first_live_session(w, p, e, a, &primary) {
            return self.reattach_row(RowKind::Session(w, p, e, a, i));
        }
        Some(Effect::Launch(LaunchRequest {
            project_id: target.project_id.clone(),
            environment_id: target.environment_id.clone(),
            agent_id: Some(id),
            session_name: None,
            force_new: false,
            new_session: false,
            harness: primary,
            prompt: None,
            label: target.label(),
            base: Default::default(),
        }))
    }

    /// Complete Enter only while the user is still on the VM they chose.
    pub(super) fn finish_agent_connect(&mut self, agent_id: &str) -> Option<Effect> {
        if self.pending_agent_connect.as_deref() != Some(agent_id) {
            return None;
        }
        self.pending_agent_connect = None;
        if self.screen != Screen::Manage || self.focus != ManageFocus::Tree {
            return None;
        }
        let RowKind::Agent(w, p, e, a) = self.selected_row()?.kind else {
            return None;
        };
        if self.tree[w].projects[p].envs[e].agents_vec().get(a)?.id != agent_id {
            return None;
        }
        self.connect_agent_row(w, p, e, a)
    }

    /// Resume a thread belonging to this VM's primary agent.
    fn first_live_session(
        &self,
        w: usize,
        p: usize,
        e: usize,
        a: usize,
        harness: &str,
    ) -> Option<usize> {
        let Load::Loaded(agents) = &self.tree.get(w)?.projects.get(p)?.envs.get(e)?.agents else {
            return None;
        };
        let LoadSessions::Loaded(sessions) = &agents.get(a)?.sessions else {
            return None;
        };
        sessions.iter().position(|session| {
            session.running
                && matches!(session.kind.as_str(), "SHELL" | "THREAD")
                && (session.harness_slug() == Some(harness)
                    || (harness == "shell" && session.is_shell()))
                && !self.ending.contains(&session.name)
        })
    }

    fn click_tree_row_inner(&mut self, row: u16) -> bool {
        let offset = row.saturating_sub(self.panes.tree.y) as usize;
        let rows = self.rows();
        // The list scrolls, so the clicked line is an offset from whatever is
        // at the top — which ratatui decides. Approximate with the same
        // window the widget would have chosen.
        let first = self.tree_scroll_offset(rows.len());
        if let Some(index) = first.checked_add(offset)
            && index < rows.len()
            && rows[index].selectable()
        {
            self.cursor = index;
            return true;
        }
        false
    }

    /// The first visible tree row, mirroring ratatui's scroll behaviour.
    fn tree_scroll_offset(&self, total: usize) -> usize {
        let height = self.panes.tree.h as usize;
        if height == 0 || total <= height {
            return 0;
        }
        self.cursor.saturating_sub(height - 1).min(total - height)
    }

    /// Begin showing the loading screen for a request. Takes the prompt with
    /// it: the task has been handed over, so the box should be empty when you
    /// come back to write the next one.
    pub fn start_loading(&mut self, req: &LaunchRequest) {
        self.clear_prompt();
        // Straight to Manage: the wait belongs in the pane the session will
        // appear in, with the tree beside it.
        self.screen = Screen::Manage;
        self.loading = Loading {
            target: req.label.clone(),
            harness: req.harness.clone(),
            active: true,
            prompt: req.prompt.clone(),
            steps: Vec::new(),
            tick: 0,
        };
    }

    /// The launch pipeline gave up. Land back in Manage with the reason, so a
    /// missing sign-in or a disabled feature is fixable without losing the tree.
    ///
    /// The reason rides an error toast over the pane rather than a header
    /// annotation: a failure squeezed in beside the wordmark reads as
    /// furniture, and this one usually carries the fix.
    pub fn launch_failed(&mut self, err: String) {
        self.loading.active = false;
        self.screen = Screen::Manage;
        let flat = err.split_whitespace().collect::<Vec<_>>().join(" ");
        self.toast_error(format!("Launch failed: {flat}"));
    }

    /// Advance the loading animation.
    pub fn tick(&mut self) {
        self.loading.tick = self.loading.tick.wrapping_add(1);
    }

    /// Record a step from the launch pipeline.
    pub fn loading_step(&mut self, text: String) {
        // Consecutive duplicates read as a stall rather than progress.
        if self.loading.steps.last() == Some(&text) {
            return;
        }
        self.loading.steps.push(text);
    }

    pub fn active_session(&self) -> Option<&super::session::Session> {
        self.active.and_then(|i| self.sessions.get(i))
    }

    /// The connection whose terminal output is actually visible. Tree
    /// navigation can show a detail card while another connection stays open.
    pub fn displayed_session_index(&self) -> Option<usize> {
        if self.loading.active {
            return None;
        }
        if self.focus == ManageFocus::Session || self.pane_is_full() {
            return self.active;
        }
        let kind = self.selected_row()?.kind;
        match kind {
            RowKind::Session(..) => self.pane_for_row(kind),
            _ => None,
        }
    }

    /// Show the pane belonging to the session row under the cursor, if it has
    /// one. Called after every cursor move: walking the tree is how sessions
    /// are switched now, so the pane follows the highlight.
    fn sync_active_to_cursor(&mut self) {
        let Some(row) = self.selected_row() else {
            return;
        };
        let RowKind::Session(w, p, e, a, i) = row.kind else {
            return;
        };
        let Some(name) = self
            .console_session(w, p, e, a, i)
            .map(|session| session.name.clone())
        else {
            return;
        };
        if let Some(index) = self.sessions.iter().position(|s| s.durable_name == name) {
            self.active = Some(index);
        }
    }

    /// The console session a row points at.
    pub fn console_session(
        &self,
        w: usize,
        p: usize,
        e: usize,
        a: usize,
        i: usize,
    ) -> Option<&ConsoleSession> {
        let Load::Loaded(agents) = &self.tree.get(w)?.projects.get(p)?.envs.get(e)?.agents else {
            return None;
        };
        let LoadSessions::Loaded(sessions) = &agents.get(a)?.sessions else {
            return None;
        };
        sessions.get(i)
    }

    /// Is this console session already open in a pane?
    fn pane_for(&self, name: &str) -> Option<usize> {
        self.sessions.iter().position(|s| s.durable_name == name)
    }

    /// The sessions the background auto-connect should attach right now:
    /// every listed session on a running agent that has no pane yet, each
    /// once per run. Marks what it returns as in flight, so the rows wear
    /// spinners and the next pass doesn't return them again.
    ///
    /// Empty while a connect could not quietly succeed: an unregistered key
    /// would land the pane on the relay's signup screen, the wizard means
    /// nothing is set up yet, and `railway code` came for its one session.
    pub fn take_auto_connects(&mut self) -> Vec<AutoConnect> {
        if self.quit_when_done
            || self.wizard.is_some()
            || !matches!(self.ssh_key, SshKeyState::Ready | SshKeyState::Unknown)
        {
            return Vec::new();
        }
        let mut out = Vec::new();
        let mut already_open = Vec::new();
        for ws in &self.tree {
            for proj in &ws.projects {
                for env in &proj.envs {
                    let Load::Loaded(agents) = &env.agents else {
                        continue;
                    };
                    for agent in agents {
                        // Only a green agent: attaching to a sleeping or
                        // waking VM would hang the pane, and the wake path
                        // reattaches on its own once the agent is up.
                        if agent.status != "running" || self.ops.contains_key(agent.id.as_str()) {
                            continue;
                        }
                        let LoadSessions::Loaded(sessions) = &agent.sessions else {
                            continue;
                        };
                        for session in sessions {
                            // `created_at` is only absent on the placeholders
                            // adopted from our own panes — already attached by
                            // definition.
                            if !session.is_interesting()
                                // Conversation history is resumable, not a list
                                // of processes to attach in the background.
                                || super::super::client_sessions::is_client(&session.name)
                                || session.created_at.is_none()
                                || self.ending.contains(&session.name)
                                || self.auto_attempted.contains(&session.name)
                            {
                                continue;
                            }
                            if self.pane_for(&session.name).is_some() {
                                // Attached by some other path; remember that,
                                // so closing the pane later doesn't get undone
                                // by the next sweep.
                                already_open.push(session.name.clone());
                                continue;
                            }
                            out.push(AutoConnect {
                                agent_id: agent.id.clone(),
                                agent_name: agent.name.clone(),
                                environment_id: env.id.clone(),
                                session_name: session.name.clone(),
                            });
                        }
                    }
                }
            }
        }
        self.auto_attempted.extend(already_open);
        // Bounded fan-out: an account with a dozen running agents must not
        // open every session's ssh at once — each attach is a relay
        // connection, a reader thread, and a full replay competing for the
        // render lock. Only what fits under the cap starts now; the rest are
        // left unmarked, and every completion wakes the loop, which calls
        // here again and takes the next batch.
        let budget = AUTO_CONNECT_INFLIGHT.saturating_sub(self.connecting.len());
        out.truncate(budget);
        for connect in &out {
            self.auto_attempted.insert(connect.session_name.clone());
            self.connecting.insert(connect.session_name.clone());
        }
        out
    }

    /// Adopt a session the background auto-connect opened. Quietly: the pane
    /// joins `sessions` and its row turns green, but focus, screen, cursor
    /// and prompt all stay where they are — coming up connected must not
    /// yank the keyboard out from under whatever is being typed.
    pub fn attach_session_background(
        &mut self,
        session: super::session::Session,
        agent_id: String,
    ) {
        self.connecting.remove(&session.durable_name);
        self.auto_attempted.insert(session.durable_name.clone());
        self.drop_seen.remove(&session.durable_name);
        // A pane opening proves a wake landed, same as a foreground attach.
        if self.ops.get(agent_id.as_str()) == Some(&AgentOp::Wake.pending_label()) {
            self.ops.remove(agent_id.as_str());
        }
        if self
            .watching
            .get(agent_id.as_str())
            .is_some_and(|w| w.want == "running")
        {
            self.watching.remove(agent_id.as_str());
        }
        self.sessions.push(session);
        self.adopt_pane_sessions();
    }

    /// A background attach didn't make it. Quietly again: the spinner comes
    /// off, the reason rides the status line rather than a toast, and the
    /// name stays attempted so the failure isn't retried in a loop —
    /// double-clicking the row still connects by hand.
    pub fn auto_connect_failed(&mut self, session_name: &str, err: &str) {
        self.connecting.remove(session_name);
        let flat = err.split_whitespace().collect::<Vec<_>>().join(" ");
        self.status = format!("Couldn't connect {session_name}: {flat}");
    }

    /// Adopt a freshly opened session, make it active, and focus it.
    ///
    /// Appended rather than replacing: several agents can be working at once,
    /// and closing one because another opened would throw away a running task.
    pub fn attach_session(&mut self, session: super::session::Session, agent_id: String) {
        self.loading.active = false;
        self.connecting.remove(&session.durable_name);
        self.auto_attempted.insert(session.durable_name.clone());
        self.drop_seen.remove(&session.durable_name);
        // A pane just opened on this agent, so a wake we were waiting for has
        // demonstrably landed — whatever the status projection still says. Left
        // alone, `waking…` would sit on the row until a poll happened to catch
        // `running`, and the 1.5s watch tick would keep asking the environment
        // for up to WAKE_PATIENCE about an agent already taking keystrokes.
        // Sleep and delete are not settled by this: neither is proven by a pane
        // opening, and a delete is about to take the row away regardless.
        if self.ops.get(agent_id.as_str()) == Some(&AgentOp::Wake.pending_label()) {
            self.ops.remove(agent_id.as_str());
        }
        if self
            .watching
            .get(agent_id.as_str())
            .is_some_and(|w| w.want == "running")
        {
            self.watching.remove(agent_id.as_str());
        }
        // The session is what was opened, so that is what the cursor should be
        // on. The agent is only a fallback for a session whose row does not
        // exist yet — a fresh launch, whose session list has not come back.
        self.pending_select_session = Some(self.sessions_next_name(&session));
        self.pending_select = Some(agent_id);
        self.sessions.push(session);
        self.active = Some(self.sessions.len() - 1);
        self.focus = ManageFocus::Session;
        self.screen = Screen::Manage;
        self.clear_prompt();
        self.status.clear();
        // The session just opened is a fact; put it in the tree now rather
        // than after the platform lists it (this also lands the cursor on it).
        self.adopt_pane_sessions();
        if self.pending_select_session.is_none() {
            // Landed on the session; the agent fallback is not needed.
            self.pending_select = None;
        } else {
            self.select_pending();
        }
    }

    /// Fold every open pane's session into the tree, ahead of the platform.
    ///
    /// We opened these sessions ourselves — the pane is attached over ssh —
    /// so waiting for `cloudAgentConsoleSessions` to list them is waiting for
    /// the relay's bookkeeping to catch up with a fact we already know. On a
    /// fresh agent that wait was the whole story: the settle refreshes fired
    /// before the agent row existed, and the session showed up disconnected-
    /// looking (or not at all) until the next sweep. Called after every load,
    /// so a platform reply that hasn't caught up yet can't erase the row; the
    /// reply that has simply replaces it with the real record.
    pub fn adopt_pane_sessions(&mut self) {
        // First, reconcile names. The relay registers a session under a name
        // of its own — the one the client sent rides along only as an env
        // stamp — so once the platform lists the session a pane opened, that
        // listing's name is the durable identity: reattach, copy-ssh and kill
        // all go by it. The pane we hold takes the listed name over the one it
        // was minted with, and the placeholder row under the minted name
        // vanishes with the rename. Matched conservatively: only a listed
        // session that is running, `attached` (we demonstrably are), and not
        // already claimed by another pane — newest first when several fit.
        for i in 0..self.sessions.len() {
            if self.sessions[i].ended()
                || super::super::client_sessions::is_client(&self.sessions[i].durable_name)
            {
                continue;
            }
            let agent_id = self.sessions[i].agent_id.clone();
            let minted = self.sessions[i].durable_name.clone();
            let listed = self.agent_session_names(&agent_id);
            if listed.is_empty() || listed.iter().any(|(name, ..)| *name == minted) {
                continue;
            }
            let claimed: std::collections::HashSet<String> = self
                .sessions
                .iter()
                .map(|pane| pane.durable_name.clone())
                .collect();
            let real = listed
                .into_iter()
                .filter(|(name, attached, running, _)| {
                    // Never adopt a name whose attach is in flight: the
                    // auto-connect that dialed it is about to land a pane
                    // under that exact name, and two panes sharing a durable
                    // name would misroute reattach/copy-ssh/kill by
                    // first-match.
                    *attached
                        && *running
                        && !claimed.contains(name)
                        && !self.connecting.contains(name.as_str())
                })
                .max_by_key(|(_, _, _, created)| *created)
                .map(|(name, ..)| name);
            if let Some(real) = real {
                if self.pending_select_session.as_deref() == Some(minted.as_str()) {
                    self.pending_select_session = Some(real.clone());
                }
                // The listed name is attached now, whatever it was minted as —
                // auto-connect must treat it as already tried.
                self.auto_attempted.insert(real.clone());
                if self.sessions[i].console_name.is_some() {
                    self.sessions[i].console_name = Some(real.clone());
                }
                self.sessions[i].durable_name = real;
            }
        }

        // Then adopt what is still missing: a pane whose session the platform
        // has not listed yet gets a placeholder row, so a fresh launch shows
        // selected and connected instead of waiting on the relay's
        // bookkeeping. The reconciliation above retires it as soon as the
        // real record lands.
        let panes: Vec<_> = self
            .sessions
            .iter()
            .filter(|pane| !pane.ended())
            .map(|pane| {
                (
                    pane.agent_id.clone(),
                    pane.durable_name.clone(),
                    pane.client_thread.clone(),
                )
            })
            .collect();
        for (agent_id, name, thread) in panes {
            if self.deleted_threads.contains(&name) {
                continue;
            }
            'tree: for ws in &mut self.tree {
                for proj in &mut ws.projects {
                    for env in &mut proj.envs {
                        let Load::Loaded(agents) = &mut env.agents else {
                            continue;
                        };
                        let Some(agent) = agents.iter_mut().find(|a| a.id == agent_id) else {
                            continue;
                        };
                        let ours = if let Some((harness, _, _)) =
                            super::super::client_sessions::parse_name(&name)
                        {
                            let mut row =
                                ConsoleSession::client_thread(&agent_id, harness, thread.as_ref());
                            row.name = name.clone();
                            row
                        } else {
                            ConsoleSession {
                                name: name.clone(),
                                kind: "SHELL".into(),
                                command: None,
                                running: true,
                                attached: true,
                                created_at: None,
                                snapshot: None,
                            }
                        };
                        match &mut agent.sessions {
                            LoadSessions::Loaded(sessions) => {
                                if !sessions.iter().any(|s| s.name == name) {
                                    sessions.push(ours);
                                }
                            }
                            other => *other = LoadSessions::Loaded(vec![ours]),
                        }
                        break 'tree;
                    }
                }
            }
        }
        self.select_pending_session();
    }

    fn delete_thread_row(
        &mut self,
        w: usize,
        p: usize,
        e: usize,
        a: usize,
        i: usize,
    ) -> Option<Effect> {
        let env = self.tree.get_mut(w)?.projects.get_mut(p)?.envs.get_mut(e)?;
        let Load::Loaded(agents) = &mut env.agents else {
            return None;
        };
        let agent = agents.get_mut(a)?;
        let LoadSessions::Loaded(rows) = &mut agent.sessions else {
            return None;
        };
        let row = rows.get(i)?.clone();
        if !self.deleted_threads.insert(row.name.clone()) {
            return None;
        }
        let agent_id = agent.id.clone();
        let environment_id = env.id.clone();
        let name = row.name.clone();
        let mut order = self
            .deleting_threads
            .values()
            .find(|d| d.environment == environment_id && d.agent_id == agent_id)
            .map(|d| d.order.clone())
            .unwrap_or_default();
        for row in rows.iter() {
            if !order.contains(&row.name) {
                order.push(row.name.clone());
            }
        }
        rows.remove(i);
        self.deleting_threads.insert(
            name.clone(),
            DeletedThread {
                environment: environment_id.clone(),
                agent_id: agent_id.clone(),
                order,
                row,
            },
        );
        self.connecting.remove(&name);
        if self.pending_select_session.as_deref() == Some(&name) {
            self.pending_select_session = None;
        }
        self.clamp_cursor();
        self.persist_threads(&agent_id);
        Some(Effect::DeleteThread {
            agent_id,
            environment_id,
            session_name: name,
        })
    }

    pub(super) fn thread_deleted(&mut self, name: &str, error: Option<String>) {
        let Some(DeletedThread {
            environment,
            agent_id,
            order,
            row,
        }) = self.deleting_threads.remove(name)
        else {
            return;
        };
        if let Some(error) = error {
            self.deleted_threads.remove(name);
            let selected = self.selected_row().and_then(|r| match r.kind {
                RowKind::Session(w, p, e, a, i) => {
                    self.console_session(w, p, e, a, i).map(|r| r.name.clone())
                }
                _ => None,
            });
            for ws in &mut self.tree {
                for project in &mut ws.projects {
                    for env in &mut project.envs {
                        if env.id != environment {
                            continue;
                        }
                        let Load::Loaded(agents) = &mut env.agents else {
                            continue;
                        };
                        let Some(agent) = agents.iter_mut().find(|a| a.id == agent_id) else {
                            continue;
                        };
                        match &mut agent.sessions {
                            LoadSessions::Loaded(rows) if !rows.iter().any(|r| r.name == name) => {
                                let index = order
                                    .iter()
                                    .skip_while(|id| id.as_str() != name)
                                    .skip(1)
                                    .find_map(|id| rows.iter().position(|r| &r.name == id))
                                    .unwrap_or(rows.len());
                                rows.insert(index, row.clone())
                            }
                            LoadSessions::Loaded(_) => {}
                            other => *other = LoadSessions::Loaded(vec![row.clone()]),
                        }
                    }
                }
            }
            if let Some(selected) = selected {
                self.pending_select_session = Some(selected);
                self.select_pending_session();
            }
            self.toast_error(format!("Couldn't delete {}: {error}", row.short_name()));
        }
        self.persist_threads(&agent_id);
    }

    /// A native client selected a conversation; adopt its exact provider ID.
    pub(super) fn client_thread_selected(
        &mut self,
        client_id: &str,
        thread: super::super::client_sessions::Thread,
    ) -> Option<String> {
        let index = self
            .sessions
            .iter()
            .position(|s| s.client_id.as_deref() == Some(client_id))?;
        Some(self.adopt_thread(index, thread))
    }

    fn adopt_thread(
        &mut self,
        index: usize,
        thread: super::super::client_sessions::Thread,
    ) -> String {
        let old = self.sessions[index].durable_name.clone();
        let selected = self.selected_row().is_some_and(|row| {
            if let RowKind::Session(w, p, e, a, i) = row.kind {
                self.console_session(w, p, e, a, i)
                    .is_some_and(|row| row.name == old)
            } else {
                false
            }
        });
        let pane = &mut self.sessions[index];
        let agent_id = pane.agent_id.clone();
        let draft =
            super::super::client_sessions::parse_name(&old).is_none_or(|(_, _, id)| id.is_none());
        let name = super::super::client_sessions::name(&pane.harness, &agent_id, Some(&thread.id));
        if self.deleted_threads.contains(&name) {
            return agent_id;
        }
        let row = ConsoleSession::client_thread(&agent_id, &pane.harness, Some(&thread));
        pane.durable_name = name.clone();
        pane.client_thread = Some(thread);
        if selected || self.pending_select_session.as_deref() == Some(&old) {
            self.pending_select_session = Some(name.clone());
        }
        self.connecting.remove(&old);
        self.auto_attempted.insert(name.clone());
        for ws in &mut self.tree {
            for project in &mut ws.projects {
                for env in &mut project.envs {
                    let Load::Loaded(agents) = &mut env.agents else {
                        continue;
                    };
                    let Some(agent) = agents.iter_mut().find(|a| a.id == agent_id) else {
                        continue;
                    };
                    let LoadSessions::Loaded(rows) = &mut agent.sessions else {
                        continue;
                    };
                    if let Some(i) = rows.iter().position(|r| r.name == old && draft) {
                        rows[i] = row.clone();
                        let mut index = 0;
                        rows.retain(|r| {
                            let keep = r.name != name || index == i;
                            index += 1;
                            keep
                        });
                    } else if let Some(existing) = rows.iter_mut().find(|r| r.name == name) {
                        *existing = row.clone();
                    } else {
                        rows.push(row.clone());
                    }
                }
            }
        }
        self.adopt_pane_sessions();
        agent_id
    }

    /// What a maximized-header tab says for the pane at `index`: the
    /// session's own label — its seeded task, or its harness-led name — not
    /// the agent it happens to run on. Falls back to the pane's durable name
    /// while the platform hasn't listed the session yet.
    pub fn session_tab_label(&self, index: usize) -> String {
        let Some(pane) = self.sessions.get(index) else {
            return String::new();
        };
        for ws in &self.tree {
            for proj in &ws.projects {
                for env in &proj.envs {
                    let Load::Loaded(agents) = &env.agents else {
                        continue;
                    };
                    let Some(agent) = agents.iter().find(|a| a.id == pane.agent_id) else {
                        continue;
                    };
                    if let LoadSessions::Loaded(sessions) = &agent.sessions
                        && let Some(session) = sessions.iter().find(|s| s.name == pane.durable_name)
                    {
                        return truncate(&session.short_name(), 20);
                    }
                }
            }
        }
        truncate(&pane.durable_name, 20)
    }

    /// The session pane's title, read like a project reference:
    /// `project / agent / session`. The session leg is the listed session's
    /// short name once the platform has it, the pane's durable name until
    /// then; the project leg drops off when the agent isn't in the tree yet,
    /// leaving `agent / session` rather than a hole.
    pub fn pane_breadcrumb(&self, pane: &super::session::Session) -> String {
        let mut project = None;
        let mut session = None;
        'tree: for ws in &self.tree {
            for proj in &ws.projects {
                for env in &proj.envs {
                    let Load::Loaded(agents) = &env.agents else {
                        continue;
                    };
                    let Some(agent) = agents.iter().find(|a| a.id == pane.agent_id) else {
                        continue;
                    };
                    project = Some(proj.name.clone());
                    if let LoadSessions::Loaded(sessions) = &agent.sessions
                        && let Some(listed) = sessions.iter().find(|s| s.name == pane.durable_name)
                    {
                        session = Some(listed.short_name());
                    }
                    break 'tree;
                }
            }
        }
        let session = session.unwrap_or_else(|| pane.durable_name.clone());
        match project {
            Some(project) => format!("{project} / {} / {session}", pane.agent_name),
            None => format!("{} / {session}", pane.agent_name),
        }
    }

    /// Every session the platform lists for an agent, as
    /// `(name, attached, running, created_at)` — the fields pane
    /// reconciliation matches on.
    #[allow(clippy::type_complexity)]
    fn agent_session_names(
        &self,
        agent_id: &str,
    ) -> Vec<(String, bool, bool, Option<chrono::DateTime<chrono::Utc>>)> {
        for ws in &self.tree {
            for proj in &ws.projects {
                for env in &proj.envs {
                    let Load::Loaded(agents) = &env.agents else {
                        continue;
                    };
                    let Some(agent) = agents.iter().find(|a| a.id == agent_id) else {
                        continue;
                    };
                    let LoadSessions::Loaded(sessions) = &agent.sessions else {
                        return Vec::new();
                    };
                    return sessions
                        .iter()
                        // Placeholders carry no timestamp; only platform
                        // records can be adopted as a pane's real name.
                        .filter(|s| s.created_at.is_some())
                        .filter(|s| s.is_shell())
                        .map(|s| (s.name.clone(), s.attached, s.running, s.created_at))
                        .collect();
                }
            }
        }
        Vec::new()
    }

    /// Show an already-open session. Returns false when there isn't one.
    ///
    /// A pane whose connection has ended doesn't count — "connect" must not
    /// resolve to a corpse — and asking for the agent again is the natural
    /// moment to clear such panes out of the way of the fresh connection.
    pub fn activate_session(&mut self, agent_id: &str) -> bool {
        match self
            .sessions
            .iter()
            .position(|s| s.agent_id == agent_id && !s.ended())
        {
            Some(i) => {
                self.active = Some(i);
                self.focus = ManageFocus::Session;
                true
            }
            None => {
                while let Some(i) = self.sessions.iter().position(|s| s.agent_id == agent_id) {
                    drop(self.take_session(i));
                }
                false
            }
        }
    }

    /// Drop a session's local half without sleeping its agent — for handing
    /// the same session to a full-screen client, which needs the box awake.
    pub fn detach_session(&mut self, index: usize) -> Option<super::session::Session> {
        self.take_session(index)
    }

    /// User-requested discovery on one running machine, coalesced in flight.
    pub fn refresh_agent_sessions(&mut self, agent_id: &str) -> Option<Effect> {
        if self.thread_refreshing(agent_id) {
            return None;
        }
        for w in 0..self.tree.len() {
            for p in 0..self.tree[w].projects.len() {
                for e in 0..self.tree[w].projects[p].envs.len() {
                    let Load::Loaded(agents) = &self.tree[w].projects[p].envs[e].agents else {
                        continue;
                    };
                    let Some(a) = agents.iter().position(|agent| agent.id == agent_id) else {
                        continue;
                    };
                    if agents[a].status != "running" {
                        return None;
                    }
                    return Some(Effect::LoadSessions {
                        agent_id: agent_id.to_string(),
                        environment_id: self.tree[w].projects[p].envs[e].id.clone(),
                        path: (w, p, e, a),
                    });
                }
            }
        }
        None
    }

    /// Remove a session by index, keeping `active` pointing at something real.
    pub fn take_session(&mut self, index: usize) -> Option<super::session::Session> {
        if index >= self.sessions.len() {
            return None;
        }
        let session = self.sessions.remove(index);
        let had_active = self.active.is_some();
        self.active = self.active.and_then(|active| {
            if self.sessions.is_empty() {
                None
            } else {
                Some(if active > index {
                    active - 1
                } else {
                    active.min(self.sessions.len() - 1)
                })
            }
        });
        if self.sessions.is_empty() && had_active && self.focus != ManageFocus::Tree {
            self.focus = ManageFocus::Tree;
        }
        self.unmaximize_without_a_session();
        Some(session)
    }

    /// Close panes whose ssh finished — the harness exited and the remote
    /// command ran out.
    ///
    /// The reader thread flips `ended` and wakes the loop, which lands here.
    /// With the pane remote command's shell fallback gone, "finished" now
    /// includes ctrl-c: interrupting the agent out of existence ends the
    /// session rather than dropping into a VM shell inside the frame. Only a
    /// clean exit reaps (see [`Session::finished`]): a dropped connection or
    /// a failed connect exits nonzero, and that pane stays up — it holds the
    /// only account of what happened, and the recovery keys can reconnect it.
    /// When the last pane closes under `railway code`, the TUI leaves with it
    /// — see [`Self::quit_when_done`].
    /// A finish this soon after connecting is a harness that cannot start;
    /// replacing it would just watch it die again, forever.
    const RESPAWN_MIN_AGE: std::time::Duration = std::time::Duration::from_secs(10);

    /// Keystrokes this close to the end mean the user ended it themselves —
    /// ctrl-c, ctrl-d, and `/exit` all arrive as input moments before ssh
    /// does. A respawn then would undo the gesture.
    const DELIBERATE_EXIT_WINDOW: std::time::Duration = std::time::Duration::from_secs(5);

    pub fn reap_ended_sessions(&mut self) -> Option<Effect> {
        let mut closed = None;
        let mut respawn = None;
        let mut i = 0;
        while i < self.sessions.len() {
            if self.sessions[i].finished() {
                // Judged before the take, while the pane still knows: only
                // the session the user was typing into earns a replacement,
                // and only when nothing says they ended it on purpose. A
                // background pane ending must never conjure sessions the
                // user is not looking at.
                let watched = self.screen == Screen::Manage
                    && self.focus == ManageFocus::Session
                    && self.active == Some(i);
                let unasked = !self.sessions[i].input_within(Self::DELIBERATE_EXIT_WINDOW);
                let settled = self.sessions[i].age() >= Self::RESPAWN_MIN_AGE;
                // Dropping the session detaches its local half; the agent
                // stays running (sleeping is deliberate, never a side effect).
                if let Some(session) = self.take_session(i) {
                    if watched
                        && unasked
                        && settled
                        && !super::super::client_sessions::is_client(&session.durable_name)
                    {
                        respawn = Some((session.agent_id.clone(), session.harness.clone()));
                    }
                    closed = Some(session.agent_name.clone());
                }
            } else {
                i += 1;
            }
        }
        self.notice_dropped_panes();
        let agent_name = closed?;
        if self.quit_when_done && self.sessions.is_empty() {
            self.exit_note = Some(format!(
                "Session ended — agent {agent_name} is still running. `railway ca sleep {agent_name}` stops the compute bill."
            ));
            return Some(Effect::Quit);
        }
        // The session died out from under the user: start a fresh one on the
        // same agent so the pane they were working in comes back, rather than
        // leaving them at a toast. Skipped when another pane on the agent is
        // still up (that one is the work now), and while a dialog owns the
        // keyboard — a launch underneath a y/n would race its answer.
        if let Some((agent_id, harness)) = respawn
            && !self.sessions.iter().any(|s| s.agent_id == agent_id)
            && self.confirm.is_none()
            && self.ssh_gate.is_none()
            && let Some(effect) = self.respawn_on(&agent_id, &harness)
        {
            self.toast(format!(
                "Session on {agent_name} ended — starting a new one"
            ));
            return Some(effect);
        }
        self.toast(format!("Session on {agent_name} ended"));
        None
    }

    /// A replacement session for one that died unasked (see the respawn arm
    /// of [`Self::reap_ended_sessions`]).
    ///
    /// Deliberately not [`Self::launch`]: that reads the launcher's draft, and
    /// a respawn must not submit whatever half-sentence is sitting in the
    /// prompt box. Same harness as the session that died, a fresh durable
    /// session (`force_new` — the old one exited with its harness), and only
    /// onto a machine the platform still says is running: waking an agent is
    /// a gesture, never a reap side effect.
    fn respawn_on(&mut self, agent_id: &str, harness: &str) -> Option<Effect> {
        for w in 0..self.tree.len() {
            for p in 0..self.tree[w].projects.len() {
                for e in 0..self.tree[w].projects[p].envs.len() {
                    let agents = self.tree[w].projects[p].envs[e].agents_vec();
                    let Some(agent) = agents.iter().find(|agent| agent.id == agent_id) else {
                        continue;
                    };
                    if agent.status != "running" {
                        return None;
                    }
                    let target = self.target_at((w, p, e))?;
                    let harness = if harness.is_empty() {
                        self.harness_name().to_string()
                    } else {
                        harness.to_string()
                    };
                    return Some(Effect::Launch(LaunchRequest {
                        project_id: target.project_id.clone(),
                        environment_id: target.environment_id.clone(),
                        agent_id: Some(agent_id.to_string()),
                        session_name: None,
                        force_new: true,
                        new_session: false,
                        harness,
                        prompt: None,
                        label: target.label(),
                        base: Default::default(),
                    }));
                }
            }
        }
        None
    }

    /// A reconnect aimed at a session the agent no longer has — it closed, or
    /// the machine died and came back without it. Connecting was the ask, so
    /// the answer is a fresh session on that agent, not an error: the stale
    /// row goes now (the platform just said it does not exist), and the
    /// replacement runs the harness the row named where it still names one.
    pub fn reattach_target_gone(
        &mut self,
        agent_id: &str,
        agent_name: &str,
        session_name: &str,
    ) -> Option<Effect> {
        self.connecting.remove(session_name);
        let harness = self
            .remove_session_row(agent_id, session_name)
            .unwrap_or_default();
        if let Some(effect) = self.respawn_on(agent_id, &harness) {
            self.toast(format!(
                "Session {session_name} is gone — starting a new one"
            ));
            return Some(effect);
        }
        // No replacement to offer — the agent stopped running underneath the
        // reconnect. Say what happened and re-ask for the list, so the tree
        // settles on the truth rather than the row that just misled us.
        self.toast_error(format!(
            "Session {session_name} is gone, and {agent_name} isn't running"
        ));
        self.refresh_agent_sessions(agent_id)
    }

    /// Drop one session row from the tree — the platform just said the
    /// session does not exist — returning the harness it claimed to run, for
    /// a replacement to launch.
    fn remove_session_row(&mut self, agent_id: &str, session_name: &str) -> Option<String> {
        let mut harness = None;
        'search: for ws in &mut self.tree {
            for project in &mut ws.projects {
                for env in &mut project.envs {
                    let Load::Loaded(agents) = &mut env.agents else {
                        continue;
                    };
                    let Some(agent) = agents.iter_mut().find(|agent| agent.id == agent_id) else {
                        continue;
                    };
                    let LoadSessions::Loaded(sessions) = &mut agent.sessions else {
                        break 'search;
                    };
                    let Some(i) = sessions.iter().position(|s| s.name == session_name) else {
                        break 'search;
                    };
                    harness = sessions.remove(i).harness_slug().map(str::to_string);
                    break 'search;
                }
            }
        }
        self.clamp_cursor();
        harness
    }

    /// A pane whose connection just DIED (rather than finished) pulls the
    /// keyboard to itself, once: its banner says "r reconnects", and r has to
    /// mean that immediately — not the tree's refresh — without needing a
    /// click first. Once per drop: Esc-ing back to the tree sticks, and a
    /// reconnected pane that drops again gets to announce itself again.
    ///
    /// Only the pane on screen: a background pane (an auto-connect the user
    /// never opened) dropping must not yank the keyboard out from under
    /// whatever they are doing — its banner waits on its row. And never over
    /// a dialog or the launcher prompt: a y/n mid-answer or a sentence
    /// mid-typing would route keystrokes into the corpse, where a stray `x`
    /// closes it.
    fn notice_dropped_panes(&mut self) {
        for i in 0..self.sessions.len() {
            if !self.sessions[i].dropped() {
                continue;
            }
            let name = self.sessions[i].durable_name.clone();
            if !self.drop_seen.insert(name) {
                continue;
            }
            if self.screen == Screen::Manage
                && self.active == Some(i)
                && !self.launcher_selected()
                && self.confirm.is_none()
                && self.ssh_gate.is_none()
            {
                self.focus = ManageFocus::Session;
            }
        }
    }

    /// Any pane that has ended but whose finished/dropped call is still
    /// waiting on ssh's exit status. The loop polls briefly while this holds
    /// — the EOF that woke it can beat waitpid, and nothing else would wake
    /// the loop again to ask.
    pub fn awaiting_exit_status(&self) -> bool {
        self.sessions.iter().any(|s| s.awaiting_exit_status())
    }

    /// Hand the whole terminal to the session under the cursor.
    ///
    /// ⌥enter is the intended chord, but plenty of terminals do not send a
    /// modifier with Enter at all, so `f` does the same thing.
    ///
    /// Deliberately not shift+enter: that one belongs to the harness, where it
    /// is the newline every text field gives you. This binding only ever fires
    /// with the tree focused, so ⌥enter inside a session still reaches the
    /// agent as `ESC CR` — which is the other newline chord harnesses take.
    fn full_screen_current(&mut self) -> Option<Effect> {
        // The row under the cursor if it names a session, else whatever the
        // pane is showing.
        if let Some(row) = self.selected_row()
            && let RowKind::Session(w, p, e, a, i) = row.kind
            && let Some(session) = self.console_session(w, p, e, a, i)
        {
            let name = session.name.clone();
            if super::super::client_sessions::is_client(&name) {
                self.maximized = true;
                return self.reattach_row(row.kind);
            }
            let (agent_id, agent_name) = self.agent_at(w, p, e, a)?;
            return Some(Effect::FullScreen {
                agent_id,
                session_name: name,
                agent_name,
            });
        }
        let session = self.sessions.get(self.active?)?;
        if super::super::client_sessions::is_client(&session.durable_name) {
            self.maximized = true;
            return None;
        }
        Some(Effect::FullScreen {
            agent_id: session.agent_id.clone(),
            session_name: session.durable_name.clone(),
            agent_name: session.agent_name.clone(),
        })
    }

    /// Choose the VM the user is looking at, never the default launch target
    /// or a different pane when the tree has focus.
    fn shell_agent(&self) -> Option<(String, String)> {
        if self.focus == ManageFocus::Session && self.active.is_some() {
            let session = self.active_session()?;
            return Some((session.agent_id.clone(), session.agent_name.clone()));
        }
        match self.selected_row()?.kind {
            RowKind::Agent(w, p, e, a) | RowKind::Session(w, p, e, a, _) => {
                self.agent_at(w, p, e, a)
            }
            _ => None,
        }
    }

    fn open_shell(&mut self) -> Option<Effect> {
        let Some((agent_id, agent_name)) = self.shell_agent() else {
            self.status = "Select a VM to open an SSH shell".into();
            return None;
        };
        Some(Effect::OpenShell {
            agent_id,
            agent_name,
        })
    }

    /// Keys for a pane whose connection is gone — its ssh exited (ended) or
    /// its attach is streaming nothing (stalled).
    ///
    /// Reconnect, close, or step back out; everything else is swallowed
    /// rather than written into a pty nothing is reading. Enter is taken as
    /// reconnect because it is the reflex after "connection closed", and
    /// reconnecting is the only thing it could mean here.
    fn dead_pane_key(&mut self, index: usize, key: KeyEvent) -> Option<Effect> {
        match key.code {
            KeyCode::Char('r') | KeyCode::Char('R') | KeyCode::Enter => {
                self.reconnect_session(index)
            }
            KeyCode::Char('x') | KeyCode::Char('X') => Some(Effect::CloseSession { index }),
            // Nothing in the pane can receive an Escape any more, so it
            // releases to the tree — the same place the release chords go.
            KeyCode::Esc => {
                self.focus = ManageFocus::Tree;
                self.maximized = false;
                None
            }
            _ => None,
        }
    }

    /// Drop a pane whose connection died and dial its durable session again.
    ///
    /// Through [`Effect::Reattach`] rather than respawning ssh from the
    /// pane's stored plumbing: the reattach path re-resolves the identity and
    /// passes the ssh-key gate, so a key deregistered mid-session gets the
    /// gate's question instead of another connection that dies the same way.
    fn reconnect_session(&mut self, index: usize) -> Option<Effect> {
        let session = self.take_session(index)?;
        let Some(environment_id) = session.environment_id() else {
            // A target that isn't `agent:<env>:<id>` has nothing to resolve;
            // the session row in the tree still knows how to reach it.
            self.toast_error("Couldn't resolve this session — reconnect from its row in the tree");
            return None;
        };
        self.status = format!("Reconnecting to {}", session.durable_name);
        Some(Effect::Reattach {
            agent_id: session.agent_id.clone(),
            agent_name: session.agent_name.clone(),
            environment_id,
            session_name: session.durable_name.clone(),
        })
    }

    /// Connect to a session row: show its pane if we have one, else reattach.
    fn reattach_row(&mut self, kind: RowKind) -> Option<Effect> {
        let RowKind::Session(w, p, e, a, i) = kind else {
            return None;
        };
        let name = self.console_session(w, p, e, a, i)?.name.clone();
        let (agent_id, agent_name) = self.agent_at(w, p, e, a)?;
        self.target = self.target_at((w, p, e));

        // An attach already in flight — usually the startup auto-connect —
        // would race a second ssh onto the same session.
        if self.connecting.contains(&name) {
            self.status = format!("Connecting to {name}");
            return None;
        }

        // Already open: this means "put me in it", not "open another one" —
        // unless the pane's connection has died, in which case "connect"
        // means what it says. Focusing the corpse was a trap: the dead pane
        // blocked every reattach to its session until someone discovered
        // that `x` on the *agent* row closes panes.
        if let Some(index) = self.pane_for(&name) {
            if self.sessions[index].ended() {
                drop(self.take_session(index));
            } else {
                self.active = Some(index);
                self.focus = ManageFocus::Session;
                return None;
            }
        }
        // Not open: reconnect straight to it. Reattaching needs no credential,
        // no skills sync and no provisioning — the agent is already set up,
        // which is what makes this instant rather than a launch.
        let environment_id = self.tree[w].projects[p].envs[e].id.clone();
        let status = self
            .agent_status(w, p, e, a)
            .unwrap_or_else(|| "unknown".into());
        if status != "running" {
            self.status = format!("{agent_name} is {status} — press w to wake it first");
            return None;
        }
        Some(Effect::Reattach {
            agent_id,
            agent_name,
            environment_id,
            session_name: name,
        })
    }

    /// The status of the agent the cursor is on, directly or via a session.
    /// The footer uses it to offer sleep or wake, never both.
    pub fn selected_agent_status(&self) -> Option<String> {
        let row = self.selected_row()?;
        let (w, p, e, a) = match row.kind {
            RowKind::Agent(w, p, e, a) | RowKind::Session(w, p, e, a, _) => (w, p, e, a),
            _ => return None,
        };
        self.agent_status(w, p, e, a)
    }

    /// The open pane a row refers to: a session's own, or the first one on an
    /// agent.
    pub fn pane_for_row(&self, kind: RowKind) -> Option<usize> {
        match kind {
            RowKind::Session(w, p, e, a, i) => {
                let name = self.console_session(w, p, e, a, i)?.name.clone();
                self.pane_for(&name)
            }
            RowKind::Agent(w, p, e, a) => {
                let (agent_id, _) = self.agent_at(w, p, e, a)?;
                self.sessions.iter().position(|s| s.agent_id == agent_id)
            }
            _ => None,
        }
    }

    fn agent_status(&self, w: usize, p: usize, e: usize, a: usize) -> Option<String> {
        let Load::Loaded(agents) = &self.tree.get(w)?.projects.get(p)?.envs.get(e)?.agents else {
            return None;
        };
        Some(agents.get(a)?.status.clone())
    }

    fn agent_at(&self, w: usize, p: usize, e: usize, a: usize) -> Option<(String, String)> {
        let Load::Loaded(agents) = &self.tree.get(w)?.projects.get(p)?.envs.get(e)?.agents else {
            return None;
        };
        let agent = agents.get(a)?;
        Some((agent.id.clone(), agent.name.clone()))
    }

    /// Cycle focus: tree → sessions → the pane → tree, skipping what isn't
    /// there. One key to move between the three things on this screen.
    fn cycle_focus(&mut self) {
        self.focus_panel(match self.focus {
            ManageFocus::Tree => ManageFocus::Session,
            ManageFocus::Session => ManageFocus::Tree,
        });
    }

    /// Move the cursor onto the agent a launch just opened, if its row exists
    /// yet. Called again after each load, since the row appears only once the
    /// environment's agents have arrived.
    pub fn select_pending(&mut self) {
        let Some(id) = self.pending_select.clone() else {
            return;
        };
        let rows = self.rows();
        for (i, row) in rows.iter().enumerate() {
            if let RowKind::Agent(w, p, e, a) = row.kind
                && self.tree[w].projects[p].envs[e]
                    .agents_vec()
                    .get(a)
                    .is_some_and(|agent| agent.id == id)
            {
                self.cursor = i;
                self.pending_select = None;
                return;
            }
        }
    }

    /// Running agents whose sessions have not been fetched.
    ///
    /// Called after an environment loads, so the `(N)` beside an agent is
    /// there without expanding it. Only running agents: a sleeping box has
    /// nothing running on it, and asking would spend a request to learn that.
    pub fn sessions_to_prefetch(&mut self) -> Vec<Effect> {
        let mut out = Vec::new();
        for w in 0..self.tree.len() {
            for p in 0..self.tree[w].projects.len() {
                for e in 0..self.tree[w].projects[p].envs.len() {
                    let environment_id = self.tree[w].projects[p].envs[e].id.clone();
                    let Load::Loaded(agents) = &mut self.tree[w].projects[p].envs[e].agents else {
                        continue;
                    };
                    for (a, agent) in agents.iter_mut().enumerate() {
                        if agent.status != "running"
                            || self.discovered.contains(&agent.id)
                            || self.thread_polls.contains(&agent.id)
                        {
                            continue;
                        }
                        if !matches!(agent.sessions, LoadSessions::Loaded(_)) {
                            agent.sessions = LoadSessions::Loading;
                        }
                        self.discovered.insert(agent.id.clone());
                        self.thread_polls.insert(agent.id.clone());
                        out.push(Effect::LoadSessions {
                            agent_id: agent.id.clone(),
                            environment_id: environment_id.clone(),
                            path: (w, p, e, a),
                        });
                    }
                }
            }
        }
        out
    }

    /// The agents whose session lists a refresh should ask about again.
    ///
    /// Deliberately narrower than [`Self::sessions_to_prefetch`], which fills in
    /// every running agent's count once. `cloudAgentConsoleSessions` takes one
    /// agent — `CloudAgent.sessions` in the schema is snapshots, not console
    /// sessions, so there is no batch form — which makes a full sweep one
    /// request per agent, every tick. Only what someone is looking at is worth
    /// that: an expanded row, whose session rows are on screen, or an agent with
    /// an open pane. In practice nought to two, whatever the size of the
    /// account.
    ///
    /// Unlike the prefetch it does not blank the list on its way out: the rows
    /// stay put and are replaced when the reply lands, so nothing flickers on a
    /// timer.
    pub fn sessions_to_refresh(&self) -> Vec<Effect> {
        let mut out = Vec::new();
        for (w, ws) in self.tree.iter().enumerate() {
            for (p, project) in ws.projects.iter().enumerate() {
                for (e, env) in project.envs.iter().enumerate() {
                    let Load::Loaded(agents) = &env.agents else {
                        continue;
                    };
                    for (a, agent) in agents.iter().enumerate() {
                        // A sleeping box runs nothing, so asking would spend a
                        // request to learn that.
                        if agent.status != "running" {
                            continue;
                        }
                        // An agent whose count was never fetched is left to
                        // [`Self::sessions_to_prefetch`], which the same reply
                        // runs — and which has already marked what it claimed
                        // as loading. Asking about those here as well would be
                        // two requests for one agent.
                        if agent.sessions == LoadSessions::Loading
                            || self.thread_polls.contains(&agent.id)
                        {
                            continue;
                        }
                        // Explicit refresh also retries failed discovery.
                        let failed = matches!(agent.sessions, LoadSessions::Failed(_));
                        // Loaded threads are visible even on collapsed agents.
                        let visible = matches!(&agent.sessions, LoadSessions::Loaded(sessions)
                            if sessions.iter().any(|s| s.is_interesting()));
                        let watched = agent.expanded
                            || visible
                            || self.sessions.iter().any(|s| s.agent_id == agent.id);
                        if !watched && !failed {
                            continue;
                        }
                        out.push(Effect::LoadSessions {
                            agent_id: agent.id.clone(),
                            environment_id: env.id.clone(),
                            path: (w, p, e, a),
                        });
                    }
                }
            }
        }
        out
    }

    /// The environments to fetch before anyone touches a key, on a backboard
    /// that predates `myCloudAgents`.
    ///
    /// Only where the answer is needed immediately: the prompt's target, which
    /// New Session reads to decide whether it has an agent to work on, and the
    /// default project, whose agents the tree wants to lead with. Everything
    /// else loads when its row is expanded.
    ///
    /// This used to be every environment in every project in every workspace,
    /// which is one request each. That is fine on a small account and hundreds
    /// of requests on a large one — enough to rate limit the caller before the
    /// tree had finished drawing, and enough backend load per launch to be
    /// worth not doing. The cost of loading less is that a project's agent
    /// count appears when you open it rather than immediately.
    pub fn initial_environments(&mut self) -> Vec<Effect> {
        let mut wanted: Vec<String> = self.known_environments.clone();
        if let Some(target) = self.target.as_ref() {
            wanted.push(target.environment_id.clone());
        }
        // The default project's environments, whose agents the tree leads
        // with and where a launch with no target lands.
        if let Some(project_id) = self.default_project.clone() {
            for ws in &self.tree {
                for project in &ws.projects {
                    if project.id != project_id {
                        continue;
                    }
                    wanted.extend(project.envs.iter().map(|env| env.id.clone()));
                }
            }
        }

        let mut out = Vec::new();
        for w in 0..self.tree.len() {
            for p in 0..self.tree[w].projects.len() {
                for e in 0..self.tree[w].projects[p].envs.len() {
                    let env = &mut self.tree[w].projects[p].envs[e];
                    if env.agents != Load::NotLoaded || !wanted.contains(&env.id) {
                        continue;
                    }
                    env.agents = Load::Loading;
                    out.push(Effect::LoadAgents {
                        environment_id: env.id.clone(),
                        path: (w, p, e),
                    });
                }
            }
        }
        out
    }

    /// After the next load, open this agent so the session that was just
    /// started is visible underneath it — which is where it belongs, and where
    /// someone will look for it.
    pub fn expand_agent_after_load(&mut self, agent_id: String) {
        self.pending_expand = Some(agent_id);
    }

    fn sessions_next_name(&self, session: &super::session::Session) -> String {
        session.durable_name.clone()
    }

    /// Put the cursor on a session row once it exists, and drop the agent-row
    /// fallback that was holding the place.
    fn select_pending_session(&mut self) {
        let Some(name) = self.pending_select_session.clone() else {
            return;
        };
        let rows = self.rows();
        for (i, row) in rows.iter().enumerate() {
            // By the session's own name, not the row label — the label carries
            // the agent's name too.
            let RowKind::Session(w, p, e, a, idx) = row.kind else {
                continue;
            };
            if self
                .console_session(w, p, e, a, idx)
                .is_some_and(|session| session.name == name)
            {
                self.cursor = i;
                self.pending_select_session = None;
                self.pending_select = None;
                return;
            }
        }
    }

    /// Honour a queued expand once the agent's row exists.
    pub fn expand_pending(&mut self) -> Option<Effect> {
        let id = self.pending_expand.clone()?;
        for w in 0..self.tree.len() {
            for p in 0..self.tree[w].projects.len() {
                for e in 0..self.tree[w].projects[p].envs.len() {
                    let Load::Loaded(agents) = &self.tree[w].projects[p].envs[e].agents else {
                        continue;
                    };
                    if let Some(a) = agents.iter().position(|agent| agent.id == id) {
                        self.pending_expand = None;
                        return self.set_agent_expanded((w, p, e, a), true);
                    }
                }
            }
        }
        None
    }

    /// Expand the path to an environment so a launched agent becomes visible.
    /// Returns the load request when its agents have not been fetched yet.
    pub fn reveal_environment(&mut self, environment_id: &str) -> Option<Effect> {
        for w in 0..self.tree.len() {
            for p in 0..self.tree[w].projects.len() {
                for e in 0..self.tree[w].projects[p].envs.len() {
                    if self.tree[w].projects[p].envs[e].id != environment_id {
                        continue;
                    }
                    self.tree[w].expanded = true;
                    self.tree[w].projects[p].expanded = true;
                    // Always refetch: the launch may have just created the
                    // agent we are about to select. What is already loaded
                    // stays on screen while the reply is on its way — blanking
                    // it would fold the group mid-poll and shove every row
                    // (and the cursor) somewhere else.
                    self.tree[w].projects[p].envs[e].expanded = true;
                    if !matches!(self.tree[w].projects[p].envs[e].agents, Load::Loaded(_)) {
                        self.tree[w].projects[p].envs[e].agents = Load::Loading;
                    }
                    return Some(Effect::LoadAgents {
                        environment_id: environment_id.to_string(),
                        path: (w, p, e),
                    });
                }
            }
        }
        None
    }

    /// The chords that work everywhere. Settings is worth one because it is
    /// only reachable by chord. Option+T selects a target; themes live in settings.
    fn alt_action(&mut self, action: char) -> Option<Effect> {
        self.status.clear();
        match action {
            'o' if self.screen == Screen::Manage && self.confirm.is_none() && !self.keys_open => {
                self.open_shell()
            }
            'b' if self.screen == Screen::Manage && self.confirm.is_none() && !self.keys_open => {
                self.open_bootstraps()
            }
            'b' if self.screen == Screen::HarnessPick => self.open_launch_bootstraps(),
            't' => {
                self.start_target_pick();
                None
            }
            's' => {
                self.start_settings();
                None
            }
            'f' => {
                let was_full = self.pane_is_full();
                self.toggle_maximized();
                (was_full && !self.pane_is_full()).then_some(Effect::RefreshAll)
            }
            ']' => self.cycle_session(true),
            '[' => self.cycle_session(false),
            // Everything, everywhere: `r` refreshes the environment under the
            // cursor, and this is the one that answers "something changed and I
            // don't know where".
            'r' => {
                self.status = "Refreshing…".into();
                self.refresh_announce = true;
                Some(Effect::RefreshAll)
            }
            // The launchers float over the tree the launch aims at; the
            // New Session row's own prompt box covers the plain case.
            // Option+n chooses a harness for a new session on the current VM.
            'n' if self.screen == Screen::Manage => self.pick_new_session(),
            'p' if self.screen == Screen::Manage => {
                self.manage_prompt = Some(String::new());
                self.screen = Screen::ManagePrompt;
                None
            }
            _ => None,
        }
    }

    /// Move the pane to the next or previous open session, wrapping.
    ///
    /// Scoped to panes that are already open rather than every session in the
    /// tree, and that is the whole design: waking a sleeping agent is a cold
    /// boot — seconds of wall clock and a VM that starts billing — so holding
    /// `⌥⇧]` or `⌥⇧[` must never fan out wakes across agents you were only
    /// passing through. Opening something new stays the deliberate `enter` on
    /// a row.
    fn cycle_session(&mut self, forward: bool) -> Option<Effect> {
        match self.sessions.len() {
            0 => {
                self.status = "No open sessions".to_string();
                return None;
            }
            // Nothing to move to, but silence would read as a broken key.
            1 => {
                self.status = "Only one session open".to_string();
                return None;
            }
            _ => {}
        }
        let count = self.sessions.len();
        let next = match (self.active, forward) {
            (Some(i), true) => (i + 1) % count,
            (Some(i), false) => (i + count - 1) % count,
            // No pane yet: forward starts at the front, back at the end.
            (None, true) => 0,
            (None, false) => count - 1,
        };
        self.active = Some(next);
        self.select_row_for_active();
        if let Some(name) = self.active_session().map(|s| s.agent_name.clone()) {
            self.status = format!("Session {}/{} · {name}", next + 1, count);
        }
        None
    }

    /// Put the tree cursor on the row belonging to the active pane.
    ///
    /// The inverse of `sync_active_to_cursor`, which runs after every cursor
    /// move. Cycling moves the pane directly, so without this the highlight
    /// would still sit on the previous session and the next arrow key would
    /// drag the pane straight back to it.
    fn select_row_for_active(&mut self) {
        let Some(name) = self.active_session().map(|s| s.durable_name.clone()) else {
            return;
        };
        let rows = self.rows();
        for (i, row) in rows.iter().enumerate() {
            let RowKind::Session(w, p, e, a, idx) = row.kind else {
                continue;
            };
            if self
                .console_session(w, p, e, a, idx)
                .is_some_and(|cs| cs.name == name)
            {
                self.cursor = i;
                return;
            }
        }
    }

    /// Gate a connect on the SSH key. `true` means the effect was consumed
    /// here — held behind the register question, or refused with the recipe —
    /// and the caller must not proceed with it.
    pub fn hold_for_ssh_key(&mut self, held: HeldConnect) -> bool {
        match &self.ssh_key {
            SshKeyState::NeedsRegistration(offer) => {
                self.ssh_gate = Some(SshGate {
                    offer: offer.clone(),
                    then: Some(held),
                });
                true
            }
            SshKeyState::NoLocalKeys => {
                self.toast_error("No SSH key found — run: ssh-keygen -t ed25519");
                true
            }
            SshKeyState::Ready | SshKeyState::Unknown => false,
        }
    }

    /// Offer key registration as part of setup, when the check said one is
    /// needed. No held connect: declining just ends the question.
    pub fn offer_ssh_key_setup(&mut self) {
        if self.ssh_gate.is_none()
            && let SshKeyState::NeedsRegistration(offer) = &self.ssh_key
        {
            self.ssh_gate = Some(SshGate {
                offer: offer.clone(),
                then: None,
            });
        }
    }

    /// Raise a confirmation in the corner.
    pub fn toast(&mut self, text: impl Into<String>) {
        self.raise_toast(text, true);
    }

    /// The same, for something that did not work.
    pub fn toast_error(&mut self, text: impl Into<String>) {
        self.raise_toast(text, false);
    }

    fn raise_toast(&mut self, text: impl Into<String>, ok: bool) {
        self.toast = Some(Toast {
            text: text.into(),
            at: std::time::Instant::now(),
            ok,
        });
    }

    /// Drop it once it has had its time. Called from the event loop, which
    /// wakes for exactly this.
    pub fn expire_toast(&mut self) {
        if self.toast.as_ref().is_some_and(Toast::expired) {
            self.toast = None;
        }
    }

    /// How long the toast has left, for the loop to sleep on.
    pub fn toast_remaining(&self) -> std::time::Duration {
        self.toast
            .as_ref()
            .map(Toast::remaining)
            .unwrap_or(TOAST_LIFETIME)
    }

    /// Time until an attached pane would first count as stalled, for the loop
    /// to wake once and draw the notice. `None` when no pane is waiting on
    /// its first byte.
    pub fn stall_check_remaining(&self) -> Option<std::time::Duration> {
        self.sessions
            .iter()
            .filter_map(|session| session.stall_remaining())
            .min()
    }

    /// Give the session pane the whole screen, or give the tree back.
    ///
    /// Only where there is a session to give it to: with nothing open, a
    /// screen of empty pane is not a state worth being able to reach by
    /// accident.
    fn toggle_maximized(&mut self) {
        if self.screen != Screen::Manage {
            return;
        }
        if self.maximized {
            self.maximized = false;
            self.status = String::new();
            return;
        }
        if self.active.is_none() {
            self.status = "Connect to a session first — ⌥f gives it the screen".into();
            return;
        }
        self.maximized = true;
        // Nothing else is on screen, so nothing else should have the keyboard.
        self.focus = ManageFocus::Session;
    }

    /// Is the cursor on the pinned New Session row? While it is, the session
    /// pane shows the launcher.
    pub fn launcher_selected(&self) -> bool {
        self.focus == ManageFocus::Tree
            && self
                .selected_row()
                .is_some_and(|row| row.kind == RowKind::NewSession)
    }

    /// [`Self::launcher_selected`], with the prompt holding the keyboard.
    /// False on the same row after Esc — the "home" state, where letters are
    /// keys again and `q` quits.
    pub fn new_session_selected(&self) -> bool {
        self.launcher_selected() && self.prompt_focused
    }

    /// Keys while the cursor stands on New Session: the old menu's prompt box,
    /// without the separate screen. Everything unhandled falls back to the
    /// tree, so ↑/↓ still walk away from the row.
    fn on_key_new_session(&mut self, key: KeyEvent) -> Result<Option<Effect>, KeyEvent> {
        match key.code {
            // Typing is refused while shell is selected — the box says so —
            // rather than cleared: a draft typed for a real agent survives
            // cycling past shell.
            KeyCode::Char(c)
                if !key.modifiers.contains(KeyModifiers::CONTROL) && !self.shell_selected() =>
            {
                self.prompt_insert(c);
                Ok(None)
            }
            KeyCode::Backspace if !self.shell_selected() => {
                self.prompt_backspace();
                Ok(None)
            }
            // The cursor moves through the draft; a typo is fixed in place
            // rather than by erasing back to it.
            KeyCode::Left if !self.shell_selected() => {
                self.prompt_cursor = self.prompt_cursor.saturating_sub(1);
                Ok(None)
            }
            KeyCode::Right if !self.shell_selected() => {
                self.prompt_cursor = (self.prompt_cursor + 1).min(self.prompt.chars().count());
                Ok(None)
            }
            KeyCode::Home if !self.shell_selected() => {
                self.prompt_cursor = 0;
                Ok(None)
            }
            KeyCode::End if !self.shell_selected() => {
                self.prompt_cursor = self.prompt.chars().count();
                Ok(None)
            }
            KeyCode::Tab if opencode_alternate(self.harness).is_some() => {
                self.harness = opencode_alternate(self.harness).unwrap();
                Ok(None)
            }
            KeyCode::BackTab => {
                self.harness = (self.harness + 1) % HARNESSES.len();
                Ok(None)
            }
            // ⇧enter is the newline every text field owes a paragraph-sized
            // prompt; plain enter still launches. ALT is accepted alongside
            // SHIFT because most terminals cannot say "shifted Enter" at all
            // (the kitty disambiguate mode exempts Enter by design) — the
            // ones configured to send it, Claude Code's own /terminal-setup
            // included, bind it to `ESC CR`, which parses as alt+enter. A
            // terminal that reports neither sends a plain Enter, so the chord
            // degrades to launching — never to a lost draft.
            KeyCode::Enter
                if key
                    .modifiers
                    .intersects(KeyModifiers::SHIFT | KeyModifiers::ALT)
                    && !self.shell_selected() =>
            {
                self.prompt_insert('\n');
                Ok(None)
            }
            KeyCode::Enter => Ok(self.launch_from_prompt()),
            // Esc walks up, one step per press: a draft is cleared first, so
            // a stray Esc mid-typing doesn't throw the session away…
            KeyCode::Esc if !self.prompt.is_empty() => {
                self.clear_prompt();
                Ok(None)
            }
            // …then the prompt lets go of the keyboard. That is the top of
            // the chain — home — where letters are keys again and `q` quits.
            KeyCode::Esc => {
                self.prompt_focused = false;
                Ok(None)
            }
            _ => Err(key),
        }
    }

    /// The byte offset of the prompt cursor, for splicing into the string.
    fn prompt_byte(&self) -> usize {
        self.prompt
            .char_indices()
            .nth(self.prompt_cursor)
            .map(|(i, _)| i)
            .unwrap_or(self.prompt.len())
    }

    fn prompt_insert(&mut self, c: char) {
        let at = self.prompt_byte();
        self.prompt.insert(at, c);
        self.prompt_cursor += 1;
    }

    fn prompt_insert_str(&mut self, text: &str) {
        let at = self.prompt_byte();
        self.prompt.insert_str(at, text);
        self.prompt_cursor += text.chars().count();
    }

    fn prompt_backspace(&mut self) {
        if self.prompt_cursor == 0 {
            return;
        }
        self.prompt_cursor -= 1;
        let at = self.prompt_byte();
        self.prompt.remove(at);
    }

    pub fn clear_prompt(&mut self) {
        self.prompt.clear();
        self.prompt_cursor = 0;
    }

    /// Launch what the prompt box holds — onto a brand-new agent, the same
    /// default the dashboard has: each task gets a VM of its own. A blank
    /// prompt launches the session bare: the harness comes up empty, ready
    /// for its first prompt inside.
    fn launch_from_prompt(&mut self) -> Option<Effect> {
        self.launch_new_agent()
    }

    /// A new agent in the target project, carrying the prompt draft if one is
    /// written: the new-VM picker and the prompt box all end
    /// here.
    fn launch_new_agent(&mut self) -> Option<Effect> {
        if self.target.is_none() {
            self.start_target_pick();
            self.status = "Pick where this should run".into();
            return None;
        }
        self.launch(None, true)
    }

    fn on_key_manage(&mut self, key: KeyEvent) -> Option<Effect> {
        // A held action owns the keyboard until it is answered. Anything other
        // than yes cancels: a mistyped key must never be taken as consent.
        if let Some(pending) = self.confirm.clone() {
            self.confirm = None;
            return match key.code {
                KeyCode::Char('y') | KeyCode::Char('Y') => {
                    self.ops
                        .insert(pending.agent_id.clone(), pending.op.pending_label());
                    Some(Effect::Agent {
                        op: pending.op,
                        agent_id: pending.agent_id,
                        environment_id: pending.environment_id,
                    })
                }
                _ => {
                    self.status = "Cancelled".into();
                    None
                }
            };
        }

        // The overlay is a look-up, not a mode: the next key puts it away and
        // is otherwise ignored, so nothing happens by surprise while reading.
        if self.keys_open {
            self.keys_open = false;
            return None;
        }

        // On the New Session row the keyboard writes the prompt; only what
        // the prompt doesn't take (↑ ↓, tab, mouse chords) falls through to
        // the tree below.
        let key = if self.new_session_selected() {
            match self.on_key_new_session(key) {
                Ok(effect) => return effect,
                Err(key) => key,
            }
        } else {
            key
        };

        let row = self.selected_row();
        match key.code {
            KeyCode::Char('?') => {
                self.keys_open = true;
                None
            }
            KeyCode::Up | KeyCode::Char('k') => self.move_cursor(-1),
            KeyCode::Down | KeyCode::Char('j') => self.move_cursor(1),
            // Full screen, before the plain Enter arm below claims the key.
            KeyCode::Enter if key.modifiers.contains(KeyModifiers::ALT) => {
                self.full_screen_current()
            }
            KeyCode::Char('f') => self.full_screen_current(),
            // A separate shell on this exact VM, even from a session row.
            KeyCode::Char('c') => {
                let (w, p, e, a) = match row?.kind {
                    RowKind::Agent(w, p, e, a) | RowKind::Session(w, p, e, a, _) => (w, p, e, a),
                    _ => {
                        self.status = "Select a VM or session to copy its SSH shell command".into();
                        return None;
                    }
                };
                let (agent_id, _) = self.agent_at(w, p, e, a)?;
                Some(Effect::CopySsh {
                    agent_id,
                    environment_id: self.tree[w].projects[p].envs[e].id.clone(),
                })
            }
            KeyCode::Right | KeyCode::Char('l') => self.set_expanded(row?.kind, true),
            KeyCode::Left | KeyCode::Char('h') => self.set_expanded(row?.kind, false),
            KeyCode::Enter => {
                let kind = row?.kind;
                match kind {
                    // From home, Enter steps back into the prompt.
                    RowKind::NewSession => {
                        self.prompt_focused = true;
                        None
                    }
                    RowKind::Agent(w, p, e, a) => self.connect_agent_row(w, p, e, a),
                    RowKind::Session(..) => self.reattach_row(kind),
                    // A toggle: open drills straight through to the first
                    // environment's agents — what someone opening a project is
                    // looking for — and a second enter folds the whole thing
                    // back up rather than going dead once everything under it
                    // is already open. The cursor stays on the project row so
                    // the second enter lands where the first one did.
                    RowKind::Project(w, p) => {
                        let open = self
                            .tree
                            .get(w)
                            .and_then(|ws| ws.projects.get(p))
                            .is_some_and(|project| project.expanded);
                        if open {
                            self.set_expanded(RowKind::Project(w, p), false)
                        } else {
                            self.set_expanded(RowKind::Project(w, p), true);
                            self.set_expanded(RowKind::Environment(w, p, 0), true)
                        }
                    }
                    // Workspaces and environments toggle the same way: enter
                    // on something already open closes it.
                    RowKind::Workspace(w) => {
                        let open = self.tree.get(w).is_some_and(|ws| ws.expanded);
                        self.set_expanded(RowKind::Workspace(w), !open)
                    }
                    RowKind::Environment(w, p, e) => {
                        let open = self
                            .tree
                            .get(w)
                            .and_then(|ws| ws.projects.get(p))
                            .and_then(|project| project.envs.get(e))
                            .is_some_and(|env| env.expanded);
                        self.set_expanded(RowKind::Environment(w, p, e), !open)
                    }
                    other => self.set_expanded(other, true),
                }
            }
            // `n` is the dashboard's New Agent button: pick the harness,
            // then a fresh agent — in the row's own project when the cursor
            // names one (the footer advertises row-local behavior), falling
            // back to the prompt's target from the launcher and the tail.
            // On an agent (or one of its threads) the box already exists, so
            // the pick starts a new session ON it instead.
            KeyCode::Char('n') => {
                if self.loading.active {
                    return None;
                }
                if let Some(target) = self.bootstrap_target().or_else(|| self.target.clone()) {
                    self.begin_harness_pick(target, None);
                } else {
                    self.start_target_pick();
                }
                None
            }
            KeyCode::Char('t') => {
                let path = self.env_of(row?.kind)?;
                self.target = self.target_at(path);
                self.status = match &self.target {
                    Some(t) => format!("Target set to {}", t.label()),
                    None => String::new(),
                };
                None
            }
            // `tab` walks the three panes; `^o` (see `on_key`) is the way back
            // out of a focused session.
            KeyCode::Tab => {
                self.cycle_focus();
                None
            }
            // `x` ends the highlighted session — on the agent, not just here.
            // Connected or not: the session lives on the VM either way.
            KeyCode::Char('x') | KeyCode::Char('X') => {
                let kind = row?.kind;
                let RowKind::Session(w, p, e, a, i) = kind else {
                    // On an agent, close our window onto it without ending
                    // anything; ending is `d`, and it asks first.
                    return match self.pane_for_row(kind) {
                        Some(index) => Some(Effect::CloseSession { index }),
                        None => {
                            self.status = "Select a session to end".into();
                            None
                        }
                    };
                };
                let name = self.console_session(w, p, e, a, i)?.name.clone();
                let (agent_id, _) = self.agent_at(w, p, e, a)?;
                let environment_id = self.tree[w].projects[p].envs[e].id.clone();
                if super::super::client_sessions::is_client(&name) {
                    if super::super::client_sessions::parse_name(&name)
                        .is_some_and(|(_, _, id)| id.is_none())
                    {
                        return self
                            .pane_for_row(kind)
                            .map(|index| Effect::CloseSession { index });
                    }
                    return self.delete_thread_row(w, p, e, a, i);
                }
                self.ending.insert(name.clone());
                Some(Effect::KillSession {
                    agent_id,
                    environment_id,
                    session_name: name,
                })
            }
            // Lifecycle. Sleep and wake are reversible and act immediately;
            // delete takes the disk with it, so it asks first.
            KeyCode::Char('b') => self.open_bootstraps(),
            KeyCode::Char('s') => self.agent_op(AgentOp::Sleep),
            KeyCode::Char('w') => self.agent_op(AgentOp::Wake),
            KeyCode::Char('d') => self.agent_op(AgentOp::Delete),
            // Startup loads only what a keypress needs, so this is how an agent
            // in a project you haven't opened gets found.
            KeyCode::Char('R') => Some(Effect::ScanEverywhere),
            KeyCode::Char('r') => {
                let (w, p, e) = self.env_of(row?.kind)?;
                let env = self.tree.get_mut(w)?.projects.get_mut(p)?.envs.get_mut(e)?;
                // What is already loaded stays put while the reply is on its
                // way: blanking it would fold the group and move every row.
                if !matches!(env.agents, Load::Loaded(_)) {
                    env.agents = Load::Loading;
                }
                for agent in env.agents_vec() {
                    self.discovered.remove(&agent.id);
                }
                Some(Effect::LoadAgents {
                    environment_id: env.id.clone(),
                    path: (w, p, e),
                })
            }
            // Esc walks back up the chain, one step per press, and never
            // quits: a maximized pane gets the tree back first…
            KeyCode::Esc if self.maximized => {
                self.maximized = false;
                None
            }
            // …then any thread returns to the launcher; on the launcher's
            // unfocused home (the focused case cleared the draft and let go
            // of the keyboard above) there is nowhere further up, and `q` is
            // the way out.
            KeyCode::Esc => {
                if self.cursor != 0 {
                    self.cursor = 0;
                    self.prompt_focused = true;
                }
                None
            }
            KeyCode::Char('q') => Some(Effect::Quit),
            _ => None,
        }
    }

    /// The Option+p composer creates a session on the selected VM, or a VM
    /// in the selected project/environment when no VM is selected.
    fn new_here_prompted(&mut self, prompt: Option<String>) -> Option<Effect> {
        let kind = self.selected_row().map(|row| row.kind);
        match kind {
            Some(RowKind::Agent(w, p, e, a)) | Some(RowKind::Session(w, p, e, a, _)) => {
                let (agent_id, agent_name) = self.agent_at(w, p, e, a)?;
                self.target = self.target_at((w, p, e));
                let target = self.target.clone()?;
                Some(Effect::Launch(LaunchRequest {
                    project_id: target.project_id,
                    environment_id: target.environment_id,
                    agent_id: Some(agent_id),
                    session_name: None,
                    force_new: false,
                    new_session: true,
                    harness: self.harness_name().to_string(),
                    prompt,
                    label: format!("{agent_name} · new session"),
                    base: Default::default(),
                }))
            }
            Some(RowKind::Environment(w, p, e)) => {
                self.target = self.target_at((w, p, e));
                match prompt {
                    Some(p) => self.launch_prompted(None, true, Some(p)),
                    None => self.launch(None, true),
                }
            }
            Some(RowKind::Project(w, p)) => {
                // A project is not a place an agent can live; its first
                // environment is the only unambiguous reading, and the status
                // line says which one it picked.
                let env = self.tree.get(w)?.projects.get(p)?.envs.first()?;
                let name = env.name.clone();
                self.target = self.target_at((w, p, 0));
                self.status = format!("New agent in {name}");
                match prompt {
                    Some(p) => self.launch_prompted(None, true, Some(p)),
                    None => self.launch(None, true),
                }
            }
            _ if self.target.is_some() => match prompt {
                Some(p) => self.launch_prompted(None, true, Some(p)),
                None => self.launch(None, true),
            },
            _ => {
                self.start_target_pick();
                self.status = "Pick where this should run".into();
                None
            }
        }
    }

    fn begin_harness_pick(&mut self, target: Target, agent_id: Option<String>) {
        self.harness_pick_connect = false;
        self.harness_pick_target = Some(target);
        self.harness_pick_agent = agent_id;
        self.harness_pick = Some(self.harness);
        self.harness_bootstrap = Default::default();
        self.harness_use_bootstrap = true;
        self.screen = Screen::HarnessPick;
    }

    fn pick_new_session(&mut self) -> Option<Effect> {
        if self.loading.active {
            return None;
        }
        let selected = if self.focus == ManageFocus::Session && self.active.is_some() {
            self.active_session()
                .and_then(|s| s.environment_id().map(|e| (s.agent_id.clone(), e)))
        } else {
            match self.selected_row().map(|r| r.kind) {
                Some(RowKind::Agent(w, p, e, a) | RowKind::Session(w, p, e, a, _)) => self
                    .agent_at(w, p, e, a)
                    .map(|(id, _)| (id, self.tree[w].projects[p].envs[e].id.clone())),
                _ => None,
            }
        };
        let Some((id, env)) = selected else {
            self.toast_error("Select a VM to start a new session. Press n for a new VM.");
            return None;
        };
        let path = self.tree.iter().enumerate().find_map(|(w, ws)| {
            ws.projects
                .iter()
                .enumerate()
                .find_map(|(p, pr)| pr.envs.iter().position(|e| e.id == env).map(|e| (w, p, e)))
        });
        let Some(target) = path.and_then(|p| self.target_at(p)) else {
            self.toast_error("The VM's project is unavailable. Refresh the tree and try again.");
            return None;
        };
        self.begin_harness_pick(target, Some(id));
        None
    }

    fn toggle_launch_bootstrap(&mut self) {
        use super::bootstrap_setup::LaunchChoice;
        self.harness_use_bootstrap = !self.harness_use_bootstrap;
        if self.harness_use_bootstrap && self.harness_bootstrap == LaunchChoice::None {
            self.harness_bootstrap = LaunchChoice::Default;
        }
    }

    /// Choose an agent for a new VM (`n`) or a session on the current VM (`⌥n`).
    fn on_key_harness_pick(&mut self, key: KeyEvent) -> Option<Effect> {
        if self.harness_pick_agent.is_none() {
            if key.code == KeyCode::Char('b') {
                return self.open_launch_bootstraps();
            }
            if key.code == KeyCode::Char(' ') {
                self.toggle_launch_bootstrap();
                return None;
            }
        }
        let cursor = self.harness_pick?;
        let visible = harness_picker_indices(cursor);
        let row = visible.iter().position(|index| *index == cursor)?;
        match key.code {
            KeyCode::Up | KeyCode::Char('k') => {
                self.harness_pick = Some(visible[row.saturating_sub(1)]);
                None
            }
            KeyCode::Down | KeyCode::Char('j') => {
                self.harness_pick = Some(visible[(row + 1).min(visible.len() - 1)]);
                None
            }
            KeyCode::Tab => {
                self.harness_pick = Some(opencode_alternate(cursor).unwrap_or(cursor));
                None
            }
            KeyCode::Enter => {
                use super::bootstrap_setup::LaunchChoice;
                let picked = cursor.min(HARNESSES.len() - 1);
                let connecting = std::mem::take(&mut self.harness_pick_connect);
                if !connecting {
                    self.harness = picked;
                }
                let target = self
                    .harness_pick_target
                    .take()
                    .or_else(|| self.target.clone())?;
                let agent_id = self.harness_pick_agent.take();
                let existing = agent_id.is_some();
                if connecting && let Some(id) = &agent_id {
                    let path = self.tree.iter().enumerate().find_map(|(w, ws)| {
                        ws.projects.iter().enumerate().find_map(|(p, project)| {
                            project.envs.iter().enumerate().find_map(|(e, env)| {
                                env.agents_vec()
                                    .iter()
                                    .position(|agent| &agent.id == id)
                                    .map(|a| (w, p, e, a))
                            })
                        })
                    })?;
                    self.harness_pick = None;
                    self.screen = Screen::Manage;
                    self.target = Some(target);
                    return self.connect_primary_agent(
                        path.0,
                        path.1,
                        path.2,
                        path.3,
                        HARNESSES[picked].into(),
                    );
                }
                let mut base = crate::commands::code::LaunchArgs::default();
                if !existing {
                    let choice = if self.harness_use_bootstrap {
                        self.harness_bootstrap.clone()
                    } else {
                        LaunchChoice::None
                    };
                    base.set_bootstrap_choice(
                        match &choice {
                            LaunchChoice::Named(name) => Some(name.clone()),
                            _ => None,
                        },
                        matches!(choice, LaunchChoice::None),
                    );
                }
                self.harness_pick = None;
                self.screen = Screen::Manage;
                Some(Effect::Launch(LaunchRequest {
                    project_id: target.project_id.clone(),
                    environment_id: target.environment_id.clone(),
                    agent_id,
                    session_name: None,
                    force_new: !existing,
                    new_session: existing && !connecting,
                    harness: self.harness_name().into(),
                    prompt: (!existing && !self.shell_selected() && !self.prompt.trim().is_empty())
                        .then(|| self.prompt.trim().into()),
                    label: target.label(),
                    base: Box::new(base),
                }))
            }
            KeyCode::Esc => {
                self.harness_pick = None;
                self.harness_pick_agent = None;
                self.harness_pick_target = None;
                self.harness_pick_connect = false;
                self.screen = Screen::Manage;
                None
            }
            _ => None,
        }
    }

    /// Keys while the ⌥p composer is up: the launcher prompt box's contract —
    /// type, shift+tab cycles the agent, enter sends, esc closes. And the
    /// launcher box's shell contract too: typing goes inert, and enter
    /// launches the session bare, since a shell has nothing to hand a prompt
    /// to.
    fn on_key_manage_prompt(&mut self, key: KeyEvent) -> Option<Effect> {
        let mut draft = self.manage_prompt.take()?;
        match key.code {
            KeyCode::Char(c)
                if !key.modifiers.contains(KeyModifiers::CONTROL) && !self.shell_selected() =>
            {
                draft.push(c);
                self.manage_prompt = Some(draft);
                None
            }
            KeyCode::Backspace if !self.shell_selected() => {
                draft.pop();
                self.manage_prompt = Some(draft);
                None
            }
            KeyCode::Tab if opencode_alternate(self.harness).is_some() => {
                self.harness = opencode_alternate(self.harness).unwrap();
                self.manage_prompt = Some(draft);
                None
            }
            KeyCode::BackTab => {
                self.harness = (self.harness + 1) % HARNESSES.len();
                self.manage_prompt = Some(draft);
                None
            }
            // Same newline chord as the launcher's box — the two are the
            // same control. ALT rides along for the same reason it does
            // there: most terminals deliver ⇧enter as `ESC CR`, alt+enter.
            KeyCode::Enter
                if key
                    .modifiers
                    .intersects(KeyModifiers::SHIFT | KeyModifiers::ALT)
                    && !self.shell_selected() =>
            {
                draft.push('\n');
                self.manage_prompt = Some(draft);
                None
            }
            KeyCode::Enter if self.shell_selected() => {
                self.screen = Screen::Manage;
                self.new_here_prompted(None)
            }
            KeyCode::Enter if !draft.trim().is_empty() => {
                self.screen = Screen::Manage;
                self.new_here_prompted(Some(draft.trim().to_string()))
            }
            // Enter on an empty draft is a slip, not a request for an
            // unprompted session; the box stays up.
            KeyCode::Enter => {
                self.manage_prompt = Some(draft);
                None
            }
            KeyCode::Esc => {
                self.screen = Screen::Manage;
                None
            }
            _ => {
                self.manage_prompt = Some(draft);
                None
            }
        }
    }

    /// Start a lifecycle action on the agent under the cursor.
    ///
    /// Let the server decide no-ops from live VM state: this tree's observation
    /// can predate a sleep or wake elsewhere. Only duplicate in-flight requests
    /// are suppressed locally.
    fn agent_op(&mut self, op: AgentOp) -> Option<Effect> {
        let row = self.selected_row()?;
        // A session belongs to an agent, so acting on it from a session row is
        // unambiguous — and it is where the cursor usually is.
        let (w, p, e, a) = match row.kind {
            RowKind::Agent(w, p, e, a) | RowKind::Session(w, p, e, a, _) => (w, p, e, a),
            _ => {
                self.status = "Select an agent first".into();
                return None;
            }
        };
        let env = &self.tree[w].projects[p].envs[e];
        let agent = env.agents_vec().get(a)?;
        if self.ops.contains_key(&agent.id) {
            return None;
        }
        let pending = PendingConfirm {
            op,
            agent_id: agent.id.clone(),
            agent_name: agent.name.clone(),
            environment_id: env.id.clone(),
        };
        if op == AgentOp::Delete {
            self.confirm = Some(pending);
            return None;
        }
        self.ops
            .insert(pending.agent_id.clone(), op.pending_label());
        Some(Effect::Agent {
            op,
            agent_id: pending.agent_id,
            environment_id: pending.environment_id,
        })
    }

    /// A kill finished. The row is refetched either way; this only clears the
    /// label and reports a failure.
    pub fn session_killed(&mut self, session_name: &str, error: Option<String>) {
        match error {
            // It is still there, so put it back rather than leave a row hidden
            // for a session that is very much alive.
            Some(err) => {
                self.ending.remove(session_name);
                self.status = format!("Couldn't end {session_name}: {err}");
            }
            None => self.status = format!("Ended {session_name}"),
        }
    }

    /// Every environment that has not been fetched, as load requests.
    ///
    /// The whole-account scan, which is what `shift+r` asks for. Startup no
    /// longer does this: it is one request per environment, so it costs a large
    /// account hundreds of them. As a deliberate action the cost is the user's
    /// to spend, and a rate limit stops it partway rather than pressing on.
    pub fn scan_environments(&mut self) -> Vec<Effect> {
        let mut out = Vec::new();
        for w in 0..self.tree.len() {
            for p in 0..self.tree[w].projects.len() {
                for e in 0..self.tree[w].projects[p].envs.len() {
                    let env = &mut self.tree[w].projects[p].envs[e];
                    if env.agents != Load::NotLoaded {
                        continue;
                    }
                    env.agents = Load::Loading;
                    out.push(Effect::LoadAgents {
                        environment_id: env.id.clone(),
                        path: (w, p, e),
                    });
                }
            }
        }
        out
    }

    /// The environments a refresh should ask about again, one request each.
    ///
    /// Only for callers that cannot use the account-wide query — see
    /// [`Self::account_query_unavailable`]. Scoped to environments that already
    /// have an answer: those are the ones with rows on screen that could now be
    /// wrong. Environments that have never loaded are left to `shift+r`, since
    /// asking about all of them is the request-per-environment cost this TUI is
    /// careful about. One still `Loading` is already on its way.
    pub fn environments_to_refresh(&self) -> Vec<Effect> {
        let mut out = Vec::new();
        for (w, ws) in self.tree.iter().enumerate() {
            for (p, project) in ws.projects.iter().enumerate() {
                for (e, env) in project.envs.iter().enumerate() {
                    if !matches!(env.agents, Load::Loaded(_) | Load::Failed(_)) {
                        continue;
                    }
                    out.push(Effect::LoadAgents {
                        environment_id: env.id.clone(),
                        path: (w, p, e),
                    });
                }
            }
        }
        out
    }

    /// A background fetch was refused for rate limiting.
    ///
    /// Anything still in flight is put back to "not loaded" rather than left
    /// spinning: the request is not coming, and a row that never resolves reads
    /// as a hung UI. Expanding it later retries, which is the right amount of
    /// work for the user to have to do.
    pub fn rate_limited(&mut self, retry_after_secs: Option<u64>) {
        // A rate-limited batch is abandoned, so its in-flight marks would
        // otherwise stick and stop the fast poll forever.
        self.thread_polls.clear();
        for ws in &mut self.tree {
            for project in &mut ws.projects {
                for env in &mut project.envs {
                    if env.agents == Load::Loading {
                        env.agents = Load::NotLoaded;
                    }
                    if let Load::Loaded(agents) = &mut env.agents {
                        for agent in agents {
                            if agent.sessions == LoadSessions::Loading {
                                agent.sessions = LoadSessions::NotLoaded;
                            }
                        }
                    }
                }
            }
        }
        // Hold off the automatic refresh for as long as we were told, or a
        // minute when we were told nothing: answering a 429 by polling on
        // schedule is how a rate limit becomes a longer one. A keypress still
        // asks — that is the user's request to spend, and by then the window may
        // have passed.
        self.refresh_paused_until = Some(
            std::time::Instant::now()
                + std::time::Duration::from_secs(retry_after_secs.unwrap_or(60)),
        );
        self.refreshing = false;
        // The toast below is the answer to whatever asked; a pending "up to
        // date" line must not be claimed by the next refresh to succeed.
        self.refresh_announce = false;
        self.toast_error(match retry_after_secs {
            Some(secs) if secs > 90 => format!(
                "Rate limited — try again in about {} minutes",
                secs.div_ceil(60)
            ),
            Some(secs) => format!("Rate limited — try again in {secs}s"),
            None => "Rate limited by the API".to_string(),
        });
        self.status = "Rate limited. Open a row to load it, or r to retry".into();
    }

    /// A lifecycle mutation came back.
    ///
    /// Accepted is not arrived: for sleep and wake the platform reports the old
    /// status until the VM actually gets there, so the label stays up and the
    /// environment is polled until it does. An error ends it immediately —
    /// there is nothing to wait for.
    pub fn agent_op_finished(
        &mut self,
        agent_id: &str,
        environment_id: &str,
        op: AgentOp,
        error: Option<String>,
    ) {
        if let Some(err) = error {
            self.ops.remove(agent_id);
            self.watching.remove(agent_id);
            self.status = err;
            return;
        }
        // An already-in-flight refresh describes the world before this
        // acknowledgement. It cannot complete this watch or resurrect a delete.
        self.agent_snapshot_floor
            .insert(environment_id.to_string(), std::time::Instant::now());
        let (want, patience) = match op {
            AgentOp::Wake => ("running", WAKE_PATIENCE),
            AgentOp::Sleep => ("sleeping", SLEEP_PATIENCE),
            // The row is about to disappear; there is no state to settle into.
            AgentOp::Delete => {
                self.ops.remove(agent_id);
                self.watching.remove(agent_id);
                return;
            }
        };
        self.watching.insert(
            agent_id.to_string(),
            AgentWatch {
                want,
                environment_id: environment_id.to_string(),
                until: std::time::Instant::now() + patience,
            },
        );
    }

    /// Is anything still on its way? Drives the polling in the event loop.
    pub fn watching_agents(&self) -> bool {
        !self.watching.is_empty()
    }

    /// Agents this TUI holds an open, unfinished pane on, and how long the
    /// youngest such pane has been open.
    ///
    /// An ended pane does not count: the connection is gone, so it is no longer
    /// evidence of anything. The age is what lets [`displayed_status`] tell the
    /// projection's normal lag apart from an agent that is stuck.
    fn agents_with_live_panes(&self) -> std::collections::HashMap<&str, std::time::Duration> {
        let mut open: std::collections::HashMap<&str, std::time::Duration> =
            std::collections::HashMap::new();
        for session in self.sessions.iter().filter(|s| !s.ended()) {
            let age = session.open_for();
            open.entry(session.agent_id.as_str())
                .and_modify(|held| {
                    if age < *held {
                        *held = age;
                    }
                })
                .or_insert(age);
        }
        open
    }

    /// Ask one environment per tick, rotating fairly through concurrent watches.
    pub fn watch_tick(&mut self) -> Option<Effect> {
        self.give_up_on_stale_watches();
        if self
            .refresh_paused_until
            .is_some_and(|until| until > std::time::Instant::now())
        {
            return None;
        }
        let environments: std::collections::BTreeSet<_> = self
            .watching
            .values()
            .map(|watch| watch.environment_id.clone())
            .collect();
        let environment_id = environments
            .iter()
            .find(|env| {
                self.last_watched_environment
                    .as_ref()
                    .is_none_or(|last| *env > last)
            })
            .or_else(|| environments.first())?
            .clone();
        self.last_watched_environment = Some(environment_id.clone());
        self.reveal_environment(&environment_id)
    }

    pub(super) fn mark_thread_refresh(&mut self, agent_id: &str) {
        self.thread_polls.insert(agent_id.into());
    }

    pub(super) fn thread_refreshing(&self, agent_id: &str) -> bool {
        self.thread_polls.contains(agent_id)
    }

    /// On-demand work: what [`Self::sessions_to_refresh`] names, minus
    /// agents whose previous ask is still in flight, marked as in flight.
    pub fn threads_to_refresh(&mut self) -> Vec<Effect> {
        let effects: Vec<Effect> = self
            .sessions_to_refresh()
            .into_iter()
            .filter(|effect| match effect {
                Effect::LoadSessions { agent_id, .. } => !self.thread_polls.contains(agent_id),
                _ => true,
            })
            .collect();
        for effect in &effects {
            if let Effect::LoadSessions { agent_id, .. } = effect {
                self.thread_polls.insert(agent_id.clone());
            }
        }
        effects
    }

    /// Start a new on-demand discovery pass, coalescing concurrent requests.
    pub fn refresh_started(&mut self) {
        self.refreshing = true;
        self.discovered.clear();
    }

    /// A refresh finished, whatever it found.
    pub fn refresh_finished(&mut self) {
        self.refreshing = false;
    }

    /// Report a finished account-wide refresh — but only when someone asked for
    /// one.
    ///
    /// Only the explicit refresh chord needs a status-line acknowledgement.
    pub fn refreshed(&mut self, agents: usize) {
        if !std::mem::take(&mut self.refresh_announce) {
            return;
        }
        self.status = match agents {
            0 => "Up to date — no agents on this account".into(),
            1 => "Up to date — 1 agent".into(),
            n => format!("Up to date — {n} agents"),
        };
    }

    /// Stop waiting for what is not coming, and put the real status back rather
    /// than leaving "waking…" on the row forever.
    fn give_up_on_stale_watches(&mut self) {
        let now = std::time::Instant::now();
        let expired: Vec<String> = self
            .watching
            .iter()
            .filter(|(_, watch)| watch.until <= now)
            .map(|(id, _)| id.clone())
            .collect();
        for id in expired {
            self.watching.remove(&id);
            self.ops.remove(&id);
            self.status = "That agent is taking longer than expected — r refreshes".into();
        }
    }

    /// Clear a watch on arrival, disappearance, or an observation that cannot
    /// reach the target. A terminal state should not hide under "waking…" until
    /// the patience expires.
    fn settle_watched_agents(&mut self, answered: &[String]) {
        if self.watching.is_empty() {
            return;
        }
        let mut arrived: Vec<String> = Vec::new();
        let mut failures = Vec::new();
        for (id, watch) in &self.watching {
            // A failed refresh or another environment's response supplies no
            // new evidence about this operation. Retain its pending label.
            if !answered.contains(&watch.environment_id) {
                continue;
            }
            match self.agent_by_id(id) {
                // Gone from the list entirely: deleted elsewhere, or never
                // there. Either way nothing is coming.
                None => arrived.push(id.clone()),
                Some(agent) if agent.status == watch.want => arrived.push(id.clone()),
                Some(agent)
                    if !crate::controllers::cloud_agent::Status::from_label(&agent.status)
                        .is_live() =>
                {
                    arrived.push(id.clone());
                    let action = if watch.want == "running" {
                        "wake"
                    } else {
                        "sleep"
                    };
                    failures.push(format!(
                        "Couldn't {action} agent {}: reported as {}",
                        agent.name, agent.status
                    ));
                }
                Some(_) => {}
            }
        }
        for id in arrived {
            self.watching.remove(&id);
            self.ops.remove(&id);
        }
        if !failures.is_empty() {
            failures.sort();
            // The account-wide refresh handler's generic completion message
            // must not erase the operation failure this snapshot just revealed.
            self.refresh_announce = false;
            self.status = failures.join("; ");
        }
    }

    /// An agent as the tree currently has it, wherever it lives.
    fn agent_by_id(&self, agent_id: &str) -> Option<&Agent> {
        self.tree.iter().find_map(|ws| {
            ws.projects.iter().find_map(|project| {
                project
                    .envs
                    .iter()
                    .find_map(|env| env.agents_vec().iter().find(|agent| agent.id == agent_id))
            })
        })
    }

    fn set_expanded(&mut self, kind: RowKind, open: bool) -> Option<Effect> {
        match kind {
            // A group is always open; there is nothing to do in either
            // direction, and quietly folding agents away would be the old
            // tree's problem reintroduced on purpose.
            RowKind::OtherProjects => {
                self.others_expanded = Some(open);
            }
            RowKind::Workspace(w) => {
                self.tree.get_mut(w)?.expanded = open;
            }
            RowKind::Project(w, p) => {
                self.tree.get_mut(w)?.projects.get_mut(p)?.expanded = open;
            }
            RowKind::Environment(w, p, e) => {
                if open {
                    let effect = self.expand_env((w, p, e));
                    self.clamp_cursor();
                    return effect;
                }
                self.tree
                    .get_mut(w)?
                    .projects
                    .get_mut(p)?
                    .envs
                    .get_mut(e)?
                    .expanded = false;
            }
            RowKind::Agent(w, p, e, a) if open => {
                let effect = self.set_agent_expanded((w, p, e, a), true);
                self.clamp_cursor();
                return effect;
            }
            // Collapsing walks out one level at a time: an expanded agent
            // closes itself, and only a closed one closes its environment.
            RowKind::Agent(w, p, e, a)
                if self
                    .tree
                    .get(w)
                    .and_then(|ws| ws.projects.get(p))
                    .and_then(|proj| proj.envs.get(e))
                    .map(|env| env.agents_vec().get(a).is_some_and(|ag| ag.expanded))
                    .unwrap_or(false) =>
            {
                self.set_agent_expanded((w, p, e, a), false);
                self.clamp_cursor();
                return None;
            }
            // A session row collapses the agent it belongs to, and the cursor
            // follows it up.
            RowKind::Session(w, p, e, a, _) if !open => {
                self.set_agent_expanded((w, p, e, a), false);
                if let Some(i) = self
                    .rows()
                    .iter()
                    .position(|r| r.kind == RowKind::Agent(w, p, e, a))
                {
                    self.cursor = i;
                }
                self.clamp_cursor();
                return None;
            }
            // A closed agent is as far out as `h` goes: the threads list is
            // flat, so there is no parent row above it to walk to.
            _ => {}
        }
        self.clamp_cursor();
        None
    }
}

/// A rule between the tree's sections: under the pinned New Session row, and
/// between the agent groups and the projects tail — so each section reads as
/// its own thing rather than as one more group.
fn separator_row() -> Row {
    Row {
        depth: 0,
        kind: RowKind::Separator,
        label: String::new(),
        note: String::new(),
        status: None,
        expanded: None,
        dimmed: true,
    }
}

fn note_row(w: usize, p: usize, e: usize, depth: usize, text: &str) -> Row {
    Row {
        depth,
        kind: RowKind::Note(w, p, e),
        label: text.to_string(),
        note: String::new(),
        status: None,
        expanded: None,
        dimmed: false,
    }
}

/// Display order for a group's agents: running first, waking next, sleeping
/// last, then by name. Indices for the same reason as [`App::agent_groups`].
///
/// Ranks on [`displayed_status`], not the raw one, so an agent with a pane open
/// does not sit in the waking band while its row reads `running`.
fn sorted_agents(
    agents: &[Agent],
    attached: &std::collections::HashMap<&str, std::time::Duration>,
) -> Vec<usize> {
    let rank = |agent: &Agent| match displayed_status(agent, attached) {
        "running" => 0,
        "starting" => 1,
        _ => 2,
    };
    let mut order: Vec<usize> = (0..agents.len()).collect();
    order.sort_by(|&a, &b| {
        rank(&agents[a]).cmp(&rank(&agents[b])).then_with(|| {
            agents[a]
                .name
                .to_lowercase()
                .cmp(&agents[b].name.to_lowercase())
        })
    });
    order
}

/// The status to show for an agent, which is not always the one the platform
/// last reported.
///
/// A pane we are attached to and that has not ended is direct evidence the
/// agent is up — there is a shell running on it. The platform's status lags
/// that: a shell routes as soon as the container exists, while `RUNNING`
/// additionally waits on route publication, a projection hop, and a poll
/// interval, which is exactly why the launcher stopped gating attach on it
/// (#1098). So a freshly created agent spends its first seconds reported as
/// `starting` while its session is already open and taking keystrokes, and the
/// tree calls that "waking" — about an agent the user is typing into.
///
/// Only `starting` is overridden, and only for [`STARTING_GRACE`] after the
/// pane opened. Two reasons for the bound:
///
/// - A pane can outlive the thing it is attached to, so `sleeping`, `crashed`,
///   `failed` or `deleting` alongside a live pane is news the user needs
///   rather than a lag to paper over.
/// - The lag is small. Measured over ten `railway code --claude --new` runs,
///   status reached RUNNING 5.3–14.2s after create — before the harness
///   answered, every time. An agent still `starting` well past that is not
///   lagging, it is stuck, and the row saying `running` would hide the only
///   signal the user has. That case is real: it is what prompted this fix.
///
/// So the override covers the window the lag actually lives in, and past it
/// the platform's own answer stands.
fn displayed_status<'a>(
    agent: &'a Agent,
    attached: &std::collections::HashMap<&str, std::time::Duration>,
) -> &'a str {
    let open_for = attached.get(agent.id.as_str());
    match open_for {
        Some(open_for) if agent.status == "starting" && *open_for < STARTING_GRACE => "running",
        _ => &agent.status,
    }
}

/// How long after a pane opens a `starting` status is still treated as the
/// projection catching up. Generously past the measured lag (worst observed
/// 14.2s from create, and a pane opens partway into that), so a normal boot is
/// never shown as stuck — but bounded, so a stuck one stops being shown as
/// healthy.
const STARTING_GRACE: std::time::Duration = std::time::Duration::from_secs(45);

/// Display order for a workspace's projects: the ones with agents first, then
/// alphabetically within each group.
///
/// Returns indices rather than sorting the tree, so `RowKind` keeps pointing at
/// the same project as counts arrive and the order shifts under it — the cursor
/// is restored by identity, not by position.
fn sorted_projects(ws: &WorkspaceNode, default_project: Option<&str>) -> Vec<usize> {
    let mut order: Vec<usize> = (0..ws.projects.len()).collect();
    order.sort_by(|a, b| {
        let (pa, pb) = (&ws.projects[*a], &ws.projects[*b]);
        let is_default = |p: &ProjectNode| Some(p.id.as_str()) == default_project;
        // The default first, then the ones with agents, then alphabetical.
        is_default(pb)
            .cmp(&is_default(pa))
            .then_with(|| (project_agent_count(pb) > 0).cmp(&(project_agent_count(pa) > 0)))
            .then_with(|| pa.name.to_lowercase().cmp(&pb.name.to_lowercase()))
    });
    order
}

/// Agents known to be in a project, across the environments that have answered.
fn project_agent_count(project: &ProjectNode) -> usize {
    project
        .envs
        .iter()
        .filter_map(|env| match &env.agents {
            Load::Loaded(agents) => Some(agents.len()),
            _ => None,
        })
        .sum()
}

/// Map a keystroke to an Alt-chord action letter.
///
/// Two ways in. The real one is `KeyModifiers::ALT`, which is what a terminal
/// sends when Option is configured as Meta (iTerm2's default; Terminal.app
/// needs "Use Option as Meta key"). Without that, macOS composes Option+letter
/// into a character, so those are matched as well — except Option+N, which is a
/// dead key for `~` and emits nothing at all until the next keystroke. That one
/// is unreachable without Meta, which is why every card also keeps its bare
/// letter while the cards have focus.
///
/// The brackets are the non-letters, and they are not equals. `ESC ]` is OSC,
/// which terminals effectively never send, so under Meta ⌥] is safe
/// everywhere. ⌥[ under Meta is the two bytes `ESC [` — byte-identical to the
/// CSI prefix that starts every arrow key — so a legacy terminal can never
/// deliver it; the parser eats the bytes as an unfinished escape sequence and
/// no key event exists to match, and a terminal or window manager that binds
/// ⌥[ itself never lets it through at all. That is why the ADVERTISED chords
/// are the shifted pair: ⌥⇧[ is `ESC {`, which no escape sequence begins with
/// and nothing conventionally binds, so it arrives everywhere Meta does. The
/// unshifted forms stay in the table as silent aliases for the terminals that
/// can say them unambiguously: under the kitty keyboard protocol (pushed at
/// startup) they arrive as genuine ALT+bracket events, and composed-mode
/// macOS folds both shift states into the same curly quotes anyway.
/// Everywhere else the unshifted chord is simply absent — it can go dead, but
/// never misfire.
fn alt_chord(key: &KeyEvent) -> Option<char> {
    const ACTIONS: &[char] = &['b', 'o', 't', 'f', 's', 'n', 'p', 'r', ']', '['];
    if key.modifiers.contains(KeyModifiers::ALT) {
        if let KeyCode::Char(c) = key.code {
            let c = match c.to_ascii_lowercase() {
                // ⌥⇧[ arrives as ALT+`{` where shift reaches us as the
                // character; fold the braces onto the bracket chords, the
                // same way the letters fold their capitals.
                '{' => '[',
                '}' => ']',
                c => c,
            };
            return ACTIONS.contains(&c).then_some(c);
        }
        return None;
    }
    // macOS Option-composed characters, for the terminals that send them.
    // ⌥n has no composed form: Option+N is the dead key for `~` and emits
    // nothing until the next keystroke, so without Meta it simply doesn't
    // exist — the same trade ⌥[ documents above.
    match key.code {
        KeyCode::Char('') => Some('b'),
        KeyCode::Char('ø') | KeyCode::Char('Ø') => Some('o'),
        KeyCode::Char('') | KeyCode::Char('') => Some('t'),
        KeyCode::Char('ƒ') => Some('f'),
        KeyCode::Char('ß') => Some('s'),
        KeyCode::Char('π') => Some('p'),
        // Option+r composes to ®, Option+shift+R to ‰ — one chord as far as
        // anyone pressing it is concerned, the way the bracket pair below folds
        // its shifted forms and the Meta path folds its capitals.
        KeyCode::Char('®') | KeyCode::Char('') => Some('r'),
        // Option+] composes to a left curly single quote, Option+shift+] to
        // the right one; Option+[ does the same with the double quotes. Each
        // pair is one chord as far as anyone pressing it is concerned,
        // matching how the letters fold their shifted forms.
        KeyCode::Char('\u{2018}') | KeyCode::Char('\u{2019}') => Some(']'),
        KeyCode::Char('\u{201C}') | KeyCode::Char('\u{201D}') => Some('['),
        _ => None,
    }
}

/// Fold a fresh agent list into the one on screen.
///
/// The platform owns membership, order and status; the TUI owns whether a row
/// is open and what its sessions are. Replacing the vector wholesale — which is
/// what every refresh used to do — threw the second half away, because
/// `fetch_agents` can only build rows that are collapsed with no sessions. The
/// visible cost was an expanded agent folding shut on every `r`, and on every
/// 1.5s poll tick while an agent woke; the invisible one was a session list
/// dropped and immediately refetched, one request per agent. Carrying it across
/// is what makes refreshing cheap enough to do on a timer.
///
/// Matched by id, so a rename or a status change lands and an agent that has
/// gone from the fresh list is gone from the tree.
fn merge_agents(previous: Vec<Agent>, fresh: Vec<Agent>) -> Vec<Agent> {
    let mut kept: HashMap<String, (bool, LoadSessions)> = previous
        .into_iter()
        .map(|agent| (agent.id, (agent.expanded, agent.sessions)))
        .collect();
    fresh
        .into_iter()
        .map(|mut agent| {
            if let Some((expanded, sessions)) = kept.remove(&agent.id) {
                agent.expanded = expanded;
                // Saved conversations survive sleep; live shell transports do not.
                agent.sessions = if agent.status == "running" {
                    sessions
                } else if let LoadSessions::Loaded(rows) = sessions {
                    let rows = super::cache::snapshot(&agent.id, rows);
                    if rows.is_empty() {
                        LoadSessions::NotLoaded
                    } else {
                        LoadSessions::Loaded(rows)
                    }
                } else {
                    LoadSessions::NotLoaded
                };
            }
            agent
        })
        .collect()
}

impl EnvNode {
    fn agents_vec(&self) -> &[Agent] {
        match &self.agents {
            Load::Loaded(a) => a,
            _ => &[],
        }
    }
}

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

    fn key(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }
    fn ctrl(c: char) -> KeyEvent {
        KeyEvent::new(KeyCode::Char(c), KeyModifiers::CONTROL)
    }

    fn tree() -> Vec<WorkspaceNode> {
        vec![WorkspaceNode {
            id: "ws_1".into(),
            name: "Railway".into(),
            expanded: false,
            projects: vec![ProjectNode {
                id: "proj_1".into(),
                name: "devtools".into(),
                expanded: false,
                envs: vec![
                    EnvNode {
                        id: "env_prod".into(),
                        name: "production".into(),
                        expanded: false,
                        agents: Load::NotLoaded,
                    },
                    EnvNode {
                        id: "env_stg".into(),
                        name: "staging".into(),
                        expanded: false,
                        agents: Load::NotLoaded,
                    },
                ],
            }],
        }]
    }

    fn app() -> App {
        App::new(tree(), None, Some("claude"), None, None, true)
    }

    #[test]
    fn bootstrap_shortcut_reopens_picker_and_create_preserves_the_prompt() {
        let mut a = app();
        a.target = a.target_at((0, 0, 0));
        a.prompt = "Keep this draft".into();
        a.bootstrap_defaults.insert(
            "env_prod".into(),
            super::super::bootstrap_setup::DefaultState::Ready("dev".into()),
        );
        assert_eq!(
            a.on_key(KeyEvent::new(KeyCode::Char('b'), KeyModifiers::CONTROL)),
            Some(Effect::LoadBootstraps {
                environment_id: "env_prod".into()
            })
        );
        assert_eq!(a.screen, Screen::BootstrapPick);
        let picker = a.bootstrap_picker.as_mut().unwrap();
        picker.loaded(Ok(vec![]));
        picker.cursor = picker.create_index();
        a.on_key(key(KeyCode::Enter));
        assert_eq!(a.screen, Screen::BootstrapSetup);
        assert!(a.bootstrap_form.as_ref().unwrap().return_to_prompt);
        a.on_key(key(KeyCode::Esc));
        assert_eq!(a.screen, Screen::BootstrapPick);
        a.on_key(key(KeyCode::Esc));
        assert_eq!(a.screen, Screen::Manage);
        assert_eq!(a.prompt, "Keep this draft");
    }

    #[test]
    fn bootstrap_setup_preserves_prompt_harness_and_target_until_finished() {
        let mut a = app();
        a.target = Some(Target {
            project_id: "proj_1".into(),
            project_name: "Demo".into(),
            environment_id: "env_prod".into(),
            environment_name: "production".into(),
        });
        a.prompt = "Fix the bug".into();
        let harness = a.harness;
        a.start_bootstrap_setup();
        let form = a.bootstrap_form.as_mut().unwrap();
        form.name = "dev".into();
        form.repo = "railwayapp/cli".into();
        form.harness = 0;
        form.field = form.submit_field();
        let Some(Effect::CreateBootstrap(req)) = a.on_key(key(KeyCode::Enter)) else {
            panic!("expected setup");
        };
        assert_eq!(req.harness, "railway");
        assert_eq!(req.target.environment_id, "env_prod");
        for event in [
            key(KeyCode::Enter),
            key(KeyCode::Esc),
            KeyEvent::new(KeyCode::Char('t'), KeyModifiers::CONTROL),
            KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL),
        ] {
            assert!(a.on_key(event).is_none());
            assert_eq!(a.screen, Screen::BootstrapSetup);
        }
        let form = a.bootstrap_form.as_mut().unwrap();
        form.running = false;
        form.finished = true;
        a.on_key(key(KeyCode::Enter));
        assert_eq!(a.screen, Screen::Manage);
        assert_eq!(a.prompt, "Fix the bug");
        assert_eq!(a.harness, harness);
        let Some(Effect::Launch(req)) = a.on_key(key(KeyCode::Enter)) else {
            panic!("expected launch");
        };
        assert_eq!(req.harness, "claude");
        assert_eq!(req.prompt.as_deref(), Some("Fix the bug"));
        assert!(req.force_new);
    }

    /// One workspace, four projects, deliberately out of alphabetical order.
    fn ordering_app() -> App {
        let env = |id: &str, name: &str| EnvNode {
            id: id.into(),
            name: name.into(),
            expanded: false,
            agents: Load::NotLoaded,
        };
        let project = |id: &str, name: &str| ProjectNode {
            id: id.into(),
            name: name.into(),
            expanded: false,
            envs: vec![env(&format!("{id}-prod"), "production")],
        };
        let tree = vec![WorkspaceNode {
            id: "ws_1".into(),
            name: "Railway".into(),
            expanded: true,
            projects: vec![
                project("p1", "zebra"),
                project("p2", "Alpha"),
                project("p3", "mono"),
                project("p4", "beta"),
            ],
        }];
        App::new(tree, None, Some("claude"), None, None, true)
    }

    fn project_order(a: &App) -> Vec<String> {
        a.rows()
            .into_iter()
            .filter(|r| matches!(r.kind, RowKind::Project(..)))
            .map(|r| r.label)
            .collect()
    }

    /// A target-less app with nothing loaded yet: the pinned launcher first,
    /// ruled off from the rest, then — with no agents to lead with — the
    /// projects tail as the whole tree, open, behind the search hint.
    #[test]
    fn opens_with_the_projects_tail_open() {
        let a = app();
        let rows = a.rows();
        assert_eq!(rows.len(), 5, "{rows:#?}");
        assert_eq!(rows[0].label, "New Agent");
        assert!(rows[0].selectable());
        assert!(matches!(rows[1].kind, RowKind::Separator));
        assert_eq!(rows[2].label, "looking for cloud agents…");
        assert!(!rows[2].selectable());
        assert_eq!(rows[3].label, "projects");
        assert_eq!(rows[4].label, "devtools");
        // The cursor starts on the launcher: the prompt is the first thing.
        assert_eq!(a.cursor, 0);
    }

    #[test]
    fn expanding_an_environment_requests_its_agents_once() {
        let mut a = app();
        a.screen = Screen::Manage;
        a.cursor = 4; // devtools
        assert_eq!(a.on_key(key(KeyCode::Right)), None);
        a.cursor = 5; // production
        let effect = a.on_key(key(KeyCode::Right)).unwrap();
        assert_eq!(
            effect,
            Effect::LoadAgents {
                environment_id: "env_prod".into(),
                path: (0, 0, 0)
            }
        );
        // Collapsing and re-expanding must not refetch — the result is cached.
        a.on_key(key(KeyCode::Left));
        assert_eq!(a.on_key(key(KeyCode::Right)), None);
    }

    #[test]
    fn a_loading_environment_shows_a_note_that_cannot_be_selected() {
        let mut a = app();
        a.screen = Screen::Manage;
        a.cursor = 4; // devtools
        a.on_key(key(KeyCode::Right));
        a.cursor = 5; // production
        a.on_key(key(KeyCode::Right));
        let rows = a.rows();
        let note = rows.iter().find(|r| r.label == "loading…").unwrap();
        assert!(!note.selectable());

        // Down from the environment skips the note and lands on staging.
        a.on_key(key(KeyCode::Down));
        assert_eq!(a.selected_row().unwrap().label, "staging");
    }

    fn loaded_app() -> App {
        let mut a = app();
        a.screen = Screen::Manage;
        a.tree[0].projects[0].expanded = true;
        a.tree[0].projects[0].envs[0].expanded = true;
        a.agents_loaded(
            (0, 0, 0),
            Ok(vec![agent("ca_1", "nimble-otter", "running")]),
        );
        a
    }

    #[test]
    fn pre_mutation_snapshot_cannot_settle_a_new_operation() {
        for scoped in [false, true] {
            for op in [AgentOp::Wake, AgentOp::Sleep] {
                for status in [
                    "running",
                    "sleeping",
                    "failed",
                    "crashed",
                    "future_state",
                    "missing",
                ] {
                    let mut a = loaded_app();
                    let asked_at = std::time::Instant::now();
                    a.ops.insert("ca_1".into(), op.pending_label());
                    a.agent_op_finished("ca_1", "env_prod", op, None);
                    let agents = if status == "missing" {
                        vec![]
                    } else {
                        vec![agent("ca_1", "nimble-otter", status)]
                    };
                    if scoped {
                        a.agents_loaded_at((0, 0, 0), "env_prod", Ok(agents), asked_at);
                    } else {
                        a.my_agents_loaded(
                            agents
                                .into_iter()
                                .map(|agent| ("env_prod".into(), agent))
                                .collect(),
                            asked_at,
                        );
                    }
                    assert!(
                        a.watching_agents(),
                        "{op:?}/{status}: response predates acceptance"
                    );
                    assert_eq!(a.agent_by_id("ca_1").unwrap().status, "running");
                    let target = if op == AgentOp::Wake {
                        "running"
                    } else {
                        "sleeping"
                    };
                    a.agents_loaded((0, 0, 0), Ok(vec![agent("ca_1", "nimble-otter", target)]));
                    assert!(
                        !a.watching_agents(),
                        "a post-acceptance snapshot can settle it"
                    );
                }
            }
        }
    }

    #[test]
    fn overlapping_snapshots_keep_the_newest_request_in_every_arrival_order() {
        // All 6 arrival orders x all 8 mixtures of account/scoped responses.
        for order in [
            [0, 1, 2],
            [0, 2, 1],
            [1, 0, 2],
            [1, 2, 0],
            [2, 0, 1],
            [2, 1, 0],
        ] {
            for sources in 0..8 {
                let mut a = loaded_app();
                let start = std::time::Instant::now();
                let states = ["sleeping", "starting", "failed"];
                let mut newest = 0;
                for index in order {
                    let asked_at = start + std::time::Duration::from_millis(index as u64);
                    let node = agent("ca_1", "nimble-otter", states[index]);
                    if sources & (1 << index) == 0 {
                        a.agents_loaded_at((0, 0, 0), "env_prod", Ok(vec![node]), asked_at);
                    } else {
                        a.my_agents_loaded(vec![("env_prod".into(), node)], asked_at);
                    }
                    newest = newest.max(index);
                    assert_eq!(
                        a.agent_by_id("ca_1").unwrap().status,
                        states[newest],
                        "{order:?}, sources {sources}"
                    );
                }
            }
        }
    }

    #[test]
    fn scoped_responses_cannot_be_misfiled_after_tree_reordering() {
        let mut a = loaded_app();
        a.tree[0].projects[0].envs.swap(0, 1);
        a.agents_loaded_at(
            (0, 0, 0),
            "env_prod",
            Ok(vec![agent("ca_1", "nimble-otter", "failed")]),
            std::time::Instant::now(),
        );
        assert_eq!(a.agent_by_id("ca_1").unwrap().status, "running");
        assert!(a.tree[0].projects[0].envs[0].agents_vec().is_empty());
    }

    #[test]
    fn announced_account_refresh_keeps_the_operation_failure_visible() {
        let mut a = loaded_app();
        a.ops.insert("ca_1".into(), AgentOp::Wake.pending_label());
        a.agent_op_finished("ca_1", "env_prod", AgentOp::Wake, None);
        a.refresh_announce = true;
        a.my_agents_loaded(
            vec![("env_prod".into(), agent("ca_1", "nimble-otter", "crashed"))],
            std::time::Instant::now(),
        );
        a.refreshed(1);
        assert!(a.status.contains("crashed"), "{}", a.status);
        assert!(!a.watching_agents());
    }

    #[test]
    fn concurrent_operation_watches_poll_every_environment() {
        let mut a = loaded_app();
        a.agents_loaded((0, 0, 1), Ok(vec![agent("ca_2", "other", "sleeping")]));
        let other_env = a.tree[0].projects[0].envs[1].id.clone();
        a.agent_op_finished("ca_1", "env_prod", AgentOp::Sleep, None);
        a.agent_op_finished("ca_2", &other_env, AgentOp::Wake, None);
        let mut polled = std::collections::HashSet::new();
        for _ in 0..4 {
            let Some(Effect::LoadAgents { environment_id, .. }) = a.watch_tick() else {
                panic!("a watch should poll");
            };
            polled.insert(environment_id);
        }
        assert_eq!(
            polled.len(),
            2,
            "one pending VM must not starve another environment"
        );
    }

    #[test]
    fn operation_polling_honors_retry_after_and_still_expires() {
        let mut a = loaded_app();
        a.ops.insert("ca_1".into(), AgentOp::Wake.pending_label());
        a.agent_op_finished("ca_1", "env_prod", AgentOp::Wake, None);
        a.rate_limited(Some(30));
        assert!(
            a.watch_tick().is_none(),
            "Retry-After also applies to operation polls"
        );
        assert!(a.watching_agents());
        a.watching.get_mut("ca_1").unwrap().until = std::time::Instant::now();
        assert!(a.watch_tick().is_none());
        assert!(!a.watching_agents());
        assert!(a.ops.is_empty());
    }

    #[test]
    fn enter_on_an_agent_connects_to_that_agent_and_retargets() {
        let mut a = loaded_app();
        a.primary_harnesses.insert("ca_1".into(), "codex".into());
        if let Load::Loaded(agents) = &mut a.tree[0].projects[0].envs[0].agents {
            agents[0].sessions = LoadSessions::Loaded(Vec::new());
        }
        a.prompt = "a draft for later".into();
        a.cursor = a
            .rows()
            .iter()
            .position(|r| r.label == "nimble-otter")
            .unwrap();
        let Effect::Launch(req) = a.on_key(key(KeyCode::Enter)).unwrap() else {
            panic!("expected a launch");
        };
        assert_eq!(req.agent_id.as_deref(), Some("ca_1"));
        assert!(!req.force_new);
        assert_eq!(req.environment_id, "env_prod");
        assert_eq!(req.project_id, "proj_1");
        assert_eq!(req.harness, "codex", "the VM wins over the default");
        assert_eq!(
            req.prompt, None,
            "connecting must not submit a leftover draft"
        );
        assert_eq!(a.harness_name(), "claude");
        assert_eq!(a.target.unwrap().label(), "devtools/production");
    }

    /// Connecting to an agent that already has a running session reattaches
    /// to it, rather than minting another durable session — which, for a
    /// harness like railway's, is just another window onto the same
    /// conversation under a new name.
    #[test]
    fn connecting_to_an_agent_reattaches_to_its_running_session() {
        let mut a = loaded_app();
        if let Load::Loaded(agents) = &mut a.tree[0].projects[0].envs[0].agents {
            agents[0].sessions = LoadSessions::Loaded(vec![ConsoleSession {
                name: "claude-one".into(),
                kind: "SHELL".into(),
                command: Some("claude".into()),
                running: true,
                attached: false,
                created_at: None,
                snapshot: None,
            }]);
        }
        a.cursor = a
            .rows()
            .iter()
            .position(|r| r.label == "nimble-otter")
            .unwrap();
        let effect = a.on_key(key(KeyCode::Enter));
        assert!(
            matches!(
                effect,
                Some(Effect::Reattach { ref session_name, .. }) if session_name == "claude-one"
            ),
            "a plain connect must not mint a session: {effect:?}"
        );

        // Enter connects to the VM even when the launcher holds a draft.
        a.prompt = "fix the tests".into();
        a.cursor = a
            .rows()
            .iter()
            .position(|r| r.label == "nimble-otter")
            .unwrap();
        assert!(
            matches!(a.on_key(key(KeyCode::Enter)), Some(Effect::Reattach { session_name, .. }) if session_name == "claude-one")
        );
        assert_eq!(a.prompt, "fix the tests");
    }

    #[test]
    fn an_unknown_vm_asks_for_its_agent_without_using_or_changing_the_default() {
        for sessions in [
            LoadSessions::Loaded(Vec::new()),
            LoadSessions::Failed("unavailable".into()),
        ] {
            let mut a = loaded_app();
            if let Load::Loaded(agents) = &mut a.tree[0].projects[0].envs[0].agents {
                agents[0].sessions = sessions;
            }
            a.set_harness(Some("codex"));
            a.cursor = a
                .rows()
                .iter()
                .position(|r| r.label == "nimble-otter")
                .unwrap();
            assert_eq!(a.on_key(key(KeyCode::Enter)), None);
            assert_eq!(a.screen, Screen::HarnessPick);
            assert!(a.harness_pick_connect);
            assert_eq!(a.harness_pick_agent.as_deref(), Some("ca_1"));
            assert_ne!(a.harness_pick, Some(a.harness), "no default preselection");
            a.harness_pick = HARNESSES.iter().position(|h| *h == "opencode2");
            let Some(Effect::Launch(req)) = a.on_key(key(KeyCode::Enter)) else {
                panic!("chosen agent launches on the existing VM");
            };
            assert_eq!(req.agent_id.as_deref(), Some("ca_1"));
            assert_eq!(req.harness, "opencode2");
            assert!(!req.force_new && !req.new_session);
            assert_eq!(
                a.harness_name(),
                "codex",
                "connection choice does not change the launch default"
            );
        }
    }

    #[test]
    fn enter_uses_the_primary_agent_among_multiple_open_harnesses() {
        let mut a = loaded_app();
        let mut secondary = session("ca_1", "nimble-otter");
        secondary.harness = "claude".into();
        secondary.durable_name = "secondary".into();
        a.attach_session(secondary, "ca_1".into());
        let mut primary = session("ca_1", "nimble-otter");
        primary.harness = "codex".into();
        primary.durable_name = "primary".into();
        a.attach_session(primary, "ca_1".into());
        a.primary_harnesses.insert("ca_1".into(), "codex".into());
        a.active = Some(0);
        a.focus = ManageFocus::Tree;
        a.cursor = a
            .rows()
            .iter()
            .position(|r| r.label == "nimble-otter")
            .unwrap();
        assert_eq!(a.on_key(key(KeyCode::Enter)), None);
        assert_eq!(a.active, Some(1));
        assert_eq!(a.focus, ManageFocus::Session);
        // Without VM metadata these two harnesses are ambiguous: ask.
        a.primary_harnesses.clear();
        a.focus = ManageFocus::Tree;
        assert_eq!(a.on_key(key(KeyCode::Enter)), None);
        assert_eq!(a.screen, Screen::HarnessPick);
        a.harness_pick = HARNESSES.iter().position(|h| *h == "claude");
        assert_eq!(
            a.on_key(key(KeyCode::Enter)),
            None,
            "reuse the chosen open session"
        );
        assert_eq!(a.active, Some(0));
        assert_eq!(a.sessions.len(), 2);
    }

    #[test]
    fn enter_waits_for_vm_discovery_and_ignores_it_after_navigation() {
        for navigate in [false, true] {
            let mut a = loaded_app();
            a.cursor = a
                .rows()
                .iter()
                .position(|r| r.label == "nimble-otter")
                .unwrap();
            assert!(
                matches!(a.on_key(key(KeyCode::Enter)), Some(Effect::LoadSessions { agent_id, .. }) if agent_id == "ca_1")
            );
            assert_eq!(
                a.on_key(key(KeyCode::Enter)),
                None,
                "coalesce an in-flight lookup"
            );
            a.primary_harnesses.insert("ca_1".into(), "grok".into());
            a.sessions_loaded((0, 0, 0, 0), "ca_1", Ok(Vec::new()));
            if navigate {
                a.cursor = 0;
            }
            let effect = a.finish_agent_connect("ca_1");
            if navigate {
                assert_eq!(effect, None);
            } else {
                assert!(
                    matches!(effect, Some(Effect::Launch(req)) if req.harness == "grok" && req.agent_id.as_deref() == Some("ca_1"))
                );
            }
        }
    }

    #[test]
    fn cached_threads_do_not_override_primary_discovery_in_flight() {
        let mut a = loaded_app();
        if let Load::Loaded(agents) = &mut a.tree[0].projects[0].envs[0].agents {
            agents[0].sessions =
                LoadSessions::Loaded(vec![ConsoleSession::client_thread("ca_1", "claude", None)]);
        }
        a.thread_polls.insert("ca_1".into());
        a.cursor = a
            .rows()
            .iter()
            .position(|r| r.label == "nimble-otter")
            .unwrap();
        assert_eq!(
            a.on_key(key(KeyCode::Enter)),
            None,
            "wait for the existing discovery request"
        );
        a.primary_harnesses.insert("ca_1".into(), "codex".into());
        a.sessions_loaded((0, 0, 0, 0), "ca_1", Ok(Vec::new()));
        assert!(
            matches!(a.finish_agent_connect("ca_1"), Some(Effect::Launch(req)) if req.harness == "codex")
        );
    }

    /// A tab names the session, not the agent: the seeded task once the
    /// platform lists it, the durable name until then.
    #[test]
    fn tabs_are_named_by_their_sessions() {
        let mut a = loaded_app();
        let mut pane = session("ca_1", "nimble-otter");
        pane.durable_name = "railway-t5soqz".into();
        a.attach_session(pane, "ca_1".into());
        assert_eq!(a.session_tab_label(0), "railway-t5soqz", "not yet listed");

        a.sessions_loaded(
            (0, 0, 0, 0),
            "ca_1",
            Ok(vec![ConsoleSession {
                name: "merry-daisy-ld9".into(),
                kind: "SHELL".into(),
                command: Some("exec bash -l".into()),
                running: true,
                attached: true,
                created_at: chrono::DateTime::from_timestamp(1_700_000_000, 0),
                snapshot: None,
            }]),
        );
        assert_eq!(
            a.session_tab_label(0),
            "merry-daisy-ld9",
            "a shell tab takes the listed transport name"
        );
    }

    /// The pane's title reads like a project reference — project / agent /
    /// session — using the listed session's short name once the platform has
    /// it, and degrading gracefully while it doesn't.
    #[test]
    fn the_pane_title_is_a_project_path() {
        let mut a = loaded_app();
        let mut pane = session("ca_1", "nimble-otter");
        pane.durable_name = "merry-daisy-ld9".into();
        // Before the listing lands: the durable name stands in.
        assert_eq!(
            a.pane_breadcrumb(&pane),
            "devtools / nimble-otter / merry-daisy-ld9"
        );

        a.sessions_loaded(
            (0, 0, 0, 0),
            "ca_1",
            Ok(vec![ConsoleSession {
                name: "merry-daisy-ld9".into(),
                kind: "SHELL".into(),
                command: Some(
                    "export RAILWAY_CODE_AUTOSTARTED=1; railway-agent-tui --session \
                     \"$RAILWAY_DURABLE_SESSION_NAME\" 'ship it'; printf 'x'"
                        .into(),
                ),
                running: true,
                attached: true,
                created_at: chrono::DateTime::from_timestamp(1_700_000_000, 0),
                snapshot: None,
            }]),
        );
        assert_eq!(
            a.pane_breadcrumb(&pane),
            "devtools / nimble-otter / railway-ld9",
            "the listed session's short name takes over"
        );

        // An agent the tree doesn't know: no project leg, no hole.
        let stray = session("ca_unknown", "wandering-ox");
        assert_eq!(a.pane_breadcrumb(&stray), "wandering-ox / test");
    }

    /// The maximized header's tabs switch panes on a click.
    #[test]
    fn clicking_a_header_tab_switches_the_pane() {
        let mut a = with_sessions(&["ca_1", "ca_2"]);
        a.maximized = true;
        a.focus = ManageFocus::Session;
        a.active = Some(0);
        a.panes.tabs[0] = PaneBox {
            x: 24,
            y: 1,
            w: 10,
            h: 1,
        };
        a.panes.tabs[1] = PaneBox {
            x: 35,
            y: 1,
            w: 10,
            h: 1,
        };
        assert_eq!(a.on_mouse(MouseAction::Down, 38, 1), None);
        assert_eq!(a.active, Some(1), "the click picked the second tab");
        assert!(a.maximized, "and the layout stayed put");
    }

    /// One click on a session's row selects it and keeps the keyboard in the
    /// tree — the sidebar is threads now, and a single click that handed the
    /// keyboard over made the list unbrowsable from a focused pane. A double
    /// click steps into the pane; ^o (or Esc) is the way back, after which x
    /// acts on the highlighted row instead of typing into it.
    #[test]
    fn clicking_the_list_takes_the_keyboard_back_from_a_session() {
        let mut a = loaded_app();
        if let Load::Loaded(agents) = &mut a.tree[0].projects[0].envs[0].agents {
            agents[0].sessions = LoadSessions::Loaded(vec![ConsoleSession {
                name: "claude-one".into(),
                kind: "SHELL".into(),
                command: None,
                running: true,
                attached: false,
                created_at: None,
                snapshot: None,
            }]);
        }
        let mut pane = session("ca_1", "nimble-otter");
        pane.durable_name = "claude-one".into();
        a.sessions = vec![pane];
        a.active = Some(0);
        a.focus = ManageFocus::Session;
        a.panes = panes_fixture();

        let row = a
            .rows()
            .iter()
            .position(|r| r.label == "[S] claude-one")
            .unwrap() as u16;
        a.on_mouse(MouseAction::Down, 5, 3 + row);
        assert_eq!(a.focus, ManageFocus::Tree, "one click selects the row");
        // A second click inside the double-click window steps in.
        a.on_mouse(MouseAction::Down, 5, 3 + row);
        assert_eq!(
            a.focus,
            ManageFocus::Session,
            "a double click means type-into-the-session"
        );

        // ^o hands the keyboard back to the list…
        a.on_key(ctrl('o'));
        assert_eq!(a.focus, ManageFocus::Tree, "^o returns to the rows");

        // …and x now ends the highlighted session instead of typing into it.
        let effect = a.on_key(key(KeyCode::Char('x')));
        assert!(
            matches!(effect, Some(Effect::KillSession { ref session_name, .. }) if session_name == "claude-one"),
            "{effect:?}"
        );
    }

    /// The relay registers a session under its own name, not the one the
    /// pane was minted with — so when the listing arrives, the pane adopts
    /// the listed name and the placeholder collapses into the real row,
    /// rather than both standing as duplicates.
    #[test]
    fn client_conversation_keeps_its_identity_and_reconnects_without_becoming_an_ssh_session() {
        let mut a = loaded_app();
        let name = super::super::super::client_sessions::name("codex", "ca_1", Some("thread-1"));
        let thread = super::super::super::client_sessions::Thread {
            id: "thread-1".into(),
            title: "Fix deployment startup".into(),
            directory: "/app".into(),
            created_at: chrono::DateTime::from_timestamp(1_700_000_000, 0),
            updated_at: "now".into(),
            state: "idle".into(),
        };
        let mut pane = session("ca_1", "nimble-otter");
        pane.durable_name = name.clone();
        pane.harness = "codex".into();
        a.attach_session(pane, "ca_1".into());
        let shell = ConsoleSession {
            name: "unrelated-shell".into(),
            kind: "SHELL".into(),
            command: Some("bash".into()),
            running: true,
            attached: true,
            created_at: None,
            snapshot: None,
        };
        a.sessions_loaded((0, 0, 0, 0), "ca_1", Ok(vec![shell.clone()]));
        assert_eq!(
            a.sessions[0].durable_name, name,
            "never adopt the SSH shell's identity"
        );
        for _ in 0..2 {
            a.sessions_loaded(
                (0, 0, 0, 0),
                "ca_1",
                Ok(vec![
                    shell.clone(),
                    ConsoleSession::client_thread("ca_1", "codex", Some(&thread)),
                ]),
            );
        }
        let rows = a.rows();
        let instance_rows: Vec<_> = rows
            .iter()
            .enumerate()
            .filter(|(_, r)| r.label == "Fix deployment startup")
            .collect();
        assert_eq!(instance_rows.len(), 1);
        assert!(
            a.take_auto_connects()
                .iter()
                .all(|c| c.session_name != name),
            "history never spawns clients automatically"
        );
        a.cursor = instance_rows[0].0;
        a.focus = ManageFocus::Tree;
        assert_eq!(a.on_key(key(KeyCode::Char('f'))), None);
        assert!(a.maximized);
        a.focus = ManageFocus::Tree;
        assert!(matches!(
            a.on_key(key(KeyCode::Char('x'))),
            Some(Effect::DeleteThread { .. })
        ));
        drop(a.take_session(0));
        // A rejected delete restores the resumable native row, not an SSH name.
        a.thread_deleted(&name, Some("offline".into()));
        a.cursor = a
            .rows()
            .iter()
            .position(|r| r.label == "Fix deployment startup")
            .unwrap();
        a.focus = ManageFocus::Tree;
        assert!(
            matches!(a.on_key(key(KeyCode::Enter)), Some(Effect::Reattach { session_name, agent_id, .. }) if session_name == name && agent_id == "ca_1")
        );
    }

    #[test]
    fn all_harnesses_promote_and_rename_a_thread_in_place_without_stealing_navigation() {
        use super::super::super::{client_sessions, remote_threads::tests::thread};
        for harness in [
            "claude",
            "grok",
            "codex",
            "opencode",
            "opencode2",
            "railway",
        ] {
            let mut app = loaded_app();
            let mut pane = session("ca_1", "box");
            pane.harness = harness.into();
            pane.durable_name = client_sessions::draft_name(harness, "ca_1", "our-pane");
            pane.client_id = Some("our-pane".into());
            app.attach_session(pane, "ca_1".into());
            let draft_index = app.cursor;
            assert_eq!(app.selected_row().unwrap().label, "New Thread");
            let mut saved = thread(harness, "real-id").thread;
            saved.title = "New Thread".into();
            app.client_thread_selected("our-pane", saved.clone());
            assert_eq!(app.cursor, draft_index);
            assert_eq!(
                app.sessions[0].durable_name,
                client_sessions::name(harness, "ca_1", Some("real-id"))
            );
            // Move elsewhere while a title is generated in the active pane.
            app.focus = ManageFocus::Tree;
            app.cursor = 0;
            saved.title = "Typical weather in Sacramento".into();
            app.client_thread_selected("our-pane", saved.clone());
            assert_eq!(
                app.cursor, 0,
                "{harness}: title updates must not move the cursor"
            );
            assert!(
                app.rows()[draft_index]
                    .label
                    .starts_with("Typical weather in ")
            );
            assert_eq!(
                app.sessions[0].client_thread.as_ref().unwrap().title,
                "Typical weather in Sacramento"
            );
            let before: Vec<_> = app
                .rows()
                .iter()
                .map(|r| (r.kind, r.label.clone()))
                .collect();
            app.set_agent_expanded((0, 0, 0, 0), true);
            app.mark_thread_refresh("ca_1");
            assert!(app.thread_refreshing("ca_1"));
            assert_eq!(
                before,
                app.rows()
                    .iter()
                    .map(|r| (r.kind, r.label.clone()))
                    .collect::<Vec<_>>()
            );
            app.sessions_loaded(
                (0, 0, 0, 0),
                "ca_1",
                Ok(vec![ConsoleSession::client_thread(
                    "ca_1",
                    harness,
                    Some(&saved),
                )]),
            );
            assert_eq!(app.cursor, 0);
            assert!(!app.thread_refreshing("ca_1"));
            assert!(app.rows().iter().all(|r| !r.label.starts_with("[S]")));
        }
    }

    #[test]
    fn refresh_preserves_order_selection_and_an_explicitly_collapsed_agent() {
        use super::super::super::remote_threads::tests::thread;
        let mut app = loaded_app();
        let mut first = thread("claude", "first").thread;
        first.title = "First title".into();
        let mut second = thread("claude", "second").thread;
        second.title = "Second title".into();
        let rows = |first: &super::super::super::client_sessions::Thread,
                    second: &super::super::super::client_sessions::Thread| {
            vec![
                ConsoleSession::client_thread("ca_1", "claude", Some(first)),
                ConsoleSession::client_thread("ca_1", "claude", Some(second)),
            ]
        };
        app.set_agent_expanded((0, 0, 0, 0), true);
        app.sessions_loaded((0, 0, 0, 0), "ca_1", Ok(rows(&first, &second)));
        app.cursor = app
            .rows()
            .iter()
            .position(|r| r.label == "Second title")
            .unwrap();
        let selected = app.cursor;
        first.title = "Renamed first title".into();
        app.sessions_loaded((0, 0, 0, 0), "ca_1", Ok(rows(&second, &first)));
        assert_eq!(app.cursor, selected);
        assert_eq!(app.selected_row().unwrap().label, "Second title");
        assert_eq!(app.rows()[selected - 1].label, "Renamed first title");
        app.cursor = app
            .rows()
            .iter()
            .position(|r| matches!(r.kind, RowKind::Agent(0, 0, 0, 0)))
            .unwrap();
        app.set_agent_expanded((0, 0, 0, 0), false);
        let collapsed = app.rows();
        assert!(matches!(
            app.auto_expand_agent(),
            Some(Effect::LoadSessions { .. })
        ));
        app.sessions_loaded((0, 0, 0, 0), "ca_1", Err("offline".into()));
        assert_eq!(app.rows().len(), collapsed.len());
        assert_eq!(app.selected_row().unwrap().expanded, Some(false));
    }

    #[test]
    fn only_interactive_vm_shells_use_session_rows() {
        let mut row = ConsoleSession {
            name: "console".into(),
            kind: "SHELL".into(),
            command: Some("exec bash -l".into()),
            running: true,
            attached: false,
            created_at: None,
            snapshot: None,
        };
        assert!(row.is_interesting());
        assert!(row.thread_label().starts_with("[S]"));
        for harness in [
            "claude",
            "grok",
            "codex",
            "opencode",
            "opencode2",
            "railway-agent-tui",
        ] {
            row.command = Some(format!("export RAILWAY_CODE_AUTOSTARTED=1; {harness}"));
            assert!(!row.is_interesting(), "{harness} is not a shell");
            assert!(!row.thread_label().starts_with("[S]"));
        }
        row.kind = "EXEC".into();
        row.command = Some("python3 -".into());
        assert!(!row.is_interesting());
    }

    #[test]
    fn remote_threads_adopt_the_exact_pane_and_resume_from_the_left_list() {
        use super::super::super::remote_threads::tests::thread;
        for harness in ["claude", "grok"] {
            let mut a = loaded_app();
            let mut pane = session("ca_1", "box");
            pane.durable_name = "relay-one".into();
            pane.console_name = Some("relay-one".into());
            pane.client_id = Some("our-pane".into());
            a.attach_session(pane, "ca_1".into());
            let mut first = thread(harness, "first");
            first.pane_id = Some("our-pane".into());
            first.console_name = Some("relay-one".into());
            first.thread.title = "First task".into();
            a.remote_threads_loaded("ca_1", &[first.clone()]);
            a.sessions_loaded(
                (0, 0, 0, 0),
                "ca_1",
                Ok(vec![ConsoleSession::client_thread(
                    "ca_1",
                    harness,
                    Some(&first.thread),
                )]),
            );
            assert_eq!(a.sessions[0].durable_name, first.name("ca_1"));
            assert_eq!(a.sessions[0].console_name.as_deref(), Some("relay-one"));
            assert_eq!(a.selected_row().unwrap().label, "First task");
            let mut second = first.clone();
            second.thread.id = "second".into();
            second.thread.title = "Second task".into();
            first.pane_id = None;
            first.console_name = None;
            a.remote_threads_loaded("ca_1", &[first.clone(), second.clone()]);
            let rows = vec![
                ConsoleSession::client_thread("ca_1", harness, Some(&first.thread)),
                ConsoleSession::client_thread("ca_1", harness, Some(&second.thread)),
            ];
            a.sessions_loaded((0, 0, 0, 0), "ca_1", Ok(rows));
            assert_eq!(a.sessions[0].durable_name, second.name("ca_1"));
            assert_eq!(a.selected_row().unwrap().label, "Second task");
            assert!(a.take_auto_connects().is_empty());
            let mut partial = Vec::new();
            a.preserve_failed_threads("ca_1", &[harness.into()], &mut partial);
            assert_eq!(partial.len(), 2);
            drop(a.take_session(0));
            a.cursor = a
                .rows()
                .iter()
                .position(|row| row.label == "First task")
                .unwrap();
            a.focus = ManageFocus::Tree;
            assert!(
                matches!(a.on_key(key(KeyCode::Enter)), Some(Effect::Reattach { session_name, agent_id, .. })
                if session_name == first.name("ca_1") && agent_id == "ca_1")
            );
        }
    }

    #[test]
    fn native_thread_selection_and_title_refresh_follow_ids_not_row_positions() {
        use super::super::super::client_sessions::{self, Thread};
        let mut a = loaded_app();
        let mut pane = session("ca_1", "box");
        pane.harness = "codex".into();
        pane.durable_name = client_sessions::name("codex", "ca_1", None);
        pane.client_id = Some("local-client".into());
        a.attach_session(pane, "ca_1".into());
        let first = Thread {
            id: "thread-1".into(),
            title: "First conversation".into(),
            directory: "/app".into(),
            created_at: None,
            updated_at: String::new(),
            state: "idle".into(),
        };
        a.client_thread_selected("local-client", first.clone());
        assert_eq!(a.session_tab_label(0), "First conversation");
        assert!(!a.rows().iter().any(|r| r.label.contains("New codex")));
        let mut second = first.clone();
        second.id = "thread-2".into();
        second.title = "Second conversation".into();
        a.client_thread_selected("local-client", second.clone());
        assert_eq!(
            a.sessions[0].durable_name,
            client_sessions::name("codex", "ca_1", Some("thread-2"))
        );
        let rows = vec![
            ConsoleSession::client_thread("ca_1", "codex", Some(&first)),
            ConsoleSession::client_thread("ca_1", "codex", Some(&second)),
        ];
        a.sessions_loaded((0, 0, 0, 0), "ca_1", Ok(rows));
        a.cursor = a
            .rows()
            .iter()
            .position(|r| r.label == "First conversation")
            .unwrap();
        let mut renamed = first.clone();
        renamed.title = "Renamed conversation".into();
        a.sessions_loaded(
            (0, 0, 0, 0),
            "ca_1",
            Ok(vec![
                ConsoleSession::client_thread("ca_1", "codex", Some(&second)),
                ConsoleSession::client_thread("ca_1", "codex", Some(&renamed)),
            ]),
        );
        assert_eq!(a.selected_row().unwrap().label, "Renamed conversation");
        assert!(a.take_auto_connects().is_empty());
    }

    #[test]
    fn a_platform_listing_renames_the_pane_instead_of_duplicating() {
        let mut a = loaded_app();
        let mut pane = session("ca_1", "nimble-otter");
        pane.durable_name = "railway-t5soqz".into();
        a.attach_session(pane, "ca_1".into());
        assert_eq!(a.selected_row().unwrap().label, "[S] railway-t5soqz");

        // The platform lists the same session under its own petname.
        a.sessions_loaded(
            (0, 0, 0, 0),
            "ca_1",
            Ok(vec![ConsoleSession {
                name: "merry-daisy-ld9".into(),
                kind: "SHELL".into(),
                command: Some("exec bash -l".into()),
                running: true,
                attached: true,
                created_at: chrono::DateTime::from_timestamp(1_700_000_000, 0),
                snapshot: None,
            }]),
        );

        assert_eq!(
            a.sessions[0].durable_name, "merry-daisy-ld9",
            "the pane took the listed name"
        );
        let rows = a.rows();
        let threads: Vec<&Row> = rows
            .iter()
            .filter(|r| matches!(r.kind, RowKind::Session(..)))
            .collect();
        assert_eq!(threads.len(), 1, "one session, one row: {rows:#?}");
        assert_eq!(
            threads[0].label, "[S] merry-daisy-ld9",
            "the shell name leads"
        );
        assert!(threads[0].note.is_empty(), "the orb and name are the row");
        assert_eq!(
            threads[0].status.as_deref(),
            Some("connected"),
            "and the pane counts as attached to it"
        );
        assert_eq!(
            a.selected_row().unwrap().label,
            "[S] merry-daisy-ld9",
            "the cursor followed the rename"
        );
    }

    /// A running agent with one listed, running session — the shape startup
    /// auto-connect acts on.
    fn app_with_listed_session() -> App {
        let mut a = loaded_app();
        a.sessions_loaded(
            (0, 0, 0, 0),
            "ca_1",
            Ok(vec![ConsoleSession {
                name: "merry-daisy-ld9".into(),
                kind: "SHELL".into(),
                command: None,
                running: true,
                attached: false,
                created_at: chrono::DateTime::from_timestamp(1_700_000_000, 0),
                snapshot: None,
            }]),
        );
        a
    }

    /// Coming up, every listed session on a running agent gets a background
    /// attach: returned once, spinner on while it is in flight, and the pane
    /// joins without stealing the keyboard when it opens.
    #[test]
    fn startup_auto_connects_listed_sessions_once() {
        let mut a = app_with_listed_session();
        assert_eq!(
            a.take_auto_connects(),
            vec![AutoConnect {
                agent_id: "ca_1".into(),
                agent_name: "nimble-otter".into(),
                environment_id: "env_prod".into(),
                session_name: "merry-daisy-ld9".into(),
            }]
        );
        let rows = a.rows();
        let row = rows
            .iter()
            .find(|r| matches!(r.kind, RowKind::Session(..)))
            .unwrap();
        assert_eq!(
            row.status.as_deref(),
            Some("connecting"),
            "the spinner is on while the attach is in flight"
        );
        assert!(
            a.take_auto_connects().is_empty(),
            "one attempt per session per run"
        );

        // The pane opens quietly: the spinner becomes the connected dot, and
        // focus, cursor and the welcome pane all stay put.
        let cursor = a.cursor;
        let mut pane = session("ca_1", "nimble-otter");
        pane.durable_name = "merry-daisy-ld9".into();
        a.attach_session_background(pane, "ca_1".into());
        assert!(a.connecting.is_empty());
        assert_eq!(a.focus, ManageFocus::Tree, "no focus steal");
        assert_eq!(a.active, None, "the pane waits to be picked");
        assert_eq!(a.cursor, cursor, "no cursor jump");
        let rows = a.rows();
        let row = rows
            .iter()
            .find(|r| matches!(r.kind, RowKind::Session(..)))
            .unwrap();
        assert_eq!(row.status.as_deref(), Some("connected"));
    }

    /// A sleeping agent's sessions are neither auto-attached nor ever shown
    /// green — a session can't be better off than the agent it runs on. The
    /// same for an agent mid-operation: `sleeping…` on the orb means hands
    /// off.
    #[test]
    fn a_sleeping_agents_sessions_are_never_green_or_auto_connected() {
        let mut a = app_with_listed_session();
        if let Load::Loaded(agents) = &mut a.tree[0].projects[0].envs[0].agents {
            agents[0].status = "sleeping".into();
        }
        assert!(a.take_auto_connects().is_empty());
        // Even a pane still open onto it does not make the row green.
        let mut pane = session("ca_1", "nimble-otter");
        pane.durable_name = "merry-daisy-ld9".into();
        a.sessions = vec![pane];
        let rows = a.rows();
        let row = rows
            .iter()
            .find(|r| matches!(r.kind, RowKind::Session(..)))
            .unwrap();
        assert_eq!(row.status, None, "not green while the agent sleeps");

        // A pending op holds auto-connect off too, even while the platform
        // still says running.
        let mut b = app_with_listed_session();
        b.ops.insert("ca_1".into(), AgentOp::Sleep.pending_label());
        assert!(b.take_auto_connects().is_empty());
    }

    /// Auto-connect stays quiet where a connect couldn't: `railway code` came
    /// for its one session, and an unregistered key would land every pane on
    /// the relay's signup screen.
    #[test]
    fn auto_connect_waits_for_the_gates() {
        let mut a = app_with_listed_session();
        a.quit_when_done = true;
        assert!(a.take_auto_connects().is_empty());

        let mut b = app_with_listed_session();
        b.ssh_key = SshKeyState::NeedsRegistration(offer());
        assert!(b.take_auto_connects().is_empty());
        // The gate clearing lets the next pass start it.
        b.ssh_key = SshKeyState::Ready;
        assert_eq!(b.take_auto_connects().len(), 1);
    }

    /// `x` closes our window onto a session; the next sweep must not reopen
    /// what was deliberately closed.
    #[test]
    fn a_closed_pane_is_not_reopened_by_auto_connect() {
        let mut a = app_with_listed_session();
        let mut pane = session("ca_1", "nimble-otter");
        pane.durable_name = "merry-daisy-ld9".into();
        a.attach_session(pane, "ca_1".into());
        assert!(a.take_auto_connects().is_empty(), "already attached");
        drop(a.take_session(0));
        assert!(a.take_auto_connects().is_empty(), "closed means closed");
    }

    /// Enter on a session whose attach is already in flight must not race a
    /// second ssh onto the same session — and a failed background attempt
    /// hands the row back to manual connects instead of retrying in a loop.
    #[test]
    fn a_connecting_session_refuses_a_second_attach() {
        let mut a = app_with_listed_session();
        assert_eq!(a.take_auto_connects().len(), 1);
        a.cursor = a
            .rows()
            .iter()
            .position(|r| matches!(r.kind, RowKind::Session(..)))
            .unwrap();
        assert_eq!(a.on_key(key(KeyCode::Enter)), None);
        assert!(a.status.starts_with("Connecting"), "{}", a.status);

        a.auto_connect_failed("merry-daisy-ld9", "relay said no");
        assert!(a.connecting.is_empty());
        assert!(
            a.take_auto_connects().is_empty(),
            "a failure is not retried in a loop"
        );
        let effect = a.on_key(key(KeyCode::Enter));
        assert!(
            matches!(effect, Some(Effect::Reattach { .. })),
            "but connecting by hand still works: {effect:?}"
        );
    }

    /// Startup fan-out is bounded: only [`AUTO_CONNECT_INFLIGHT`] attaches
    /// run at once, and the rest start as those land — never a thundering
    /// herd of ssh connections on a fleet-sized account.
    #[test]
    fn auto_connect_fan_out_is_capped() {
        let mut a = loaded_app();
        let sessions: Vec<ConsoleSession> = (0..5)
            .map(|i| ConsoleSession {
                name: format!("merry-daisy-{i}"),
                kind: "SHELL".into(),
                command: None,
                running: true,
                attached: false,
                created_at: chrono::DateTime::from_timestamp(1_700_000_000 + i, 0),
                snapshot: None,
            })
            .collect();
        a.sessions_loaded((0, 0, 0, 0), "ca_1", Ok(sessions));

        assert_eq!(a.take_auto_connects().len(), 3, "first batch fills the cap");
        assert!(
            a.take_auto_connects().is_empty(),
            "nothing more while the cap is full"
        );
        // One lands (or fails): exactly one slot's worth starts next.
        a.auto_connect_failed("merry-daisy-0", "relay said no");
        assert_eq!(a.take_auto_connects().len(), 1);
    }

    /// A listed session whose attach is in flight is not adoption material:
    /// renaming a freshly minted pane onto it would leave two panes sharing
    /// one durable name the moment the auto-connect lands.
    #[test]
    fn adoption_skips_sessions_with_an_attach_in_flight() {
        let mut a = loaded_app();
        // Listed as attached-and-running — normally prime adoption material —
        // but its background attach is still in flight.
        a.sessions_loaded(
            (0, 0, 0, 0),
            "ca_1",
            Ok(vec![ConsoleSession {
                name: "merry-daisy-ld9".into(),
                kind: "SHELL".into(),
                command: None,
                running: true,
                attached: true,
                created_at: chrono::DateTime::from_timestamp(1_700_000_000, 0),
                snapshot: None,
            }]),
        );
        assert_eq!(a.take_auto_connects().len(), 1, "the attach is in flight");

        // A fresh launch opens its own pane under a minted name.
        let mut pane = session("ca_1", "nimble-otter");
        pane.durable_name = "railway-fresh1".into();
        a.attach_session(pane, "ca_1".into());
        assert_eq!(
            a.sessions[0].durable_name, "railway-fresh1",
            "the minted pane must not steal the in-flight name"
        );

        // Once nothing is in flight for it, adoption works as before.
        a.connecting.clear();
        a.adopt_pane_sessions();
        assert_eq!(a.sessions[0].durable_name, "merry-daisy-ld9");
    }

    /// `n` targets the row under the cursor, as the footer advertises: a new
    /// agent lands in that row's project, not wherever the prompt happened
    /// to be aimed.
    #[test]
    fn n_retargets_to_the_cursor_row() {
        let mut a = loaded_app();
        a.target = None;
        a.cursor = a
            .rows()
            .iter()
            .position(|r| r.label == "nimble-otter")
            .unwrap();
        assert_eq!(a.on_key(key(KeyCode::Char('n'))), None);
        assert_eq!(a.screen, Screen::HarnessPick);
        assert_eq!(
            a.harness_pick_target.as_ref().map(|t| t.label()),
            Some("devtools/production".to_string()),
            "the new agent goes where the cursor points"
        );
    }

    /// The cursor opens on New Session, so `t` there is a letter, not a
    /// command. Retargeting is Ctrl-T everywhere.
    #[test]
    fn t_types_in_the_prompt_and_ctrl_t_retargets() {
        let mut a = app();
        a.on_key(key(KeyCode::Char('t')));
        a.on_key(key(KeyCode::Char('e')));
        assert_eq!(a.prompt, "te");
        assert_eq!(a.screen, Screen::Manage);

        a.on_key(ctrl('t'));
        assert_eq!(a.screen, Screen::TargetPick);
        assert_eq!(a.prompt, "te", "retargeting must not eat the draft");
    }

    /// A paste lands in the prompt as text — dictation tools insert whole
    /// utterances this way. Newlines stay newlines (the box holds paragraphs,
    /// same as ⇧enter types), but a line break is never taken as Enter: a
    /// paste must not launch mid-thought.
    #[test]
    fn a_paste_lands_in_the_prompt_with_its_newlines() {
        let mut a = app();
        a.on_key(key(KeyCode::Char('f')));
        assert_eq!(a.on_paste("ix the login bug\r\nthen deploy".into()), None);
        assert_eq!(a.prompt, "fix the login bug\nthen deploy");
        assert_eq!(a.screen, Screen::Manage, "a pasted newline is not Enter");
    }

    /// ⇧enter puts a newline in the draft; plain enter still launches. The
    /// same chord works in the ⌥p composer — the two boxes are one control.
    #[test]
    fn shift_enter_breaks_the_line_in_the_prompt_boxes() {
        let shift_enter = KeyEvent::new(KeyCode::Enter, KeyModifiers::SHIFT);

        let mut a = app();
        a.on_key(key(KeyCode::Char('f')));
        a.on_key(key(KeyCode::Char('i')));
        a.on_key(key(KeyCode::Char('x')));
        assert_eq!(a.on_key(shift_enter), None);
        a.on_key(key(KeyCode::Char('g')));
        a.on_key(key(KeyCode::Char('o')));
        assert_eq!(a.prompt, "fix\ngo");
        assert_eq!(a.screen, Screen::Manage, "⇧enter is not a launch");

        let mut b = loaded_app();
        b.screen = Screen::ManagePrompt;
        b.manage_prompt = Some("fix".into());
        assert_eq!(b.on_key(shift_enter), None);
        assert_eq!(b.manage_prompt.as_deref(), Some("fix\n"));
        assert_eq!(b.screen, Screen::ManagePrompt, "the composer stays up");

        // Most terminals can't say "shifted Enter" — the configured ones
        // (Claude Code's /terminal-setup included) send `ESC CR`, which
        // parses as alt+enter. Same newline.
        let alt_enter = KeyEvent::new(KeyCode::Enter, KeyModifiers::ALT);
        let mut c = app();
        c.on_key(key(KeyCode::Char('f')));
        assert_eq!(c.on_key(alt_enter), None);
        assert_eq!(c.prompt, "f\n");
        assert_eq!(c.screen, Screen::Manage, "⌥enter in the box is a newline");
    }

    /// Where typing is refused, pasting is too; and off the prompt a paste
    /// must not be sprayed across the hotkeys.
    #[test]
    fn a_paste_respects_prompt_focus_and_shell() {
        let mut a = app();
        a.cursor = 3; // the projects tail header, not the launcher
        assert_eq!(a.on_paste("stray".into()), None);
        assert_eq!(a.prompt, "", "tree rows are not a text box");

        a.cursor = 0;
        a.harness = HARNESSES.len() - 1;
        assert!(a.shell_selected());
        assert_eq!(a.on_paste("stray".into()), None);
        assert_eq!(
            a.prompt, "",
            "the box says typing is refused; so is a paste"
        );
    }

    /// The target chooser is the setup flow's project card, not a trip through
    /// the management tree: one list of places, enter, back to the prompt.
    #[test]
    fn picking_a_target_returns_to_the_tree_with_it_set() {
        let mut a = loaded_app();
        a.on_key(ctrl('t'));
        assert_eq!(a.screen, Screen::TargetPick);

        let rows = a.target_pick.as_ref().unwrap().rows(None);
        assert!(
            rows.iter()
                .any(|(label, _)| label == "devtools (production)"),
            "{rows:?}"
        );

        let index = rows
            .iter()
            .position(|(label, _)| label == "devtools (production)")
            .unwrap();
        for _ in 0..index {
            a.on_key(key(KeyCode::Down));
        }
        // Picking here is picking a default, not pointing this one run: the
        // choice is remembered, and the tree leads with it from now on.
        let Some(Effect::SaveDefaultProject(saved)) = a.on_key(key(KeyCode::Enter)) else {
            panic!("the choice should be saved");
        };
        assert_eq!(saved.project_id, "proj_1");
        assert_eq!(a.screen, Screen::Manage);
        assert!(a.target_pick.is_none());
        assert_eq!(a.default_project.as_deref(), Some("proj_1"));
        assert_eq!(a.target.unwrap().label(), "devtools/production");
    }

    /// A session whose agent is handling the mouse itself: the click goes to
    /// the agent, which is what makes its own clickable output work.
    /// Unix only: this needs a mode-setting escape sequence to survive the trip
    /// through the pty, and Windows' ConPTY interprets those for itself instead
    /// of passing them along, so the emulator never sees the mode change. Plain
    /// text round-trips fine, which is why the rest of these run everywhere.
    #[cfg(unix)]
    #[test]
    fn clicks_reach_an_agent_that_is_using_the_mouse() {
        let mut a = mouse_aware_app();

        // The first click focuses the pane and is ours — otherwise clicking
        // into a session would poke whatever is under the pointer.
        a.focus = ManageFocus::Tree;
        assert_eq!(a.on_mouse(MouseAction::Down, 40, 4), None);
        assert_eq!(a.focus, ManageFocus::Session);
        assert!(a.selection.is_some(), "the focusing click is still ours");

        // The next one goes to the agent: no selection, nothing to copy.
        a.on_mouse(MouseAction::Up, 40, 4);
        assert_eq!(a.on_mouse(MouseAction::Down, 40, 4), None);
        assert!(a.selection.is_none(), "the click went to the agent");
        a.on_mouse(MouseAction::Drag, 44, 4);
        assert!(a.selection.is_none(), "and so did the drag");
        assert_eq!(a.on_mouse(MouseAction::Up, 44, 4), None);
        assert!(a.pending_copy.is_none(), "nothing was selected to copy");
    }

    /// Shift is the terminal's own "this click is mine": it takes the mouse
    /// back for a selection even while the agent is using it.
    /// Unix only: this needs a mode-setting escape sequence to survive the trip
    /// through the pty, and Windows' ConPTY interprets those for itself instead
    /// of passing them along, so the emulator never sees the mode change. Plain
    /// text round-trips fine, which is why the rest of these run everywhere.
    #[cfg(unix)]
    #[test]
    fn shift_takes_a_click_back_from_the_agent() {
        let mut a = mouse_aware_app();
        a.focus = ManageFocus::Session;

        assert_eq!(a.on_mouse_shifted(MouseAction::Down, 40, 4, true), None);
        assert!(a.selection.is_some(), "shift selects locally");
        a.on_mouse_shifted(MouseAction::Drag, 48, 4, true);
        a.on_mouse_shifted(MouseAction::Up, 48, 4, true);
        assert!(a.pending_copy.is_some(), "and copies");
    }

    /// A link still wins: opening it is more use than anything the agent will
    /// do with the click, and it is the case this was built for.
    /// Unix only: this needs a mode-setting escape sequence to survive the trip
    /// through the pty, and Windows' ConPTY interprets those for itself instead
    /// of passing them along, so the emulator never sees the mode change. Plain
    /// text round-trips fine, which is why the rest of these run everywhere.
    #[cfg(unix)]
    #[test]
    fn a_link_is_opened_rather_than_handed_to_the_agent() {
        let mut a = mouse_aware_app();
        a.focus = ManageFocus::Session;
        let session = a.sessions.get_mut(0).unwrap();
        session.send(b"\x1b[10;1Hsee https://railway.com/deploy now\r\n");
        for _ in 0..60 {
            if a.sessions[0].url_at(9, 8).is_some() {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(10));
        }

        let (col, row) = (34 + 8, 3 + 9);
        assert_eq!(a.on_mouse(MouseAction::Down, col, row), None);
        assert_eq!(
            a.on_mouse(MouseAction::Up, col, row),
            Some(Effect::OpenUrl("https://railway.com/deploy".into()))
        );
    }

    /// An app with a session whose agent has mouse reporting on.
    #[cfg(unix)]
    fn mouse_aware_app() -> App {
        let mut a = loaded_app();
        let mut session = super::super::session::Session::for_test("ca_1", "nimble-otter").unwrap();
        session.resize(20, 60);
        session.send(b"\x1b[?1002h\x1b[?1006h\r\n");
        for _ in 0..60 {
            if session.wants_mouse() {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
        assert!(session.wants_mouse(), "the fixture should want the mouse");
        a.attach_session(session, "ca_1".into());
        a.panes.session = PaneBox {
            x: 34,
            y: 3,
            w: 60,
            h: 20,
        };
        a.panes.session_outer = PaneBox {
            x: 33,
            y: 2,
            w: 62,
            h: 22,
        };
        a
    }

    /// The pane owns the mouse, so the terminal's own link handling never sees
    /// the click — opening it ourselves is what puts it back.
    #[test]
    fn clicking_a_link_in_a_session_opens_it() {
        let mut a = loaded_app();
        let mut session = super::super::session::Session::for_test("ca_1", "nimble-otter").unwrap();
        session.resize(6, 60);
        session.send(b"see https://railway.com/deploy now\r\n");
        // ConPTY can deliver the echoed URL in several reads on a busy runner.
        // Wait for the complete link, rather than clicking a partial hostname.
        for _ in 0..500 {
            if session.url_at(0, 8).as_deref() == Some("https://railway.com/deploy") {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
        assert_eq!(
            session.url_at(0, 8).as_deref(),
            Some("https://railway.com/deploy")
        );
        a.attach_session(session, "ca_1".into());
        a.panes.session = PaneBox {
            x: 34,
            y: 3,
            w: 60,
            h: 6,
        };
        a.panes.session_outer = PaneBox {
            x: 33,
            y: 2,
            w: 62,
            h: 8,
        };

        // Press and release without moving: that is a click.
        let (col, row) = (34 + 8, 3);
        assert_eq!(a.on_mouse(MouseAction::Down, col, row), None);
        assert_eq!(
            a.on_mouse(MouseAction::Up, col, row),
            Some(Effect::OpenUrl("https://railway.com/deploy".into()))
        );
        assert!(a.selection.is_none(), "opening a link is not a selection");
        assert!(a.pending_copy.is_none(), "and it is not a copy");
    }

    /// Dragging from a link selects it instead. Copying a URL and opening one
    /// are both things people do; the pointer moving is what tells them apart.
    #[test]
    fn dragging_from_a_link_copies_rather_than_opening_it() {
        let mut a = loaded_app();
        let mut session = super::super::session::Session::for_test("ca_1", "nimble-otter").unwrap();
        session.resize(6, 60);
        session.send(b"see https://railway.com/deploy now\r\n");
        for _ in 0..40 {
            if session
                .with_screen(|s| s.contents_between(0, 0, 0, u16::MAX))
                .is_some_and(|line| line.contains("railway.com"))
            {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
        a.attach_session(session, "ca_1".into());
        a.panes.session = PaneBox {
            x: 34,
            y: 3,
            w: 60,
            h: 6,
        };
        a.panes.session_outer = PaneBox {
            x: 33,
            y: 2,
            w: 62,
            h: 8,
        };

        a.on_mouse(MouseAction::Down, 34 + 8, 3);
        a.on_mouse(MouseAction::Drag, 34 + 20, 3);
        assert_eq!(a.on_mouse(MouseAction::Up, 34 + 20, 3), None);
        assert!(a.pending_copy.is_some(), "a drag is a selection");
    }

    /// A double click on ordinary output is not a link, and must not be treated
    /// as one.
    #[test]
    fn clicking_plain_text_opens_nothing() {
        let mut a = loaded_app();
        let mut session = super::super::session::Session::for_test("ca_1", "nimble-otter").unwrap();
        session.resize(6, 60);
        session.send(b"just some output\r\n");
        std::thread::sleep(std::time::Duration::from_millis(80));
        a.attach_session(session, "ca_1".into());
        a.panes.session = PaneBox {
            x: 34,
            y: 3,
            w: 60,
            h: 6,
        };
        a.panes.session_outer = PaneBox {
            x: 33,
            y: 2,
            w: 62,
            h: 8,
        };

        let (col, row) = (34 + 2, 3);
        a.on_mouse(MouseAction::Down, col, row);
        assert_eq!(a.on_mouse(MouseAction::Up, col, row), None);
    }

    /// The prompt box is clickable: wherever the cursor has wandered in the
    /// tree, clicking the box puts the keyboard back in the prompt.
    #[test]
    fn clicking_the_prompt_box_takes_the_keyboard_back() {
        let mut a = app();
        a.cursor = 3; // off the launcher, into the tree
        a.panes.prompt = PaneBox {
            x: 8,
            y: 10,
            w: 74,
            h: 6,
        };

        assert_eq!(a.on_mouse(MouseAction::Down, 20, 12), None);
        assert_eq!(a.cursor, 0, "the click lands on the New Session row");
        assert_eq!(a.focus, ManageFocus::Tree);

        // And typing goes into it, rather than being read as a tree hotkey.
        a.on_key(key(KeyCode::Char('h')));
        assert_eq!(a.prompt, "h");
    }

    /// Clicking the launcher pane must not hand focus to a session pane that
    /// isn't there — the keyboard stays with the tree, where the prompt reads
    /// it.
    #[test]
    fn clicking_the_launcher_pane_keeps_the_keyboard() {
        let mut a = app();
        a.panes.session_outer = PaneBox {
            x: 34,
            y: 2,
            w: 64,
            h: 20,
        };
        assert_eq!(a.on_mouse(MouseAction::Down, 40, 5), None);
        assert_eq!(a.focus, ManageFocus::Tree, "no session to type into");
        a.on_key(key(KeyCode::Char('h')));
        assert_eq!(a.prompt, "h");
    }

    /// ⌥f gives the session pane the screen, and gives it back.
    #[test]
    fn alt_f_maximizes_the_session_pane_and_restores_it() {
        let mut a = loaded_app();
        a.attach_session(
            super::super::session::Session::for_test("ca_1", "nimble-otter").unwrap(),
            "ca_1".into(),
        );
        assert!(a.active.is_some());

        assert_eq!(a.on_key(alt('f')), None);
        assert!(a.maximized);
        assert_eq!(
            a.focus,
            ManageFocus::Session,
            "nothing else is on screen to have the keyboard"
        );

        assert_eq!(a.on_key(alt('f')), Some(Effect::RefreshAll));
        assert!(!a.maximized);
    }

    /// Including from inside the session, which is where you are when you want
    /// the room. Every other key still belongs to the agent.
    #[test]
    fn alt_f_reaches_the_layout_from_inside_a_focused_session() {
        let mut a = loaded_app();
        a.attach_session(
            super::super::session::Session::for_test("ca_1", "nimble-otter").unwrap(),
            "ca_1".into(),
        );
        a.focus = ManageFocus::Session;

        assert_eq!(a.on_key(alt('f')), None);
        assert!(a.maximized);

        // ⌥s is not intercepted there — it belongs to whatever is running.
        a.on_key(alt('s'));
        assert!(a.settings.is_none());
    }

    /// The harness exiting ends its pane. Under `railway code` — one session,
    /// `quit_when_done` — the TUI leaves with it, back to the local prompt;
    /// this is what ctrl-c out of the agent lands on now that the pane's
    /// remote command has no shell fallback to strand you in.
    #[test]
    fn an_ended_session_under_railway_code_quits_the_tui() {
        let mut a = loaded_app();
        a.quit_when_done = true;
        a.attach_session(
            super::super::session::Session::for_test("ca_1", "nimble-otter").unwrap(),
            "ca_1".into(),
        );

        // Still running: nothing to reap.
        assert_eq!(a.reap_ended_sessions(), None);
        assert_eq!(a.sessions.len(), 1);

        a.sessions[0].end_for_test();
        assert_eq!(a.reap_ended_sessions(), Some(Effect::Quit));
        assert!(a.sessions.is_empty());
        let note = a.exit_note.as_deref().expect("says the agent still runs");
        assert!(note.contains("nimble-otter"), "{note}");
    }

    /// From bare `railway ca`, an ended pane closes back to the tree — the
    /// browser was asked for, so it stays.
    #[test]
    fn an_ended_session_from_the_tree_closes_back_to_it() {
        let mut a = loaded_app();
        a.attach_session(
            super::super::session::Session::for_test("ca_1", "nimble-otter").unwrap(),
            "ca_1".into(),
        );
        a.sessions[0].end_for_test();

        assert_eq!(a.reap_ended_sessions(), None);
        assert!(a.sessions.is_empty());
        assert_eq!(a.focus, ManageFocus::Tree);
        assert!(a.toast.is_some(), "the close is announced, not silent");
        assert!(a.exit_note.is_none());
    }

    /// An ssh that exits nonzero is a dropped connection or a failed connect,
    /// not a finished session: its pane holds the only account of what
    /// happened and the recovery keys can reconnect it, so it stays up — even
    /// under `railway code`.
    #[test]
    fn a_dropped_connection_keeps_its_pane() {
        let mut a = loaded_app();
        a.quit_when_done = true;
        a.attach_session(
            super::super::session::Session::for_test("ca_1", "nimble-otter").unwrap(),
            "ca_1".into(),
        );
        a.sessions[0].end_dropped_for_test();

        assert_eq!(a.reap_ended_sessions(), None);
        assert_eq!(a.sessions.len(), 1, "the pane stays for recovery");
    }

    /// The session the user was typing into finishing WITHOUT them asking —
    /// no recent input, not a boot crash — starts a replacement on the same
    /// agent, with the same harness and no prompt draft riding along.
    #[test]
    fn an_unasked_finish_of_the_focused_pane_respawns() {
        let mut a = loaded_app();
        a.attach_session(session("ca_1", "nimble-otter"), "ca_1".into());
        assert_eq!(a.focus, ManageFocus::Session, "attach focused the pane");
        a.prompt = "half a sentence".into();
        a.sessions[0].backdate_spawn_for_test(std::time::Duration::from_secs(60));
        a.sessions[0].end_for_test();

        let Some(Effect::Launch(req)) = a.reap_ended_sessions() else {
            panic!("expected a replacement launch");
        };
        assert_eq!(req.agent_id.as_deref(), Some("ca_1"));
        assert!(
            req.force_new,
            "the old durable session exited with its harness"
        );
        assert_eq!(req.prompt, None, "a respawn must not submit the draft");
        let toast = a.toast.as_ref().expect("announced").text.clone();
        assert!(toast.contains("starting a new one"), "{toast}");
    }

    /// Input just before the end is the user ending it — ctrl-c, `/exit` —
    /// and a finish that soon after connecting is a harness that cannot
    /// start. Neither earns a replacement, and nor does a pane the user
    /// was not focused on.
    #[test]
    fn deliberate_fast_or_background_finishes_do_not_respawn() {
        // Typed moments before the exit: the user asked for this.
        let mut a = loaded_app();
        a.attach_session(session("ca_1", "nimble-otter"), "ca_1".into());
        a.sessions[0].backdate_spawn_for_test(std::time::Duration::from_secs(60));
        a.sessions[0].touch_input_for_test();
        a.sessions[0].end_for_test();
        assert_eq!(a.reap_ended_sessions(), None, "ctrl-c must stay ended");

        // Died within the settle window: respawning would loop on a harness
        // that cannot boot.
        let mut b = loaded_app();
        b.attach_session(session("ca_1", "nimble-otter"), "ca_1".into());
        b.sessions[0].end_for_test();
        assert_eq!(b.reap_ended_sessions(), None, "a boot crash must not loop");

        // The keyboard was in the tree: an unwatched pane ending must not
        // conjure a session under the user's hands.
        let mut c = loaded_app();
        c.attach_session(session("ca_1", "nimble-otter"), "ca_1".into());
        c.focus = ManageFocus::Tree;
        c.sessions[0].backdate_spawn_for_test(std::time::Duration::from_secs(60));
        c.sessions[0].end_for_test();
        assert_eq!(c.reap_ended_sessions(), None, "background panes just close");
    }

    /// A drop of the pane ON SCREEN pulls the keyboard to it — the banner
    /// says "r reconnects", and r has to mean that without a click first —
    /// but only once: stepping back out with Esc sticks, however many times
    /// the reap runs over the same corpse.
    #[test]
    fn a_dropped_connection_takes_focus_once() {
        let mut a = loaded_app();
        a.attach_session(session("ca_1", "nimble-otter"), "ca_1".into());
        // The user is browsing the tree, cursor off the launcher, with the
        // pane still showing, when its connection dies.
        a.focus = ManageFocus::Tree;
        a.cursor = a
            .rows()
            .iter()
            .position(|r| matches!(r.kind, RowKind::Session(0, 0, 0, 0, _)))
            .unwrap();
        assert_eq!(a.active, Some(0), "the attached pane is on screen");
        a.sessions[0].end_dropped_for_test();

        assert_eq!(a.reap_ended_sessions(), None);
        assert_eq!(a.focus, ManageFocus::Session, "the drop took the keyboard");

        // r now means reconnect, immediately.
        let effect = a.on_key(key(KeyCode::Char('r')));
        assert!(
            matches!(effect, Some(Effect::Reattach { .. })),
            "r reconnects the dropped pane: {effect:?}"
        );

        // The same drop noticed again must not wrestle Esc for the keyboard.
        let mut b = loaded_app();
        b.attach_session(session("ca_1", "nimble-otter"), "ca_1".into());
        b.sessions[0].end_dropped_for_test();
        assert_eq!(b.reap_ended_sessions(), None);
        assert_eq!(b.on_key(key(KeyCode::Esc)), None);
        assert_eq!(b.focus, ManageFocus::Tree, "esc stepped out");
        assert_eq!(b.reap_ended_sessions(), None);
        assert_eq!(b.focus, ManageFocus::Tree, "and it stays stepped out");
    }

    /// A drop never takes the keyboard from someone who wasn't looking at
    /// the pane: not from the launcher prompt mid-sentence, and not for a
    /// background pane (an auto-connect they never opened). The banner
    /// waits on the pane instead.
    #[test]
    fn a_background_drop_does_not_steal_the_keyboard() {
        // Mid-typing at the launcher: cursor 0, prompt focused, pane showing
        // the welcome screen — keystrokes must keep landing in the draft.
        let mut a = loaded_app();
        a.attach_session(session("ca_1", "nimble-otter"), "ca_1".into());
        a.focus = ManageFocus::Tree;
        a.cursor = 0;
        a.prompt_focused = true;
        a.prompt = "half a thought".into();
        a.sessions[0].end_dropped_for_test();
        assert_eq!(a.reap_ended_sessions(), None);
        assert_eq!(
            a.focus,
            ManageFocus::Tree,
            "typing at the launcher is never interrupted"
        );

        // A pane that is not the one on screen: no steal either.
        let mut b = loaded_app();
        b.attach_session(session("ca_1", "one"), "ca_1".into());
        b.attach_session(session("ca_1", "two"), "ca_1".into());
        b.focus = ManageFocus::Tree;
        b.active = Some(1);
        b.cursor = b
            .rows()
            .iter()
            .position(|r| matches!(r.kind, RowKind::Session(0, 0, 0, 0, _)))
            .unwrap();
        b.sessions[0].end_dropped_for_test();
        assert_eq!(b.reap_ended_sessions(), None);
        assert_eq!(
            b.focus,
            ManageFocus::Tree,
            "a background pane's drop waits on its row"
        );
    }

    /// Every bare Escape belongs to the harness — even two quick ones. The
    /// old double-tap release cost the user their running turn (a single Esc
    /// cancels Claude mid-run, and the first tap always went through).
    /// ⌥⇧esc releases without sending anything.
    #[test]
    fn bare_escapes_belong_to_the_harness_and_alt_shift_esc_releases() {
        let mut a = loaded_app();
        a.attach_session(session("ca_1", "nimble-otter"), "ca_1".into());
        assert_eq!(a.focus, ManageFocus::Session);

        assert_eq!(a.on_key(key(KeyCode::Esc)), None);
        assert_eq!(a.on_key(key(KeyCode::Esc)), None);
        assert_eq!(
            a.focus,
            ManageFocus::Session,
            "two quick escapes are the harness's, not a release"
        );

        // ⌥⇧esc steps out — and unfolds a maximized layout, since focus on
        // an invisible tree helps nobody.
        a.maximized = true;
        let chord = KeyEvent::new(KeyCode::Esc, KeyModifiers::ALT | KeyModifiers::SHIFT);
        assert_eq!(a.on_key(chord), None);
        assert_eq!(a.focus, ManageFocus::Tree, "⌥⇧esc steps out");
        assert!(!a.maximized, "and brings the tree back");
    }

    /// A drop never steals the keyboard out from under a dialog — a y/n
    /// confirm answered into the wrong place is how sessions get killed by
    /// accident.
    #[test]
    fn a_drop_does_not_take_focus_from_a_dialog() {
        let mut a = loaded_app();
        a.attach_session(session("ca_1", "nimble-otter"), "ca_1".into());
        a.focus = ManageFocus::Tree;
        a.confirm = Some(PendingConfirm {
            op: AgentOp::Delete,
            agent_id: "ca_1".into(),
            environment_id: "env_prod".into(),
            agent_name: "nimble-otter".into(),
        });
        a.sessions[0].end_dropped_for_test();
        assert_eq!(a.reap_ended_sessions(), None);
        assert_eq!(a.focus, ManageFocus::Tree, "the dialog keeps the keyboard");
    }

    /// Ended but with the exit status still on its way: no call is made yet —
    /// the loop's poll (`awaiting_exit_status`) asks again — and the pane is
    /// not closed on a guess.
    #[test]
    fn a_pane_awaiting_its_exit_status_is_left_alone() {
        let mut a = loaded_app();
        a.attach_session(
            super::super::session::Session::for_test("ca_1", "nimble-otter").unwrap(),
            "ca_1".into(),
        );
        // `cat` is still running, so try_wait has nothing yet.
        a.sessions[0].mark_ended();

        assert_eq!(a.reap_ended_sessions(), None);
        assert_eq!(a.sessions.len(), 1);
        assert!(a.awaiting_exit_status(), "the loop should keep polling");
    }

    /// `railway code` collapses the tree from the first frame, before there is
    /// a session to collapse it around — the loading pane stands in for one.
    /// Without this the tree would be drawn for the whole boot and then vanish,
    /// which is the flicker the collapsed layout exists to avoid.
    #[test]
    fn a_launch_in_flight_fills_the_pane_on_its_own() {
        let mut a = loaded_app();
        a.maximized = true;
        assert!(!a.pane_is_full(), "nothing to show yet");

        a.start_loading(&launch_req());
        assert!(a.pane_is_full(), "the loading pane has the screen");

        // A launch that fails leaves neither: the tree comes back rather than
        // the screen going blank.
        a.launch_failed("no".into());
        assert!(!a.pane_is_full());
    }

    fn with_sessions(names: &[&str]) -> App {
        let mut a = loaded_app();
        for name in names {
            a.attach_session(
                super::super::session::Session::for_test(name, name).unwrap(),
                (*name).to_string(),
            );
        }
        a
    }

    /// ⌥] walks the open panes and wraps, and ⌥[ walks them the other way.
    #[test]
    fn alt_bracket_cycles_forward_through_open_sessions_and_wraps() {
        let mut a = with_sessions(&["ca_1", "ca_2", "ca_3"]);
        assert_eq!(a.active, Some(2), "the newest attach is active");

        assert_eq!(a.on_key(alt(']')), None);
        assert_eq!(a.active, Some(0), "wraps past the end");
        assert_eq!(a.on_key(alt(']')), None);
        assert_eq!(a.active, Some(1));
        assert_eq!(a.on_key(alt(']')), None);
        assert_eq!(a.active, Some(2), "back where it started");
    }

    /// The reverse chord retraces the forward one exactly, wrap included.
    #[test]
    fn alt_left_bracket_cycles_backward_and_wraps() {
        let mut a = with_sessions(&["ca_1", "ca_2", "ca_3"]);
        assert_eq!(a.active, Some(2), "the newest attach is active");

        assert_eq!(a.on_key(alt('[')), None);
        assert_eq!(a.active, Some(1));
        assert_eq!(a.on_key(alt('[')), None);
        assert_eq!(a.active, Some(0));
        assert_eq!(a.on_key(alt('[')), None);
        assert_eq!(a.active, Some(2), "wraps past the front");
    }

    /// The chord has to work from inside the pane — that is where you are when
    /// you want the next one. ⌥s must still fall through to the agent.
    #[test]
    fn alt_bracket_cycles_from_inside_a_focused_session() {
        let mut a = with_sessions(&["ca_1", "ca_2"]);
        a.focus = ManageFocus::Session;

        assert_eq!(a.on_key(alt(']')), None);
        assert_eq!(a.active, Some(0));
        assert_eq!(a.focus, ManageFocus::Session, "cycling does not detach");

        // ⌥[ is taken from the agent too — going back is the same moment as
        // going forward.
        assert_eq!(a.on_key(alt('[')), None);
        assert_eq!(a.active, Some(1), "retraces the forward step");
        assert_eq!(a.focus, ManageFocus::Session, "cycling does not detach");

        // Still only ⌥f, ⌥] and ⌥[ are taken from the agent.
        let screen = a.screen;
        a.on_key(alt('s'));
        assert_eq!(a.screen, screen, "⌥s belongs to whatever is running");
    }

    /// Cycling is scoped to panes that already exist: a keystroke must never
    /// turn into a cold boot on an agent you were passing through.
    #[test]
    fn alt_bracket_says_so_rather_than_no_opping() {
        let mut a = loaded_app();
        assert_eq!(a.on_key(alt(']')), None);
        assert_eq!(a.active, None);
        assert!(a.status.contains("No open sessions"), "{}", a.status);

        let mut b = with_sessions(&["ca_1"]);
        assert_eq!(b.on_key(alt(']')), None);
        assert_eq!(b.active, Some(0), "the only pane stays put");
        assert!(b.status.contains("Only one session"), "{}", b.status);
    }

    /// Without Option-as-Meta macOS composes the bracket chords into curly
    /// quotes — singles for ⌥], doubles for ⌥[ — and each pair folds its
    /// shifted form into the same chord.
    #[test]
    fn option_composed_curly_quotes_are_the_bracket_chords() {
        for composed in ['\u{2018}', '\u{2019}'] {
            let mut a = with_sessions(&["ca_1", "ca_2"]);
            assert_eq!(a.on_key(key(KeyCode::Char(composed))), None);
            assert_eq!(a.active, Some(0), "composed {composed:?} should cycle");
            assert!(a.prompt.is_empty(), "a chord is not text");
        }
        for composed in ['\u{201C}', '\u{201D}'] {
            let mut a = with_sessions(&["ca_1", "ca_2"]);
            assert_eq!(a.on_key(key(KeyCode::Char(composed))), None);
            assert_eq!(a.active, Some(0), "composed {composed:?} should cycle");
            assert!(a.prompt.is_empty(), "a chord is not text");
        }
    }

    /// ⌥[ only exists where the terminal can say it unambiguously — as a real
    /// ALT event under the kitty protocol, or as macOS's composed quote. In a
    /// legacy Meta terminal it is the CSI prefix `ESC [` and never reaches the
    /// key handler at all, so recognizing the clean forms risks nothing.
    #[test]
    fn alt_left_bracket_is_the_reverse_chord() {
        assert_eq!(alt_chord(&alt('[')), Some('['));
        assert_eq!(
            alt_chord(&key(KeyCode::Char('\u{201C}'))),
            Some('['),
            "the composed ⌥[ quote is the same chord"
        );
    }

    /// ⌥⇧[ and ⌥⇧] are the advertised cycle chords — `ESC {` collides with
    /// nothing, where `ESC [` is the CSI prefix half the world has claimed.
    /// Shift reaches us as the brace character, folded onto the same chords.
    #[test]
    fn alt_shift_brackets_are_the_same_chords() {
        assert_eq!(alt_chord(&alt('{')), Some('['));
        assert_eq!(alt_chord(&alt('}')), Some(']'));
        // macOS composes ⌥⇧[ to the closing curly double quote; same chord.
        assert_eq!(alt_chord(&key(KeyCode::Char('\u{201D}'))), Some('['));
        assert_eq!(alt_chord(&key(KeyCode::Char('\u{2019}'))), Some(']'));
    }

    /// A screen of empty pane is not a state worth reaching by accident.
    #[test]
    fn alt_f_does_nothing_without_a_session() {
        let mut a = loaded_app();
        assert_eq!(a.on_key(alt('f')), None);
        assert!(!a.maximized);
        assert!(a.status.contains("Connect to a session"), "{}", a.status);

        // And on the menu it is not a layout at all.
        let mut b = app();
        b.on_key(alt('f'));
        assert!(!b.maximized);
    }

    /// Ending the last session takes the layout with it, rather than leaving a
    /// full screen of nothing.
    #[test]
    fn closing_the_last_session_restores_the_tree() {
        let mut a = loaded_app();
        a.attach_session(
            super::super::session::Session::for_test("ca_1", "nimble-otter").unwrap(),
            "ca_1".into(),
        );
        a.on_key(alt('f'));
        assert!(a.maximized);

        a.take_session(0);
        assert!(!a.maximized);
        assert_eq!(a.focus, ManageFocus::Tree);
    }

    /// A pane whose ssh has died must offer a way back in: `r` drops the dead
    /// pane and dials the same durable session again — the whole recovery
    /// path a dropped connection used to be missing.
    #[test]
    fn a_dead_pane_reconnects_with_r() {
        let mut a = with_sessions(&["ca_1"]);
        a.focus = ManageFocus::Session;
        a.sessions[0].mark_ended();

        let effect = a.on_key(key(KeyCode::Char('r')));
        assert_eq!(
            effect,
            Some(Effect::Reattach {
                agent_id: "ca_1".into(),
                agent_name: "ca_1".into(),
                // for_test connects as agent:test:test — the environment is
                // read back out of the relay target.
                environment_id: "test".into(),
                session_name: "test".into(),
            })
        );
        assert!(a.sessions.is_empty(), "the dead pane is gone");
        assert!(a.status.contains("Reconnecting"), "{}", a.status);
    }

    /// Keystrokes into a dead pane go nowhere on purpose — a pty nothing
    /// reads must not eat typing — and the recovery keys do their jobs.
    #[test]
    fn a_dead_pane_swallows_typing_and_answers_the_recovery_keys() {
        let mut a = with_sessions(&["ca_1"]);
        a.focus = ManageFocus::Session;
        a.sessions[0].mark_ended();

        assert_eq!(a.on_key(key(KeyCode::Char('h'))), None, "typing vanishes");
        assert_eq!(
            a.on_key(key(KeyCode::Char('x'))),
            Some(Effect::CloseSession { index: 0 })
        );
        // Enter means reconnect here — it is the reflex after "connection
        // closed", and there is nothing else it could mean.
        assert!(matches!(
            a.on_key(key(KeyCode::Enter)),
            Some(Effect::Reattach { .. })
        ));
    }

    /// Escape on a dead pane releases to the tree: the agent that would have
    /// received it is not on the other end any more.
    #[test]
    fn escape_on_a_dead_pane_returns_to_the_tree() {
        let mut a = with_sessions(&["ca_1"]);
        a.focus = ManageFocus::Session;
        a.sessions[0].mark_ended();

        assert_eq!(a.on_key(key(KeyCode::Esc)), None);
        assert_eq!(a.focus, ManageFocus::Tree);
    }

    /// "Connect" must never resolve to a corpse: an agent whose only pane has
    /// died reads as not connected, and the dead pane is cleared out of the
    /// way of the fresh connection.
    #[test]
    fn a_dead_pane_does_not_count_as_connected() {
        let mut a = with_sessions(&["ca_1"]);
        a.sessions[0].mark_ended();

        assert!(!a.activate_session("ca_1"));
        assert!(a.sessions.is_empty(), "the dead pane was cleared");
    }

    /// Enter on a session row whose pane has died reconnects instead of
    /// focusing the corpse. The old behaviour was a trap: the dead pane
    /// blocked every reattach to its session until it was closed from the
    /// agent row, which nothing advertised.
    #[test]
    fn enter_on_a_session_row_with_a_dead_pane_reattaches() {
        let mut a = loaded_app();
        if let Load::Loaded(agents) = &mut a.tree[0].projects[0].envs[0].agents {
            agents[0].expanded = true;
            agents[0].sessions = LoadSessions::Loaded(vec![ConsoleSession {
                // The durable name for_test sessions carry.
                name: "test".into(),
                kind: "SHELL".into(),
                command: None,
                running: true,
                attached: false,
                created_at: None,
                snapshot: None,
            }]);
        }
        a.attach_session(
            super::super::session::Session::for_test("ca_1", "nimble-otter").unwrap(),
            "ca_1".into(),
        );
        a.sessions[0].mark_ended();
        a.focus = ManageFocus::Tree;
        a.cursor = a.rows().iter().position(|r| r.label == "[S] test").unwrap();

        let effect = a.on_key(key(KeyCode::Enter));
        assert_eq!(
            effect,
            Some(Effect::Reattach {
                agent_id: "ca_1".into(),
                agent_name: "nimble-otter".into(),
                environment_id: "env_prod".into(),
                session_name: "test".into(),
            })
        );
        assert!(a.sessions.is_empty(), "the dead pane went first");
    }

    /// A live pane keeps its keys: recovery must only take over once the
    /// connection is actually gone.
    #[test]
    fn a_live_pane_still_owns_the_keyboard() {
        let mut a = with_sessions(&["ca_1"]);
        a.focus = ManageFocus::Session;

        assert_eq!(a.on_key(key(KeyCode::Char('r'))), None);
        assert_eq!(a.on_key(key(KeyCode::Char('x'))), None);
        assert_eq!(
            a.sessions.len(),
            1,
            "r and x were typing, not pane commands"
        );
        assert_eq!(a.focus, ManageFocus::Session);
    }

    /// So does Esc from the tree: with the pane maximized it restores the
    /// layout first, and quits only from the restored screen.
    #[test]
    fn escaping_a_maximized_pane_restores_the_tree() {
        let mut a = loaded_app();
        a.attach_session(
            super::super::session::Session::for_test("ca_1", "nimble-otter").unwrap(),
            "ca_1".into(),
        );
        a.on_key(alt('f'));
        a.focus = ManageFocus::Tree;
        assert_eq!(a.on_key(key(KeyCode::Esc)), None);
        assert_eq!(a.screen, Screen::Manage);
        assert!(!a.maximized);
        // With nothing maximized, Esc keeps walking up the chain instead of
        // leaving: a thread hands the cursor back to the launcher.
        a.cursor = a
            .rows()
            .iter()
            .position(|r| matches!(r.kind, RowKind::Session(0, 0, 0, 0, _)))
            .unwrap();
        assert_eq!(a.on_key(key(KeyCode::Esc)), None);
        assert_eq!(a.cursor, 0);
    }

    /// Cancelling saves nothing — the default is only changed by choosing one.
    #[test]
    fn cancelling_the_target_picker_saves_nothing() {
        let mut a = loaded_app();
        a.default_project = Some("proj_9".into());
        a.on_key(ctrl('t'));
        assert_eq!(a.on_key(key(KeyCode::Esc)), None);
        assert_eq!(a.default_project.as_deref(), Some("proj_9"));
    }

    /// Escape leaves the target alone rather than clearing it.
    #[test]
    fn cancelling_the_target_picker_keeps_the_current_target() {
        let mut a = loaded_app();
        a.target = Some(Target {
            project_id: "proj_1".into(),
            project_name: "devtools".into(),
            environment_id: "env_prod".into(),
            environment_name: "production".into(),
        });
        a.on_key(ctrl('t'));
        // And it opens on the target already set, so enter changes nothing.
        let picker = a.target_pick.as_ref().unwrap();
        assert_eq!(
            picker.options[picker.cursor].environment_id, "env_prod",
            "the picker opens on the current target"
        );

        a.on_key(key(KeyCode::Esc));
        assert_eq!(a.screen, Screen::Manage);
        assert_eq!(a.target.unwrap().label(), "devtools/production");
    }

    /// Enter with no target can't launch into nowhere; it asks for one instead.
    #[test]
    fn launching_without_a_target_asks_for_one() {
        let mut a = app();
        a.prompt = "fix the tests".into();
        assert_eq!(a.on_key(key(KeyCode::Enter)), None);
        assert_eq!(a.screen, Screen::TargetPick);
        assert_eq!(a.prompt, "fix the tests");
    }

    #[test]
    fn enter_on_the_prompt_launches_into_the_target_with_the_text() {
        let mut a = app();
        a.target = Some(Target {
            project_id: "proj_1".into(),
            project_name: "devtools".into(),
            environment_id: "env_prod".into(),
            environment_name: "production".into(),
        });
        for c in "fix the tests".chars() {
            a.on_key(key(KeyCode::Char(c)));
        }
        let Effect::Launch(req) = a.on_key(key(KeyCode::Enter)).unwrap() else {
            panic!("expected a launch");
        };
        assert_eq!(req.prompt.as_deref(), Some("fix the tests"));
        assert_eq!(req.harness, "claude");
        assert_eq!(req.agent_id, None);
        assert!(req.force_new, "each prompt gets a fresh agent");
    }

    /// A blank enter launches the session bare — the harness comes up empty,
    /// ready for its first prompt inside — rather than nagging for a prompt.
    /// Whitespace never rides along as one.
    #[test]
    fn a_blank_prompt_launches_a_bare_session() {
        let mut a = app();
        a.target = Some(Target {
            project_id: "p".into(),
            project_name: "p".into(),
            environment_id: "e".into(),
            environment_name: "e".into(),
        });
        a.prompt = "   ".into();
        let Some(Effect::Launch(req)) = a.on_key(key(KeyCode::Enter)) else {
            panic!("a blank enter launches bare");
        };
        assert_eq!(req.prompt, None, "whitespace is not a prompt");
        assert!(req.force_new, "each launch is its own agent");

        // Shell too: its box says enter launches bare.
        a.harness = HARNESSES.len() - 1;
        let Effect::Launch(req) = a.on_key(key(KeyCode::Enter)).unwrap() else {
            panic!("expected a launch");
        };
        assert_eq!(req.prompt, None);
        assert!(req.force_new, "each launch is its own agent");
    }

    #[test]
    fn tab_switches_opencode_editions_and_keeps_the_prompt() {
        let mut a = app();
        a.set_harness(Some("opencode"));
        a.prompt = "explain the code".into();
        a.on_key(key(KeyCode::Tab));
        assert_eq!(a.harness_name(), "opencode2");
        assert_eq!(a.prompt, "explain the code");
        a.on_key(key(KeyCode::Tab));
        assert_eq!(a.harness_name(), "opencode");
    }

    #[test]
    fn picker_has_one_opencode_row_and_launches_the_beta_choice() {
        let mut a = app();
        a.set_harness(Some("opencode"));
        a.screen = Screen::HarnessPick;
        a.harness_pick = Some(a.harness);
        a.harness_pick_agent = Some("existing-agent".into());
        a.target = Some(Target {
            project_id: "p".into(),
            project_name: "p".into(),
            environment_id: "e".into(),
            environment_name: "e".into(),
        });
        a.on_key(key(KeyCode::Tab));
        let beta = a.harness_pick.unwrap();
        assert_eq!(HARNESSES[beta], "opencode2");
        assert_eq!(harness_picker_indices(beta).len(), HARNESSES.len() - 1);
        a.on_key(key(KeyCode::Down));
        assert_eq!(HARNESSES[a.harness_pick.unwrap()], "shell");
        a.on_key(key(KeyCode::Up));
        assert_eq!(HARNESSES[a.harness_pick.unwrap()], "opencode");
        a.on_key(key(KeyCode::Tab));
        let Some(Effect::Launch(request)) = a.on_key(key(KeyCode::Enter)) else {
            panic!("expected launch");
        };
        assert_eq!(request.harness, "opencode2");
        assert_eq!(request.agent_id.as_deref(), Some("existing-agent"));
    }

    #[test]
    fn shift_tab_cycles_the_harness_on_the_prompt() {
        let mut a = app();
        assert_eq!(a.harness_name(), "claude");
        a.set_harness(Some("railway"));
        a.on_key(key(KeyCode::BackTab));
        assert_eq!(a.harness_name(), "grok");
        a.on_key(key(KeyCode::BackTab));
        assert_eq!(a.harness_name(), "codex");
        a.on_key(key(KeyCode::BackTab));
        assert_eq!(a.harness_name(), "claude");
        a.on_key(key(KeyCode::BackTab));
        assert_eq!(a.harness_name(), "opencode");
        a.on_key(key(KeyCode::BackTab));
        assert_eq!(a.harness_name(), "opencode2");
        a.on_key(key(KeyCode::BackTab));
        assert_eq!(a.harness_name(), "shell", "shell closes the cycle");
        a.on_key(key(KeyCode::BackTab));
        assert_eq!(a.harness_name(), "railway", "cycling wraps");
    }

    /// The order is a contract: `railway` is the unconfigured default, and
    /// `shell` sits after every real agent on every surface that lists them.
    #[test]
    fn railway_leads_the_harnesses_and_shell_closes_them() {
        assert_eq!(HARNESSES.first(), Some(&"railway"));
        assert_eq!(HARNESSES.last(), Some(&"shell"));
        assert_eq!(default_harnesses(), &HARNESSES[..HARNESSES.len() - 1]);
        assert!(
            !default_harnesses().contains(&"shell"),
            "shell is not a saveable default"
        );
    }

    /// The shell option takes no prompt: the menu box refuses keystrokes while
    /// it is selected, keeps a draft typed for a real agent, and launches
    /// without one.
    #[test]
    fn the_prompt_goes_inert_on_shell() {
        let mut a = app();
        a.target = Some(Target {
            project_id: "p".into(),
            project_name: "p".into(),
            environment_id: "e".into(),
            environment_name: "e".into(),
        });
        a.on_key(key(KeyCode::Char('h')));
        a.on_key(key(KeyCode::Char('i')));
        assert_eq!(a.prompt, "hi");
        while a.harness_name() != "shell" {
            a.on_key(key(KeyCode::BackTab));
        }
        a.on_key(key(KeyCode::Char('x')));
        a.on_key(key(KeyCode::Backspace));
        assert_eq!(a.prompt, "hi", "typing is refused, the draft survives");
        let Effect::Launch(req) = a.on_key(key(KeyCode::Enter)).unwrap() else {
            panic!("expected a launch");
        };
        assert_eq!(req.harness, "shell");
        assert_eq!(req.prompt, None, "a leftover draft must not ride along");
        while a.harness_name() != "claude" {
            a.on_key(key(KeyCode::BackTab));
        }
        a.on_key(key(KeyCode::Char('!')));
        assert_eq!(a.prompt, "hi!", "typing resumes on a real agent");
    }

    fn alt(c: char) -> KeyEvent {
        KeyEvent::new(KeyCode::Char(c), KeyModifiers::ALT)
    }

    /// Alt-chords are the point: they work from the prompt, where a bare letter
    /// is text.
    #[test]
    fn alt_chords_work_while_typing() {
        let mut a = app();
        a.on_key(key(KeyCode::Char('s')));
        assert_eq!(a.prompt, "s", "a bare letter is still text");
        assert_eq!(a.on_key(alt('s')), None);
        assert_eq!(a.screen, Screen::Settings, "⌥s opens settings in place");
        assert_eq!(a.prompt, "s", "the chord must not touch the draft");
    }

    /// Terminals that compose Option+letter instead of sending Meta still get
    /// the chords there are.
    #[test]
    fn macos_composed_option_characters_are_accepted() {
        let mut a = app();
        assert_eq!(a.on_key(key(KeyCode::Char('ß'))), None);
        assert_eq!(a.screen, Screen::Settings);
        assert!(a.prompt.is_empty(), "a chord is not text");
    }

    #[test]
    fn option_t_opens_the_target_picker_without_changing_the_draft_or_theme() {
        for chord in [
            alt('t'),
            alt('T'),
            key(KeyCode::Char('')),
            key(KeyCode::Char('')),
        ] {
            let mut a = app();
            a.prompt = "keep this draft".into();
            let theme = a.theme.slug;
            assert_eq!(a.on_key(chord), None);
            assert_eq!(a.screen, Screen::TargetPick);
            assert_eq!(a.theme.slug, theme);
            assert_eq!(a.prompt, "keep this draft");
        }
    }

    /// ⌥r asks for everything again, from wherever you are: the tree, the menu
    /// prompt where a bare `r` is text, and its macOS composed form.
    #[test]
    fn alt_r_refreshes_from_anywhere() {
        let mut a = loaded_app();
        assert_eq!(a.on_key(alt('r')), Some(Effect::RefreshAll));
        assert!(a.refresh_announce, "a keypress deserves an answer");

        let mut b = app();
        b.on_key(key(KeyCode::Char('r')));
        assert_eq!(b.prompt, "r", "a bare letter is still text");
        assert_eq!(b.on_key(alt('r')), Some(Effect::RefreshAll));
        assert_eq!(b.prompt, "r", "the chord must not touch the draft");

        // ⌥R, and the characters a stock macOS terminal composes for both.
        let mut c = app();
        assert_eq!(
            c.on_key(KeyEvent::new(KeyCode::Char('R'), KeyModifiers::ALT)),
            Some(Effect::RefreshAll)
        );
        let mut d = app();
        assert_eq!(d.on_key(key(KeyCode::Char('®'))), Some(Effect::RefreshAll));
        assert!(d.prompt.is_empty(), "a chord is not text");
        let mut e = app();
        assert_eq!(e.on_key(key(KeyCode::Char(''))), Some(Effect::RefreshAll));
    }

    /// And from inside a session, where the tree is what you cannot see. A chord
    /// that silently did nothing half the time you pressed it would be worse
    /// than one the agent never gets.
    #[test]
    fn alt_r_refreshes_from_a_focused_session() {
        let mut a = with_sessions(&["ca_1"]);
        a.focus = ManageFocus::Session;
        assert_eq!(a.on_key(alt('r')), Some(Effect::RefreshAll));
        // A bare `r` still belongs to whatever is running in there.
        assert_eq!(a.on_key(key(KeyCode::Char('r'))), None);
    }

    /// `r` stays the cheap one — the environment under the cursor, one request —
    /// and the two must not collapse into each other.
    #[test]
    fn bare_r_still_refreshes_only_this_environment() {
        let mut a = loaded_app();
        a.cursor = a
            .rows()
            .iter()
            .position(|r| r.label == "nimble-otter")
            .unwrap();
        assert_eq!(
            a.on_key(key(KeyCode::Char('r'))),
            Some(Effect::LoadAgents {
                environment_id: "env_prod".into(),
                path: (0, 0, 0)
            })
        );
    }

    /// Ctrl+T remains a compatibility alias for Option+T.
    #[test]
    fn ctrl_t_still_opens_the_target_picker() {
        let mut a = app();
        let theme = a.theme.slug;
        a.on_key(ctrl('t'));
        assert_eq!(a.theme.slug, theme, "^t must not change the theme");
        assert_eq!(a.screen, Screen::TargetPick);
    }

    /// Finishing the wizard marks the app configured, so a re-run is offered
    /// through ⌥s rather than pushed at every start.
    #[test]
    fn finishing_setup_marks_the_app_configured() {
        let mut a = app();
        a.configured = false;
        a.start_wizard(false);
        assert_eq!(a.screen, Screen::Setup);
        let wizard = a.wizard.as_mut().unwrap();
        wizard.step = crate::commands::cloud_agent::tui::wizard::Step::Theme;
        assert!(matches!(
            a.on_key(key(KeyCode::Enter)),
            Some(Effect::SaveSetup(_))
        ));
        assert!(a.configured);
        assert_eq!(a.screen, Screen::Manage, "setup lands back on the tree");
    }

    /// Settings keeps the chord setup had, from either focus and mid-prompt.
    #[test]
    fn alt_s_opens_settings_from_anywhere() {
        let mut a = app();
        a.prompt = "fix the tests".into();
        assert_eq!(a.on_key(alt('s')), None);
        assert_eq!(a.screen, Screen::Settings);
        assert_eq!(a.prompt, "fix the tests", "the draft survives");
    }

    /// The settings card edits in place: changing the agent is one keypress
    /// and one save, not a walk through the flow.
    #[test]
    fn settings_cycles_the_agent_and_saves() {
        let mut a = app();
        a.on_key(alt('s'));
        let Some(Effect::SaveSettings(outcome)) = a.on_key(key(KeyCode::Right)) else {
            panic!("expected a save");
        };
        assert_eq!(outcome.agent, "opencode");
        assert_eq!(
            outcome.theme, a.theme.slug,
            "the rest rides along unchanged"
        );
    }

    /// The theme applies to the whole screen as it cycles — a colour scheme
    /// is picked by looking at it, exactly like the wizard's theme step.
    #[test]
    fn settings_previews_the_theme_live() {
        let mut a = app();
        a.on_key(alt('s'));
        for _ in 0..3 {
            a.on_key(key(KeyCode::Down)); // down to the theme row
        }
        let first = a.theme.slug;
        let Some(Effect::SaveSettings(outcome)) = a.on_key(key(KeyCode::Right)) else {
            panic!("expected a save");
        };
        assert_ne!(a.theme.slug, first, "the whole screen follows");
        assert_eq!(outcome.theme, a.theme.slug);
    }

    /// The card opens showing the saved default project, not a blank.
    #[test]
    fn settings_opens_on_the_saved_default_project() {
        let mut a = app();
        a.default_project = Some("proj_1".into());
        a.target = Some(Target {
            project_id: "proj_1".into(),
            project_name: "devtools".into(),
            environment_id: "env_prod".into(),
            environment_name: "production".into(),
        });
        a.on_key(alt('s'));
        let settings = a.settings.as_ref().unwrap();
        assert_eq!(
            settings.project.as_ref().unwrap().project_name,
            "devtools",
            "seeded from the target, which holds the saved default"
        );
    }

    /// The last row hands over to the wizard, skipping its intro — choosing
    /// it has already answered "set up?".
    #[test]
    fn settings_can_replay_first_run_setup() {
        let mut a = app();
        a.on_key(alt('s'));
        for _ in 0..5 {
            a.on_key(key(KeyCode::Down)); // down to the last row
        }
        assert_eq!(a.on_key(key(KeyCode::Enter)), None);
        assert_eq!(a.screen, Screen::Setup);
        assert!(a.settings.is_none(), "the card handed over");
        assert_eq!(
            a.wizard.as_ref().unwrap().step,
            crate::commands::cloud_agent::tui::wizard::Step::Target
        );
    }

    /// Esc closes the card without ceremony: every change already saved.
    #[test]
    fn settings_escape_just_closes() {
        let mut a = app();
        a.on_key(alt('s'));
        assert_eq!(a.on_key(key(KeyCode::Esc)), None);
        assert_eq!(a.screen, Screen::Manage);
        assert!(a.settings.is_none());
    }

    /// ←/→ move through the draft, and editing happens at the cursor — a typo
    /// mid-sentence is fixed in place, not by erasing back to it.
    #[test]
    fn arrow_keys_move_the_prompt_cursor() {
        let mut a = app();
        for c in "fix bug".chars() {
            a.on_key(key(KeyCode::Char(c)));
        }
        for _ in 0..3 {
            a.on_key(key(KeyCode::Left));
        }
        a.on_key(key(KeyCode::Char('a')));
        assert_eq!(a.prompt, "fix abug");
        a.on_key(key(KeyCode::Backspace));
        assert_eq!(a.prompt, "fix bug");
        a.on_key(key(KeyCode::Home));
        a.on_key(key(KeyCode::Right));
        a.on_key(key(KeyCode::Backspace));
        assert_eq!(a.prompt, "ix bug");
        a.on_key(key(KeyCode::End));
        a.on_key(key(KeyCode::Char('!')));
        assert_eq!(a.prompt, "ix bug!");
        // The cursor never runs past either end.
        for _ in 0..20 {
            a.on_key(key(KeyCode::Right));
        }
        assert_eq!(a.prompt_cursor, a.prompt.chars().count());
    }

    /// A paste lands at the cursor, like typing does.
    #[test]
    fn a_paste_lands_at_the_cursor() {
        let mut a = app();
        for c in "fix the".chars() {
            a.on_key(key(KeyCode::Char(c)));
        }
        for _ in 0..3 {
            a.on_key(key(KeyCode::Left));
        }
        a.on_paste("up ".into());
        assert_eq!(a.prompt, "fix up the");
    }

    /// Sessions are named universally by `harness-<random>`: the harness is
    /// read off the launch line's binary, and a relay petname folds down to
    /// its random suffix. No prompt parsing — the task lives in the detail
    /// card's command line, not the name.
    #[test]
    fn session_names_are_harness_led() {
        let minted = ConsoleSession {
            name: "claude-one".into(),
            kind: "SHELL".into(),
            command: Some(
                "export PATH=/x; export RAILWAY_CODE_AUTOSTARTED=1; \
                 claude 'fix the login bug'; printf 'x'"
                    .into(),
            ),
            running: true,
            attached: false,
            created_at: None,
            snapshot: None,
        };
        assert_eq!(
            minted.short_name(),
            "claude-one",
            "a minted name already leads with its harness — and the prompt \
             stays out of it"
        );

        // The relay names sessions itself; the harness is prefixed onto the
        // petname's random suffix, flags and prompt ignored alike.
        let renamed = ConsoleSession {
            name: "merry-daisy-ld9".into(),
            kind: "SHELL".into(),
            command: Some(
                "export RAILWAY_CODE_AUTOSTARTED=1; railway-agent-tui --session \
                 \"$RAILWAY_DURABLE_SESSION_NAME\" 'ship the release'; printf 'x'"
                    .into(),
            ),
            running: true,
            attached: false,
            created_at: None,
            snapshot: None,
        };
        assert_eq!(renamed.short_name(), "railway-ld9");

        // No command on record: the name stands as it is.
        let unknown = ConsoleSession {
            name: "quiet-depot-x7v".into(),
            kind: "SHELL".into(),
            command: None,
            running: true,
            attached: false,
            created_at: None,
            snapshot: None,
        };
        assert_eq!(unknown.short_name(), "quiet-depot-x7v");
    }

    #[test]
    fn esc_walks_home_and_q_quits_there() {
        let mut a = app();
        a.prompt = "half a thought".into();
        // One step per press: the draft first…
        assert_eq!(a.on_key(key(KeyCode::Esc)), None);
        assert!(a.prompt.is_empty());
        // …then the prompt lets go of the keyboard…
        assert_eq!(a.on_key(key(KeyCode::Esc)), None);
        assert!(!a.prompt_focused, "home: letters are keys again");
        // …and Esc never quits — q does, now that it is a key.
        assert_eq!(a.on_key(key(KeyCode::Esc)), None);
        assert_eq!(a.on_key(key(KeyCode::Char('q'))), Some(Effect::Quit));
    }

    /// From a thread, Esc returns to the launcher with the prompt focused —
    /// the same place the screen opens on.
    #[test]
    fn esc_from_a_thread_returns_to_the_launcher() {
        let mut a = loaded_app();
        a.cursor = a
            .rows()
            .iter()
            .position(|r| r.label == "nimble-otter")
            .unwrap();
        assert_eq!(a.on_key(key(KeyCode::Esc)), None);
        assert_eq!(a.cursor, 0, "back on the launcher");
        assert!(a.new_session_selected(), "with the prompt focused");
    }

    /// The loading screen has to show the task, not just a spinner — that is
    /// the whole reason the wait moved inside the TUI.
    #[test]
    fn launching_shows_the_task_and_its_steps() {
        let mut a = app();
        let req = LaunchRequest {
            project_id: "p".into(),
            environment_id: "e".into(),
            agent_id: None,
            session_name: None,
            force_new: false,
            new_session: false,
            harness: "claude".into(),
            prompt: Some("fix the tests".into()),
            label: "devtools/production".into(),
            base: Default::default(),
        };
        a.start_loading(&req);
        assert!(a.loading.active, "the pane shows the wait");
        assert_eq!(
            a.screen,
            Screen::Manage,
            "the tree stays visible while it starts"
        );
        assert_eq!(a.loading.prompt.as_deref(), Some("fix the tests"));
        assert_eq!(a.loading.target, "devtools/production");

        a.loading_step("Creating a cloud agent".into());
        a.loading_step("Creating a cloud agent".into());
        a.loading_step("Provisioning claude".into());
        assert_eq!(a.loading.steps.len(), 2, "repeats read as a stall");

        // The tree is still usable while an agent boots.
        assert_eq!(a.on_key(key(KeyCode::Down)), None);
    }

    #[test]
    fn a_failed_launch_lands_in_manage_with_the_reason() {
        let mut a = app();
        a.launch_failed("no codex sign-in".into());
        assert_eq!(a.screen, Screen::Manage);
        // The reason rides an error toast, not the header status line.
        let toast = a.toast.as_ref().expect("an error toast");
        assert!(!toast.ok);
        assert!(toast.text.contains("no codex sign-in"), "{}", toast.text);
    }

    /// Revealing an environment expands its ancestors and refetches — the agent
    /// may have just been created, so a cached list would not contain it.
    #[test]
    fn revealing_an_environment_expands_and_refetches() {
        let mut a = app();
        a.agents_loaded((0, 0, 0), Ok(vec![]));
        let effect = a.reveal_environment("env_prod").unwrap();
        assert_eq!(
            effect,
            Effect::LoadAgents {
                environment_id: "env_prod".into(),
                path: (0, 0, 0)
            }
        );
        assert!(a.tree[0].expanded);
        assert!(a.tree[0].projects[0].expanded);
        assert!(a.tree[0].projects[0].envs[0].expanded);
        assert!(a.reveal_environment("nope").is_none());
    }

    /// The agent a launch opened should be under the cursor once its row shows
    /// up, however late the fetch lands.
    #[test]
    fn a_pending_selection_lands_when_the_rows_arrive() {
        let mut a = app();
        a.tree[0].projects[0].expanded = true;
        a.tree[0].projects[0].envs[0].expanded = true;
        a.pending_select = Some("ca_2".into());
        a.agents_loaded(
            (0, 0, 0),
            Ok(vec![
                agent("ca_1", "first", "sleeping"),
                agent("ca_2", "second", "running"),
            ]),
        );
        assert_eq!(a.selected_row().unwrap().label, "second");
        assert!(a.pending_select.is_none(), "consumed once it lands");
    }

    #[test]
    fn bootstrap_form_targets_the_selected_vm() {
        let mut a = loaded_app();
        a.cursor = a
            .rows()
            .iter()
            .position(|r| r.label == "nimble-otter")
            .unwrap();
        assert_eq!(
            a.on_key(key(KeyCode::Char('b'))),
            Some(Effect::LoadBootstraps {
                environment_id: "env_prod".into()
            })
        );
        assert_eq!(a.screen, Screen::BootstrapSetup);
        let form = a.bootstrap_form.as_ref().unwrap();
        assert_eq!(form.snapshot.as_ref().unwrap().agent_id, "ca_1");
        assert!(!form.return_to_prompt);
        a.on_key(key(KeyCode::Esc));
        assert!(a.ops.is_empty());
        a.agents_loaded(
            (0, 0, 0),
            Ok(vec![agent("ca_1", "nimble-otter", "sleeping")]),
        );
        a.cursor = a
            .rows()
            .iter()
            .position(|r| r.label == "nimble-otter")
            .unwrap();
        assert_eq!(a.on_key(key(KeyCode::Char('b'))), None);
        assert!(a.status.contains("Wake"));
    }

    /// Delete asks first; anything but `y` cancels. A mistyped key must never
    /// be read as consent to destroy a disk.
    #[test]
    fn delete_requires_a_yes() {
        let mut a = loaded_app();
        a.cursor = a
            .rows()
            .iter()
            .position(|r| r.label == "nimble-otter")
            .unwrap();

        assert_eq!(a.on_key(key(KeyCode::Char('d'))), None);
        let confirm = a.confirm.clone().expect("delete should ask");
        assert_eq!(confirm.op, AgentOp::Delete);
        assert!(confirm.question().contains("nimble-otter"));

        // A stray key cancels and runs nothing.
        assert_eq!(a.on_key(key(KeyCode::Char('j'))), None);
        assert!(a.confirm.is_none());
        assert!(a.ops.is_empty());

        a.on_key(key(KeyCode::Char('d')));
        let effect = a.on_key(key(KeyCode::Char('y'))).unwrap();
        assert_eq!(
            effect,
            Effect::Agent {
                op: AgentOp::Delete,
                agent_id: "ca_1".into(),
                environment_id: "env_prod".into()
            }
        );
        assert_eq!(a.ops.get("ca_1").copied(), Some("deleting…"));
    }

    /// Sleep and wake send intent even when the last observation suggests a
    /// no-op. The server can see a newer state than this tree.
    #[test]
    fn sleep_and_wake_let_the_server_decide_no_ops() {
        let mut a = loaded_app();
        a.cursor = a
            .rows()
            .iter()
            .position(|r| r.label == "nimble-otter")
            .unwrap();

        // Last observed running, but it may have slept elsewhere since then.
        assert!(matches!(
            a.on_key(key(KeyCode::Char('w'))),
            Some(Effect::Agent {
                op: AgentOp::Wake,
                ..
            })
        ));
        assert_eq!(
            a.on_key(key(KeyCode::Char('w'))),
            None,
            "no duplicate requests"
        );
        a.agent_op_finished("ca_1", "env_prod", AgentOp::Wake, None);
        a.agents_loaded(
            (0, 0, 0),
            Ok(vec![agent("ca_1", "nimble-otter", "running")]),
        );

        let effect = a.on_key(key(KeyCode::Char('s'))).unwrap();
        assert_eq!(
            effect,
            Effect::Agent {
                op: AgentOp::Sleep,
                agent_id: "ca_1".into(),
                environment_id: "env_prod".into()
            }
        );
        assert_eq!(a.ops.get("ca_1").copied(), Some("sleeping…"));

        // While an op is in flight the row is claimed, and a second key does
        // not queue a duplicate.
        assert_eq!(a.on_key(key(KeyCode::Char('s'))), None);
        let row = a.selected_row().unwrap();
        assert_eq!(
            row.status.as_deref(),
            Some("sleeping…"),
            "the orb carries the op"
        );

        // Accepted is not arrived: the label stays up and the environment keeps
        // being asked until the agent says it is actually asleep.
        a.agent_op_finished("ca_1", "env_prod", AgentOp::Sleep, None);
        assert!(a.watching_agents());
        assert_eq!(
            a.selected_row().unwrap().status.as_deref(),
            Some("sleeping…")
        );

        a.agents_loaded(
            (0, 0, 0),
            Ok(vec![agent("ca_1", "nimble-otter", "sleeping")]),
        );
        assert!(!a.watching_agents(), "it arrived");
        assert!(a.ops.is_empty());
        assert_eq!(
            a.selected_row().unwrap().status.as_deref(),
            Some("sleeping")
        );

        // Last observed sleeping, but it may have woken elsewhere since then.
        assert!(matches!(
            a.on_key(key(KeyCode::Char('s'))),
            Some(Effect::Agent {
                op: AgentOp::Sleep,
                ..
            })
        ));
    }

    #[test]
    fn terminal_observations_end_operation_watches_immediately() {
        for op in [AgentOp::Wake, AgentOp::Sleep] {
            for status in ["crashed", "failed", "deleting", "future_state"] {
                let mut a = loaded_app();
                a.ops.insert("ca_1".into(), op.pending_label());
                a.agent_op_finished("ca_1", "env_prod", op, None);
                a.agents_loaded((0, 0, 0), Ok(vec![agent("ca_1", "nimble-otter", status)]));
                assert!(!a.watching_agents(), "{op:?}: {status}");
                assert!(a.ops.is_empty(), "{op:?}: {status}");
                assert!(a.status.contains("nimble-otter"), "{}", a.status);
                assert!(a.status.contains(status), "{}", a.status);
                assert!(a.watch_tick().is_none());
            }
        }
    }

    #[test]
    fn operation_watches_require_a_successful_refresh_of_their_environment() {
        for old_status in ["running", "failed"] {
            let mut a = loaded_app();
            a.agents_loaded(
                (0, 0, 0),
                Ok(vec![agent("ca_1", "nimble-otter", old_status)]),
            );
            a.ops.insert("ca_1".into(), AgentOp::Wake.pending_label());
            a.agent_op_finished("ca_1", "env_prod", AgentOp::Wake, None);
            a.agents_loaded((0, 0, 0), Err("temporarily unavailable".into()));
            assert!(
                a.watching_agents(),
                "old {old_status} is not a new observation"
            );
            a.agents_loaded((0, 0, 1), Ok(vec![]));
            assert!(
                a.watching_agents(),
                "an unrelated environment cannot settle this watch"
            );
            a.agents_loaded(
                (0, 0, 0),
                Ok(vec![agent("ca_1", "nimble-otter", "running")]),
            );
            assert!(!a.watching_agents());
            assert!(a.ops.is_empty());
        }
    }

    /// The bug this exists for: a wake is accepted long before the VM is up,
    /// and the list keeps saying `sleeping` in the meantime. Dropping the label
    /// on the first answer made a wake that was working look like one that had
    /// failed and rolled back.
    #[test]
    fn a_wake_holds_its_label_until_the_agent_is_actually_running() {
        let mut a = loaded_app();
        a.cursor = a
            .rows()
            .iter()
            .position(|r| r.label == "nimble-otter")
            .unwrap();
        a.agents_loaded(
            (0, 0, 0),
            Ok(vec![agent("ca_1", "nimble-otter", "sleeping")]),
        );

        assert!(matches!(
            a.on_key(key(KeyCode::Char('w'))),
            Some(Effect::Agent {
                op: AgentOp::Wake,
                ..
            })
        ));
        a.agent_op_finished("ca_1", "env_prod", AgentOp::Wake, None);

        // Still asleep as far as the platform is concerned. The row must not
        // flip back.
        a.agents_loaded(
            (0, 0, 0),
            Ok(vec![agent("ca_1", "nimble-otter", "sleeping")]),
        );
        assert_eq!(a.selected_row().unwrap().status.as_deref(), Some("waking…"));
        assert!(a.watching_agents(), "and it keeps asking");
        assert!(a.watch_tick().is_some(), "by refetching the environment");

        // Booting is still not up.
        a.agents_loaded(
            (0, 0, 0),
            Ok(vec![agent("ca_1", "nimble-otter", "starting")]),
        );
        assert_eq!(a.selected_row().unwrap().status.as_deref(), Some("waking…"));
        assert!(a.watching_agents());

        a.agents_loaded(
            (0, 0, 0),
            Ok(vec![agent("ca_1", "nimble-otter", "running")]),
        );
        assert!(!a.watching_agents());
        assert!(a.ops.is_empty());
        assert_eq!(a.selected_row().unwrap().status.as_deref(), Some("running"));
    }

    /// An agent that never arrives stops being waited on, and the row goes back
    /// to reporting what the platform says rather than lying forever.
    #[test]
    fn a_wake_that_never_lands_gives_up() {
        let mut a = loaded_app();
        a.agents_loaded(
            (0, 0, 0),
            Ok(vec![agent("ca_1", "nimble-otter", "sleeping")]),
        );
        a.agent_op_finished("ca_1", "env_prod", AgentOp::Wake, None);
        a.ops.insert("ca_1".into(), "waking…");

        a.watching.get_mut("ca_1").unwrap().until = std::time::Instant::now();
        a.watch_tick();
        assert!(!a.watching_agents());
        assert!(a.ops.is_empty());
        assert!(a.status.contains("longer than expected"), "{}", a.status);
    }

    /// An agent that disappears while being waited on is not waited on.
    #[test]
    fn a_watched_agent_that_vanishes_is_dropped() {
        let mut a = loaded_app();
        a.agent_op_finished("ca_1", "env_prod", AgentOp::Wake, None);
        a.agents_loaded((0, 0, 0), Ok(Vec::new()));
        assert!(!a.watching_agents());
        assert!(a.ops.is_empty());
    }

    /// A delete has no state to settle into — the row goes away.
    #[test]
    fn a_delete_does_not_wait_for_anything() {
        let mut a = loaded_app();
        a.ops.insert("ca_1".into(), "deleting…");
        a.agent_op_finished("ca_1", "env_prod", AgentOp::Delete, None);
        assert!(!a.watching_agents());
        assert!(a.ops.is_empty());
    }

    #[test]
    fn lifecycle_keys_need_an_agent_row() {
        let mut a = loaded_app();
        // Home: letters are keys, but there is no agent under the cursor.
        a.cursor = 0;
        a.prompt_focused = false;
        assert_eq!(a.on_key(key(KeyCode::Char('d'))), None);
        assert!(a.confirm.is_none());
        assert!(a.status.contains("Select an agent"));
    }

    #[test]
    fn a_failed_op_reports_and_clears_its_label() {
        let mut a = loaded_app();
        a.ops.insert("ca_1".into(), "deleting…");
        a.agent_op_finished(
            "ca_1",
            "env_prod",
            AgentOp::Delete,
            Some("permission denied".into()),
        );
        assert!(a.ops.is_empty());
        assert!(!a.watching_agents(), "there is nothing to wait for");
        assert!(a.status.contains("permission denied"));
    }

    /// An agent as the loader builds one: no sessions fetched, collapsed.
    /// The reported bug: create a new agent, land in its session, and the tree
    /// still calls it "waking" while you are typing into it.
    ///
    /// The launcher attaches as soon as the SSH route answers, which is several
    /// seconds before the status projection reaches RUNNING (#1098). Nothing
    /// was wrong with the pane — the row was reporting a status the CLI itself
    /// had already decided not to wait for.
    #[test]
    fn an_agent_with_a_pane_open_is_not_still_waking() {
        let mut a = loaded_app();
        a.agents_loaded(
            (0, 0, 0),
            Ok(vec![agent("ca_new", "just-created", "starting")]),
        );

        let status_for = |a: &App| {
            a.rows()
                .into_iter()
                .find(|r| r.label == "just-created")
                .unwrap()
                .status
        };
        assert_eq!(
            status_for(&a).as_deref(),
            Some("starting"),
            "no pane yet: report what we know"
        );

        a.attach_session(
            super::super::session::Session::for_test("ca_new", "just-created").unwrap(),
            "ca_new".to_string(),
        );

        assert_eq!(
            status_for(&a).as_deref(),
            Some("running"),
            "a live pane is proof the agent is up, whatever the projection says"
        );
    }

    /// The override is scoped to the lag it exists for. A pane can outlive what
    /// it is attached to, and every other status alongside a live pane is news
    /// rather than latency.
    #[test]
    fn only_starting_is_overridden_by_a_live_pane() {
        let mut a = loaded_app();
        let attached: std::collections::HashMap<&str, std::time::Duration> =
            std::iter::once(("ca_1", std::time::Duration::from_secs(1))).collect();

        for status in ["sleeping", "crashed", "failed", "deleting"] {
            let agent = agent("ca_1", "nimble-otter", status);
            assert_eq!(
                displayed_status(&agent, &attached),
                status,
                "{status} must survive an attached pane"
            );
        }

        // And an ended pane stops being evidence of anything.
        a.agents_loaded(
            (0, 0, 0),
            Ok(vec![agent("ca_1", "nimble-otter", "starting")]),
        );
        let session = super::super::session::Session::for_test("ca_1", "nimble-otter").unwrap();
        session.mark_ended();
        a.attach_session(session, "ca_1".to_string());
        assert_eq!(
            a.rows()
                .into_iter()
                .find(|r| r.label == "nimble-otter")
                .unwrap()
                .status
                .as_deref(),
            Some("starting")
        );
    }

    /// A pane opening settles the wake it was waiting on, rather than leaving
    /// `waking…` up and the 1.5s watch tick asking about an agent that is
    /// already taking keystrokes.
    #[test]
    fn attaching_settles_the_wake_it_was_waiting_for() {
        let mut a = loaded_app();
        a.agents_loaded(
            (0, 0, 0),
            Ok(vec![agent("ca_1", "nimble-otter", "starting")]),
        );
        a.ops.insert("ca_1".into(), AgentOp::Wake.pending_label());
        a.agent_op_finished("ca_1", "env_prod", AgentOp::Wake, None);
        assert!(a.watching_agents());

        a.attach_session(
            super::super::session::Session::for_test("ca_1", "nimble-otter").unwrap(),
            "ca_1".to_string(),
        );

        assert!(a.ops.is_empty(), "the wake landed");
        assert!(
            !a.watching_agents(),
            "and there is nothing left to poll for"
        );
    }

    /// A sleep is not settled by a pane opening — nothing about an attach says
    /// the agent went to sleep, and dropping the label would strand the poll.
    #[test]
    fn attaching_does_not_settle_an_unrelated_op() {
        let mut a = loaded_app();
        a.ops.insert("ca_1".into(), AgentOp::Sleep.pending_label());
        a.agent_op_finished("ca_1", "env_prod", AgentOp::Sleep, None);

        a.attach_session(
            super::super::session::Session::for_test("ca_1", "nimble-otter").unwrap(),
            "ca_1".to_string(),
        );

        assert_eq!(a.ops.get("ca_1").copied(), Some("sleeping…"));
        assert!(a.watching_agents());
    }

    /// The bound that keeps the override honest. A pane that has been open
    /// well past the measured lag is no longer evidence the agent is merely
    /// catching up — it is evidence it is stuck, and that is exactly the case
    /// the user hit. The row must go back to reporting what the platform says.
    #[test]
    fn a_long_open_pane_stops_excusing_a_starting_agent() {
        let agent = agent("ca_1", "nimble-otter", "starting");
        let attached = |secs| -> std::collections::HashMap<&str, std::time::Duration> {
            std::iter::once(("ca_1", std::time::Duration::from_secs(secs))).collect()
        };

        assert_eq!(
            displayed_status(&agent, &attached(1)),
            "running",
            "just attached: the projection is still catching up"
        );
        assert_eq!(
            displayed_status(&agent, &attached(STARTING_GRACE.as_secs() - 1)),
            "running",
            "inside the grace window"
        );
        assert_eq!(
            displayed_status(&agent, &attached(STARTING_GRACE.as_secs())),
            "starting",
            "past it, the platform's answer stands — a stuck agent must not read as running"
        );
        assert_eq!(
            displayed_status(&agent, &attached(600)),
            "starting",
            "and it stays that way"
        );
    }

    /// The grace window has to cover a real boot with room to spare, or a
    /// normal launch would flicker into looking stuck. Worst observed was
    /// 14.2s from create across ten runs, and the pane opens partway into that.
    #[test]
    fn the_grace_window_clears_a_measured_boot() {
        assert!(
            STARTING_GRACE >= std::time::Duration::from_secs(30),
            "too tight for a slow-but-healthy boot"
        );
    }

    fn agent(id: &str, name: &str, status: &str) -> Agent {
        Agent {
            id: id.into(),
            name: name.into(),
            status: status.into(),
            sessions: LoadSessions::NotLoaded,
            expanded: false,
        }
    }

    /// A tree pane on the left and a session pane on the right, with the
    /// borders their clicks have to land on.
    fn panes_fixture() -> PaneRects {
        let tree = PaneBox {
            x: 1,
            y: 3,
            w: 30,
            h: 10,
        };
        let session = PaneBox {
            x: 34,
            y: 3,
            w: 40,
            h: 10,
        };
        PaneRects {
            tree,
            session,
            tree_outer: PaneBox {
                x: tree.x - 1,
                y: tree.y - 1,
                w: tree.w + 2,
                h: tree.h + 2,
            },
            session_outer: PaneBox {
                x: session.x - 1,
                y: session.y - 1,
                w: session.w + 2,
                h: session.h + 2,
            },
            ..Default::default()
        }
    }

    fn session(id: &str, name: &str) -> super::super::session::Session {
        super::super::session::Session::for_test(id, name).expect("test session")
    }

    /// Opening a second session must not close the first — the whole point is
    /// several agents working at once.
    #[test]
    fn sessions_accumulate_and_the_newest_is_active() {
        let mut a = loaded_app();
        a.attach_session(session("ca_1", "nimble-otter"), "ca_1".into());
        a.attach_session(session("ca_2", "quiet-harbor"), "ca_2".into());

        assert_eq!(a.sessions.len(), 2);
        assert_eq!(a.active, Some(1));
        assert_eq!(a.active_session().unwrap().agent_name, "quiet-harbor");
        assert_eq!(a.focus, ManageFocus::Session);
    }

    /// Enter on an agent that is already open switches to it instead of
    /// starting a second ssh into the same box.
    #[test]
    fn connecting_to_an_open_agent_switches_rather_than_relaunching() {
        let mut a = loaded_app();
        a.attach_session(session("ca_1", "nimble-otter"), "ca_1".into());
        a.focus = ManageFocus::Tree;
        a.active = None;
        a.cursor = a
            .rows()
            .iter()
            .position(|r| matches!(r.kind, RowKind::Session(0, 0, 0, 0, _)))
            .unwrap();

        assert_eq!(a.on_key(key(KeyCode::Enter)), None, "no launch");
        assert_eq!(a.active, Some(0));
        assert_eq!(a.focus, ManageFocus::Session);
        assert_eq!(a.sessions.len(), 1, "no duplicate session");
    }

    #[test]
    fn closing_a_session_keeps_the_active_pointer_valid() {
        let mut a = loaded_app();
        a.attach_session(session("ca_1", "one"), "ca_1".into());
        a.attach_session(session("ca_2", "two"), "ca_2".into());

        a.take_session(1).unwrap();
        assert_eq!(a.sessions.len(), 1);
        assert_eq!(a.active, Some(0));

        a.take_session(0).unwrap();
        assert!(a.sessions.is_empty());
        assert_eq!(a.active, None);
        assert_eq!(a.focus, ManageFocus::Tree, "nothing left to focus");
        assert!(a.take_session(0).is_none(), "out of range is not a panic");
    }

    #[test]
    fn closing_background_sessions_preserves_a_focused_disconnected_card() {
        let mut a = loaded_app();
        a.attach_session(session("ca_1", "one"), "ca_1".into());
        a.attach_session(session("ca_2", "two"), "ca_2".into());
        a.active = None;
        a.focus = ManageFocus::Session;
        a.take_session(0).unwrap();
        assert_eq!(a.active, None);
        assert_eq!(a.focus, ManageFocus::Session);
        a.take_session(0).unwrap();
        assert_eq!(a.active, None);
        assert_eq!(a.focus, ManageFocus::Session);
    }

    #[test]
    fn tab_moves_between_the_tree_and_the_pane() {
        let mut a = loaded_app();
        a.focus = ManageFocus::Tree;
        // Nothing open: tab has nowhere to go.
        a.on_key(key(KeyCode::Tab));
        assert_eq!(a.focus, ManageFocus::Tree);

        a.attach_session(session("ca_1", "one"), "ca_1".into());
        a.focus = ManageFocus::Tree;
        a.on_key(key(KeyCode::Tab));
        assert_eq!(a.focus, ManageFocus::Session);
    }

    /// Once the session has focus, tab belongs to the agent — coding agents
    /// bind it for completion, so intercepting it would break them. `^o` is the
    /// single reserved chord, and the only way back to the tree.
    #[test]
    fn a_focused_session_keeps_tab_and_only_ctrl_o_releases_it() {
        let mut a = loaded_app();
        a.attach_session(session("ca_1", "one"), "ca_1".into());
        assert_eq!(a.focus, ManageFocus::Session);

        a.on_key(key(KeyCode::Tab));
        assert_eq!(a.focus, ManageFocus::Session, "tab went to the agent");
        a.on_key(key(KeyCode::Esc));
        assert_eq!(a.focus, ManageFocus::Session, "esc went to the agent");
        a.on_key(ctrl('c'));
        assert_eq!(a.focus, ManageFocus::Session, "^c interrupts the agent");

        a.on_key(ctrl('o'));
        assert_eq!(a.focus, ManageFocus::Tree);
    }

    /// Walking onto a session row shows its pane; enter puts the keyboard in
    /// it rather than opening anything.
    #[test]
    fn moving_onto_a_session_row_switches_the_pane() {
        let mut a = loaded_app();
        if let Load::Loaded(agents) = &mut a.tree[0].projects[0].envs[0].agents {
            agents[0].expanded = true;
            agents[0].sessions = LoadSessions::Loaded(vec![
                ConsoleSession {
                    name: "claude-one".into(),
                    kind: "SHELL".into(),
                    command: None,
                    running: true,
                    attached: true,
                    created_at: None,
                    snapshot: None,
                },
                ConsoleSession {
                    name: "claude-two".into(),
                    kind: "SHELL".into(),
                    command: None,
                    running: true,
                    attached: true,
                    created_at: None,
                    snapshot: None,
                },
            ]);
        }
        let mut first = session("ca_1", "nimble-otter");
        first.durable_name = "claude-one".into();
        let mut second = session("ca_1", "nimble-otter");
        second.durable_name = "claude-two".into();
        a.sessions = vec![first, second];
        a.active = Some(0);
        a.focus = ManageFocus::Tree;

        let two = a
            .rows()
            .iter()
            .position(|r| r.label == "[S] claude-two")
            .unwrap();
        a.cursor = two - 1;
        a.on_key(key(KeyCode::Down));
        assert_eq!(a.active, Some(1), "the pane follows the highlight");
        assert_eq!(a.focus, ManageFocus::Tree, "moving does not steal focus");

        // Enter drops in; it must not launch anything.
        assert_eq!(a.on_key(key(KeyCode::Enter)), None);
        assert_eq!(a.focus, ManageFocus::Session);
        assert_eq!(a.sessions.len(), 2, "no new session was opened");
    }

    /// Clicking a row with children opens it, and clicking again closes it —
    /// the one gesture every tree has.
    #[test]
    fn clicking_a_collapsible_row_toggles_it() {
        let mut a = ordering_app();
        a.screen = Screen::Manage;
        a.panes = panes_fixture();
        let alpha = a.rows().iter().position(|r| r.label == "Alpha").unwrap();

        // Closed in the fixture; a click opens it and shows its environment.
        a.on_mouse(MouseAction::Down, 5, 3 + alpha as u16);
        assert!(a.tree[0].projects[1].expanded);
        assert!(a.rows().iter().any(|r| r.label == "production"));

        // And a second click closes it again.
        a.on_mouse(MouseAction::Down, 5, 3 + alpha as u16);
        assert!(!a.tree[0].projects[1].expanded);
    }

    /// The projects tail folds and unfolds like any other branch, and its
    /// state sticks once it has been touched.
    #[test]
    fn clicking_the_tail_header_toggles_it() {
        let mut a = ordering_app();
        a.screen = Screen::Manage;
        a.panes = panes_fixture();
        let header = a
            .rows()
            .iter()
            .position(|r| matches!(r.kind, RowKind::OtherProjects))
            .unwrap();

        // Open (nothing else to show); a click folds every project away.
        a.on_mouse(MouseAction::Down, 5, 3 + header as u16);
        assert!(
            !a.rows()
                .iter()
                .any(|r| matches!(r.kind, RowKind::Project(..)))
        );

        // And a second click brings them back.
        a.on_mouse(MouseAction::Down, 5, 3 + header as u16);
        assert!(
            a.rows()
                .iter()
                .any(|r| matches!(r.kind, RowKind::Project(..)))
        );
    }

    /// Clicking a collapsed environment has to fetch its agents, the same as
    /// the keyboard does.
    #[test]
    fn clicking_an_environment_loads_its_agents() {
        let mut a = app();
        a.screen = Screen::Manage;
        a.tree[0].projects[0].expanded = true;
        a.panes = panes_fixture();
        let production = a
            .rows()
            .iter()
            .position(|r| r.label == "production")
            .unwrap();

        assert_eq!(
            a.on_mouse(MouseAction::Down, 5, 3 + production as u16),
            Some(Effect::LoadAgents {
                environment_id: "env_prod".into(),
                path: (0, 0, 0)
            })
        );
    }

    /// Clicking a session that is not connected says so rather than silently
    /// spending an ssh.
    #[test]
    fn double_clicking_a_disconnected_session_reattaches() {
        let mut a = loaded_app();
        if let Load::Loaded(agents) = &mut a.tree[0].projects[0].envs[0].agents {
            agents[0].expanded = true;
            agents[0].sessions = LoadSessions::Loaded(vec![ConsoleSession {
                name: "claude-one".into(),
                kind: "SHELL".into(),
                command: None,
                running: true,
                attached: false,
                created_at: None,
                snapshot: None,
            }]);
        }
        a.panes = panes_fixture();
        let row = a
            .rows()
            .iter()
            .position(|r| r.label == "[S] claude-one")
            .unwrap();
        let effect = a.on_mouse(MouseAction::Down, 5, 3 + row as u16);
        assert!(
            matches!(effect, Some(Effect::LoadSessions { .. })),
            "the first click validates the list instead of spending an ssh: {effect:?}"
        );
        let effect = a.on_mouse(MouseAction::Down, 5, 3 + row as u16);
        assert!(
            matches!(effect, Some(Effect::Reattach { .. })),
            "a double click connects: {effect:?}"
        );
    }

    /// The reattach prompt answers the click that raised it: clicking a
    /// connected session afterwards clears it, the same as a keypress would,
    /// instead of leaving "not connected" standing over a connected pane.
    #[test]
    fn one_click_selects_and_a_double_click_connects() {
        let mut a = loaded_app();
        if let Load::Loaded(agents) = &mut a.tree[0].projects[0].envs[0].agents {
            agents[0].expanded = true;
            agents[0].sessions = LoadSessions::Loaded(vec![
                ConsoleSession {
                    name: "claude-one".into(),
                    kind: "SHELL".into(),
                    command: None,
                    running: true,
                    attached: true,
                    created_at: None,
                    snapshot: None,
                },
                ConsoleSession {
                    name: "claude-two".into(),
                    kind: "SHELL".into(),
                    command: None,
                    running: true,
                    attached: false,
                    created_at: None,
                    snapshot: None,
                },
            ]);
        }
        let mut pane = super::super::session::Session::for_test("ca_1", "nimble-otter").unwrap();
        pane.durable_name = "claude-one".into();
        a.sessions = vec![pane];
        a.active = Some(0);
        a.panes = panes_fixture();

        // A disconnected sibling: one click selects, says how to connect, and
        // re-asks the platform so a row that no longer exists validates away;
        // the second click (a double) reattaches.
        let two = a
            .rows()
            .iter()
            .position(|r| r.label == "[S] claude-two")
            .unwrap();
        let effect = a.on_mouse(MouseAction::Down, 5, 3 + two as u16);
        assert!(
            matches!(effect, Some(Effect::LoadSessions { .. })),
            "a click on a disconnected row validates the list: {effect:?}"
        );
        assert_eq!(a.focus, ManageFocus::Tree, "nothing to type into yet");
        assert!(a.status.contains("Double-click"), "{}", a.status);
        let effect = a.on_mouse(MouseAction::Down, 5, 3 + two as u16);
        assert!(
            matches!(effect, Some(Effect::Reattach { .. })),
            "{effect:?}"
        );

        let one = a
            .rows()
            .iter()
            .position(|r| r.label == "[S] claude-one")
            .unwrap();
        a.on_mouse(MouseAction::Down, 5, 3 + one as u16);
        assert_eq!(a.active, Some(0), "one click shows the open pane");
        assert_eq!(
            a.focus,
            ManageFocus::Tree,
            "but the keyboard stays with the tree until a double click"
        );
        a.on_mouse(MouseAction::Down, 5, 3 + one as u16);
        assert_eq!(
            a.focus,
            ManageFocus::Session,
            "a double click hands it the keyboard"
        );
    }

    /// Enter on a project toggles it: the first press opens it straight
    /// through to its first environment's agents, and a second press folds
    /// it back up instead of going dead. The cursor stays on the project so
    /// the second press lands where the first one did.
    #[test]
    fn enter_on_a_project_toggles_it() {
        let mut a = app();
        a.screen = Screen::Manage;
        a.cursor = a.rows().iter().position(|r| r.label == "devtools").unwrap();

        let effect = a.on_key(key(KeyCode::Enter));
        assert_eq!(
            effect,
            Some(Effect::LoadAgents {
                environment_id: "env_prod".into(),
                path: (0, 0, 0)
            })
        );
        assert!(a.tree[0].projects[0].expanded);
        assert!(a.tree[0].projects[0].envs[0].expanded);
        assert!(
            !a.tree[0].projects[0].envs[1].expanded,
            "only the first one"
        );
        assert_eq!(
            a.selected_row().unwrap().label,
            "devtools",
            "the cursor stays put, so enter again can close it"
        );

        assert_eq!(a.on_key(key(KeyCode::Enter)), None);
        assert!(
            !a.tree[0].projects[0].expanded,
            "the second enter folds the project"
        );
    }

    /// The new-VM picker creates a fresh VM with the chosen harness.
    #[test]
    fn n_picks_a_harness_then_makes_a_new_agent() {
        let mut a = app();
        a.screen = Screen::Manage;
        a.prompt_focused = false; // home: n is a key, not a letter
        a.target = Some(Target {
            project_id: "p1".into(),
            project_name: "devtools".into(),
            environment_id: "env_prod".into(),
            environment_name: "production".into(),
        });
        let opened_on = a.harness;
        assert_eq!(a.on_key(key(KeyCode::Char('n'))), None);
        assert_eq!(a.screen, Screen::HarnessPick);
        assert_eq!(
            a.harness_pick,
            Some(opened_on),
            "the picker opens on the current choice"
        );
        a.on_key(key(KeyCode::Down));
        let effect = a.on_key(key(KeyCode::Enter));
        assert_eq!(a.screen, Screen::Manage);
        let Some(Effect::Launch(req)) = effect else {
            panic!("expected a launch, got {effect:?}");
        };
        let picked = (opened_on + 1).min(HARNESSES.len() - 1);
        assert_eq!(
            req.harness, HARNESSES[picked],
            "the picked harness rides along"
        );
        assert!(req.force_new, "a fresh agent, like the dashboard's New");
        assert_eq!(req.agent_id, None);

        // Esc just closes it.
        a.on_key(key(KeyCode::Char('n')));
        assert_eq!(a.on_key(key(KeyCode::Esc)), None);
        assert_eq!(a.screen, Screen::Manage);
    }

    #[test]
    fn alt_n_chooses_a_new_session_on_the_selected_vm() {
        let mut a = loaded_app();
        a.cursor = a
            .rows()
            .iter()
            .position(|r| matches!(r.kind, RowKind::Agent(..)))
            .unwrap();
        assert_eq!(a.on_key(alt('n')), None);
        assert_eq!(a.screen, Screen::HarnessPick);
        assert_eq!(a.harness_pick_agent.as_deref(), Some("ca_1"));
        a.harness_pick = HARNESSES.iter().position(|h| *h == "codex");
        let Some(Effect::Launch(req)) = a.on_key(key(KeyCode::Enter)) else {
            panic!("expected a new session");
        };
        assert!(!req.force_new);
        assert!(req.new_session);
        assert_eq!(req.agent_id.as_deref(), Some("ca_1"));
        assert_eq!(req.environment_id, "env_prod");
        assert_eq!(req.harness, "codex");
        assert_eq!(req.prompt, None);
    }

    #[test]
    fn alt_n_without_a_selected_vm_does_not_create_one() {
        let mut a = app();
        a.screen = Screen::Manage;
        a.target = a.target_at((0, 0, 0));
        assert_eq!(a.on_key(alt('n')), None);
        assert_eq!(a.screen, Screen::Manage);
        assert!(a.harness_pick.is_none());
    }

    #[test]
    fn n_on_a_vm_creates_a_fresh_vm_and_supports_launch_bootstrap_overrides() {
        use super::super::bootstrap_setup::LaunchChoice;
        for choice in [
            LaunchChoice::Default,
            LaunchChoice::Named("dev".into()),
            LaunchChoice::None,
        ] {
            let mut a = loaded_app();
            a.cursor = a
                .rows()
                .iter()
                .position(|r| matches!(r.kind, RowKind::Agent(..)))
                .unwrap();
            assert_eq!(a.on_key(key(KeyCode::Char('n'))), None);
            assert_eq!(a.screen, Screen::HarnessPick);
            assert_eq!(a.harness_pick_agent, None);
            a.harness_bootstrap = choice.clone();
            let Some(Effect::Launch(req)) = a.on_key(key(KeyCode::Enter)) else {
                panic!("expected new VM")
            };
            assert!(req.force_new);
            assert!(!req.new_session);
            assert_eq!(req.agent_id, None);
            assert_eq!(req.environment_id, "env_prod");
            let mut expected = crate::commands::code::LaunchArgs::default();
            expected.set_bootstrap_choice(
                match &choice {
                    LaunchChoice::Named(name) => Some(name.clone()),
                    _ => None,
                },
                choice == LaunchChoice::None,
            );
            assert_eq!(*req.base, expected);
        }
    }

    #[test]
    fn project_bootstrap_picker_n_opens_new_vm_and_clean_vm_can_be_toggled() {
        use super::super::bootstrap_setup::LaunchChoice;
        let mut a = loaded_app();
        a.tree[0].projects[0].envs[0].agents = Load::Loaded(vec![]);
        a.cursor = a
            .rows()
            .iter()
            .position(|r| matches!(r.kind, RowKind::Project(..)))
            .unwrap();
        a.on_key(key(KeyCode::Char('b')));
        let target = a.bootstrap_picker.as_ref().unwrap().target.clone();
        a.on_key(key(KeyCode::Char('n')));
        assert_eq!(a.screen, Screen::HarnessPick);
        assert_eq!(a.harness_pick_target, Some(target));
        assert!(matches!(
            a.on_key(key(KeyCode::Char('b'))),
            Some(Effect::LoadBootstraps { .. })
        ));
        let picker = a.bootstrap_picker.as_mut().unwrap();
        assert!(picker.for_launch);
        picker.loaded(Ok(vec![]));
        picker.cursor = 1; // clean VM is the final item
        assert_eq!(
            a.on_key(key(KeyCode::Enter)),
            None,
            "launch choice must not set the project default"
        );
        assert_eq!(a.screen, Screen::HarnessPick);
        assert!(!a.harness_use_bootstrap);
        assert_eq!(a.harness_bootstrap, LaunchChoice::None);
        a.on_key(key(KeyCode::Char(' ')));
        assert!(a.harness_use_bootstrap);
        assert_eq!(a.harness_bootstrap, LaunchChoice::Default);
        a.on_key(key(KeyCode::Char(' ')));
        let Some(Effect::Launch(req)) = a.on_key(key(KeyCode::Enter)) else {
            panic!("expected new VM")
        };
        let mut expected = crate::commands::code::LaunchArgs::default();
        expected.set_bootstrap_choice(None, true);
        assert_eq!(*req.base, expected);
    }

    /// ⌥p floats the menu's prompt box over the tree: type, shift+tab to
    /// change the agent, enter to spin up a session carrying the prompt.
    #[test]
    fn alt_p_composes_a_prompted_session() {
        let mut a = app();
        a.screen = Screen::Manage;
        a.target = Some(Target {
            project_id: "p1".into(),
            project_name: "devtools".into(),
            environment_id: "env_prod".into(),
            environment_name: "production".into(),
        });
        assert_eq!(a.on_key(alt('p')), None);
        assert_eq!(a.screen, Screen::ManagePrompt);
        for c in "fix it".chars() {
            a.on_key(key(KeyCode::Char(c)));
        }
        let before = a.harness;
        a.on_key(key(KeyCode::BackTab));
        assert_eq!(a.harness, (before + 1) % HARNESSES.len());

        let effect = a.on_key(key(KeyCode::Enter));
        assert_eq!(a.screen, Screen::Manage);
        let Some(Effect::Launch(req)) = effect else {
            panic!("expected a launch, got {effect:?}");
        };
        assert_eq!(req.prompt.as_deref(), Some("fix it"));

        // An empty draft doesn't send: enter is a slip there, and the menu
        // box's own contract is that esc closes without launching.
        a.on_key(alt('p'));
        assert_eq!(a.on_key(key(KeyCode::Enter)), None);
        assert_eq!(a.screen, Screen::ManagePrompt, "nothing to send yet");
        assert_eq!(a.on_key(key(KeyCode::Esc)), None);
        assert_eq!(a.screen, Screen::Manage);
    }

    /// The ⌥p composer follows the menu box's shell contract: cycling can
    /// land on shell, typing goes inert there, and enter launches the session
    /// bare instead of demanding a prompt a shell could never take.
    #[test]
    fn alt_p_launches_a_bare_shell_session() {
        let mut a = app();
        a.screen = Screen::Manage;
        a.target = Some(Target {
            project_id: "p1".into(),
            project_name: "devtools".into(),
            environment_id: "env_prod".into(),
            environment_name: "production".into(),
        });
        a.on_key(alt('p'));
        for c in "fix it".chars() {
            a.on_key(key(KeyCode::Char(c)));
        }
        while a.harness_name() != "shell" {
            a.on_key(key(KeyCode::BackTab));
        }
        a.on_key(key(KeyCode::Char('x')));
        assert_eq!(
            a.manage_prompt.as_deref(),
            Some("fix it"),
            "typing is refused while shell is selected"
        );
        let effect = a.on_key(key(KeyCode::Enter));
        assert_eq!(a.screen, Screen::Manage);
        let Some(Effect::Launch(req)) = effect else {
            panic!("expected a launch, got {effect:?}");
        };
        assert_eq!(req.harness, "shell");
        assert_eq!(req.prompt, None, "the abandoned draft must not ride along");
    }

    /// The agent picker offers shell last and launches it without a prompt.
    #[test]
    fn the_picker_offers_shell_last() {
        let mut a = app();
        a.screen = Screen::Manage;
        a.prompt_focused = false; // home: n is a key, not a letter
        a.target = Some(Target {
            project_id: "p1".into(),
            project_name: "devtools".into(),
            environment_id: "env_prod".into(),
            environment_name: "production".into(),
        });
        a.on_key(key(KeyCode::Char('n')));
        for _ in 0..HARNESSES.len() {
            a.on_key(key(KeyCode::Down));
        }
        assert_eq!(
            a.harness_pick,
            Some(HARNESSES.len() - 1),
            "the cursor bottoms out on shell"
        );
        let effect = a.on_key(key(KeyCode::Enter));
        let Some(Effect::Launch(req)) = effect else {
            panic!("expected a launch, got {effect:?}");
        };
        assert_eq!(req.harness, "shell");
        assert_eq!(req.prompt, None);
        assert!(req.force_new, "the picker makes a new agent");
    }

    /// The launchers work from inside a session, which is where the thought
    /// "this needs its own session" actually arrives. The card floated over
    /// it takes the keyboard while it is up — otherwise the draft would be
    /// typed into the harness — and focus returns to the session on esc.
    #[test]
    fn alt_p_and_alt_n_reach_past_a_focused_session() {
        let mut a = loaded_app();
        a.screen = Screen::Manage;
        a.target = Some(Target {
            project_id: "p1".into(),
            project_name: "devtools".into(),
            environment_id: "env_prod".into(),
            environment_name: "production".into(),
        });
        a.sessions
            .push(super::super::session::Session::for_test("ca_1", "builder").unwrap());
        a.active = Some(0);
        a.focus = ManageFocus::Session;

        assert_eq!(a.on_key(alt('p')), None);
        assert_eq!(
            a.screen,
            Screen::ManagePrompt,
            "⌥p is not swallowed by the session"
        );
        for c in "ship it".chars() {
            a.on_key(key(KeyCode::Char(c)));
        }
        assert_eq!(
            a.manage_prompt.as_deref(),
            Some("ship it"),
            "the card has the keyboard, not the harness"
        );
        assert_eq!(a.on_key(key(KeyCode::Esc)), None);
        assert_eq!(a.screen, Screen::Manage);
        assert_eq!(
            a.focus,
            ManageFocus::Session,
            "closing the card returns to typing in the session"
        );

        // Option+n chooses a new session on the focused VM.
        a.sessions[0].ssh_target = "agent:env_prod:ca_1".into();
        assert_eq!(a.on_key(alt('n')), None);
        assert_eq!(a.screen, Screen::HarnessPick);
        let Some(Effect::Launch(req)) = a.on_key(key(KeyCode::Enter)) else {
            panic!("expected new session")
        };
        assert_eq!(req.agent_id.as_deref(), Some("ca_1"));
        assert!(req.new_session);
        assert!(!req.force_new);
    }

    /// Releasing a focused session with ⇧esc also un-maximizes: focus moving
    /// to a pane that is folded away would land on something invisible.
    #[test]
    fn releasing_a_maximized_session_restores_the_tree() {
        let mut a = loaded_app();
        a.screen = Screen::Manage;
        a.sessions
            .push(super::super::session::Session::for_test("ca_1", "builder").unwrap());
        a.active = Some(0);
        a.focus = ManageFocus::Session;
        a.maximized = true;
        let esc = KeyEvent::new(KeyCode::Esc, KeyModifiers::SHIFT);
        assert_eq!(a.on_key(esc), None);
        assert_eq!(a.focus, ManageFocus::Tree);
        assert!(!a.maximized, "the tree pane comes back with focus");
    }

    /// Every environment is a row, not just each project's first: an agent
    /// lives in an environment, so that is what is being chosen.
    #[test]
    fn the_target_picker_lists_every_environment() {
        let a = app();
        let picker = TargetPicker::new(&a.tree, None, None);
        let labels: Vec<String> = picker.rows(None).into_iter().map(|(l, _)| l).collect();
        assert!(
            labels.contains(&"devtools (production)".to_string()),
            "{labels:?}"
        );
        assert!(
            labels.contains(&"devtools (staging)".to_string()),
            "{labels:?}"
        );
    }

    /// The default project leads the list and says so, the same as it does in
    /// the tree.
    #[test]
    fn the_target_picker_leads_with_the_default_project() {
        let a = ordering_app();
        let picker = TargetPicker::new(&a.tree, Some("p3"), None);
        let rows = picker.rows(Some("p3"));
        assert_eq!(rows[0].1, "default");
        assert!(rows[0].0.starts_with("mono"), "{rows:?}");
        assert!(
            rows[1..].iter().all(|(_, tag)| tag.is_empty()),
            "only the default is tagged"
        );
    }

    /// An environment in the tail carries no marker at all unless it is
    /// mid-load or failed — everything down there is empty, so a count would
    /// say nothing.
    #[test]
    fn tail_environments_have_no_empty_marker() {
        let mut a = app();
        let note =
            |a: &App, name: &str| a.rows().into_iter().find(|r| r.label == name).unwrap().note;
        a.tree[0].projects[0].expanded = true;
        assert_eq!(note(&a, "production"), "", "not loaded yet");

        a.agents_loaded((0, 0, 0), Ok(Vec::new()));
        assert_eq!(note(&a, "production"), "", "loaded and empty");

        a.tree[0].projects[0].envs[1].agents = Load::Loading;
        assert_eq!(note(&a, "staging"), "");
    }

    /// The dot next to a session means "open in this UI", nothing else. The
    /// platform's own `attached` flag counts other clients too, which is why
    /// the old label flickered between attached and running.
    #[test]
    fn a_session_is_marked_connected_only_when_this_ui_has_it() {
        let mut a = loaded_app();
        if let Load::Loaded(agents) = &mut a.tree[0].projects[0].envs[0].agents {
            agents[0].expanded = true;
            agents[0].sessions = LoadSessions::Loaded(vec![ConsoleSession {
                name: "claude-one".into(),
                kind: "SHELL".into(),
                command: None,
                running: true,
                // The agent says someone is attached; that someone is not us.
                attached: true,
                created_at: None,
                snapshot: None,
            }]);
        }
        let row = |a: &App| {
            a.rows()
                .into_iter()
                .find(|r| r.label == "[S] claude-one")
                .unwrap()
        };
        assert_eq!(row(&a).status, None, "not open here, so no marker");
        assert!(row(&a).note.is_empty(), "the project lives in the card");

        let mut pane = session("ca_1", "nimble-otter");
        pane.durable_name = "claude-one".into();
        a.sessions = vec![pane];
        assert_eq!(row(&a).status.as_deref(), Some("connected"));
    }

    /// `x` ends the highlighted session on the agent — connected or not. It
    /// used to close only our window onto it, which looked like nothing
    /// happened.
    #[test]
    fn x_ends_the_highlighted_session() {
        let mut a = loaded_app();
        if let Load::Loaded(agents) = &mut a.tree[0].projects[0].envs[0].agents {
            agents[0].expanded = true;
            agents[0].sessions = LoadSessions::Loaded(vec![ConsoleSession {
                name: "claude-one".into(),
                kind: "SHELL".into(),
                command: None,
                running: true,
                attached: false,
                created_at: None,
                snapshot: None,
            }]);
        }
        a.cursor = a
            .rows()
            .iter()
            .position(|r| r.label == "[S] claude-one")
            .unwrap();

        assert_eq!(
            a.on_key(key(KeyCode::Char('x'))),
            Some(Effect::KillSession {
                agent_id: "ca_1".into(),
                environment_id: "env_prod".into(),
                session_name: "claude-one".into(),
            }),
            "not connected is no excuse — the session is on the VM"
        );
        // Optimistic: the row goes at once. The agent takes a second or two to
        // reap the processes, and a row that reads "running" in the meantime
        // looks like the key did nothing.
        assert!(
            !a.rows().iter().any(|r| r.label == "[S] claude-one"),
            "the session should be gone from the tree immediately"
        );
        assert!(
            a.rows().iter().any(|r| r.label == "nimble-otter"),
            "with its only thread ending, the agent row returns"
        );

        // A kill that fails puts it back rather than hiding a live session.
        a.session_killed("claude-one", Some("permission denied".into()));
        assert!(a.rows().iter().any(|r| r.label == "[S] claude-one"));
        assert!(a.status.contains("permission denied"));
    }

    /// The optimism is settled by the agent's own list: a session that is still
    /// reported stays hidden, and one that has gone stops being tracked.
    #[test]
    fn a_hidden_session_is_forgotten_once_the_agent_agrees() {
        let mut a = loaded_app();
        if let Load::Loaded(agents) = &mut a.tree[0].projects[0].envs[0].agents {
            agents[0].expanded = true;
        }
        a.ending.insert("claude-one".into());

        // Still listed: keep hiding it, the kill has not landed yet.
        a.sessions_loaded(
            (0, 0, 0, 0),
            "ca_1",
            Ok(vec![ConsoleSession {
                name: "claude-one".into(),
                kind: "SHELL".into(),
                command: None,
                running: true,
                attached: false,
                created_at: None,
                snapshot: None,
            }]),
        );
        assert!(a.ending.contains("claude-one"));
        assert!(!a.rows().iter().any(|r| r.label == "[S] claude-one"));

        // Gone from the agent: stop tracking it.
        a.sessions_loaded((0, 0, 0, 0), "ca_1", Ok(Vec::new()));
        assert!(a.ending.is_empty());
    }

    /// One click on a connected session row shows the pane but keeps the
    /// keyboard in the tree — with the sidebar listing threads, most rows are
    /// connected sessions, and browsing must stay possible. A double click is
    /// what steps in to type.
    #[test]
    fn one_click_views_and_two_clicks_connect() {
        let mut a = loaded_app();
        if let Load::Loaded(agents) = &mut a.tree[0].projects[0].envs[0].agents {
            agents[0].expanded = true;
            agents[0].sessions = LoadSessions::Loaded(vec![ConsoleSession {
                name: "claude-one".into(),
                kind: "SHELL".into(),
                command: None,
                running: true,
                attached: true,
                created_at: None,
                snapshot: None,
            }]);
        }
        let mut pane = session("ca_1", "nimble-otter");
        pane.durable_name = "claude-one".into();
        a.sessions = vec![pane];
        a.active = None;
        a.focus = ManageFocus::Tree;
        a.panes = panes_fixture();

        let row = a
            .rows()
            .iter()
            .position(|r| r.label == "[S] claude-one")
            .unwrap() as u16;

        a.on_mouse(MouseAction::Down, 5, 3 + row);
        assert_eq!(a.active, Some(0), "one click shows it");
        assert_eq!(a.focus, ManageFocus::Tree, "the keyboard stays in the tree");

        a.on_mouse(MouseAction::Down, 5, 3 + row);
        assert_eq!(a.focus, ManageFocus::Session, "a double click steps in");
    }

    /// A reconnect whose target session turns out not to exist launches a
    /// replacement on the same agent — same harness, stale row dropped —
    /// instead of failing. Connecting was the ask; a dead name must not
    /// answer it with an error.
    #[test]
    fn a_reconnect_to_a_gone_session_starts_a_new_one() {
        let mut a = loaded_app();
        if let Load::Loaded(agents) = &mut a.tree[0].projects[0].envs[0].agents {
            agents[0].expanded = true;
            agents[0].sessions = LoadSessions::Loaded(vec![ConsoleSession {
                name: "claude-one".into(),
                kind: "SHELL".into(),
                command: Some("claude --resume".into()),
                running: true,
                attached: false,
                created_at: None,
                snapshot: None,
            }]);
        }

        let Some(Effect::Launch(req)) =
            a.reattach_target_gone("ca_1", "nimble-otter", "claude-one")
        else {
            panic!("expected a replacement launch");
        };
        assert_eq!(req.agent_id.as_deref(), Some("ca_1"));
        assert!(req.force_new, "the dead name must not be redialed");
        assert_eq!(req.harness, "claude", "same harness the dead session ran");
        assert_eq!(req.prompt, None);
        assert!(
            !a.rows().iter().any(|r| r.label.contains("claude-one")),
            "the stale row is gone"
        );

        // The agent stopped running underneath the reconnect: nothing to
        // launch onto — the truth gets refetched instead.
        let mut b = loaded_app();
        if let Load::Loaded(agents) = &mut b.tree[0].projects[0].envs[0].agents {
            agents[0].expanded = true;
            agents[0].status = "sleeping".into();
            agents[0].sessions = LoadSessions::Loaded(vec![ConsoleSession {
                name: "claude-one".into(),
                kind: "SHELL".into(),
                command: None,
                running: true,
                attached: false,
                created_at: None,
                snapshot: None,
            }]);
        }
        let effect = b.reattach_target_gone("ca_1", "nimble-otter", "claude-one");
        assert_eq!(effect, None, "a sleeping VM must not be dialed for history");
        assert!(!b.toast.as_ref().unwrap().ok, "announced as a failure");
    }

    /// A refresh that finds an agent no longer running drops its session
    /// list: those sessions lived on the machine, and the machine is gone.
    /// Carrying them showed reattach rows for sessions that no longer exist —
    /// forever, because the refresh cadence only re-asks running agents.
    #[test]
    fn sleep_drops_the_carried_session_list() {
        let session = ConsoleSession {
            name: "claude-one".into(),
            kind: "SHELL".into(),
            command: None,
            running: true,
            attached: false,
            created_at: None,
            snapshot: None,
        };
        let previous = vec![Agent {
            id: "ca_1".into(),
            name: "nimble-otter".into(),
            status: "running".into(),
            sessions: LoadSessions::Loaded(vec![session]),
            expanded: true,
        }];
        let mut asleep = previous.clone();
        asleep[0].status = "sleeping".into();
        asleep[0].sessions = LoadSessions::NotLoaded;

        let merged = merge_agents(previous.clone(), asleep);
        assert_eq!(
            merged[0].sessions,
            LoadSessions::NotLoaded,
            "a sleeping machine has no console sessions to keep"
        );
        assert!(merged[0].expanded, "the fold state is still ours to keep");

        let mut still_running = previous.clone();
        still_running[0].sessions = LoadSessions::NotLoaded;
        let merged = merge_agents(previous, still_running);
        assert!(
            matches!(&merged[0].sessions, LoadSessions::Loaded(s) if s.len() == 1),
            "a running agent keeps its list until the reply replaces it"
        );
    }

    /// Clicking the session panel is itself a request to type in it.
    #[test]
    fn clicking_the_session_panel_takes_the_keyboard() {
        let mut a = loaded_app();
        a.attach_session(session("ca_1", "one"), "ca_1".into());
        a.focus = ManageFocus::Tree;
        a.panes = panes_fixture();

        a.on_mouse(MouseAction::Down, 40, 5);
        assert_eq!(a.focus, ManageFocus::Session);
    }

    /// Four ways out of a focused session, because terminals disagree about
    /// what they report: a modified Escape needs the enhanced keyboard
    /// protocol, so `^]` and `^o` have to work without it. ⇧esc carries the
    /// pair, because macOS composes Option into a character and Escape has
    /// none to compose to, which leaves ⌥esc unsendable on a stock terminal.
    #[test]
    fn every_release_chord_works() {
        for release in [
            KeyEvent::new(KeyCode::Esc, KeyModifiers::ALT),
            KeyEvent::new(KeyCode::Esc, KeyModifiers::SHIFT),
            KeyEvent::new(KeyCode::Char(']'), KeyModifiers::CONTROL),
            KeyEvent::new(KeyCode::Char('o'), KeyModifiers::CONTROL),
        ] {
            let mut a = loaded_app();
            a.attach_session(session("ca_1", "one"), "ca_1".into());
            assert_eq!(a.focus, ManageFocus::Session);
            a.on_key(release);
            assert_eq!(a.focus, ManageFocus::Tree, "{release:?} should release");
        }

        // A bare escape still belongs to the agent — it is how you leave a
        // mode in every editor.
        let mut a = loaded_app();
        a.attach_session(session("ca_1", "one"), "ca_1".into());
        a.on_key(key(KeyCode::Esc));
        assert_eq!(a.focus, ManageFocus::Session);
    }

    /// `n` on an agent pins that agent, so the launch cannot wander off and
    /// create a second VM.
    #[test]
    fn n_opens_the_picker_from_any_row() {
        let mut a = loaded_app();
        a.cursor = a
            .rows()
            .iter()
            .position(|r| r.label == "nimble-otter")
            .unwrap();
        assert_eq!(a.on_key(key(KeyCode::Char('n'))), None);
        assert_eq!(a.screen, Screen::HarnessPick, "n is the New Agent button");
    }

    /// `?` opens the key list, and the next key just puts it away — reading
    /// the keys must not trigger one.
    #[test]
    fn the_key_overlay_is_a_lookup_not_a_mode() {
        let mut a = loaded_app();
        a.cursor = a
            .rows()
            .iter()
            .position(|r| r.label == "nimble-otter")
            .unwrap();

        assert_eq!(a.on_key(key(KeyCode::Char('?'))), None);
        assert!(a.keys_open);

        // `d` would normally ask to delete; here it only closes the overlay.
        assert_eq!(a.on_key(key(KeyCode::Char('d'))), None);
        assert!(!a.keys_open);
        assert!(a.confirm.is_none(), "a key read is not a key pressed");
    }

    /// `c` copies a shell command for the VM behind either kind of row.
    #[test]
    fn c_copies_an_ssh_shell_command_for_a_vm_or_session() {
        let mut a = loaded_app();
        if let Load::Loaded(agents) = &mut a.tree[0].projects[0].envs[0].agents {
            agents[0].expanded = true;
            agents[0].sessions = LoadSessions::Loaded(vec![ConsoleSession {
                name: "claude-one".into(),
                kind: "SHELL".into(),
                command: None,
                running: true,
                attached: false,
                created_at: None,
                snapshot: None,
            }]);
        }
        a.cursor = a
            .rows()
            .iter()
            .position(|r| r.label == "[S] claude-one")
            .unwrap();
        assert_eq!(
            a.on_key(key(KeyCode::Char('c'))),
            Some(Effect::CopySsh {
                agent_id: "ca_1".into(),
                environment_id: "env_prod".into(),
            })
        );

        a.cursor = a
            .rows()
            .iter()
            .position(|r| r.label == "nimble-otter")
            .unwrap();
        assert_eq!(
            a.on_key(key(KeyCode::Char('c'))),
            Some(Effect::CopySsh {
                agent_id: "ca_1".into(),
                environment_id: "env_prod".into(),
            })
        );

        // Off any session row — home, where letters are keys — c has nothing
        // to copy.
        a.cursor = 0;
        a.prompt_focused = false;
        assert_eq!(a.on_key(key(KeyCode::Char('c'))), None);
        assert!(a.status.contains("Select a VM"), "{}", a.status);
    }

    #[test]
    fn option_b_uses_the_bootstrap_action_in_each_context() {
        for chord in [alt('b'), alt('B'), key(KeyCode::Char('')), ctrl('b')] {
            let mut a = loaded_app();
            a.cursor = a
                .rows()
                .iter()
                .position(|r| matches!(r.kind, RowKind::Agent(..)))
                .unwrap();
            assert!(matches!(
                a.on_key(chord),
                Some(Effect::LoadBootstraps { .. })
            ));
            assert_eq!(a.screen, Screen::BootstrapSetup);
            assert_eq!(
                a.bootstrap_form
                    .as_ref()
                    .unwrap()
                    .snapshot
                    .as_ref()
                    .unwrap()
                    .agent_id,
                "ca_1"
            );

            let mut a = loaded_app();
            a.tree[0].projects[0].envs[0].agents = Load::Loaded(vec![]);
            a.cursor = a
                .rows()
                .iter()
                .position(|r| matches!(r.kind, RowKind::Project(..)))
                .unwrap();
            assert!(matches!(
                a.on_key(chord),
                Some(Effect::LoadBootstraps { .. })
            ));
            assert_eq!(a.screen, Screen::BootstrapPick);
            assert!(!a.bootstrap_picker.as_ref().unwrap().for_launch);
        }
        let mut a = loaded_app();
        a.cursor = a
            .rows()
            .iter()
            .position(|r| matches!(r.kind, RowKind::Agent(..)))
            .unwrap();
        a.on_key(key(KeyCode::Char('n')));
        assert_eq!(a.screen, Screen::HarnessPick);
        assert!(matches!(
            a.on_key(alt('b')),
            Some(Effect::LoadBootstraps { .. })
        ));
        assert!(a.bootstrap_picker.as_ref().unwrap().for_launch);
    }

    #[test]
    fn option_b_captures_the_focused_vm_without_switching_to_the_selected_row() {
        let mut a = loaded_app();
        a.agents_loaded(
            (0, 0, 0),
            Ok(vec![
                agent("ca_1", "nimble-otter", "running"),
                agent("ca_2", "other-vm", "running"),
            ]),
        );
        a.attach_session(session("ca_1", "nimble-otter"), "ca_1".into());
        a.cursor = a.rows().iter().position(|r| r.label == "other-vm").unwrap();
        a.focus = ManageFocus::Session;
        assert!(matches!(
            a.on_key(alt('b')),
            Some(Effect::LoadBootstraps { .. })
        ));
        assert_eq!(a.screen, Screen::BootstrapSetup);
        assert_eq!(
            a.bootstrap_form
                .as_ref()
                .unwrap()
                .snapshot
                .as_ref()
                .unwrap()
                .agent_id,
            "ca_1"
        );
        assert_eq!(a.sessions.len(), 1);
        a.on_key(key(KeyCode::Esc));
        assert_eq!(a.focus, ManageFocus::Session);
        assert_eq!(a.on_key(alt('t')), None);
        assert_eq!(a.screen, Screen::TargetPick);
    }

    #[test]
    fn option_o_opens_the_selected_vm_including_without_an_agent_session() {
        for chord in [alt('o'), alt('O'), key(KeyCode::Char('ø'))] {
            let mut a = loaded_app();
            a.cursor = a
                .rows()
                .iter()
                .position(|r| r.label == "nimble-otter")
                .unwrap();
            assert_eq!(
                a.on_key(chord),
                Some(Effect::OpenShell {
                    agent_id: "ca_1".into(),
                    agent_name: "nimble-otter".into(),
                })
            );
            assert!(a.sessions.is_empty());
        }
    }

    #[test]
    fn option_o_uses_the_focused_panes_vm_and_keeps_the_session() {
        let mut a = loaded_app();
        a.attach_session(session("ca_other", "other-vm"), "ca_other".into());
        a.cursor = a
            .rows()
            .iter()
            .position(|r| r.label == "nimble-otter")
            .unwrap();
        a.focus = ManageFocus::Session;
        assert_eq!(
            a.on_key(alt('o')),
            Some(Effect::OpenShell {
                agent_id: "ca_other".into(),
                agent_name: "other-vm".into(),
            })
        );
        assert_eq!(a.sessions.len(), 1);
        assert_eq!(a.focus, ManageFocus::Session);

        // With the tree focused, its row wins over that unrelated pane.
        a.focus = ManageFocus::Tree;
        assert_eq!(
            a.on_key(alt('o')),
            Some(Effect::OpenShell {
                agent_id: "ca_1".into(),
                agent_name: "nimble-otter".into(),
            })
        );
        a.cursor = 0;
        assert_eq!(a.on_key(alt('o')), None);
        assert!(a.status.contains("Select a VM"));
    }

    #[test]
    fn option_o_respects_dialogs_and_the_ssh_key_gate() {
        let mut a = loaded_app();
        a.cursor = a
            .rows()
            .iter()
            .position(|r| r.label == "nimble-otter")
            .unwrap();
        a.on_key(key(KeyCode::Char('?')));
        assert_eq!(a.on_key(alt('o')), None);
        a.keys_open = false;
        a.on_key(key(KeyCode::Char('d')));
        assert!(a.confirm.is_some());
        assert_eq!(a.on_key(alt('o')), None);
        a.confirm = None;

        let held = HeldConnect::OpenShell {
            agent_id: "ca_1".into(),
            agent_name: "nimble-otter".into(),
        };
        a.ssh_key = SshKeyState::NeedsRegistration(offer());
        assert!(a.hold_for_ssh_key(held.clone()));
        assert_eq!(a.ssh_gate.as_ref().unwrap().then, Some(held.clone()));
        assert_eq!(
            held.into_effect(),
            Effect::OpenShell {
                agent_id: "ca_1".into(),
                agent_name: "nimble-otter".into(),
            }
        );
    }

    /// Landing on an agent opens it, so its sessions are there without a
    /// second keypress.
    #[test]
    fn highlighting_an_agent_expands_it() {
        let mut a = loaded_app();
        let agent_row = a
            .rows()
            .iter()
            .position(|r| r.label == "nimble-otter")
            .unwrap();
        a.cursor = agent_row - 1;

        // Sessions unknown: arriving asks for them, which expands the row.
        let effect = a.on_key(key(KeyCode::Down));
        assert_eq!(
            effect,
            Some(Effect::LoadSessions {
                agent_id: "ca_1".into(),
                environment_id: "env_prod".into(),
                path: (0, 0, 0, 0)
            })
        );

        a.sessions_loaded(
            (0, 0, 0, 0),
            "ca_1",
            Ok(vec![ConsoleSession {
                name: "claude-one".into(),
                kind: "SHELL".into(),
                command: None,
                running: true,
                attached: true,
                created_at: None,
                snapshot: None,
            }]),
        );
        assert!(a.rows().iter().any(|r| r.label == "[S] claude-one"));
    }

    /// An agent known to have nothing running is left closed: expanding it
    /// would swap its sessions for a "no sessions" line.
    #[test]
    fn an_idle_agent_is_not_auto_expanded() {
        let mut a = loaded_app();
        if let Load::Loaded(agents) = &mut a.tree[0].projects[0].envs[0].agents {
            agents[0].sessions = LoadSessions::Loaded(Vec::new());
        }
        let agent_row = a
            .rows()
            .iter()
            .position(|r| r.label == "nimble-otter")
            .unwrap();
        a.cursor = agent_row - 1;

        assert!(matches!(
            a.on_key(key(KeyCode::Down)),
            Some(Effect::LoadSessions { .. })
        ));
        assert!(
            !a.rows()
                .iter()
                .any(|r| r.label == "no sessions on this agent")
        );
    }

    /// Reattaching keeps the cursor on the session, not the agent above it —
    /// the session is what was opened.
    #[test]
    fn attaching_selects_the_session_row() {
        let mut a = loaded_app();
        if let Load::Loaded(agents) = &mut a.tree[0].projects[0].envs[0].agents {
            agents[0].expanded = true;
            agents[0].sessions = LoadSessions::Loaded(vec![ConsoleSession {
                name: "claude-one".into(),
                kind: "SHELL".into(),
                command: None,
                running: true,
                attached: false,
                created_at: None,
                snapshot: None,
            }]);
        }
        let mut pane = session("ca_1", "nimble-otter");
        pane.durable_name = "claude-one".into();
        a.attach_session(pane, "ca_1".into());

        assert_eq!(a.selected_row().unwrap().label, "[S] claude-one");
        assert!(a.pending_select.is_none(), "the agent fallback was dropped");
    }

    /// A brand-new session doesn't wait for the platform to list it: the pane
    /// we just attached is proof, so its row appears — selected and connected
    /// — the moment the launch lands.
    #[test]
    fn a_new_session_takes_the_cursor_at_once() {
        let mut a = loaded_app();
        let mut pane = session("ca_1", "nimble-otter");
        pane.durable_name = "claude-new".into();
        a.attach_session(pane, "ca_1".into());
        let row = a.selected_row().unwrap();
        assert_eq!(
            row.label, "[S] claude-new",
            "adopted before the platform lists it"
        );
        assert_eq!(row.status.as_deref(), Some("connected"));

        if let Load::Loaded(agents) = &mut a.tree[0].projects[0].envs[0].agents {
            agents[0].expanded = true;
        }
        a.sessions_loaded(
            (0, 0, 0, 0),
            "ca_1",
            Ok(vec![ConsoleSession {
                name: "claude-new".into(),
                kind: "SHELL".into(),
                command: None,
                running: true,
                attached: true,
                created_at: None,
                snapshot: None,
            }]),
        );
        assert_eq!(a.selected_row().unwrap().label, "[S] claude-new");
    }

    /// A session with no pane reconnects directly — no provisioning flow for a
    /// box that is already set up.
    #[test]
    fn enter_on_a_closed_session_reattaches_without_provisioning() {
        let mut a = loaded_app();
        if let Load::Loaded(agents) = &mut a.tree[0].projects[0].envs[0].agents {
            agents[0].expanded = true;
            agents[0].sessions = LoadSessions::Loaded(vec![ConsoleSession {
                name: "claude-one".into(),
                kind: "SHELL".into(),
                command: None,
                running: true,
                attached: false,
                created_at: None,
                snapshot: None,
            }]);
        }
        a.cursor = a
            .rows()
            .iter()
            .position(|r| r.label == "[S] claude-one")
            .unwrap();

        assert_eq!(
            a.on_key(key(KeyCode::Enter)),
            Some(Effect::Reattach {
                agent_id: "ca_1".into(),
                agent_name: "nimble-otter".into(),
                environment_id: "env_prod".into(),
                session_name: "claude-one".into(),
            })
        );
    }

    /// A sleeping agent cannot be reattached to; say so instead of failing in
    /// ssh a second later.
    #[test]
    fn reattaching_to_a_sleeping_agent_asks_for_a_wake() {
        let mut a = loaded_app();
        if let Load::Loaded(agents) = &mut a.tree[0].projects[0].envs[0].agents {
            agents[0].status = "sleeping".into();
            agents[0].expanded = true;
            agents[0].sessions = LoadSessions::Loaded(vec![ConsoleSession {
                name: "claude-one".into(),
                kind: "SHELL".into(),
                command: None,
                running: true,
                attached: false,
                created_at: None,
                snapshot: None,
            }]);
        }
        a.cursor = a
            .rows()
            .iter()
            .position(|r| r.label == "[S] claude-one")
            .unwrap();
        assert_eq!(a.on_key(key(KeyCode::Enter)), None);
        assert!(a.status.contains("press w to wake"), "{}", a.status);
    }

    /// The count of sessions rides beside the agent's status, like a project's
    /// agent count.
    #[test]
    fn sessions_nest_under_their_agent() {
        let mut a = loaded_app();
        let rows = a.rows();
        let agent = rows.iter().find(|r| r.label == "nimble-otter").unwrap();
        assert_eq!(
            agent.status.as_deref(),
            Some("running"),
            "the orb carries the status"
        );

        if let Load::Loaded(agents) = &mut a.tree[0].projects[0].envs[0].agents {
            agents[0].sessions = LoadSessions::Loaded(vec![
                ConsoleSession {
                    name: "claude-one".into(),
                    kind: "SHELL".into(),
                    command: None,
                    running: true,
                    attached: false,
                    created_at: None,
                    snapshot: None,
                },
                // A finished provisioning exec is not a session anyone has.
                ConsoleSession {
                    name: "setup".into(),
                    kind: "EXEC".into(),
                    command: None,
                    running: false,
                    attached: false,
                    created_at: None,
                    snapshot: None,
                },
            ]);
        }
        let rows = a.rows();
        let agent = rows
            .iter()
            .position(|r| r.label == "nimble-otter")
            .expect("the agent heads its threads");
        let thread = rows
            .iter()
            .position(|r| r.label == "[S] claude-one")
            .expect("the running session is a child thread");
        assert_eq!(thread, agent + 1, "nested right under it: {rows:#?}");
        assert_eq!(rows[thread].depth, 1);
        assert!(
            !rows.iter().any(|r| r.label.contains("setup")),
            "a finished provisioning exec is not a thread"
        );
        assert_eq!(
            rows[agent].status.as_deref(),
            Some("running"),
            "the orb carries the status; no tag rides beside it"
        );
        assert!(rows[agent].note.is_empty());
    }

    /// Loading, failure, and an empty result all keep a single agent row.
    /// Only actual sessions become children; the orb/detail pane carry state.
    #[test]
    fn agents_without_sessions_have_no_placeholder_rows() {
        for sessions in [
            LoadSessions::NotLoaded,
            LoadSessions::Loading,
            LoadSessions::Failed("temporary failure".into()),
            LoadSessions::Loaded(vec![]),
        ] {
            let mut a = loaded_app();
            if let Load::Loaded(agents) = &mut a.tree[0].projects[0].envs[0].agents {
                agents[0].sessions = sessions;
            }
            let rows = a.rows();
            let agent = rows
                .iter()
                .position(|r| r.label == "nimble-otter")
                .expect("the agent keeps its row");
            assert!(rows[agent].selectable());
            assert_eq!(rows[agent].status.as_deref(), Some("running"));
            assert!(
                rows.get(agent + 1).is_none_or(|row| row.depth == 0),
                "an agent without sessions has no child rows: {rows:#?}"
            );
        }
    }

    /// Counts appear without expanding every agent: running ones are
    /// prefetched when their environment loads, sleeping ones are not.
    #[test]
    fn running_agents_prefetch_their_sessions() {
        let mut a = app();
        a.agents_loaded(
            (0, 0, 0),
            Ok(vec![
                agent("ca_1", "awake", "running"),
                agent("ca_2", "asleep", "sleeping"),
            ]),
        );
        let effects = a.sessions_to_prefetch();
        assert_eq!(effects.len(), 1, "{effects:?}");
        assert_eq!(
            effects[0],
            Effect::LoadSessions {
                agent_id: "ca_1".into(),
                environment_id: "env_prod".into(),
                path: (0, 0, 0, 0)
            }
        );
        assert!(
            a.sessions_to_prefetch().is_empty(),
            "already in flight, not asked twice"
        );
    }

    /// A project whose last agent is gone folds itself away — an open, empty
    /// project holds space for nothing.
    #[test]
    fn an_emptied_project_collapses() {
        let mut a = app();
        a.tree[0].projects[0].expanded = true;
        a.tree[0].projects[0].envs[0].expanded = true;
        a.agents_loaded((0, 0, 0), Ok(vec![agent("ca_1", "one", "running")]));
        a.agents_loaded((0, 0, 1), Ok(Vec::new()));
        assert!(a.tree[0].projects[0].expanded, "it still has an agent");

        // The last one goes.
        a.agents_loaded((0, 0, 0), Ok(Vec::new()));
        assert!(!a.tree[0].projects[0].expanded);
        assert!(!a.tree[0].projects[0].envs[0].expanded);
    }

    /// Not while an environment is still loading: collapsing then would hide
    /// agents that are about to arrive.
    #[test]
    fn a_project_stays_open_while_an_environment_is_loading() {
        let mut a = app();
        a.tree[0].projects[0].expanded = true;
        a.tree[0].projects[0].envs[1].agents = Load::Loading;
        a.agents_loaded((0, 0, 0), Ok(Vec::new()));
        assert!(a.tree[0].projects[0].expanded);
    }

    /// The default project leads the tail and is never dimmed — it is where
    /// agents go, so it has to be findable even while empty.
    #[test]
    fn the_default_project_leads_the_tail() {
        let mut a = ordering_app();
        a.default_project = Some("p3".into());
        assert_eq!(project_order(&a), ["mono", "Alpha", "beta", "zebra"]);

        let rows = a.rows();
        let mono = rows.iter().position(|r| r.label == "mono").unwrap();
        assert_eq!(rows[mono].note, "(default)", "marked, and not dimmed");
        assert!(!rows[mono].dimmed, "the default is always findable");
    }

    /// The rule sits between the agent groups and the projects tail, and
    /// moving down skips it rather than landing on it.
    #[test]
    fn a_rule_separates_the_groups_from_the_tail() {
        let mut a = ordering_app();
        a.agents_loaded((0, 0, 0), Ok(vec![agent("ca_1", "one", "running")]));
        let rows = a.rows();
        // The last rule: the first one sits under the New Session row.
        let sep = rows
            .iter()
            .rposition(|r| matches!(r.kind, RowKind::Separator))
            .expect("a rule under the groups");
        assert!(
            matches!(rows[sep - 1].kind, RowKind::Agent(..)),
            "{rows:#?}"
        );
        assert!(matches!(rows[sep + 1].kind, RowKind::OtherProjects));
        assert!(!rows[sep].selectable(), "the rule is not a stop");

        a.screen = Screen::Manage;
        a.cursor = sep - 1;
        a.on_key(key(KeyCode::Down));
        assert!(matches!(
            a.selected_row().unwrap().kind,
            RowKind::OtherProjects
        ));
    }

    /// With no agents there are no groups, so the tail gets no rule of its
    /// own — the only one left is the launcher's, right under New Session.
    #[test]
    fn no_groups_means_no_rule() {
        let a = ordering_app();
        let seps: Vec<usize> = a
            .rows()
            .iter()
            .enumerate()
            .filter(|(_, r)| matches!(r.kind, RowKind::Separator))
            .map(|(i, _)| i)
            .collect();
        assert_eq!(seps, vec![1], "only the launcher's rule");
    }

    /// Alphabetical, case-insensitively — a capitalised project should not
    /// sort above every lowercase one.
    #[test]
    fn projects_sort_alphabetically_when_none_have_agents() {
        let a = ordering_app();
        assert_eq!(project_order(&a), ["Alpha", "beta", "mono", "zebra"]);
    }

    /// A project that gains agents leaves the tail and leads the tree as a
    /// group — groups with something running first.
    #[test]
    fn projects_with_agents_lead_the_thread_list() {
        let mut a = ordering_app();
        // `zebra` gains a sleeping agent, `mono` a running one.
        a.agents_loaded((0, 0, 0), Ok(vec![agent("ca_1", "one", "sleeping")]));
        a.agents_loaded((0, 2, 0), Ok(vec![agent("ca_2", "two", "running")]));
        let threads: Vec<String> = a
            .rows()
            .iter()
            .filter(|r| matches!(r.kind, RowKind::Agent(..)))
            .map(|r| r.label.clone())
            .collect();
        assert_eq!(threads, ["two", "one"], "running leads");

        // Threads exist now, so the untouched tail folded itself away…
        assert_eq!(project_order(&a), Vec::<String>::new());
        // …and holds the rest once opened.
        a.others_expanded = Some(true);
        assert_eq!(project_order(&a), ["Alpha", "beta"]);

        // An environment that answers with nothing does not promote anyone.
        a.agents_loaded((0, 1, 0), Ok(Vec::new()));
        assert_eq!(project_order(&a), ["Alpha", "beta"]);
    }

    /// Empty projects are de-emphasised, and stop being so the moment they
    /// have something in them.
    #[test]
    fn projects_without_agents_are_dimmed() {
        let mut a = ordering_app();
        assert!(
            a.rows()
                .iter()
                .filter(|r| matches!(r.kind, RowKind::Project(..)))
                .all(|r| r.dimmed)
        );

        a.agents_loaded((0, 2, 0), Ok(vec![agent("ca_1", "one", "running")]));
        // With an agent, mono's thread is on the list and its project row is
        // gone from the tail.
        let rows = a.rows();
        assert!(rows.iter().any(|r| r.label == "one"), "{rows:#?}");
        assert!(!rows.iter().any(|r| r.label == "mono"));
    }

    /// Re-ordering must not move the selection to a different row: the cursor
    /// is an index, and the row under it would otherwise change.
    #[test]
    fn the_cursor_stays_on_its_row_when_the_order_changes() {
        let mut a = ordering_app();
        // `zebra` has a sleeping agent, and the cursor is on it.
        a.agents_loaded((0, 0, 0), Ok(vec![agent("ca_1", "one", "sleeping")]));
        a.cursor = a.rows().iter().position(|r| r.label == "one").unwrap();

        // `mono` gains a running agent and its group jumps above zebra's.
        a.agents_loaded((0, 2, 0), Ok(vec![agent("ca_2", "two", "running")]));
        assert_eq!(a.selected_row().unwrap().label, "one");
    }

    /// The tail header counts the projects folded under it, and says what
    /// they are other than once there are groups to be other than.
    #[test]
    fn the_tail_header_counts_its_projects() {
        let mut a = ordering_app();
        let header = |a: &App| {
            a.rows()
                .into_iter()
                .find(|r| matches!(r.kind, RowKind::OtherProjects))
                .unwrap()
        };
        assert_eq!(header(&a).label, "projects");
        assert_eq!(header(&a).note, "(4)");

        a.agents_loaded((0, 0, 0), Ok(vec![agent("ca_1", "one", "running")]));
        assert_eq!(header(&a).label, "other projects");
        assert_eq!(header(&a).note, "(3)");
    }

    /// Expanding an agent asks the platform what is running on it, every time:
    /// sessions come and go while you are looking elsewhere.
    #[test]
    fn expanding_an_agent_fetches_its_sessions() {
        let mut a = loaded_app();
        let row = a
            .rows()
            .iter()
            .position(|r| r.label == "nimble-otter")
            .unwrap();
        a.cursor = row;

        let effect = a.on_key(key(KeyCode::Right)).unwrap();
        assert_eq!(
            effect,
            Effect::LoadSessions {
                agent_id: "ca_1".into(),
                environment_id: "env_prod".into(),
                path: (0, 0, 0, 0)
            }
        );
        // While the reply is on its way the agent row stays put.
        assert!(a.rows().iter().any(|r| r.label == "nimble-otter"));

        a.sessions_loaded(
            (0, 0, 0, 0),
            "ca_1",
            Ok(vec![ConsoleSession {
                name: "sess-7".into(),
                command: Some("bash -l".into()),
                kind: "SHELL".into(),
                running: true,
                attached: false,
                created_at: None,
                snapshot: None,
            }]),
        );
        let rows = a.rows();
        let session_row = rows.iter().find(|r| r.label == "[S] sess-7").unwrap();
        assert!(matches!(session_row.kind, RowKind::Session(0, 0, 0, 0, 0)));
        assert_eq!(session_row.depth, 1, "a child of its agent");
        assert!(
            rows.iter().any(|r| r.label == "nimble-otter"),
            "the agent still heads its threads"
        );
    }

    /// A session's label has to be readable. The platform reports the whole
    /// launch line — PATH exports, a token source, a terminal-reset printf —
    /// and only the harness invocation in the middle means anything.
    #[test]
    fn session_labels_lift_the_harness_out_of_the_launch_line() {
        let raw = concat!(
            r#"export PATH="$HOME/.local/bin:$PATH"; [ -f ~/.gh-token ] && export GH_TOKEN="$(cat ~/.gh-token)"; "#,
            "export RAILWAY_CODE_AUTOSTARTED=1; claude 'Clone the repo'; printf '\033[?25h'; exec bash -l"
        );
        let session = ConsoleSession {
            name: "claude-3habai".into(),
            kind: "SHELL".into(),
            command: Some(raw.into()),
            running: true,
            attached: true,
            created_at: None,
            snapshot: None,
        };
        assert_eq!(
            session.short_name(),
            "claude-3habai",
            "rows are named by the session, not the launch line"
        );
        assert_eq!(session.command_summary(), "claude 'Clone the repo'");

        // Nothing recognisable: fall back to the first line, trimmed.
        let other = ConsoleSession {
            command: Some("npm run dev\nmore".into()),
            attached: false,
            created_at: None,
            snapshot: None,
            ..session.clone()
        };
        assert_eq!(other.command_summary(), "npm run dev");

        // No command at all: the name is all there is.
        let bare = ConsoleSession {
            command: None,
            ..session.clone()
        };
        assert_eq!(bare.command_summary(), "claude-3habai");
        let blank = ConsoleSession {
            command: Some("   ".into()),
            ..session.clone()
        };
        assert_eq!(blank.command_summary(), "claude-3habai");

        // Long ones are cut rather than overflowing the pane.
        let long = ConsoleSession {
            command: Some(format!("claude '{}'", "x".repeat(400))),
            ..session
        };
        assert!(
            long.command_summary().chars().count() <= 160,
            "{}",
            long.command_summary()
        );
        assert!(long.command_summary().ends_with(''));
    }

    /// Only what is still running is listed: finished provisioning execs, and
    /// shells that have ended — including one just killed, which should leave
    /// the list rather than linger and look like the kill failed.
    #[test]
    fn only_running_sessions_are_listed() {
        let exec = ConsoleSession {
            name: "zesty-spencer-htv".into(),
            kind: "EXEC".into(),
            command: Some("umask 077\ncat > ~/.claude-code-env".into()),
            running: false,
            attached: false,
            created_at: None,
            snapshot: None,
        };
        assert!(!exec.is_interesting());

        let detached = ConsoleSession {
            running: true,
            ..exec.clone()
        };
        assert!(
            !detached.is_interesting(),
            "a provisioning exec is never a conversation"
        );

        let dead_shell = ConsoleSession {
            kind: "SHELL".into(),
            running: false,
            ..exec
        };
        assert!(!dead_shell.is_interesting(), "an ended shell is gone");
    }

    /// The tree hides the noise, and says so when that is all there was.
    #[test]
    fn an_agent_with_only_provisioning_execs_reads_as_empty() {
        let mut a = loaded_app();
        a.tree[0].projects[0].envs[0].expanded = true;
        if let Load::Loaded(agents) = &mut a.tree[0].projects[0].envs[0].agents {
            agents[0].expanded = true;
            agents[0].sessions = LoadSessions::Loaded(vec![ConsoleSession {
                name: "zesty-spencer-htv".into(),
                kind: "EXEC".into(),
                command: Some("umask 077".into()),
                running: false,
                attached: false,
                created_at: None,
                snapshot: None,
            }]);
        }
        let rows = a.rows();
        assert!(
            rows.iter().any(|r| r.label == "nimble-otter"),
            "the agent keeps its own row: {rows:#?}"
        );
        assert!(
            !rows.iter().any(|r| r.label.contains("zesty-spencer")),
            "a finished exec is not a thread"
        );
    }

    /// A second prompt is a second piece of work: it must open its own session
    /// rather than dropping you back into the first.
    #[test]
    fn a_prompt_always_wants_its_own_session() {
        let base = LaunchRequest {
            project_id: "p".into(),
            environment_id: "e".into(),
            agent_id: None,
            session_name: None,
            force_new: false,
            new_session: false,
            harness: "claude".into(),
            prompt: None,
            label: "p/e".into(),
            base: Default::default(),
        };
        // A plain connect reuses whatever is open.
        assert!(!base.wants_new_session());
        // A prompt does not.
        assert!(
            LaunchRequest {
                prompt: Some("fix the tests".into()),
                ..base.clone()
            }
            .wants_new_session()
        );
        // Nor does an explicit new agent.
        assert!(
            LaunchRequest {
                force_new: true,
                ..base.clone()
            }
            .wants_new_session()
        );
        // Reattaching is neither: it joins a named session.
        assert!(
            !LaunchRequest {
                session_name: Some("claude-ab12cd".into()),
                prompt: Some("ignored".into()),
                ..base
            }
            .wants_new_session()
        );
    }

    /// Submitting hands the task over; the box should be empty for the next
    /// one, whatever happens to the launch afterwards.
    #[test]
    fn submitting_clears_the_prompt() {
        let mut a = app();
        a.target = Some(Target {
            project_id: "p".into(),
            project_name: "p".into(),
            environment_id: "e".into(),
            environment_name: "e".into(),
        });
        for c in "fix the tests".chars() {
            a.on_key(key(KeyCode::Char(c)));
        }
        let Effect::Launch(req) = a.on_key(key(KeyCode::Enter)).unwrap() else {
            panic!("expected a launch");
        };
        a.start_loading(&req);
        assert!(a.prompt.is_empty());
        assert_eq!(a.loading.prompt.as_deref(), Some("fix the tests"));
    }

    /// A session started from the TUI shows up under its agent without having
    /// to close and reopen the row — the platform registers it a moment after
    /// ssh connects, so the list is asked again.
    #[test]
    fn a_new_session_can_be_refreshed_into_view() {
        let mut a = loaded_app();
        // Explicit selection refreshes even a collapsed machine's cached list.
        assert!(matches!(
            a.refresh_agent_sessions("ca_1"),
            Some(Effect::LoadSessions { .. })
        ));

        if let Load::Loaded(agents) = &mut a.tree[0].projects[0].envs[0].agents {
            agents[0].expanded = true;
        }
        assert_eq!(
            a.refresh_agent_sessions("ca_1"),
            Some(Effect::LoadSessions {
                agent_id: "ca_1".into(),
                environment_id: "env_prod".into(),
                path: (0, 0, 0, 0)
            })
        );
        assert_eq!(a.refresh_agent_sessions("nope"), None);
    }

    #[test]
    fn discovery_is_on_demand_and_sleep_keeps_cached_threads_without_dialing() {
        let mut app = loaded_app();
        let thread = super::super::super::remote_threads::tests::thread("claude", "saved");
        let row = ConsoleSession::client_thread("ca_1", "claude", Some(&thread.thread));
        app.sessions_loaded((0, 0, 0, 0), "ca_1", Ok(vec![row.clone()]));
        assert!(app.sessions_to_prefetch().is_empty());
        assert_eq!(app.activity.next(std::time::Instant::now()), None);
        app.refresh_started();
        assert_eq!(app.sessions_to_prefetch().len(), 1);
        assert!(app.sessions_to_prefetch().is_empty());
        assert!(app.refresh_agent_sessions("ca_1").is_none());
        app.sessions_loaded((0, 0, 0, 0), "ca_1", Ok(vec![row]));
        app.refresh_finished();
        let previous = app.tree[0].projects[0].envs[0].agents_vec().to_vec();
        let mut asleep = previous.clone();
        asleep[0].status = "sleeping".into();
        app.tree[0].projects[0].envs[0].agents = Load::Loaded(merge_agents(previous, asleep));
        app.refresh_started();
        assert!(app.sessions_to_prefetch().is_empty());
        assert!(app.refresh_agent_sessions("ca_1").is_none());
        assert!(app.set_agent_expanded((0, 0, 0, 0), true).is_none());
        assert!(
            matches!(&app.tree[0].projects[0].envs[0].agents_vec()[0].sessions, LoadSessions::Loaded(rows) if rows.len() == 1 && rows[0].short_name() == thread.thread.title)
        );
    }

    #[test]
    fn deleting_a_conversation_is_immediate_scoped_and_rollback_survives_stale_replies() {
        let mut app = loaded_app();
        let cache_dir = tempfile::tempdir().unwrap();
        app.thread_cache = Some(super::super::cache::Cache::for_test(
            cache_dir.path().into(),
        ));
        let row = |harness, id| {
            ConsoleSession::client_thread(
                "ca_1",
                harness,
                Some(&super::super::super::remote_threads::tests::thread(harness, id).thread),
            )
        };
        let first = row("claude", "first");
        let victim = row("claude", "target");
        let other_harness = row("grok", "target");
        let rows = vec![first.clone(), victim.clone(), other_harness.clone()];
        app.sessions_loaded((0, 0, 0, 0), "ca_1", Ok(rows.clone()));
        app.cursor = app
            .rows()
            .iter()
            .position(|r| matches!(r.kind, RowKind::Session(0, 0, 0, 0, 1)))
            .unwrap();
        app.focus = ManageFocus::Tree;
        let mut pane = super::super::session::Session::for_test("ca_1", "VM").unwrap();
        pane.durable_name = victim.name.clone();
        pane.harness = "claude".into();
        pane.client_id = Some("pane-exact".into());
        app.sessions.push(pane);
        assert!(
            matches!(app.on_key(key(KeyCode::Char('X'))), Some(Effect::DeleteThread { session_name, .. }) if session_name == victim.name)
        );
        assert_eq!(
            app.tree[0].projects[0].envs[0].agents_vec()[0].sessions,
            LoadSessions::Loaded(vec![first.clone(), other_harness.clone()])
        );
        app.sessions_loaded((0, 0, 0, 0), "ca_1", Ok(rows.clone()));
        app.client_thread_selected(
            "pane-exact",
            super::super::super::remote_threads::tests::thread("claude", "target").thread,
        );
        assert_eq!(
            app.thread_cache
                .as_ref()
                .unwrap()
                .read("env_prod", "ca_1")
                .unwrap()
                .len(),
            2
        );
        assert_eq!(
            app.tree[0].projects[0].envs[0].agents_vec()[0].sessions,
            LoadSessions::Loaded(vec![first.clone(), other_harness.clone()])
        );
        app.thread_deleted(&victim.name, Some("permission denied".into()));
        assert_eq!(
            app.thread_cache
                .as_ref()
                .unwrap()
                .read("env_prod", "ca_1")
                .unwrap()
                .len(),
            3
        );
        assert_eq!(
            app.tree[0].projects[0].envs[0].agents_vec()[0].sessions,
            LoadSessions::Loaded(rows.clone())
        );
        assert!(
            app.toast
                .as_ref()
                .is_some_and(|t| t.text.contains("permission denied"))
        );
        app.cursor = app
            .rows()
            .iter()
            .position(|r| matches!(r.kind, RowKind::Session(0, 0, 0, 0, 1)))
            .unwrap();
        assert!(matches!(
            app.on_key(key(KeyCode::Char('x'))),
            Some(Effect::DeleteThread { .. })
        ));
        app.thread_deleted(&victim.name, None);
        app.sessions_loaded((0, 0, 0, 0), "ca_1", Ok(rows));
        assert_eq!(
            app.tree[0].projects[0].envs[0].agents_vec()[0].sessions,
            LoadSessions::Loaded(vec![first, other_harness])
        );
    }

    #[test]
    fn concurrent_deletion_failures_restore_original_order_in_either_completion_order() {
        for reverse in [false, true] {
            let mut app = loaded_app();
            let rows: Vec<_> = ["first", "second", "third"]
                .into_iter()
                .map(|id| {
                    ConsoleSession::client_thread(
                        "ca_1",
                        "claude",
                        Some(
                            &super::super::super::remote_threads::tests::thread("claude", id)
                                .thread,
                        ),
                    )
                })
                .collect();
            app.sessions_loaded((0, 0, 0, 0), "ca_1", Ok(rows.clone()));
            app.delete_thread_row(0, 0, 0, 0, 1).unwrap();
            app.delete_thread_row(0, 0, 0, 0, 1).unwrap();
            for i in if reverse { [2, 1] } else { [1, 2] } {
                app.thread_deleted(&rows[i].name, Some("offline".into()));
            }
            assert_eq!(
                app.tree[0].projects[0].envs[0].agents_vec()[0].sessions,
                LoadSessions::Loaded(rows)
            );
        }
    }

    /// An open pane counts as looking too. Sessions started and ended in there
    /// change the count beside the agent, and refusing to refetch a collapsed
    /// row left that count wrong until it was expanded again.
    #[test]
    fn an_agent_with_an_open_pane_refreshes_while_collapsed() {
        let mut a = with_sessions(&["ca_1"]);
        assert!(
            !a.tree[0].projects[0].envs[0].agents_vec()[0].expanded,
            "collapsed, on purpose"
        );
        assert_eq!(
            a.refresh_agent_sessions("ca_1"),
            Some(Effect::LoadSessions {
                agent_id: "ca_1".into(),
                environment_id: "env_prod".into(),
                path: (0, 0, 0, 0)
            })
        );
    }

    /// A refresh asks about the sessions of what is being looked at, and nothing
    /// else: `cloudAgentConsoleSessions` takes one agent, so a sweep would be a
    /// request per agent on every tick.
    #[test]
    fn a_refresh_only_asks_about_sessions_someone_can_see() {
        let mut a = loaded_app();
        a.agents_loaded(
            (0, 0, 0),
            Ok(vec![
                agent("ca_1", "nimble-otter", "running"),
                agent("ca_2", "quiet-one", "running"),
                agent("ca_3", "asleep", "sleeping"),
            ]),
        );
        if let Load::Loaded(agents) = &mut a.tree[0].projects[0].envs[0].agents {
            for agent in agents.iter_mut() {
                agent.sessions = LoadSessions::Loaded(Vec::new());
            }
            agents[0].expanded = true;
        }
        assert_eq!(
            a.sessions_to_refresh(),
            vec![Effect::LoadSessions {
                agent_id: "ca_1".into(),
                environment_id: "env_prod".into(),
                path: (0, 0, 0, 0)
            }],
            "the expanded one, not the collapsed one and not the sleeping one"
        );

        // The list is not blanked on the way out: a timer must not make the rows
        // flicker.
        assert_eq!(
            a.tree[0].projects[0].envs[0].agents_vec()[0].sessions,
            LoadSessions::Loaded(Vec::new())
        );
    }

    /// A session refresh that fails keeps the list it had, the same way the
    /// agent list does — an error where the rows were, once every 25s, would be
    /// a worse screen than a slightly old list.
    #[test]
    fn a_failed_session_refresh_keeps_the_sessions() {
        let mut a = loaded_app();
        let sessions = vec![ConsoleSession {
            name: "sess-7".into(),
            kind: "SHELL".into(),
            command: None,
            running: true,
            attached: false,
            created_at: None,
            snapshot: None,
        }];
        a.sessions_loaded((0, 0, 0, 0), "ca_1", Ok(sessions.clone()));
        a.sessions_loaded((0, 0, 0, 0), "ca_1", Err("502 from backboard".into()));

        assert_eq!(
            a.tree[0].projects[0].envs[0].agents_vec()[0].sessions,
            LoadSessions::Loaded(sessions)
        );
        assert!(a.status.contains("502 from backboard"), "{}", a.status);
        // Quietly: a background refresh must not raise a toast per tick.
        assert!(a.toast.is_none());
    }

    /// Without `myCloudAgents` a refresh asks per environment — but only about
    /// the ones with rows on screen. Sweeping the account is `shift+r`, which is
    /// a deliberate act because it costs a request each.
    #[test]
    fn the_fallback_refresh_asks_only_about_answered_environments() {
        let mut a = loaded_app();
        // env_prod is loaded (loaded_app), env_stg has never been asked about.
        assert_eq!(
            a.environments_to_refresh(),
            vec![Effect::LoadAgents {
                environment_id: "env_prod".into(),
                path: (0, 0, 0)
            }]
        );

        // One still in flight is already on its way.
        a.tree[0].projects[0].envs[0].agents = Load::Loading;
        assert!(a.environments_to_refresh().is_empty());
    }

    /// ⌥enter hands the whole terminal over; `f` does the same, because
    /// plenty of terminals never send a modifier with Enter.
    #[test]
    fn full_screen_has_two_ways_in() {
        let mut a = loaded_app();
        a.attach_session(session("ca_1", "nimble-otter"), "ca_1".into());
        a.focus = ManageFocus::Tree;

        let alt_enter = KeyEvent::new(KeyCode::Enter, KeyModifiers::ALT);
        let Some(Effect::FullScreen {
            agent_id,
            session_name,
            ..
        }) = a.on_key(alt_enter)
        else {
            panic!("expected a full-screen request");
        };
        assert_eq!(agent_id, "ca_1");
        assert_eq!(session_name, "test");

        assert!(matches!(
            a.on_key(key(KeyCode::Char('f'))),
            Some(Effect::FullScreen { .. })
        ));
    }

    /// shift+enter belongs to the harness, which reads it as the newline every
    /// text field gives you. The TUI must not claim it from either focus.
    #[test]
    fn shift_enter_is_the_harnesss_to_keep() {
        let shift_enter = KeyEvent::new(KeyCode::Enter, KeyModifiers::SHIFT);

        // With the tree focused it is not the full-screen chord any more; the
        // row under the cursor is a workspace, so a plain Enter would expand
        // it and a claimed shift+enter would show up as something happening.
        let mut a = loaded_app();
        a.attach_session(session("ca_1", "nimble-otter"), "ca_1".into());
        a.focus = ManageFocus::Tree;
        assert!(
            !matches!(a.on_key(shift_enter), Some(Effect::FullScreen { .. })),
            "shift+enter must not hand the terminal over"
        );

        // And with the session focused it falls straight through to the agent,
        // like every other key the pane does not reserve.
        let mut b = loaded_app();
        b.attach_session(session("ca_1", "nimble-otter"), "ca_1".into());
        b.focus = ManageFocus::Session;
        assert_eq!(b.on_key(shift_enter), None);
        assert_eq!(b.focus, ManageFocus::Session, "it must not release either");
    }

    /// Rows are named by the session — the seeded task stays in the detail
    /// card's command line, not the name.
    #[test]
    fn session_rows_show_the_session_name() {
        let session = ConsoleSession {
            name: "claude-3habai".into(),
            kind: "SHELL".into(),
            command: Some(
                "export PATH=x; export RAILWAY_CODE_AUTOSTARTED=1; claude 'do the thing'; exec bash -l"
                    .into(),
            ),
            running: true,
            attached: true,
            created_at: None,
                    snapshot: None,
        };
        assert_eq!(session.short_name(), "claude-3habai");
        // The command is still available, for the pane with room for it.
        assert_eq!(session.command_summary(), "claude 'do the thing'");
    }

    /// Selection is line-wise, the way a terminal selects: to the end of the
    /// first line, whole lines through the middle, and up to the cursor on the
    /// last. A rectangle would clip every line of agent output to the same
    /// columns.
    #[test]
    fn selection_is_linewise_not_rectangular() {
        let pane = PaneBox {
            x: 10,
            y: 5,
            w: 20,
            h: 6,
        };
        let selection = Selection {
            pane: ManageFocus::Session,
            anchor: (25, 5),
            cursor: (14, 7),
        };
        assert_eq!(
            selection.spans(pane),
            vec![(5, 25, 29), (6, 10, 29), (7, 10, 14)]
        );

        // Dragging backwards selects the same text.
        let backwards = Selection {
            anchor: (14, 7),
            cursor: (25, 5),
            ..selection
        };
        assert_eq!(backwards.spans(pane), selection.spans(pane));

        // One line stays one span.
        let single = Selection {
            anchor: (12, 6),
            cursor: (18, 6),
            ..selection
        };
        assert_eq!(single.spans(pane), vec![(6, 12, 18)]);

        // Rows outside the pane are dropped rather than clamped into it.
        let overflowing = Selection {
            anchor: (12, 1),
            cursor: (18, 99),
            ..selection
        };
        let spans = overflowing.spans(pane);
        assert!(
            spans.iter().all(|(y, ..)| (5..=10).contains(y)),
            "{spans:?}"
        );
    }

    /// A drag stays in the pane it began in — copying agent output must not
    /// pick up tree rows that happen to sit at the same screen rows.
    #[test]
    fn a_selection_is_confined_to_one_pane() {
        let mut a = loaded_app();
        a.panes = panes_fixture();

        // Press inside the session pane, then drag far into the tree. With no
        // session open the keyboard stays with the tree — the pane is the
        // launcher or a detail card — but the drag is still a selection.
        assert_eq!(a.on_mouse(MouseAction::Down, 40, 5), None);
        assert_eq!(a.focus, ManageFocus::Tree, "nothing there to type into");
        a.on_mouse(MouseAction::Drag, 2, 8);

        let selection = a.selection.unwrap();
        assert_eq!(selection.pane, ManageFocus::Session);
        let spans = selection.spans(a.panes.session);
        assert!(
            spans.iter().all(|(_, x0, _)| *x0 >= 34),
            "clamped to the session pane: {spans:?}"
        );

        // Releasing arms the copy for the next frame.
        a.on_mouse(MouseAction::Up, 34, 8);
        assert!(a.pending_copy.is_some());
    }

    /// Clicking another panel takes the keyboard back from a focused session —
    /// reaching for a panel with the mouse says as much as the chord does.
    #[test]
    fn clicking_away_releases_a_focused_session() {
        let mut a = loaded_app();
        a.attach_session(session("ca_1", "one"), "ca_1".into());
        a.panes = panes_fixture();
        assert_eq!(a.focus, ManageFocus::Session);

        // A click on the tree's border counts as a click on the tree.
        a.on_mouse(MouseAction::Down, 0, 2);
        assert_eq!(a.focus, ManageFocus::Tree);
    }

    #[test]
    fn clicking_the_tree_moves_the_cursor_and_focus() {
        let mut a = loaded_app();
        a.focus = ManageFocus::Session;
        a.panes = panes_fixture();
        // Row 1 is the launcher's rule, so the first row a click can land on
        // below the launcher is the group at 2.
        a.on_mouse(MouseAction::Down, 5, 5);
        assert_eq!(a.focus, ManageFocus::Tree);
        assert_eq!(a.cursor, 2, "third visible row");

        // A click that lands on nothing changes neither.
        a.on_mouse(MouseAction::Down, 200, 200);
        assert_eq!(a.focus, ManageFocus::Tree);
    }

    /// A click without a drag is not a selection; the highlight must not stick.
    #[test]
    fn a_plain_click_leaves_no_selection() {
        let mut a = loaded_app();
        a.panes = panes_fixture();
        a.on_mouse(MouseAction::Down, 5, 4);
        a.on_mouse(MouseAction::Up, 5, 4);
        assert!(a.selection.is_none());
        assert!(a.pending_copy.is_none());
    }

    /// Startup loads what a keypress needs and nothing else. Loading every
    /// environment in every project is one request each, which is what rate
    /// limited a real account.
    #[test]
    fn startup_loads_only_the_target_and_the_default_project() {
        let mut a = app();
        assert!(
            a.initial_environments().is_empty(),
            "no target and no default means nothing to load up front"
        );

        let mut a = app();
        a.target = Some(Target {
            project_id: "proj_1".into(),
            project_name: "devtools".into(),
            environment_id: "env_stg".into(),
            environment_name: "staging".into(),
        });
        let effects = a.initial_environments();
        assert_eq!(effects.len(), 1, "just the target: {effects:?}");
        assert!(matches!(
            &effects[0],
            Effect::LoadAgents { environment_id, .. } if environment_id == "env_stg"
        ));
        assert!(
            a.initial_environments().is_empty(),
            "what is already in flight is not asked for twice"
        );
    }

    /// The default project is where the tree opens and where an untargeted
    /// launch lands, so all of its environments load up front.
    #[test]
    fn startup_loads_every_environment_of_the_default_project() {
        let mut a = app();
        a.default_project = Some("proj_1".into());
        let effects = a.initial_environments();
        assert_eq!(effects.len(), 2, "production and staging: {effects:?}");
    }

    /// An agent this machine made is one you expect to find without hunting,
    /// even in a project that is neither the target nor the default.
    #[test]
    fn startup_loads_environments_this_machine_has_used() {
        let mut a = app();
        a.known_environments = vec!["env_stg".into()];
        let effects = a.initial_environments();
        assert_eq!(effects.len(), 1);
        assert!(matches!(
            &effects[0],
            Effect::LoadAgents { environment_id, .. } if environment_id == "env_stg"
        ));
    }

    /// One `myCloudAgents` reply answers for the whole account: agents land in
    /// their environments, and every other environment is loaded as empty —
    /// absence from the response means "none of yours here", not "unknown".
    #[test]
    fn my_agents_loaded_settles_every_environment() {
        let mut a = app();
        a.my_agents_loaded(
            vec![
                ("env_stg".into(), agent("ca_1", "fix-login", "running")),
                ("env_stg".into(), agent("ca_2", "bump-deps", "sleeping")),
                // An environment the tree doesn't know is ignored, not invented.
                ("env_gone".into(), agent("ca_3", "orphan", "running")),
            ],
            std::time::Instant::now(),
        );

        let stg = &a.tree[0].projects[0].envs[1].agents;
        let Load::Loaded(agents) = stg else {
            panic!("staging should be loaded: {stg:?}");
        };
        assert_eq!(
            agents.iter().map(|a| a.id.as_str()).collect::<Vec<_>>(),
            ["ca_1", "ca_2"]
        );
        assert_eq!(
            a.tree[0].projects[0].envs[0].agents,
            Load::Loaded(vec![]),
            "an environment absent from the reply has no agents of the caller's"
        );
    }

    /// A snapshot is a refresh, and a refresh has to be able to say that an
    /// agent is gone. Refusing to touch environments that already had a list is
    /// what made every full refresh a no-op, leaving relaunching the TUI as the
    /// only way to see a change made anywhere else.
    #[test]
    fn a_snapshot_replaces_what_the_tree_already_had() {
        let mut a = app();
        a.tree[0].projects[0].envs[0].agents = Load::Loaded(vec![
            agent("ca_kept", "still-here", "sleeping"),
            agent("ca_deleted", "gone-elsewhere", "running"),
        ]);
        // Still loading: its own reply has not landed to be compared, and it is
        // newer than this snapshot, so it must survive.
        a.tree[0].projects[0].envs[1].agents = Load::Loading;

        a.my_agents_loaded(
            vec![
                // Woken somewhere else, and `ca_deleted` is absent.
                ("env_prod".into(), agent("ca_kept", "still-here", "running")),
                (
                    "env_prod".into(),
                    agent("ca_new", "made-elsewhere", "running"),
                ),
                ("env_stg".into(), agent("ca_racing", "in-flight", "running")),
            ],
            std::time::Instant::now(),
        );

        let Load::Loaded(agents) = &a.tree[0].projects[0].envs[0].agents else {
            panic!("production should be loaded");
        };
        assert_eq!(
            agents.iter().map(|a| a.id.as_str()).collect::<Vec<_>>(),
            ["ca_kept", "ca_new"],
            "the snapshot decides who is there"
        );
        assert_eq!(agents[0].status, "running", "and what state they are in");
        assert_eq!(a.tree[0].projects[0].envs[1].agents, Load::Loading);
    }

    /// …but never over fresher news. A refresh in flight while an agent is
    /// deleted would otherwise put the row back — its snapshot was taken while
    /// the agent still existed — and leave it there until the next refresh.
    #[test]
    fn a_snapshot_does_not_overwrite_a_later_answer() {
        let mut a = app();
        let asked_at = std::time::Instant::now();
        // The environment answers for itself after the account-wide request went
        // out: `d` on an agent, and the refetch that proves it is gone.
        a.agents_loaded(
            (0, 0, 0),
            Ok(vec![agent("ca_kept", "the-survivor", "running")]),
        );

        a.my_agents_loaded(
            vec![
                (
                    "env_prod".into(),
                    agent("ca_kept", "the-survivor", "running"),
                ),
                (
                    "env_prod".into(),
                    agent("ca_deleted", "deleted-just-now", "running"),
                ),
            ],
            asked_at,
        );

        let Load::Loaded(agents) = &a.tree[0].projects[0].envs[0].agents else {
            panic!("production should be loaded");
        };
        assert_eq!(
            agents.iter().map(|a| a.id.as_str()).collect::<Vec<_>>(),
            ["ca_kept"],
            "the deleted agent must not come back"
        );
        // Environments that had nothing newer still take the snapshot.
        assert_eq!(a.tree[0].projects[0].envs[1].agents, Load::Loaded(vec![]));
    }

    /// The one thing a refresh must not touch: what the person looking at it
    /// has open. Every refresh used to fold expanded agents shut and drop their
    /// session lists, because the rows are rebuilt from a query that cannot know
    /// either — which is also why the 1.5s poll during a wake made the tree
    /// jump.
    #[test]
    fn a_refresh_keeps_rows_open_and_their_sessions() {
        let mut a = loaded_app();
        let (w, p, e) = (0, 0, 0);
        let sessions = LoadSessions::Loaded(vec![ConsoleSession {
            name: "claude-3s9r89".into(),
            kind: "SHELL".into(),
            command: Some("claude".into()),
            running: true,
            attached: false,
            created_at: None,
            snapshot: None,
        }]);
        if let Load::Loaded(agents) = &mut a.tree[w].projects[p].envs[e].agents {
            agents[0].expanded = true;
            agents[0].sessions = sessions.clone();
        }
        let id = a.tree[w].projects[p].envs[e].agents_vec()[0].id.clone();

        // The same environment comes back from the platform: same agent, no idea
        // that anything is open.
        a.agents_loaded(
            (w, p, e),
            Ok(vec![Agent {
                id: id.clone(),
                name: "nimble-otter".into(),
                status: "running".into(),
                sessions: LoadSessions::NotLoaded,
                expanded: false,
            }]),
        );

        let agents = a.tree[w].projects[p].envs[e].agents_vec();
        assert!(agents[0].expanded, "the row must stay open");
        assert_eq!(agents[0].sessions, sessions, "and keep its session rows");

        // An account-wide refresh has to carry it too — that is the one that
        // runs on a timer.
        a.my_agents_loaded(
            vec![("env_prod".into(), agent(&id, "nimble-otter", "running"))],
            std::time::Instant::now(),
        );
        let agents = a.tree[w].projects[p].envs[e].agents_vec();
        assert!(agents[0].expanded);
        assert_eq!(agents[0].sessions, sessions);
    }

    /// A newcomer starts collapsed. Carrying state across ids would put one
    /// agent's sessions under another's name.
    #[test]
    fn a_refresh_does_not_lend_open_state_to_a_new_agent() {
        let mut a = loaded_app();
        if let Load::Loaded(agents) = &mut a.tree[0].projects[0].envs[0].agents {
            agents[0].expanded = true;
            agents[0].sessions = LoadSessions::Loaded(Vec::new());
        }
        a.agents_loaded(
            (0, 0, 0),
            Ok(vec![agent("ca_brand_new", "newcomer", "running")]),
        );
        let agents = a.tree[0].projects[0].envs[0].agents_vec();
        assert_eq!(agents[0].id, "ca_brand_new");
        assert!(!agents[0].expanded);
        assert_eq!(agents[0].sessions, LoadSessions::NotLoaded);
    }

    /// A sessions reply is applied to the agent it was asked about, not to
    /// whichever agent now sits at the index the request went out with — an
    /// environment refetch can insert a newer agent above it meanwhile.
    #[test]
    fn a_sessions_reply_follows_its_agent_when_the_list_shifts() {
        let mut a = loaded_app();
        // The env was refetched while ca_1's sessions were in flight: a newer
        // agent now occupies index 0.
        a.agents_loaded(
            (0, 0, 0),
            Ok(vec![
                agent("ca_new", "just-created", "starting"),
                agent("ca_1", "nimble-otter", "running"),
            ]),
        );

        a.sessions_loaded(
            (0, 0, 0, 0),
            "ca_1",
            Ok(vec![ConsoleSession {
                name: "claude-one".into(),
                kind: "SHELL".into(),
                command: None,
                running: true,
                attached: false,
                created_at: None,
                snapshot: None,
            }]),
        );

        let Load::Loaded(agents) = &a.tree[0].projects[0].envs[0].agents else {
            panic!("loaded");
        };
        assert!(
            matches!(agents[0].sessions, LoadSessions::NotLoaded),
            "the newcomer at index 0 must not inherit ca_1's sessions"
        );
        assert!(matches!(agents[1].sessions, LoadSessions::Loaded(ref s) if s.len() == 1));

        // And a reply for an agent that no longer exists goes nowhere.
        a.sessions_loaded((0, 0, 0, 0), "ca_gone", Ok(Vec::new()));
    }

    /// One reply answers for every environment, so an account with no agents is
    /// a tree that has finished loading rather than one still waiting.
    #[test]
    fn an_empty_reply_still_settles_the_tree() {
        let mut a = app();
        a.my_agents_loaded(Vec::new(), std::time::Instant::now());
        for env in &a.tree[0].projects[0].envs {
            assert_eq!(env.agents, Load::Loaded(vec![]));
        }
    }

    /// `shift+r` is how an agent in a project nobody has opened gets found: the
    /// scan startup used to do, when the user asks for it.
    #[test]
    fn shift_r_scans_every_environment() {
        let mut a = loaded_app();
        // Off the launcher, where `R` is a letter for the prompt.
        a.on_key(key(KeyCode::Down));
        assert_eq!(
            a.on_key(key(KeyCode::Char('R'))),
            Some(Effect::ScanEverywhere)
        );

        let mut a = app();
        let effects = a.scan_environments();
        assert_eq!(effects.len(), 2, "every environment in the fixture");
        assert!(
            a.scan_environments().is_empty(),
            "a second scan must not refetch what is already in flight"
        );
    }

    /// A rate limit puts what was in flight back, so opening the row retries
    /// instead of showing a spinner that never resolves.
    #[test]
    fn a_rate_limit_releases_what_was_loading() {
        let mut a = app();
        a.default_project = Some("proj_1".into());
        assert_eq!(a.initial_environments().len(), 2);
        assert_eq!(a.tree[0].projects[0].envs[0].agents, Load::Loading);

        a.rate_limited(Some(43));
        assert_eq!(a.tree[0].projects[0].envs[0].agents, Load::NotLoaded);
        assert_eq!(a.tree[0].projects[0].envs[1].agents, Load::NotLoaded);
        let toast = a.toast.as_ref().expect("a toast");
        assert!(toast.text.contains("43s"), "{}", toast.text);
        assert!(!toast.ok, "a rate limit is not a success");

        // And asking again works, rather than being blocked by the old claim.
        assert_eq!(a.initial_environments().len(), 2);
    }

    #[test]
    fn ctrl_c_quits_from_anywhere() {
        let mut a = app();
        assert_eq!(a.on_key(ctrl('c')), Some(Effect::Quit));
        a.screen = Screen::Manage;
        assert_eq!(a.on_key(ctrl('c')), Some(Effect::Quit));
    }

    /// A response for a path that no longer exists must be dropped, not panic.
    #[test]
    fn a_stale_load_result_is_ignored() {
        let mut a = app();
        let before = a.rows();
        a.agents_loaded((9, 9, 9), Ok(vec![]));
        a.agents_loaded((0, 0, 5), Err("boom".into()));
        assert_eq!(a.rows(), before);
    }

    #[test]
    fn a_failed_load_says_so_rather_than_showing_empty() {
        let mut a = app();
        a.tree[0].projects[0].expanded = true;
        a.tree[0].projects[0].envs[0].expanded = true;
        a.agents_loaded((0, 0, 0), Err("502 from backboard".into()));
        let rows = a.rows();
        assert!(rows.iter().any(|r| r.label.contains("502 from backboard")));
        assert!(!rows.iter().any(|r| r.label == "no agents here"));
    }

    /// `r` refetches without blanking what is on screen: a group that
    /// vanished for every refresh would shove the rows — and the cursor —
    /// somewhere else once every poll tick during a wake.
    #[test]
    fn refreshing_a_group_keeps_it_on_screen() {
        let mut a = loaded_app();
        a.cursor = a
            .rows()
            .iter()
            .position(|r| r.label == "nimble-otter")
            .unwrap();
        let effect = a.on_key(key(KeyCode::Char('r')));
        assert_eq!(
            effect,
            Some(Effect::LoadAgents {
                environment_id: "env_prod".into(),
                path: (0, 0, 0)
            })
        );
        assert!(a.rows().iter().any(|r| r.label == "nimble-otter"));
        assert_eq!(a.selected_row().unwrap().label, "nimble-otter");

        // The same when a watch polls the environment behind the scenes.
        a.reveal_environment("env_prod");
        assert!(a.rows().iter().any(|r| r.label == "nimble-otter"));
    }

    /// A refresh that fails keeps the stale list — stale beats gone — and
    /// says why in an error toast.
    #[test]
    fn a_failed_refresh_keeps_the_agents_and_reports() {
        let mut a = loaded_app();
        a.agents_loaded((0, 0, 0), Err("502 from backboard".into()));
        assert!(a.rows().iter().any(|r| r.label == "nimble-otter"));
        let toast = a.toast.as_ref().expect("an error toast");
        assert!(!toast.ok);
        assert!(toast.text.contains("502 from backboard"), "{}", toast.text);
    }

    /// A project with agents in one environment still shows its empty ones in
    /// the tail — they have to stay reachable for `n`, `t`, and `r`.
    #[test]
    fn empty_environments_of_a_grouped_project_stay_reachable() {
        let mut a = loaded_app();
        a.others_expanded = Some(true);
        let rows = a.rows();
        assert!(
            rows.iter()
                .any(|r| r.kind == RowKind::Environment(0, 0, 1) && r.label == "staging"),
            "{rows:#?}"
        );
        // The occupied environment is a group above, not a tail row too.
        assert!(!rows.iter().any(|r| r.kind == RowKind::Environment(0, 0, 0)));

        // Once every environment has agents the project leaves the tail.
        a.agents_loaded((0, 0, 1), Ok(vec![agent("ca_9", "niner", "running")]));
        assert!(
            !a.rows()
                .iter()
                .any(|r| matches!(r.kind, RowKind::Project(..)))
        );
    }

    /// The empty state advertises `n`, so `n` must work from where the cursor
    /// starts: with a target it launches there, without one it asks for one.
    #[test]
    fn a_new_agent_without_a_target_asks_for_one_first() {
        let mut a = app();
        a.screen = Screen::Manage;
        a.on_key(key(KeyCode::Down));
        a.on_key(key(KeyCode::Char('n')));
        assert_eq!(a.screen, Screen::TargetPick, "no target: ask for one");
    }

    /// Loading an environment from the tail can promote it into a group; the
    /// cursor follows it up rather than being stranded in the folded tail.
    #[test]
    fn the_cursor_follows_an_environment_promoted_to_a_group() {
        let mut a = app();
        a.screen = Screen::Manage;
        a.cursor = a.rows().iter().position(|r| r.label == "devtools").unwrap();
        a.on_key(key(KeyCode::Right));
        a.cursor = a
            .rows()
            .iter()
            .position(|r| r.label == "production")
            .unwrap();
        a.on_key(key(KeyCode::Right));
        a.agents_loaded((0, 0, 0), Ok(vec![agent("ca_1", "one", "running")]));
        // The environment left the tail for the thread list; the cursor lands
        // on a row that still exists rather than the one that vanished.
        assert!(a.selected_row().unwrap().selectable(), "{:#?}", a.rows());
    }

    /// "None yet" is a definitive claim: the hint searches while anything is
    /// unanswered, owns up to failures, and only then declares the account
    /// empty.
    #[test]
    fn the_hint_waits_for_answers_before_claiming_empty() {
        let mut a = app();
        // The hint sits under the pinned New Session row and its rule.
        let hint = |a: &App| a.rows()[2].label.clone();
        assert_eq!(hint(&a), "looking for cloud agents…", "not loaded");

        a.tree[0].projects[0].envs[0].agents = Load::Loading;
        assert_eq!(hint(&a), "looking for cloud agents…", "still in flight");

        a.agents_loaded((0, 0, 0), Ok(Vec::new()));
        a.agents_loaded((0, 0, 1), Err("boom".into()));
        assert_eq!(hint(&a), "couldn't check every environment — r retries");

        a.agents_loaded((0, 0, 1), Ok(Vec::new()));
        assert_eq!(hint(&a), "no threads yet — the prompt above starts one");
    }

    fn offer() -> SshKeyOffer {
        SshKeyOffer {
            name: "id_ed25519".into(),
            fingerprint: "SHA256:abc".into(),
            public_key: "ssh-ed25519 AAAA test".into(),
        }
    }

    fn launch_req() -> LaunchRequest {
        LaunchRequest {
            project_id: "proj_1".into(),
            environment_id: "env_prod".into(),
            agent_id: None,
            session_name: None,
            force_new: false,
            new_session: false,
            harness: "claude".into(),
            prompt: None,
            label: "devtools/production".into(),
            base: Default::default(),
        }
    }

    #[test]
    fn bootstrap_setup_ssh_gate_can_register_or_cancel_before_spending_a_vm() {
        for accept in [true, false] {
            let mut a = app();
            let target = Target {
                project_id: "proj_1".into(),
                project_name: "Demo".into(),
                environment_id: "env_prod".into(),
                environment_name: "production".into(),
            };
            a.target = Some(target.clone());
            a.start_bootstrap_setup();
            a.bootstrap_form.as_mut().unwrap().running = true;
            let req = super::super::bootstrap_setup::Request {
                target,
                name: "dev".into(),
                repo: None,
                harness: "railway".into(),
                snapshot: None,
                make_default: true,
            };
            a.ssh_key = SshKeyState::NeedsRegistration(offer());
            assert!(a.hold_for_ssh_key(HeldConnect::Bootstrap(req.clone())));
            let effect = a.on_key(key(KeyCode::Char(if accept { 'y' } else { 'n' })));
            if accept {
                let Some(Effect::RegisterSshKey {
                    then: Some(held), ..
                }) = effect
                else {
                    panic!("registration");
                };
                assert_eq!(held.into_effect(), Effect::CreateBootstrap(req));
            } else {
                assert!(effect.is_none());
                assert!(!a.bootstrap_form.as_ref().unwrap().running);
                assert!(a.bootstrap_form.as_ref().unwrap().error.is_some());
            }
            assert_eq!(a.screen, Screen::BootstrapSetup);
        }
    }

    /// An unregistered key holds the connect behind the gate; nothing is
    /// launched until the question is answered.
    #[test]
    fn an_unregistered_key_holds_the_connect() {
        let mut a = app();
        a.ssh_key = SshKeyState::NeedsRegistration(offer());
        let held = HeldConnect::Launch(launch_req());
        assert!(a.hold_for_ssh_key(held.clone()));
        assert_eq!(
            a.ssh_gate,
            Some(SshGate {
                offer: offer(),
                then: Some(held),
            })
        );
    }

    /// A registered key, and a check that never answered, both let the
    /// connect through — the launch pipeline is the better place to fail.
    #[test]
    fn ready_and_unknown_keys_proceed() {
        let mut a = app();
        a.ssh_key = SshKeyState::Ready;
        assert!(!a.hold_for_ssh_key(HeldConnect::Launch(launch_req())));
        a.ssh_key = SshKeyState::Unknown;
        assert!(!a.hold_for_ssh_key(HeldConnect::Launch(launch_req())));
        assert!(a.ssh_gate.is_none());
    }

    /// With nothing local to offer, the connect is refused with the recipe
    /// rather than held behind a question that has no good answer.
    #[test]
    fn no_local_keys_refuses_with_the_recipe() {
        let mut a = app();
        a.ssh_key = SshKeyState::NoLocalKeys;
        assert!(a.hold_for_ssh_key(HeldConnect::Launch(launch_req())));
        assert!(a.ssh_gate.is_none());
        assert!(a.toast.as_ref().is_some_and(|t| !t.ok), "{:?}", a.toast);
    }

    /// `y` answers the gate with the register effect, carrying the held
    /// connect along to resume after the mutation.
    #[test]
    fn yes_registers_and_carries_the_held_connect() {
        let mut a = app();
        a.ssh_key = SshKeyState::NeedsRegistration(offer());
        assert!(a.hold_for_ssh_key(HeldConnect::Launch(launch_req())));
        let effect = a.on_key(key(KeyCode::Char('y')));
        assert_eq!(
            effect,
            Some(Effect::RegisterSshKey {
                offer: offer(),
                then: Some(HeldConnect::Launch(launch_req())),
            })
        );
        assert!(a.ssh_gate.is_none());
    }

    /// Anything that isn't a yes cancels: a mistyped key must never register
    /// a credential on the account.
    #[test]
    fn anything_else_cancels_the_gate() {
        let mut a = app();
        a.ssh_key = SshKeyState::NeedsRegistration(offer());
        assert!(a.hold_for_ssh_key(HeldConnect::Launch(launch_req())));
        assert_eq!(a.on_key(key(KeyCode::Enter)), None);
        assert!(a.ssh_gate.is_none());
        // The state is untouched, so the next connect asks again.
        assert_eq!(a.ssh_key, SshKeyState::NeedsRegistration(offer()));
    }

    /// Setup's offer has no held connect: declining it is not an error and
    /// says nothing about a cancelled launch.
    #[test]
    fn the_setup_offer_declines_quietly() {
        let mut a = app();
        a.ssh_key = SshKeyState::NeedsRegistration(offer());
        a.offer_ssh_key_setup();
        assert!(a.ssh_gate.is_some());
        assert_eq!(a.on_key(key(KeyCode::Esc)), None);
        assert!(a.toast.is_none(), "{:?}", a.toast);

        // With the key already registered, setup offers nothing.
        a.ssh_key = SshKeyState::Ready;
        a.offer_ssh_key_setup();
        assert!(a.ssh_gate.is_none());
    }
}