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
//! Rendering for the `railway ca` TUI. Pure draw code — every decision it
//! needs has already been made in [`super::app`].

mod bootstrap;

use ratatui::Frame;
use ratatui::layout::{Alignment, Constraint, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{
    Block, BorderType, Borders, Clear, List, ListItem, ListState, Padding, Paragraph, Wrap,
};

use super::app::{
    App, KEY_HELP, Load, LoadSessions, ManageFocus, PaneBox, PaneRects, Row, RowKind, Screen,
};
use super::theme::Theme;
use crate::vt100;

/// Drawn only when the terminal is wide and tall enough for it; below that the
/// screen still has to be usable, so a one-line wordmark stands in.
///
/// Full blocks and spaces only. The obvious figlet for this (ANSI Shadow) draws
/// its depth with `╗╔═║╚╝`, and those are box-drawing glyphs a monospace font is
/// free to render at a different weight or offset from `█` — which it does, and
/// the wordmark comes out looking sheared. Every font renders U+2588 as a full
/// cell, so a block-only mark is the same shape everywhere.
const BANNER: &str = r#"██████   █████  ██████ ██      ██   ██  █████  ██    ██
██   ██ ██   ██   ██   ██      ██   ██ ██   ██  ██  ██
██████  ███████   ██   ██      ██ █ ██ ███████   ████
██  ██  ██   ██   ██   ██      ███████ ██   ██    ██
██   ██ ██   ██ ██████ ███████ ██   ██ ██   ██    ██"#;

const BANNER_W: u16 = 55;
const BANNER_H: u16 = 5;

/// Default width of the tree column in Manage, borders included.
const TREE_W: u16 = 32;

/// Keep both panes usable without changing the saved width on window resize.
pub(super) fn sidebar_width(available: u16, preferred: Option<u16>) -> u16 {
    let maximum = available.saturating_sub(32);
    preferred.unwrap_or(TREE_W).clamp(20.min(maximum), maximum)
}

/// What a dialog spends on chrome: its two border cells. The breathing room
/// lives *outside* the boxes — see [`page`] — not between a border and its
/// text.
const DIALOG_CHROME_X: u16 = 2;
const DIALOG_CHROME_Y: u16 = 2;

/// Columns of space between the terminal's edge and the UI.
const PAGE_MARGIN_X: u16 = 2;
/// Rows of the same. Half the columns, because a terminal cell is about twice
/// as tall as it is wide — the same gap on screen on every side.
const PAGE_MARGIN_Y: u16 = 1;

/// What the page margin leaves of a `width` × `height` terminal. Skipped when
/// the terminal is too small to spend cells on air — a cramped layout beats a
/// truncated one.
///
/// The single source of that answer: [`page`] shapes what is drawn with it,
/// and [`session_pane_size`] shapes the PTY with it. They must agree — an
/// emulator wrapping wider than its pane puts the last columns of every row
/// somewhere the screen never shows, which shears anything long enough to
/// wrap (an OAuth URL loses four characters at every fold).
fn page_size(width: u16, height: u16) -> (u16, u16) {
    if width < 40 || height < 12 {
        (width, height)
    } else {
        (width - PAGE_MARGIN_X * 2, height - PAGE_MARGIN_Y * 2)
    }
}

/// The page: the frame minus a slim outer margin, so boxes never press
/// against the terminal's edges. Every screen and floating card lays out
/// against this.
fn page(f: &Frame) -> Rect {
    let area = f.area();
    let (width, height) = page_size(area.width, area.height);
    Rect {
        x: area.x + (area.width - width) / 2,
        y: area.y + (area.height - height) / 2,
        width,
        height,
    }
}

/// The prompt box's shape — width, and height in rows including borders —
/// shared by the launcher's prompt and the ⌥p composer so the two read as
/// the same control. Text rows plus the border: twice the writing room of the
/// original two rows on screens with the height for it — a prompt is a
/// paragraph these days, not a title — and a compact variant below that.
fn prompt_box_size(area: Rect) -> (u16, u16) {
    let height = if area.height >= 30 { 6 } else { 2 } + DIALOG_CHROME_Y;
    let width = 74.min(area.width.saturating_sub(2)).max(40.min(area.width));
    (width, height)
}

/// The chrome every floating card shares.
///
/// Opaque fill, because these sit *on top of* the screen rather than in it:
/// with only [`Clear`] underneath, the terminal's own background shows through
/// and the card reads as a hole punched in the page instead of a dialog above
/// it.
fn dialog_block(theme: &Theme) -> Block<'static> {
    Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(theme.accent))
        .style(Style::default().bg(theme.surface).fg(theme.fg))
}

/// Shortcut keys use the same compact filled badge throughout the TUI.
fn chord_badge(theme: &Theme, chord: &str) -> Span<'static> {
    Span::styled(
        format!(" {chord} "),
        Style::default()
            .fg(theme.on_accent)
            .bg(theme.accent_dim)
            .add_modifier(Modifier::BOLD),
    )
}

/// Footer chords: a filled key badge, then dim text for what it does.
/// Shared so the launcher and the manage screen read as the same product.
fn chord_spans(theme: &Theme, chords: &[(&str, &str)]) -> Vec<Span<'static>> {
    let mut spans = Vec::with_capacity(chords.len() * 2);
    for (chord, what) in chords {
        spans.push(chord_badge(theme, chord));
        spans.push(Span::styled(
            format!(" {what}   "),
            Style::default().fg(theme.dim),
        ));
    }
    spans
}

/// The wordmark as equal-width lines.
///
/// Each line is padded here rather than in the literal above: ratatui centres
/// every line independently, so a row that lost its trailing spaces would sit
/// half a character off from the rest — and trailing whitespace inside a source
/// literal is exactly the thing an editor or a formatter silently trims.
fn banner_lines(theme: &Theme) -> Vec<Line<'static>> {
    BANNER
        .lines()
        .map(|l| {
            let pad = (BANNER_W as usize).saturating_sub(l.chars().count());
            Line::from(Span::styled(
                format!("{l}{}", " ".repeat(pad)),
                Style::default()
                    .fg(theme.accent)
                    .add_modifier(Modifier::BOLD),
            ))
        })
        .collect()
}

/// Render; report where the panes ended up so the mouse can hit-test them, and
/// lift out any pending selection's text.
///
/// The text has to come from here because this is the only place the finished
/// frame exists: the session pane's contents are an emulator's screen composed
/// into a buffer, and what the user dragged over is that composition.
pub fn render_with_layout(app: &App, f: &mut Frame) -> (PaneRects, Option<String>) {
    let mut rects = PaneRects::default();
    render_inner(app, f, &mut rects);
    let text = app.pending_copy.and_then(|selection| {
        let bounds = match selection.pane {
            ManageFocus::Tree => rects.tree,
            ManageFocus::Session => rects.session,
        };
        let buffer = f.buffer_mut();
        let lines: Vec<String> = selection
            .spans(bounds)
            .into_iter()
            .map(|(y, x0, x1)| {
                let line: String = (x0..=x1).map(|x| buffer[(x, y)].symbol()).collect();
                line.trim_end().to_string()
            })
            .collect();
        let text = lines.join("\n");
        (!text.trim().is_empty()).then_some(text)
    });
    (rects, text)
}

fn render_inner(app: &App, f: &mut Frame, rects: &mut PaneRects) {
    f.render_widget(Clear, f.area());
    render_screen(app, f, rects);
    render_ssh_gate(app, f);
    render_toast(app, f, rects);
}

/// The register-your-SSH-key question, centered over whatever raised it. Up
/// only while [`App::ssh_gate`] holds a connect (or setup's offer); the next
/// key answers it — see the gate block at the top of [`App::on_key`].
fn render_ssh_gate(app: &App, f: &mut Frame) {
    let Some(gate) = app.ssh_gate.as_ref() else {
        return;
    };
    let theme = app.theme;
    let area = page(f);
    // Name and fingerprint on their own lines: together they outrun the card
    // and wrap mid-fingerprint, which reads as garbage. Apart, both fit.
    // Everything reads in the foreground — this card is the only thing asking
    // for attention while it is up, so nothing on it is background noise.
    let body = Style::default().fg(theme.fg);
    let lines = vec![
        Line::from(Span::styled(
            format!("  {}", gate.offer.name),
            body.add_modifier(Modifier::BOLD),
        )),
        Line::from(Span::styled(format!("  {}", gate.offer.fingerprint), body)),
        Line::from(""),
        Line::from(Span::styled(
            "  Agents are reached over SSH, and Railway only answers",
            body,
        )),
        Line::from(Span::styled(
            "  keys it knows. Registered once, it covers every agent.",
            body,
        )),
        Line::from(""),
        // The footers' badge chords, centered: the question's answers are the
        // card's focal point, not another row of copy.
        Line::from(vec![
            chord_badge(theme, "y"),
            Span::styled(" Yes — register this key", body),
            Span::raw("    "),
            chord_badge(theme, "n"),
            Span::styled(" No, not now", body),
        ])
        .alignment(Alignment::Center),
    ];
    let width = (55 + DIALOG_CHROME_X).min(area.width.saturating_sub(4));
    let height = (lines.len() as u16 + DIALOG_CHROME_Y).min(area.height.saturating_sub(2));
    let panel = centered(width, height, area);
    f.render_widget(Clear, panel);
    f.render_widget(
        Paragraph::new(lines).block(
            dialog_block(theme).title(Span::styled(
                " Register your SSH key with Railway? ",
                Style::default()
                    .fg(theme.accent)
                    .add_modifier(Modifier::BOLD),
            )),
        ),
        panel,
    );
}

/// The corner confirmation, over whatever is underneath it.
///
/// A confirmation sits bottom right, clear of the key strip on the left of the
/// same row and of the `? keys` badge on its right — a glance, out of the way.
/// An error is the thing that needs reading, so it sits front and center at
/// the bottom of the session pane (or of the page, when no pane is drawn).
fn render_toast(app: &App, f: &mut Frame, rects: &PaneRects) {
    let Some(toast) = app.toast.as_ref().filter(|toast| !toast.expired()) else {
        return;
    };
    let theme = app.theme;
    let area = page(f);
    let text = format!(" {}  {}  ", if toast.ok { "" } else { "" }, toast.text);
    let w = (text.chars().count() as u16 + DIALOG_CHROME_X).min(area.width);
    let h = 3.min(area.height);
    let rect = if toast.ok {
        // Clear of the key strip on the last row and of the pane border above
        // it, so it floats inside the pane rather than colliding with its
        // corner.
        Rect {
            x: area.right().saturating_sub(w + 2),
            y: area.bottom().saturating_sub(h + 2),
            width: w,
            height: h,
        }
    } else {
        let host = if rects.session.w > 0 {
            Rect {
                x: rects.session.x,
                y: rects.session.y,
                width: rects.session.w,
                height: rects.session.h,
            }
        } else {
            area
        };
        let w = w.min(host.width);
        Rect {
            x: host.x + host.width.saturating_sub(w) / 2,
            y: host.bottom().saturating_sub(h + 1).max(host.y),
            width: w,
            height: h,
        }
    };
    let accent = if toast.ok {
        theme.accent
    } else {
        theme.pending
    };
    f.render_widget(Clear, rect);
    f.render_widget(
        Paragraph::new(Span::styled(text, Style::default().fg(theme.fg)))
            .block(dialog_block(theme).border_style(Style::default().fg(accent))),
        rect,
    );
}

fn render_screen(app: &App, f: &mut Frame, rects: &mut PaneRects) {
    match app.screen {
        Screen::BootstrapSetup | Screen::BootstrapPick => {
            render_manage(app, f, rects);
            bootstrap::render(app, f, rects);
        }
        Screen::Setup => {
            render_manage(app, f, rects);
            render_wizard(app, f);
        }
        Screen::Settings => {
            render_manage(app, f, rects);
            render_settings(app, f);
        }
        Screen::Manage => render_manage(app, f, rects),
        Screen::TargetPick => {
            render_manage(app, f, rects);
            render_target_pick(app, f);
        }
        Screen::HarnessPick => {
            render_manage(app, f, rects);
            render_harness_pick(app, f, rects);
        }
        Screen::ManagePrompt => {
            render_manage(app, f, rects);
            render_manage_prompt(app, f);
        }
    }
}

/// A whole block, borders included — what a click may land on.
fn whole(area: Rect) -> PaneBox {
    PaneBox {
        x: area.x,
        y: area.y,
        w: area.width,
        h: area.height,
    }
}

/// The interior of a bordered block — what a selection may cover.
fn interior(area: Rect) -> PaneBox {
    PaneBox {
        x: area.x + 1,
        y: area.y + 1,
        w: area.width.saturating_sub(2),
        h: area.height.saturating_sub(2),
    }
}

fn centered(width: u16, height: u16, area: Rect) -> Rect {
    let w = width.min(area.width);
    let h = height.min(area.height);
    Rect {
        x: area.x + (area.width.saturating_sub(w)) / 2,
        y: area.y + (area.height.saturating_sub(h)) / 2,
        width: w,
        height: h,
    }
}

/// Keep one column of padding where the sidebar meets the terminal, without
/// drawing a second vertical rule. Full-screen and narrow layouts stay framed.
fn terminal_block(app: &App, frame_width: u16) -> Block<'static> {
    let split = !app.pane_is_full() && frame_width.saturating_sub(PAGE_MARGIN_X * 2) >= 70;
    Block::default()
        .borders(if split {
            Borders::TOP | Borders::BOTTOM | Borders::RIGHT
        } else {
            Borders::ALL
        })
        .padding(if split {
            Padding::left(1)
        } else {
            Padding::ZERO
        })
        .border_type(BorderType::Rounded)
}

/// The launcher, in the session pane: the wordmark and the prompt box that
/// used to be their own screen, now living beside the tree. Drawn whenever
/// the cursor stands on the pinned New Session row.
fn render_welcome(app: &App, f: &mut Frame, pane: Rect, rects: &mut PaneRects) {
    let theme = app.theme;
    let focused = app.new_session_selected();
    let block = terminal_block(app, f.area().width)
        .border_style(Style::default().fg(if focused {
            theme.accent
        } else {
            theme.accent_dim
        }))
        .title(Span::styled(" new agent ", Style::default().fg(theme.dim)));
    let area = {
        let inner = block.inner(pane);
        f.render_widget(block, pane);
        inner
    };

    let big = area.width >= BANNER_W + 2 && area.height >= 20;
    let banner_h = if big { BANNER_H } else { 1 };
    let (panel_w, prompt_h) = prompt_box_size(area);
    // The room below the prompt, outside its outline. Above it the spacing
    // is fixed: exactly two rows — the status line and one gap — separate
    // the title from the prompt box, whatever the pane's height.
    let prompt_gap = if area.height >= 26 { 2 } else { 1 };
    // banner, gap, CLOUD AGENTS, title, status, gap, prompt, gap, target.
    let bootstrap_h = if app.target.is_some() { 2 } else { 0 };
    let panel_h = banner_h + 4 + 1 + prompt_h + prompt_gap + 1 + bootstrap_h;
    let panel = centered(panel_w, panel_h.min(area.height), area);

    let rows = Layout::vertical([
        Constraint::Length(banner_h),
        Constraint::Length(1), // breathing room under the wordmark
        Constraint::Length(1), // CLOUD AGENTS
        Constraint::Length(1), // title
        Constraint::Length(1), // status
        Constraint::Length(1), // one gap: the title sits two rows up
        Constraint::Length(prompt_h),
        Constraint::Length(prompt_gap), // the prompt's room below its outline
        Constraint::Length(1),          // target
        Constraint::Length(bootstrap_h), // bootstrap for the selected project
    ])
    .split(panel);

    let wordmark = if big {
        Paragraph::new(banner_lines(theme))
    } else {
        Paragraph::new("RAILWAY CLOUD-AGENTS").style(
            Style::default()
                .fg(theme.accent)
                .add_modifier(Modifier::BOLD),
        )
    };
    f.render_widget(wordmark.alignment(Alignment::Center), rows[0]);
    if big {
        f.render_widget(
            // Fullwidth forms, so the line reads a size up from the body text
            // without a second block font to maintain.
            Paragraph::new("CLOUD AGENTS")
                .alignment(Alignment::Center)
                .style(Style::default().fg(theme.accent)),
            rows[2],
        );
    }
    f.render_widget(
        Paragraph::new("What should we build today?")
            .alignment(Alignment::Center)
            .style(Style::default().fg(theme.fg).add_modifier(Modifier::BOLD)),
        rows[3],
    );
    // Only a status goes here. The line that used to explain what the prompt
    // was for said nothing the prompt box does not already say.
    if !app.status.is_empty() {
        f.render_widget(
            Paragraph::new(app.status.clone())
                .alignment(Alignment::Center)
                .style(Style::default().fg(theme.accent)),
            rows[4],
        );
    }

    render_prompt(app, f, rows[6], focused);
    rects.prompt = whole(rows[6]);

    // Where the prompt lands, on its own line under the box. It was a chip in
    // the prompt box, which put the least-changed setting in the busiest place
    // on the screen.
    f.render_widget(
        Paragraph::new(target_line(app)).alignment(Alignment::Center),
        rows[8],
    );
    if let Some(target) = &app.target {
        use super::bootstrap_setup::DefaultState;
        let text = match app.bootstrap_defaults.get(&target.environment_id) {
            Some(DefaultState::Ready(name)) => format!("Select Bootstrap  {name} (default)"),
            Some(DefaultState::Available) => "Select Bootstrap".into(),
            Some(DefaultState::Failed(error)) => format!(
                "Bootstrap unavailable: {} — configure a new one",
                error.lines().next().unwrap_or("retry")
            ),
            Some(DefaultState::Missing) => "No bootstrap configured — set one up".into(),
            _ => "Checking bootstrap…".into(),
        };
        f.render_widget(
            Paragraph::new(Line::from(vec![
                chord_badge(theme, "⌥b"),
                Span::raw(" "),
                Span::styled(text, Style::default().fg(theme.accent)),
            ]))
            .alignment(Alignment::Center),
            Rect::new(
                rows[9].x,
                rows[9].y + 1,
                rows[9].width,
                rows[9].height.saturating_sub(1),
            ),
        );
        rects.bootstrap = whole(Rect::new(
            rows[9].x,
            rows[9].y + 1,
            rows[9].width,
            rows[9].height.saturating_sub(1),
        ));
    }
}

/// `⌥t  Target Project  name (environment)`, or an invitation to set one.
/// The shortcut sits right on the field it changes rather than in the
/// footer's own chord list, which otherwise says nothing about what "target"
/// even refers to.
fn target_line(app: &App) -> Line<'static> {
    let theme = app.theme;
    let mut spans = vec![
        chord_badge(theme, "⌥t"),
        Span::raw(" "),
        Span::styled(
            "Target Project  ",
            Style::default().fg(theme.dim).add_modifier(Modifier::BOLD),
        ),
    ];
    spans.push(match app.target.as_ref() {
        Some(target) => Span::styled(
            format!("{} ({})", target.project_name, target.environment_name),
            Style::default().fg(theme.accent),
        ),
        None => Span::styled("not set", Style::default().fg(theme.pending)),
    });
    Line::from(spans)
}

/// The wait, with the task in front of you.
///
/// The step list is a fixed height and the panel is centred once: a list that
/// grew with each step would shove everything above it up the screen, which
/// reads as flicker rather than progress. Steps wrap instead of being clipped —
/// several of them are full sentences, and a truncated one is worse than no
/// line at all.
fn render_loading(app: &App, f: &mut Frame, area: Rect) {
    let theme = app.theme;
    let loading = &app.loading;

    // The pane it is about to become: same border, same title bar, so the
    // session appearing in it reads as the same thing finishing rather than a
    // different screen replacing it.
    let block = terminal_block(app, f.area().width)
        .border_style(Style::default().fg(theme.accent))
        .title(Span::styled(
            format!(" {} · starting ", loading.harness),
            Style::default()
                .fg(theme.accent)
                .add_modifier(Modifier::BOLD),
        ));
    let area = {
        let inner = block.inner(area);
        f.render_widget(block, area);
        inner
    };

    // A stable width keeps verbose preparation details from moving the panel.
    // Only the current stage is shown; prior stages are not a scrolling log.
    let width = 56.min(area.width.saturating_sub(2));
    let prompt_h = if loading.prompt.is_some() { 4 } else { 0 };
    let gap = u16::from(prompt_h > 0);
    let panel = centered(width, 10 + prompt_h + gap, area);
    let rows = Layout::vertical([
        Constraint::Length(prompt_h),
        Constraint::Length(gap),
        Constraint::Min(3),
    ])
    .split(panel);
    if let Some(prompt) = &loading.prompt {
        f.render_widget(
            Paragraph::new(prompt.clone())
                .block(
                    dialog_block(theme)
                        .title(" Prompt ")
                        .border_style(Style::default().fg(theme.accent_dim)),
                )
                .style(Style::default().fg(theme.fg))
                .wrap(Wrap { trim: true }),
            rows[0],
        );
    }
    let block = dialog_block(theme)
        .title(" Preparing agent ")
        .padding(ratatui::widgets::Padding::new(2, 2, 1, 1));
    let inner = block.inner(rows[2]);
    f.render_widget(block, rows[2]);
    let lines = vec![
        Line::styled(loading.target.clone(), Style::default().fg(theme.dim)),
        Line::raw(""),
        Line::styled(
            spinner_frame(loading.tick).to_string(),
            Style::default().fg(theme.accent),
        ),
        Line::raw(""),
        Line::styled(
            loading
                .steps
                .last()
                .cloned()
                .unwrap_or_else(|| "Preparing the agent".into()),
            Style::default().fg(theme.accent),
        ),
    ];
    f.render_widget(
        Paragraph::new(lines)
            .alignment(Alignment::Center)
            .wrap(Wrap { trim: true }),
        inner,
    );
}

/// Braille spinner, one frame per tick.
fn spinner_frame(tick: usize) -> char {
    const FRAMES: [char; 10] = ['', '', '', '', '', '', '', '', '', ''];
    FRAMES[tick % FRAMES.len()]
}

fn render_prompt(app: &App, f: &mut Frame, area: Rect, focused: bool) {
    let theme = app.theme;
    let empty = app.prompt.is_empty();
    // The shell option takes no prompt, so the box explains itself instead of
    // taking dictation. Any draft stays in `app.prompt`, hidden until the
    // cycle moves back to a real agent.
    let (text, fg) = if app.shell_selected() {
        (
            "A plain shell on the agent — no prompt, enter to launch".to_string(),
            theme.dim,
        )
    } else if empty && !focused {
        (
            "Fix a bug, scaffold a service, explain a repo…".to_string(),
            theme.dim,
        )
    } else if focused {
        // The bar sits where the next character lands — ←/→ move it, so it is
        // not always at the end.
        let at = app
            .prompt
            .char_indices()
            .nth(app.prompt_cursor)
            .map(|(i, _)| i)
            .unwrap_or(app.prompt.len());
        (
            format!("{}{}", &app.prompt[..at], &app.prompt[at..]),
            theme.fg,
        )
    } else {
        (app.prompt.clone(), theme.fg)
    };

    // Only the harness. Where it lands is on its own line under the cards —
    // it changes rarely, and it was crowding the one control being used.
    let count = if empty || app.shell_selected() {
        String::new()
    } else {
        format!(" {} ", app.prompt.chars().count())
    };

    f.render_widget(Clear, area);

    let block = dialog_block(theme)
        .border_style(Style::default().fg(if focused {
            theme.accent
        } else {
            theme.accent_dim
        }))
        .title(Span::styled(
            " Prompt ",
            Style::default()
                .fg(if focused { theme.accent } else { theme.dim })
                .add_modifier(Modifier::BOLD),
        ))
        .title_bottom(Line::from(vec![
            Span::styled(
                format!(" {} ", super::app::harness_label(app.harness_name())),
                Style::default()
                    .fg(if focused { theme.accent } else { theme.fg })
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                if super::app::opencode_alternate(app.harness).is_some() {
                    "shift+tab · tab version "
                } else {
                    "shift+tab "
                },
                Style::default().fg(theme.dim),
            ),
        ]))
        .title_bottom(
            Line::from(Span::styled(count, Style::default().fg(theme.dim))).right_aligned(),
        );

    // Keep the CARET's line in view once the wrapped text outgrows the box —
    // not just the tail. ←/Home move the caret anywhere in the draft, and a
    // box that keeps showing the end while characters splice invisibly at
    // the front fails at the one thing it exists to do.
    let inner_w = area.width.saturating_sub(DIALOG_CHROME_X).max(1) as usize;
    let inner_h = area.height.saturating_sub(DIALOG_CHROME_Y).max(1) as usize;
    let total = wrapped_lines(&text, inner_w);
    let tail_pin = total.saturating_sub(inner_h);
    let scroll_y = if focused && !empty && !app.shell_selected() {
        // The wrapped row the caret sits on, measured over the text up to
        // and including the caret glyph. (Greedy wrapping means a caret
        // mid-word can measure one row shy of where the full text wraps it
        // — one row of slack, not a lost caret.)
        let caret_end = text
            .char_indices()
            .nth(app.prompt_cursor + 1)
            .map(|(i, _)| i)
            .unwrap_or(text.len());
        let caret_row = wrapped_lines(&text[..caret_end], inner_w);
        caret_row.saturating_sub(inner_h).min(tail_pin)
    } else {
        tail_pin
    } as u16;

    f.render_widget(
        Paragraph::new(text)
            .block(block)
            .style(Style::default().fg(fg))
            .wrap(Wrap { trim: false })
            .scroll((scroll_y, 0)),
        area,
    );
}

/// How many rows `text` occupies once wrapped at `width`, breaking on spaces
/// the way ratatui does, hard-wrapping a word that cannot fit, and starting a
/// fresh row at every `\n` — the character ⇧enter puts in a draft.
fn wrapped_lines(text: &str, width: usize) -> usize {
    if width == 0 {
        return 1;
    }
    let mut rows = 0usize;
    for line in text.split('\n') {
        rows += 1;
        let mut column = 0usize;
        for word in line.split_inclusive(' ') {
            let len = word.chars().count();
            if column + len > width && column > 0 {
                rows += 1;
                column = 0;
            }
            if len > width {
                rows += (len - 1) / width;
                column = len % width;
            } else {
                column += len;
            }
        }
    }
    rows.max(1)
}

/// The size the session pane will have, given the whole terminal — the same
/// arithmetic `render_manage` does, so the emulator and the pane agree.
/// `None` when there is no room for two panes.
pub fn session_pane_size(
    area: Option<ratatui::layout::Size>,
    maximized: bool,
    preferred_sidebar_width: Option<u16>,
) -> Option<(u16, u16)> {
    let area = area?;
    // The same inset the renderer applies — see `page_size` for why the two
    // must never disagree.
    let (width, height) = page_size(area.width, area.height);
    // Maximized there is no tree to leave room for, so no minimum width to
    // meet either.
    if !maximized && width < 70 {
        return None;
    }
    // Rows: header, gap, panes, hint. Columns: the tree, then what is left.
    // Both minus the pane's own border.
    let rows = height.saturating_sub(3).saturating_sub(2).max(1);
    let tree = if maximized {
        0
    } else {
        sidebar_width(width, preferred_sidebar_width)
    };
    let cols = width.saturating_sub(tree).saturating_sub(2).max(1);
    Some((rows, cols))
}

fn render_manage(app: &App, f: &mut Frame, rects: &mut PaneRects) {
    let theme = app.theme;
    let area = page(f);
    let chunks = Layout::vertical([
        Constraint::Length(1), // header
        Constraint::Length(1), // gap
        Constraint::Min(3),    // panes
        Constraint::Length(1), // hint
    ])
    .split(area);

    let rows = app.rows();
    let full = app.pane_is_full();
    let mut header = vec![Span::styled(
        " RAILWAY CLOUD-AGENTS ",
        Style::default()
            .fg(theme.on_accent)
            .bg(theme.accent)
            .add_modifier(Modifier::BOLD),
    )];
    if full && !app.sessions.is_empty() && !app.hide_tabs {
        // Maximized, the tree is folded away, so the open sessions become
        // tabs on the header: click one (or ⌥⇧[ ⌥⇧]) to switch panes. The
        // clickable boxes are recorded as they are laid out. Hidden entirely
        // by the ⌥s "Full-screen tabs" setting — the rects stay zeroed (a
        // fresh PaneRects every draw), so there is nothing stale to click —
        // and the header falls through to the status line instead.
        let mut x = chunks[0].x + " RAILWAY CLOUD-AGENTS ".chars().count() as u16;
        for i in 0..app.sessions.len() {
            // The tab names the session (its task, or its harness-led name),
            // not the agent it runs on — the pane's title already says that.
            let label = format!(" {} {} ", i + 1, app.session_tab_label(i));
            header.push(Span::raw(" "));
            x += 1;
            let w = label.chars().count() as u16;
            if let Some(slot) = rects.tabs.get_mut(i) {
                *slot = PaneBox {
                    x,
                    y: chunks[0].y,
                    w,
                    h: 1,
                };
            }
            let on = app.active == Some(i);
            header.push(Span::styled(
                label,
                if on {
                    Style::default()
                        .fg(theme.on_accent)
                        .bg(theme.accent)
                        .add_modifier(Modifier::BOLD)
                } else {
                    Style::default().fg(theme.dim).bg(theme.surface)
                },
            ));
            x += w;
        }
    } else if !app.status.is_empty() {
        header.push(Span::styled(
            format!("  ·  {}", app.status),
            Style::default().fg(theme.dim),
        ));
    }
    f.render_widget(Paragraph::new(Line::from(header)), chunks[0]);

    // The tree keeps the user's preferred width; narrow windows clamp it so
    // the terminal remains usable without overwriting that preference.
    // ⌥f hands the whole width to the session: the tree is navigation, and
    // once you are working in a session there is nothing to navigate.
    let two_pane = !full && chunks[2].width >= 70;
    let panes = if two_pane {
        Layout::horizontal([
            Constraint::Length(sidebar_width(chunks[2].width, app.sidebar_width)),
            Constraint::Min(32),
        ])
        .split(chunks[2])
    } else {
        Layout::horizontal([Constraint::Min(0)]).split(chunks[2])
    };

    if full {
        let pane = panes[0];
        rects.session = interior(pane);
        rects.session_outer = whole(pane);
        rects.tree = PaneBox::default();
        rects.tree_outer = PaneBox::default();
        // Same order as the two-pane branch: a launch in flight owns the pane
        // until it produces the session that replaces it.
        if app.loading.active {
            render_loading(app, f, pane);
        } else if let Some(session) = app.active_session() {
            render_session(app, session, f, pane);
        }
        render_manage_footer(app, f, chunks[3], rects);
        return;
    }

    // Too narrow for two panes: while the cursor is on New Session the
    // launcher is the screen — the prompt has the keyboard, and ↓ brings the
    // tree back.
    if !two_pane && !app.loading.active && app.launcher_selected() {
        render_welcome(app, f, panes[0], rects);
        render_manage_footer(app, f, chunks[3], rects);
        return;
    }

    let tree_focused = app.focus == ManageFocus::Tree;

    let items: Vec<ListItem> = rows
        .iter()
        .map(|r| ListItem::new(tree_line(theme, r, app, panes[0].width.saturating_sub(2))))
        .collect();
    let mut state = ListState::default();
    state.select(if rows.is_empty() {
        None
    } else {
        Some(app.cursor)
    });
    f.render_stateful_widget(
        List::new(items)
            .style(Style::default().bg(theme.sidebar))
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_type(BorderType::Rounded)
                    .border_style(Style::default().fg(if tree_focused {
                        theme.accent
                    } else {
                        theme.accent_dim
                    }))
                    .title(Span::styled(" threads ", Style::default().fg(theme.dim))),
            )
            .highlight_style(
                Style::default()
                    .add_modifier(Modifier::BOLD)
                    .bg(theme.selection),
            ),
        panes[0],
        &mut state,
    );
    rects.tree = interior(panes[0]);
    rects.tree_outer = whole(panes[0]);

    if two_pane {
        rects.session = interior(panes[1]);
        rects.session_outer = whole(panes[1]);
        rects.sidebar_divider = PaneBox {
            x: panes[0].right() - 1,
            y: panes[0].y + 1,
            w: 2,
            h: panes[0].height.saturating_sub(2),
        };
        // What the right pane shows follows the selection, not merely whether a
        // session happens to be open: standing on an agent should show that
        // agent's cards even while one of its sessions is running in the
        // background, and standing on a session that has no pane must not keep
        // showing whichever pane was connected last — it gets a card saying
        // so instead. Typing in a session is the exception — the pane it has
        // the keyboard in cannot vanish from under it.
        let selected_kind = app.selected_row().map(|row| row.kind);
        if app.loading.active {
            render_loading(app, f, panes[1]);
        } else {
            match app
                .displayed_session_index()
                .and_then(|i| app.sessions.get(i))
            {
                Some(session) => render_session(app, session, f, panes[1]),
                // The New Session row's pane is the launcher: the wordmark
                // and the prompt, where a session is about to be.
                None if matches!(selected_kind, Some(RowKind::NewSession)) => {
                    render_welcome(app, f, panes[1], rects)
                }
                None => {
                    let title = if matches!(
                        selected_kind,
                        Some(RowKind::Session(..)) | Some(RowKind::Agent(..))
                    ) {
                        " thread "
                    } else {
                        " detail "
                    };
                    f.render_widget(
                        Paragraph::new(detail_lines(app)).block(
                            terminal_block(app, f.area().width)
                                .border_style(Style::default().fg(if tree_focused {
                                    theme.accent_dim
                                } else {
                                    theme.accent
                                }))
                                .title(Span::styled(title, Style::default().fg(theme.dim))),
                        ),
                        panes[1],
                    )
                }
            }
        }
    }

    if two_pane {
        f.render_widget(
            Paragraph::new("").style(Style::default().fg(if app.resizing_sidebar() {
                theme.accent
            } else {
                theme.dim
            })),
            Rect::new(panes[0].right() - 1, panes[0].y + panes[0].height / 2, 1, 1),
        );
    }
    render_manage_footer(app, f, chunks[3], rects);
}

/// The bottom line of the Manage screen — a held confirmation, or the keys that
/// apply right now — plus the selection painted over the panes above it.
///
/// Shared with the maximized layout, which has no tree to draw but the same
/// footer and the same drag-to-copy.
fn render_manage_footer(app: &App, f: &mut Frame, area: Rect, rects: &PaneRects) {
    let theme = app.theme;
    if matches!(app.screen, Screen::BootstrapSetup | Screen::BootstrapPick) {
        bootstrap::footer(app, f, area);
        return;
    }
    if app.screen == Screen::HarnessPick {
        let mut hints = vec![
            ("↑↓", "choose agent"),
            (
                "enter",
                if app.harness_pick_connect {
                    "connect"
                } else if app.harness_pick_agent.is_some() {
                    "new session"
                } else {
                    "create VM"
                },
            ),
            ("esc", "back"),
        ];
        if app
            .harness_pick
            .is_some_and(|h| super::app::opencode_alternate(h).is_some())
        {
            hints.push(("tab", "version"));
        }
        f.render_widget(Paragraph::new(Line::from(chord_spans(theme, &hints))), area);
        return;
    }
    // A held action replaces the hint line: it is the only thing that matters
    // until it is answered, and it must not be missable.
    if let Some(confirm) = app.confirm.as_ref() {
        f.render_widget(
            Paragraph::new(Line::from(vec![
                Span::styled(
                    " confirm ",
                    Style::default()
                        .fg(theme.on_accent)
                        .bg(theme.pending)
                        .add_modifier(Modifier::BOLD),
                ),
                Span::styled(
                    format!("  {}", confirm.question()),
                    Style::default().fg(theme.fg),
                ),
            ])),
            area,
        );
        return;
    }

    // The selection is painted last, straight onto the buffer: it has to sit
    // over the pane's own colours, and only inside the pane it started in.
    if let Some(selection) = app.selection.filter(|s| !s.is_empty()) {
        let bounds = match selection.pane {
            ManageFocus::Tree => rects.tree,
            ManageFocus::Session => rects.session,
        };
        let spans = selection.spans(bounds);
        let buffer = f.buffer_mut();
        for (y, x0, x1) in spans {
            for x in x0..=x1 {
                buffer[(x, y)].set_style(
                    Style::default()
                        .bg(theme.selection)
                        .add_modifier(Modifier::BOLD),
                );
            }
        }
    }

    // The actions that apply here, and nothing else. The old strip listed
    // everything the screen could do at all times, which is a lot to read past
    // to find the one you wanted; the rest lives behind `?`.
    let sleeping = app
        .selected_agent_status()
        .is_some_and(|status| status != "running");
    let hint: Vec<(&str, &str)> = if app.pane_is_full() {
        vec![
            ("⌥f", "restore the tree"),
            ("⌥o", "SSH shell"),
            ("⌥esc", "stop typing"),
        ]
    } else if app.focus == ManageFocus::Session {
        // A dead pane's keys are recovery, not typing — the hint has to say
        // so, or "stop typing" advertises an input nothing is reading.
        if app.active_session().is_none() {
            let mut keys = vec![("esc", "back to the tree")];
            if app
                .selected_row()
                .is_some_and(|row| matches!(row.kind, RowKind::Session(..) | RowKind::Agent(..)))
            {
                keys.insert(0, ("enter", "connect"));
            }
            keys
        } else if app
            .active_session()
            .is_some_and(|s| s.ended() || s.stalled())
        {
            vec![
                ("r", "reconnect"),
                ("x", "close pane"),
                ("esc", "back to the tree"),
            ]
        } else {
            let mut keys = vec![
                ("⌥esc", "stop typing"),
                ("⌥f", "maximize"),
                ("⌥o", "SSH shell"),
            ];
            // The agent is taking the clicks, so say how to take one back — this is
            // the terminal's own convention, but nobody guesses it.
            if app.active_session().is_some_and(|s| s.wants_mouse()) {
                keys.push(("shift+drag", "select"));
            }
            keys
        }
    } else {
        match app.selected_row().map(|r| r.kind) {
            // The prompt has the keyboard: say how to launch, not how to
            // manage rows the cursor is not on. The target's own shortcut
            // sits on the target line, beside the field it changes.
            Some(RowKind::NewSession) if app.new_session_selected() => vec![
                ("enter", "launch"),
                ("shift+tab", "agent"),
                ("", "threads"),
                ("esc", "home"),
                ("⌥s", "settings"),
            ],
            // Home: the prompt has let go, so letters are keys again.
            Some(RowKind::NewSession) => vec![
                ("enter", "write a prompt"),
                ("", "threads"),
                ("⌥s", "settings"),
                ("q", "quit"),
            ],
            Some(RowKind::Session(w, p, e, a, i)) => {
                let conversation = app
                    .console_session(w, p, e, a, i)
                    .is_some_and(|s| super::super::client_sessions::is_client(&s.name));
                vec![
                    ("enter", if conversation { "resume" } else { "connect" }),
                    ("⌥o", "SSH shell"),
                    ("⌥f", "maximize"),
                    (
                        "⌥enter",
                        if conversation {
                            "maximize"
                        } else {
                            "full screen"
                        },
                    ),
                    ("c", "copy shell"),
                    (
                        "x",
                        if conversation {
                            "delete thread"
                        } else {
                            "end session"
                        },
                    ),
                    if sleeping {
                        ("w", "wake")
                    } else {
                        ("s", "sleep")
                    },
                    ("d", "delete agent"),
                ]
            }
            Some(RowKind::Agent(..)) => vec![
                ("enter", "connect"),
                ("⌥o", "shell"),
                ("n", "new VM"),
                ("⌥n", "new session"),
                if sleeping {
                    ("w", "wake")
                } else {
                    ("s", "sleep")
                },
                ("⌥b", "save bootstrap"),
                ("d", "delete"),
            ],
            Some(RowKind::Project(..) | RowKind::Environment(..)) => vec![
                ("enter", "open"),
                ("n", "new VM"),
                (
                    "⌥b",
                    if app.bootstrap_target().is_some_and(|t| {
                        matches!(
                            app.bootstrap_defaults.get(&t.environment_id),
                            Some(
                                super::bootstrap_setup::DefaultState::Ready(_)
                                    | super::bootstrap_setup::DefaultState::Available
                            )
                        )
                    }) {
                        "Select Bootstrap"
                    } else {
                        "Create Bootstrap"
                    },
                ),
                ("⌥r", "refresh"),
            ],
            _ => vec![
                ("enter", "open"),
                ("n", "new VM"),
                ("⌥r", "refresh"),
                ("shift+r", "find agents"),
            ],
        }
    };
    // Only worth advertising once there is somewhere to cycle to; on a single
    // pane the chord is a no-op and the hint would just be a lie.
    let mut hint = hint;
    if app.sessions.len() > 1 {
        hint.push(("⌥⇧[ ⌥⇧]", "switch session"));
    }
    let spans = chord_spans(theme, &hint);
    f.render_widget(Paragraph::new(Line::from(spans)), area);
    // Help sits on the far right, out of the way of the actions and always in
    // the same place — drawn second so it wins if the row ever fills up.
    f.render_widget(
        Paragraph::new(Line::from(vec![
            chord_badge(theme, "?"),
            Span::styled(" keys ", Style::default().fg(theme.dim)),
        ]))
        .alignment(Alignment::Right),
        area,
    );

    if app.keys_open {
        render_keys(app, f);
    }
}

/// One row of a card panel: a name, an optional dim tag beside it, and an
/// optional line of explanation under it.
struct PanelRow {
    label: String,
    tag: String,
    detail: String,
}

/// The centred card list both the setup flow and the target chooser are made
/// of. One shape, so choosing a target looks like answering the same question
/// setup asks — because it is.
struct Panel<'a> {
    title: &'a str,
    heading: &'a str,
    /// Progress dots: (index, total). `None` draws no dots.
    position: Option<(usize, usize)>,
    rows: &'a [PanelRow],
    cursor: usize,
    footer: Line<'static>,
}

fn render_panel(f: &mut Frame, theme: &Theme, area: Rect, panel: Panel) {
    let body_h = panel
        .rows
        .iter()
        .map(|row| if row.detail.is_empty() { 1 } else { 2 })
        .sum::<usize>() as u16;
    // No progress dots means no row held open for them.
    let dots_h = u16::from(panel.position.is_some());
    let width = (62 + DIALOG_CHROME_X).min(area.width.saturating_sub(4));
    let height = (body_h + dots_h + 5 + DIALOG_CHROME_Y).min(area.height.saturating_sub(2));
    let outer = centered(width, height, area);
    f.render_widget(Clear, outer);

    let block = dialog_block(theme).title(Span::styled(
        format!(" {} ", panel.title),
        Style::default()
            .fg(theme.accent)
            .add_modifier(Modifier::BOLD),
    ));
    let inner = block.inner(outer);
    f.render_widget(block, outer);

    let rows = Layout::vertical([
        Constraint::Length(1), // heading
        Constraint::Length(dots_h),
        Constraint::Length(1), // gap
        Constraint::Length(body_h),
        Constraint::Min(0),
        Constraint::Length(1), // footer
    ])
    .split(inner);

    f.render_widget(
        Paragraph::new(panel.heading.to_string())
            .alignment(Alignment::Center)
            .style(Style::default().fg(theme.fg).add_modifier(Modifier::BOLD)),
        rows[0],
    );

    // Dots rather than "step 2 of 4": the shape of the flow at a glance.
    if let Some((index, total)) = panel.position {
        let dots: Vec<Span> = (0..total)
            .map(|i| {
                Span::styled(
                    if i == index { "" } else { "" },
                    Style::default().fg(if i == index {
                        theme.accent
                    } else {
                        theme.accent_dim
                    }),
                )
            })
            .collect();
        f.render_widget(
            Paragraph::new(Line::from(dots)).alignment(Alignment::Center),
            rows[1],
        );
    }

    // The card clamps to the terminal, so a long list (a real account's
    // projects) can hold more rows than the body has lines. Window the rows
    // to keep the cursor visible: walk the start of the window forward until
    // everything from there through the cursor fits.
    let avail = rows[3].height as usize;
    let row_height = |row: &PanelRow| if row.detail.is_empty() { 1 } else { 2 };
    let mut first = 0usize;
    while first < panel.cursor
        && panel.rows[first..=panel.cursor.min(panel.rows.len() - 1)]
            .iter()
            .map(row_height)
            .sum::<usize>()
            > avail
    {
        first += 1;
    }

    let mut lines: Vec<Line> = Vec::with_capacity(panel.rows.len() * 2);
    for (i, row) in panel.rows.iter().enumerate().skip(first) {
        let on = i == panel.cursor;
        let mut spans = vec![
            Span::styled(
                if on { "" } else { "  " },
                Style::default().fg(theme.accent),
            ),
            Span::styled(
                row.label.clone(),
                if on {
                    Style::default()
                        .fg(theme.accent)
                        .add_modifier(Modifier::BOLD)
                } else {
                    Style::default().fg(theme.fg)
                },
            ),
        ];
        if !row.tag.is_empty() {
            spans.push(Span::styled(
                format!("  {}", row.tag),
                // The tag steps forward with its row: on the settings card it
                // is the current value, which is the thing being changed.
                Style::default().fg(if on { theme.fg } else { theme.dim }),
            ));
        }
        lines.push(Line::from(spans));
        // Only when there is something to say. An empty description line turns
        // a list of names into a list with gaps in it.
        if !row.detail.is_empty() {
            lines.push(Line::from(Span::styled(
                format!("  {}", row.detail),
                Style::default().fg(theme.dim),
            )));
        }
    }
    f.render_widget(Paragraph::new(lines), rows[3]);
    f.render_widget(
        Paragraph::new(panel.footer).alignment(Alignment::Center),
        rows[5],
    );
}

fn render_wizard(app: &App, f: &mut Frame) {
    let Some(wizard) = app.wizard.as_ref() else {
        return;
    };
    let theme = app.theme;
    let rows: Vec<PanelRow> = wizard
        .options()
        .into_iter()
        .map(|(label, detail)| PanelRow {
            label,
            tag: String::new(),
            detail,
        })
        .collect();

    let footer = if let Some(busy) = wizard.busy.as_deref() {
        Line::from(vec![
            Span::styled(
                format!("{} ", spinner_frame(app.loading.tick)),
                Style::default().fg(theme.accent),
            ),
            Span::styled(busy.to_string(), Style::default().fg(theme.fg)),
        ])
    } else if let Some(error) = wizard.error.as_deref() {
        Line::from(Span::styled(
            format!("  {error}"),
            Style::default().fg(theme.pending),
        ))
    } else {
        Line::from(chord_spans(
            theme,
            &[("↑↓", "choose"), ("enter", "next"), ("esc", "back")],
        ))
    };

    render_panel(
        f,
        theme,
        page(f),
        Panel {
            title: "setup",
            heading: wizard.title(),
            position: wizard.position(),
            rows: &rows,
            cursor: wizard.cursor,
            footer,
        },
    );
}

/// The ⌥s settings card: every preference with its current value beside it,
/// or the project sub-picker while it is open.
fn render_settings(app: &App, f: &mut Frame) {
    let Some(settings) = app.settings.as_ref() else {
        return;
    };
    let theme = app.theme;

    // The sub-picker replaces the card wholesale, like a wizard step.
    if let Some(pick) = settings.pick {
        let rows: Vec<PanelRow> = settings
            .picker_options()
            .into_iter()
            .map(|(label, tag, _)| PanelRow {
                label,
                tag,
                detail: String::new(),
            })
            .collect();
        let footer = if let Some(busy) = settings.busy.as_deref() {
            Line::from(vec![
                Span::styled(
                    format!("{} ", spinner_frame(app.loading.tick)),
                    Style::default().fg(theme.accent),
                ),
                Span::styled(busy.to_string(), Style::default().fg(theme.fg)),
            ])
        } else if let Some(error) = settings.error.as_deref() {
            Line::from(Span::styled(
                format!("  {error}"),
                Style::default().fg(theme.pending),
            ))
        } else {
            Line::from(chord_spans(
                theme,
                &[("↑↓", "choose"), ("enter", "set default"), ("esc", "back")],
            ))
        };
        render_panel(
            f,
            theme,
            page(f),
            Panel {
                title: "settings",
                heading: "Where should agents live?",
                position: None,
                rows: &rows,
                cursor: pick,
                footer,
            },
        );
        return;
    }

    let cycles = settings.cycles();
    let rows: Vec<PanelRow> = settings
        .options()
        .into_iter()
        .enumerate()
        .map(|(i, (label, value, _))| PanelRow {
            // Padded so the values read as a column.
            label: format!("{label:<19}"),
            // The highlighted value grows arrows when ←/→ changes it in
            // place — the hint that this row edits right here.
            tag: if i == settings.cursor && cycles {
                format!("{value}")
            } else {
                value
            },
            detail: String::new(),
        })
        .collect();
    let footer = Line::from(chord_spans(
        theme,
        &[
            ("↑↓", "choose"),
            ("←→", "change"),
            ("enter", "edit"),
            ("esc", "close"),
        ],
    ));
    render_panel(
        f,
        theme,
        page(f),
        Panel {
            title: "settings",
            heading: "Cloud agent settings",
            position: None,
            rows: &rows,
            cursor: settings.cursor,
            footer,
        },
    );
}

/// Choose a harness for a new VM or a session on an existing VM.
fn render_harness_pick(app: &App, f: &mut Frame, rects: &mut PaneRects) {
    use super::bootstrap_setup::{DefaultState, LaunchChoice};
    let Some(cursor) = app.harness_pick else {
        return;
    };
    let theme = app.theme;
    let indices = super::app::harness_picker_indices(cursor);
    let existing = app.harness_pick_agent.is_some();
    let target = app.harness_pick_target.as_ref().or(app.target.as_ref());
    let host = if rects.session.w > 0 {
        let r = rects.session;
        Rect::new(r.x, r.y, r.w, r.h)
    } else {
        page(f)
    };
    f.render_widget(Clear, host);
    let area = centered(
        64,
        indices.len() as u16 + if existing { 7 } else { 11 },
        host,
    );
    f.render_widget(Clear, area);
    let block = dialog_block(theme)
        .title(if existing {
            if app.harness_pick_connect {
                " Connect cloud agent "
            } else {
                " New session "
            }
        } else {
            " New Cloud Agent "
        })
        .padding(ratatui::widgets::Padding::horizontal(2));
    let inner = block.inner(area);
    f.render_widget(block, area);
    let rows = Layout::vertical([
        Constraint::Length(1),
        Constraint::Length(1),
        Constraint::Length(1),
        Constraint::Length(indices.len() as u16),
        Constraint::Length(1),
        Constraint::Length(if existing { 0 } else { 1 }),
        Constraint::Length(if existing { 0 } else { 2 }),
        Constraint::Min(0),
        Constraint::Length(1),
    ])
    .split(inner);
    f.render_widget(
        Paragraph::new(if app.harness_pick_connect {
            "Choose the agent to open on this VM"
        } else if existing {
            "Choose an agent for this VM"
        } else {
            "Choose an agent for the new VM"
        })
        .alignment(Alignment::Center)
        .style(Style::default().fg(theme.fg)),
        rows[0],
    );
    f.render_widget(
        Paragraph::new(target.map(|t| t.label()).unwrap_or_default())
            .alignment(Alignment::Center)
            .style(Style::default().fg(theme.dim)),
        rows[1],
    );
    let items: Vec<_> = indices
        .iter()
        .map(|i| {
            let label = match super::app::HARNESSES[*i] {
                "railway" => "Railway",
                "grok" => "Grok Build",
                "codex" => "ChatGPT Codex",
                "claude" => "Claude Code",
                "opencode" => "OpenCode",
                "opencode2" => "OpenCode2 [Beta]",
                "shell" => "Shell",
                other => other,
            };
            ListItem::new(label)
        })
        .collect();
    let mut state = ListState::default();
    state.select(indices.iter().position(|i| *i == cursor));
    f.render_stateful_widget(
        List::new(items).highlight_symbol("").highlight_style(
            Style::default()
                .fg(theme.accent)
                .bg(theme.selection)
                .add_modifier(Modifier::BOLD),
        ),
        rows[3],
        &mut state,
    );
    rects.harness_list = whole(rows[3]);
    if !existing {
        // List text starts after its two-column selection marker.
        let controls =
            |row: Rect| Rect::new(row.x + 2, row.y, row.width.saturating_sub(2), row.height);
        let checkbox = controls(rows[5]);
        let selector = controls(rows[6]);
        let default_name = target.and_then(|t| app.bootstrap_defaults.get(&t.environment_id));
        let selected = match &app.harness_bootstrap {
            LaunchChoice::Named(name) => name.clone(),
            LaunchChoice::None => "none".into(),
            LaunchChoice::Default => match default_name {
                Some(DefaultState::Ready(name)) => format!("{name} (project default)"),
                Some(DefaultState::Loading) | None => "checking project default…".into(),
                _ => "project default: none".into(),
            },
        };
        f.render_widget(
            Paragraph::new(Line::from(vec![
                chord_badge(theme, "space"),
                Span::raw(if app.harness_use_bootstrap {
                    " [✓] Use bootstrap"
                } else {
                    " [ ] Use bootstrap · clean VM"
                }),
            ])),
            checkbox,
        );
        f.render_widget(
            Paragraph::new(vec![
                Line::from(vec![
                    chord_badge(theme, "⌥b"),
                    Span::raw(" Select Bootstrap"),
                ]),
                Line::from(selected).style(Style::default().fg(theme.dim)),
            ]),
            selector,
        );
        rects.harness_use_bootstrap = whole(checkbox);
        rects.harness_bootstrap = whole(selector);
    }
}

/// ⌥p's composer: the launcher's prompt box, floated over the tree so a new
/// request doesn't cost the walk back to the New Session row.
fn render_manage_prompt(app: &App, f: &mut Frame) {
    let Some(draft) = app.manage_prompt.as_ref() else {
        return;
    };
    let theme = app.theme;
    let area = page(f);
    // The same box as the main screen's prompt, so composing a session here
    // feels like the same act there.
    let (w, h) = prompt_box_size(area);
    let outer = centered(w, h, area);
    f.render_widget(Clear, outer);

    let block = dialog_block(theme)
        .title(Span::styled(
            " New Session ",
            Style::default()
                .fg(theme.accent)
                .add_modifier(Modifier::BOLD),
        ))
        .title_bottom(Line::from(vec![
            Span::styled(
                format!(" {} ", super::app::harness_label(app.harness_name())),
                Style::default()
                    .fg(theme.accent)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                if super::app::opencode_alternate(app.harness).is_some() {
                    "shift+tab · tab version "
                } else {
                    "shift+tab "
                },
                Style::default().fg(theme.dim),
            ),
        ]))
        .title_bottom(
            Line::from(Span::styled(
                if app.shell_selected() {
                    " enter launch · esc close "
                } else {
                    " enter send · ⇧enter newline · esc close "
                },
                Style::default().fg(theme.dim),
            ))
            .right_aligned(),
        );

    // The launcher box's shell contract, here too: the box explains itself
    // instead of taking dictation, and the draft waits out of sight.
    let (text, fg) = if app.shell_selected() {
        (
            "A plain shell on the agent — no prompt, enter to launch".to_string(),
            theme.dim,
        )
    } else {
        (format!("{draft}"), theme.fg)
    };
    // Keep the cursor line in view once the wrapped text outgrows the box,
    // same as the launcher's prompt. The padding is chrome, not writing room, so
    // it comes off the width and the height the text gets.
    let inner_w = outer.width.saturating_sub(DIALOG_CHROME_X).max(1) as usize;
    let inner_h = outer.height.saturating_sub(DIALOG_CHROME_Y).max(1) as usize;
    let scroll_y = wrapped_lines(&text, inner_w).saturating_sub(inner_h) as u16;

    f.render_widget(
        Paragraph::new(text)
            .block(block)
            .style(Style::default().fg(fg))
            .wrap(ratatui::widgets::Wrap { trim: false })
            .scroll((scroll_y, 0)),
        outer,
    );
}

/// Choosing where the prompt lands. The setup flow's project card, minus the
/// rest of the flow.
fn render_target_pick(app: &App, f: &mut Frame) {
    let Some(picker) = app.target_pick.as_ref() else {
        return;
    };
    let theme = app.theme;
    let rows: Vec<PanelRow> = picker
        .rows(app.default_project.as_deref())
        .into_iter()
        .map(|(label, tag)| PanelRow {
            label,
            tag,
            detail: String::new(),
        })
        .collect();
    let footer = if rows.is_empty() {
        Line::from(Span::styled(
            "No projects to pick from",
            Style::default().fg(theme.dim),
        ))
    } else {
        Line::from(chord_spans(
            theme,
            &[("↑↓", "choose"), ("enter", "set target"), ("esc", "cancel")],
        ))
    };

    render_panel(
        f,
        theme,
        page(f),
        Panel {
            title: "target",
            heading: "Where should Cloud Agents run?",
            position: None,
            rows: &rows,
            cursor: picker.cursor,
            footer,
        },
    );
}

/// The full key list, over the middle of the screen. A look-up rather than a
/// mode: the next keypress dismisses it.
fn render_keys(app: &App, f: &mut Frame) {
    let theme = app.theme;
    let area = page(f);

    let chord_w = KEY_HELP
        .iter()
        .flat_map(|(_, keys)| keys.iter().map(|(chord, _)| chord.chars().count()))
        .max()
        .unwrap_or(8);
    let mut lines: Vec<Line> = Vec::new();
    for (group, keys) in KEY_HELP {
        if !lines.is_empty() {
            lines.push(Line::from(""));
        }
        lines.push(Line::from(Span::styled(
            (*group).to_string(),
            Style::default()
                .fg(theme.accent)
                .add_modifier(Modifier::BOLD),
        )));
        for (chord, what) in *keys {
            lines.push(Line::from(vec![
                Span::styled(
                    format!("{chord:>chord_w$}  "),
                    Style::default().fg(theme.fg).add_modifier(Modifier::BOLD),
                ),
                Span::styled((*what).to_string(), Style::default().fg(theme.dim)),
            ]));
        }
    }

    let rows = lines.len() as u16;
    // As wide as the widest line it has to carry, so nothing gets truncated.
    let content_w = lines
        .iter()
        .map(|line| line.width() as u16)
        .max()
        .unwrap_or(48);
    let width = (content_w + DIALOG_CHROME_X).min(area.width.saturating_sub(4));
    let height = (rows + DIALOG_CHROME_Y).min(area.height.saturating_sub(2));
    let panel = centered(width, height, area);
    f.render_widget(Clear, panel);
    f.render_widget(
        Paragraph::new(lines).block(
            dialog_block(theme)
                .title(Span::styled(
                    " keys ",
                    Style::default()
                        .fg(theme.accent)
                        .add_modifier(Modifier::BOLD),
                ))
                .title_bottom(Line::from(Span::styled(
                    " any key closes ",
                    Style::default().fg(theme.dim),
                ))),
        ),
        panel,
    );
}

/// Draw the session's emulated screen.
///
/// Cell by cell, coalescing runs that share a style — a `Span` per cell would
/// be correct and unbearably slow at eighty columns times forty rows, several
/// times a second.
fn render_session(app: &App, session: &super::session::Session, f: &mut Frame, area: Rect) {
    let theme = app.theme;
    let focused = app.focus == ManageFocus::Session;
    // The title reads like a project reference: project / agent / session.
    let title = format!(" {} ", app.pane_breadcrumb(session));
    let block = terminal_block(app, f.area().width)
        .border_style(Style::default().fg(if focused {
            theme.accent
        } else {
            theme.accent_dim
        }))
        .title(Span::styled(
            title,
            Style::default()
                .fg(if focused { theme.accent } else { theme.dim })
                .add_modifier(Modifier::BOLD),
        ))
        // Only what the footer cannot say: the state of this pane's own
        // scrollback. The way out of a focused session is a key, and the key
        // strip at the bottom of the screen already has it.
        .title_bottom(Line::from(Span::styled(
            if session.ended() {
                // The keys differ by focus: r/x are the pane's own, enter is
                // the tree's. Advertising the wrong set would send keystrokes
                // into the tree — or worse, `x` into a session row, which
                // kills the session on the agent.
                if focused {
                    " connection closed · r reconnects · x closes "
                } else {
                    " connection closed · enter on its row reconnects "
                }
            } else if session.stalled() {
                " no response "
            } else if session.scrolled_back() {
                " scrolled back · type to return "
            } else if !session.scrollable() {
                " no scrollback here "
            } else if focused {
                ""
            } else {
                " click or enter to type "
            },
            Style::default().fg(theme.dim),
        )));

    let inner = block.inner(area);
    f.render_widget(block, area);

    // An attach gone silent has nothing to draw, so say what the silence
    // means instead of showing an empty screen. The platform can list a
    // session as running after its agent slept killed the process; attaching
    // to that name streams nothing, ever.
    if session.stalled() {
        let dim = Style::default().fg(theme.dim);
        f.render_widget(
            Paragraph::new(vec![
                Line::from(""),
                Line::from(Span::styled("Nothing has arrived from this session.", dim)),
                Line::from(Span::styled(
                    "It may have ended when the agent last slept —",
                    dim,
                )),
                Line::from(Span::styled("r dials it again, x closes this pane.", dim)),
            ])
            .alignment(ratatui::layout::Alignment::Center),
            inner,
        );
        return;
    }

    let Some(lines) = session.with_screen(|screen| screen_lines(screen, focused)) else {
        return;
    };
    f.render_widget(Paragraph::new(lines), inner);

    // The connection is gone: say so ON the pane, not down in whatever
    // half-line ssh's goodbye landed on — its "client_loop: send disconnect"
    // gets folded into the screen at the cursor, which is usually the
    // harness's own text box, and reads like the harness broke. The screen
    // stays (it is the only account of what happened); the banner sits on
    // top of its first row as the headline, naming the one key that matters
    // for where the keyboard actually is.
    if session.ended() && inner.height > 0 {
        let banner = Rect {
            x: inner.x,
            y: inner.y,
            width: inner.width,
            height: 1,
        };
        f.render_widget(Clear, banner);
        f.render_widget(
            Paragraph::new(if focused {
                " ✕ disconnected — press r to reconnect · x closes "
            } else {
                " ✕ disconnected — click here (or enter on its row) to reconnect "
            })
            .alignment(ratatui::layout::Alignment::Center)
            .style(
                Style::default()
                    .bg(theme.pending)
                    .fg(theme.on_accent)
                    .add_modifier(Modifier::BOLD),
            ),
            banner,
        );
    }
}

/// Convert one emulated screen into styled lines.
fn screen_lines(screen: &vt100::Screen, focused: bool) -> Vec<Line<'static>> {
    let (rows, cols) = screen.size();
    let (cursor_row, cursor_col) = screen.cursor_position();
    let mut out = Vec::with_capacity(rows as usize);

    for row in 0..rows {
        let mut spans: Vec<Span<'static>> = Vec::new();
        let mut run = String::new();
        let mut run_style: Option<Style> = None;

        for col in 0..cols {
            // A wide character's second cell: the glyph already spans both
            // columns when drawn, so a space here would shift the rest of
            // the line right by one column per wide character.
            if screen
                .cell(row, col)
                .is_some_and(vt100::Cell::is_wide_continuation)
            {
                continue;
            }
            let (text, mut style) = match screen.cell(row, col) {
                Some(cell) => (
                    {
                        let c = cell.contents();
                        if c.is_empty() {
                            " ".to_string()
                        } else {
                            c.to_string()
                        }
                    },
                    cell_style(cell),
                ),
                None => (" ".to_string(), Style::default()),
            };
            // The cursor is drawn as a reversed cell, and only while the pane
            // has focus — two visible cursors would be a lie about where typing
            // goes.
            if focused && !screen.hide_cursor() && row == cursor_row && col == cursor_col {
                style = style.add_modifier(Modifier::REVERSED);
            }
            match run_style {
                Some(current) if current == style => run.push_str(&text),
                Some(current) => {
                    spans.push(Span::styled(std::mem::take(&mut run), current));
                    run.push_str(&text);
                    run_style = Some(style);
                }
                None => {
                    run.push_str(&text);
                    run_style = Some(style);
                }
            }
        }
        if let Some(style) = run_style {
            spans.push(Span::styled(run, style));
        }
        out.push(Line::from(spans));
    }
    out
}

fn cell_style(cell: &vt100::Cell) -> Style {
    let mut style = Style::default();
    if let Some(fg) = convert_color(cell.fgcolor()) {
        style = style.fg(fg);
    }
    if let Some(bg) = convert_color(cell.bgcolor()) {
        style = style.bg(bg);
    }
    if cell.bold() {
        style = style.add_modifier(Modifier::BOLD);
    }
    // Claude Code's ghost text — the follow-up prompt → fills in — is plain
    // SGR 2, no colour of its own; dropping dim renders it as ordinary text.
    if cell.dim() {
        style = style.add_modifier(Modifier::DIM);
    }
    if cell.italic() {
        style = style.add_modifier(Modifier::ITALIC);
    }
    if cell.underline() {
        style = style.add_modifier(Modifier::UNDERLINED);
    }
    if cell.inverse() {
        style = style.add_modifier(Modifier::REVERSED);
    }
    style
}

/// `Default` stays `None` so the terminal's own foreground and background show
/// through — the agent's palette should look like it does in a real terminal,
/// not be re-tinted by the theme.
fn convert_color(color: vt100::Color) -> Option<Color> {
    match color {
        vt100::Color::Default => None,
        vt100::Color::Idx(i) => Some(Color::Indexed(i)),
        vt100::Color::Rgb(r, g, b) => Some(Color::Rgb(r, g, b)),
    }
}

/// What a session's state is, from this UI's point of view.
///
/// "connected" means this TUI has a pane on it. The platform's `attached` flag
/// answers a different question — whether *anyone* is attached, including
/// another terminal — and reporting that made the label flicker between
/// attached and running for no reason the user could see.
fn session_state(app: &App, name: &str, running: bool) -> &'static str {
    if !running {
        "exited"
    } else if app.sessions.iter().any(|pane| pane.durable_name == name) {
        "connected"
    } else {
        "running"
    }
}

/// Trim to `max` characters, with an ellipsis — a status card is one line.
/// 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())
}

fn status_color(theme: &Theme, status: &str) -> Color {
    match status {
        "running" => theme.running,
        "sleeping" | "stopped" => theme.sleeping,
        _ => theme.pending,
    }
}

fn status_glyph(status: &str) -> &'static str {
    match status {
        "running" => "",
        "sleeping" | "stopped" => "",
        _ => "",
    }
}

fn tree_line(theme: &Theme, row: &Row, app: &App, width: u16) -> Line<'static> {
    let tick = app.loading.tick;
    let indent = "  ".repeat(row.depth);
    let label_width = usize::from(width).saturating_sub(indent.len() + 2);
    let label = if label_width == 0 {
        String::new()
    } else if console::measure_text_width(&row.label) > label_width {
        console::truncate_str(&row.label, label_width, "").into_owned()
    } else {
        row.label.clone()
    };
    let mut spans = vec![Span::raw(indent)];

    match (&row.kind, row.expanded) {
        // The launcher reads as an action, not a place: an accent `+` where
        // the other rows carry their status glyphs.
        (RowKind::NewSession, _) => {
            spans.push(Span::styled("+ ", Style::default().fg(theme.accent)));
            spans.push(Span::styled(
                label.clone(),
                Style::default().fg(theme.fg).add_modifier(Modifier::BOLD),
            ));
        }
        (RowKind::Agent(..), _) => {
            let status = row.status.as_deref().unwrap_or_default();
            // Metadata discovery does not change machine health.
            let (glyph, color) = (status_glyph(status), status_color(theme, status));
            spans.push(Span::styled(
                format!("{glyph} "),
                Style::default().fg(color),
            ));
            spans.push(Span::styled(label.clone(), Style::default().fg(theme.fg)));
        }
        (RowKind::Session(..), _) => {
            // The marker is the state: a spinner while the attach is in
            // flight or the harness is working, a filled dot when this UI has
            // it open (and the agent is green — a sleeping agent's sessions
            // never are), a hollow mark when the harness waits on a human, a
            // quiet branch otherwise.
            let (glyph, color) = match row.status.as_deref() {
                Some("connecting") => (format!("{} ", spinner_frame(tick)), theme.pending),
                Some("working") => (format!("{} ", spinner_frame(tick)), theme.running),
                Some("waiting") => ("".to_string(), theme.pending),
                Some(_) => ("".to_string(), theme.running),
                None => ("".to_string(), theme.dim),
            };
            spans.push(Span::styled(glyph, Style::default().fg(color)));
            spans.push(Span::styled(label.clone(), Style::default().fg(theme.fg)));
        }
        (RowKind::Separator, _) => spans.push(Span::styled(
            "".repeat(width.saturating_sub(2) as usize),
            Style::default().fg(theme.accent_dim),
        )),
        (RowKind::Note(..) | RowKind::Hint, _) => spans.push(Span::styled(
            label.clone(),
            Style::default()
                .fg(theme.dim)
                .add_modifier(Modifier::ITALIC),
        )),
        (_, Some(expanded)) => {
            spans.push(Span::styled(
                if expanded { "" } else { "" },
                Style::default().fg(if row.dimmed {
                    theme.accent_dim
                } else {
                    theme.accent
                }),
            ));
            // A project with nothing in it recedes rather than disappears: it
            // is still where you go to press `n`.
            let style = match row.kind {
                _ if row.dimmed => Style::default().fg(theme.dim),
                RowKind::Workspace(_) => Style::default()
                    .fg(theme.accent)
                    .add_modifier(Modifier::BOLD),
                _ => Style::default().fg(theme.fg),
            };
            spans.push(Span::styled(label.clone(), style));
        }
        _ => spans.push(Span::raw(label.clone())),
    }

    // Every thread row carries its context as a dim note: the project for a
    // session, the status for an agent still without one.
    if !row.note.is_empty() {
        spans.push(Span::styled(
            format!("  {}", row.note),
            Style::default().fg(theme.dim),
        ));
    }
    Line::from(spans)
}

fn detail_lines(app: &App) -> Vec<Line<'static>> {
    let theme = app.theme;
    // Wrapping the detail pane's key/value rows once, since several arms use it.
    let kv = |k: &str, v: String| {
        Line::from(vec![
            Span::styled(format!(" {k:<9}"), Style::default().fg(theme.dim)),
            Span::styled(v, Style::default().fg(theme.fg)),
        ])
    };

    let Some(row) = app.selected_row() else {
        return vec![Line::from(Span::styled(
            " nothing selected",
            Style::default().fg(theme.dim),
        ))];
    };

    match row.kind {
        // Unreachable in practice — the New Session row gets the launcher
        // pane, not this card — but the match must answer for it.
        RowKind::NewSession => vec![Line::from(Span::styled(
            " enter launches a new session",
            Style::default().fg(theme.dim),
        ))],
        // An agent: where it lives, and a snapshot of the threads on it.
        RowKind::Agent(w, p, e, a) => {
            let proj = &app.tree[w].projects[p];
            let env = &proj.envs[e];
            let name = row.label.clone();
            let status = row.status.clone().unwrap_or_default();
            let agent = match &env.agents {
                Load::Loaded(list) => list.get(a),
                _ => None,
            };

            let mut lines = vec![
                Line::from(Span::styled(
                    format!(" {name}"),
                    Style::default()
                        .fg(theme.accent)
                        .add_modifier(Modifier::BOLD),
                )),
                Line::from(Span::styled(
                    format!("  {} {}", status_glyph(&status), status),
                    Style::default().fg(status_color(theme, &status)),
                )),
                Line::from(""),
                kv("project", proj.name.clone()),
                kv("env", env.name.clone()),
                kv("agent", name),
                Line::from(""),
            ];

            // A snapshot of every running session: what it was started on,
            // and — for a session this UI is attached to — the last thing it
            // said. That last line is only knowable for an attached pane; the
            // platform reports state, not output.
            match agent.map(|agent| &agent.sessions) {
                Some(LoadSessions::Loaded(sessions)) => {
                    let live: Vec<_> = sessions
                        .iter()
                        .filter(|session| session.is_interesting())
                        .collect();
                    if live.is_empty() {
                        lines.push(Line::from(Span::styled(
                            "  no session running on it",
                            Style::default().fg(theme.dim),
                        )));
                    }
                    for session in live {
                        let connected = app
                            .sessions
                            .iter()
                            .find(|pane| pane.durable_name == session.name);
                        lines.push(Line::from(vec![
                            Span::styled(
                                format!("  {} ", if connected.is_some() { "" } else { " " }),
                                Style::default().fg(theme.accent),
                            ),
                            Span::styled(
                                session.short_name(),
                                Style::default().fg(theme.fg).add_modifier(Modifier::BOLD),
                            ),
                            Span::styled(
                                format!("  {}", session_state(app, &session.name, session.running)),
                                Style::default().fg(theme.dim),
                            ),
                        ]));
                        let message = match connected.and_then(|pane| pane.last_line()) {
                            Some(line) => (truncate(&line, 60), theme.fg),
                            None => ("not connected — click to attach".into(), theme.dim),
                        };
                        lines.push(Line::from(Span::styled(
                            format!("      {}", message.0),
                            Style::default().fg(message.1),
                        )));
                        lines.push(Line::from(""));
                    }
                }
                Some(LoadSessions::Loading) => lines.push(Line::from(Span::styled(
                    "  loading its sessions…",
                    Style::default().fg(theme.dim),
                ))),
                Some(LoadSessions::Failed(err)) => lines.push(Line::from(Span::styled(
                    format!("  couldn't load sessions: {err}"),
                    Style::default().fg(theme.pending),
                ))),
                _ => lines.push(Line::from(Span::styled(
                    "  no session running on it",
                    Style::default().fg(theme.dim),
                ))),
            }
            lines.push(Line::from(""));
            lines.push(Line::from(Span::styled(
                if status == "running" {
                    " enter / double-click connects · n new agent here"
                } else {
                    " w wakes it · enter / double-click connects"
                },
                Style::default().fg(theme.dim),
            )));
            lines
        }
        RowKind::Environment(w, p, e) => {
            let proj = &app.tree[w].projects[p];
            let env = &proj.envs[e];
            let count = match &env.agents {
                super::app::Load::Loaded(l) => format!("{}", l.len()),
                super::app::Load::Loading => "loading…".into(),
                super::app::Load::Failed(_) => "unknown".into(),
                super::app::Load::NotLoaded => "→ to load".into(),
            };
            vec![
                Line::from(Span::styled(
                    format!(" {}/{}", proj.name, env.name),
                    Style::default()
                        .fg(theme.accent)
                        .add_modifier(Modifier::BOLD),
                )),
                Line::from(""),
                kv("agents", count),
                Line::from(""),
                Line::from(Span::styled(
                    " n creates one here · t targets it",
                    Style::default().fg(theme.dim),
                )),
            ]
        }
        RowKind::Project(w, p) => {
            let proj = &app.tree[w].projects[p];
            vec![
                Line::from(Span::styled(
                    format!(" {}", proj.name),
                    Style::default()
                        .fg(theme.accent)
                        .add_modifier(Modifier::BOLD),
                )),
                Line::from(""),
                kv("envs", proj.envs.len().to_string()),
                kv("id", proj.id.clone()),
            ]
        }
        RowKind::Workspace(w) => {
            let ws = &app.tree[w];
            vec![
                Line::from(Span::styled(
                    format!(" {}", ws.name),
                    Style::default()
                        .fg(theme.accent)
                        .add_modifier(Modifier::BOLD),
                )),
                Line::from(""),
                kv("projects", ws.projects.len().to_string()),
            ]
        }
        // A thread: which project and agent it lives on — the context you
        // check before connecting into it.
        RowKind::Session(w, p, e, a, i) => {
            let proj = &app.tree[w].projects[p];
            let env = &proj.envs[e];
            let agent_name = match &env.agents {
                Load::Loaded(list) => list.get(a).map(|agent| agent.name.clone()),
                _ => None,
            }
            .unwrap_or_default();
            let mut lines = vec![Line::from(Span::styled(
                format!(" {}", row.label),
                Style::default()
                    .fg(theme.accent)
                    .add_modifier(Modifier::BOLD),
            ))];
            // The command lives here, not in the row: it is a whole launch
            // line, and this is the pane with room for it.
            let session = app.console_session(w, p, e, a, i);
            if let Some(session) = session {
                lines.push(Line::from(""));
                lines.push(kv("project", proj.name.clone()));
                lines.push(kv("env", env.name.clone()));
                lines.push(kv("agent", agent_name));
                lines.push(Line::from(""));
                lines.push(kv("session", session.name.clone()));
                lines.push(kv(
                    "state",
                    session_state(app, &session.name, session.running).to_string(),
                ));
                lines.push(kv("kind", session.kind.to_lowercase()));
                // What the harness inside says it is doing — the full text the
                // row's label truncates, and the state the row's glyph encodes.
                if let Some(snapshot) = &session.snapshot {
                    lines.push(kv("thread", snapshot.state.clone()));
                    if let Some(text) = snapshot
                        .latest_prompt
                        .as_deref()
                        .or(snapshot.prompt.as_deref())
                    {
                        lines.push(Line::from(""));
                        lines.push(Line::from(vec![
                            Span::styled("", Style::default().fg(theme.dim)),
                            Span::styled(truncate(text, 200), Style::default().fg(theme.fg)),
                        ]));
                    }
                    // The agent's own last words, from the daemon transcript —
                    // only railway-agent threads have one to read.
                    if let Some(reply) = snapshot.last_reply.as_deref() {
                        lines.push(Line::from(""));
                        lines.push(Line::from(Span::styled(
                            format!(" {}", truncate(reply, 300)),
                            Style::default().fg(theme.fg),
                        )));
                    }
                }
                lines.push(Line::from(""));
                lines.push(Line::from(Span::styled(
                    format!(" {}", session.command_summary()),
                    Style::default().fg(theme.dim),
                )));
            }
            lines.push(Line::from(""));
            // This card only shows for a session without a pane (one with a
            // pane shows the pane itself), so say that plainly, and say how
            // to get the pane back — via a wake first when the agent is
            // asleep, since a reattach to a sleeping agent is refused.
            let connected = session
                .is_some_and(|s| app.sessions.iter().any(|pane| pane.durable_name == s.name));
            if connected {
                lines.push(Line::from(Span::styled(
                    " enter puts the keyboard in its pane",
                    Style::default().fg(theme.dim),
                )));
            } else {
                let sleeping = app
                    .selected_agent_status()
                    .is_some_and(|status| status != "running");
                lines.push(Line::from(Span::styled(
                    " not connected — its output isn't shown here",
                    Style::default().fg(theme.pending),
                )));
                lines.push(Line::from(""));
                lines.push(Line::from(Span::styled(
                    if sleeping {
                        " w wakes the agent, then enter / double-click connects"
                    } else {
                        " enter / double-click connects · c copies the ssh command"
                    },
                    Style::default().fg(theme.dim),
                )));
            }
            lines
        }
        RowKind::OtherProjects => vec![
            Line::from(Span::styled(
                " projects without agents",
                Style::default()
                    .fg(theme.accent)
                    .add_modifier(Modifier::BOLD),
            )),
            Line::from(""),
            Line::from(Span::styled(
                " open one and press n to start an agent there",
                Style::default().fg(theme.dim),
            )),
        ],
        RowKind::Separator | RowKind::Note(..) | RowKind::Hint => vec![Line::from("")],
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::commands::cloud_agent::tui::app::{
        Agent, EnvNode, Load, LoadSessions, ProjectNode, Screen, Target, WorkspaceNode,
    };
    use ratatui::Terminal;
    use ratatui::backend::TestBackend;

    pub(super) fn app_with_tree() -> App {
        let tree = vec![WorkspaceNode {
            id: "ws_1".into(),
            name: "Railway".into(),
            expanded: true,
            projects: vec![ProjectNode {
                id: "proj_1".into(),
                name: "devtools".into(),
                expanded: true,
                envs: vec![EnvNode {
                    id: "env_prod".into(),
                    name: "production".into(),
                    expanded: true,
                    agents: Load::Loaded(vec![Agent {
                        id: "ca_1".into(),
                        name: "nimble-otter".into(),
                        status: "running".into(),
                        sessions: LoadSessions::NotLoaded,
                        expanded: false,
                    }]),
                }],
            }],
        }];
        App::new(
            tree,
            Some(Target {
                project_id: "proj_1".into(),
                project_name: "devtools".into(),
                environment_id: "env_prod".into(),
                environment_name: "production".into(),
            }),
            Some("claude"),
            None,
            None,
            true,
        )
    }

    #[test]
    fn bootstrap_setup_row_is_below_project_and_only_visible_with_target() {
        let mut app = app_with_tree();
        app.bootstrap_defaults.insert(
            "env_prod".into(),
            super::super::bootstrap_setup::DefaultState::Missing,
        );
        let screen = draw(&app, 120, 40);
        let lines: Vec<_> = screen.lines().collect();
        let project = lines
            .iter()
            .position(|l| l.contains("Target Project"))
            .unwrap();
        let bootstrap = lines
            .iter()
            .position(|l| l.contains("No bootstrap configured"))
            .unwrap();
        assert!(bootstrap >= project + 2);
        assert!(lines[bootstrap].contains("⌥b"));
        app.target = None;
        let screen = draw(&app, 120, 40);
        assert!(!screen.contains("No bootstrap configured"));
        assert!(!screen.contains("Checking bootstrap"));
    }

    #[test]
    fn bootstrap_setup_form_and_progress_keep_the_prompt_draft() {
        let mut app = app_with_tree();
        app.prompt = "Fix the CLI".into();
        app.start_bootstrap_setup();
        let screen = draw(&app, 120, 40);
        for text in [
            "Create bootstrap",
            "Repository (optional)",
            "Coding agent",
            "Name",
        ] {
            assert!(screen.contains(text), "{screen}");
        }
        let form = app.bootstrap_form.as_mut().unwrap();
        form.running = true;
        form.steps = vec!["Creating setup VM".into(), "Saving checkpoint".into()];
        let screen = draw(&app, 120, 40);
        assert!(screen.contains("Creating bootstrap"));
        assert!(screen.contains("Saving checkpoint"));
        assert_eq!(app.prompt, "Fix the CLI");
        // The form also renders in small terminals without panicking.
        draw(&app, 60, 18);
    }

    fn layout(app: &mut App, width: u16) {
        let mut terminal = Terminal::new(TestBackend::new(width, 40)).unwrap();
        terminal
            .draw(|f| app.panes = render_with_layout(app, f).0)
            .unwrap();
        if let Some((rows, cols)) = session_pane_size(
            Some(ratatui::layout::Size::new(width, 40)),
            app.pane_is_full(),
            app.sidebar_width,
        ) {
            assert_eq!((app.panes.session.h, app.panes.session.w), (rows, cols));
        }
    }

    #[test]
    fn sidebar_drag_resizes_both_panes_and_keeps_the_preferred_width() {
        use crate::commands::cloud_agent::tui::app::{Effect, MouseAction};
        let mut app = app_with_tree();
        app.focus = ManageFocus::Session;
        layout(&mut app, 120);
        assert_eq!(app.panes.tree_outer.w, TREE_W);
        let cursor = app.cursor;
        let divider = app.panes.sidebar_divider;
        assert_eq!(
            app.on_mouse(MouseAction::Down, divider.x + 1, divider.y),
            None
        );
        assert!(app.resizing_sidebar());
        assert_eq!(
            app.on_mouse(MouseAction::Drag, divider.x + 27, divider.y),
            None
        );
        assert_eq!(app.sidebar_width, Some(58));
        layout(&mut app, 120);
        assert_eq!(app.panes.tree_outer.w, 58);
        assert_eq!(
            app.on_mouse(MouseAction::Up, divider.x + 27, divider.y),
            Some(Effect::SaveSidebarWidth(58))
        );
        assert!(!app.resizing_sidebar());
        assert_eq!(app.focus, ManageFocus::Session);
        assert_eq!(app.cursor, cursor);
        assert!(app.selection.is_none() && app.pending_copy.is_none());

        layout(&mut app, 80);
        assert_eq!(app.panes.tree_outer.w, 44);
        assert_eq!(
            app.sidebar_width,
            Some(58),
            "shrinking the window must not overwrite the preference"
        );
        layout(&mut app, 120);
        assert_eq!(app.panes.tree_outer.w, 58);
        let divider = app.panes.sidebar_divider;
        app.on_mouse(MouseAction::Down, divider.x, divider.y);
        app.on_mouse(MouseAction::Drag, u16::MAX, divider.y);
        assert_eq!(
            app.sidebar_width,
            Some(84),
            "leave at least 32 columns for the terminal"
        );
        app.on_key(crossterm::event::KeyEvent::new(
            crossterm::event::KeyCode::Esc,
            crossterm::event::KeyModifiers::NONE,
        ));
        assert_eq!(app.sidebar_width, Some(58), "Escape cancels the resize");
        app.on_mouse(MouseAction::Down, divider.x, divider.y);
        app.on_mouse(MouseAction::Drag, 0, divider.y);
        assert_eq!(app.sidebar_width, Some(20));
        assert_eq!(
            app.on_mouse(MouseAction::Up, 0, divider.y),
            Some(Effect::SaveSidebarWidth(20))
        );
        layout(&mut app, 120);
        let divider = app.panes.sidebar_divider;
        app.on_mouse(MouseAction::Down, divider.x, divider.y);
        assert_eq!(
            app.on_mouse(MouseAction::Up, divider.x, divider.y),
            None,
            "clicking without a drag does not save"
        );
        app.maximized = true;
        app.loading.active = true;
        layout(&mut app, 120);
        assert_eq!(app.panes.sidebar_divider, PaneBox::default());
        assert_eq!(app.sidebar_width, Some(20));
    }

    #[test]
    fn clicking_rendered_panels_switches_focus_without_activating_blank_rows() {
        use crate::commands::cloud_agent::tui::{app::MouseAction, session::Session};
        let mut app = app_with_tree();
        app.attach_session(
            Session::for_test("ca_1", "nimble-otter").unwrap(),
            "ca_1".into(),
        );
        for width in [None, Some(58)] {
            app.sidebar_width = width;
            layout(&mut app, 120);
            let panes = app.panes;
            let cursor = app.cursor;
            let active = app.active;
            let blank_row = panes.tree.y + app.rows().len() as u16 + 1;
            assert!(panes.tree.contains(panes.tree.x, blank_row));
            let separator = app
                .rows()
                .iter()
                .position(|row| matches!(row.kind, RowKind::Separator))
                .unwrap();
            for (col, row) in [
                (panes.tree.x, blank_row),
                (panes.tree.x, panes.tree.y + separator as u16),
                (panes.tree_outer.x, panes.tree.y),
                (panes.tree.x, panes.tree_outer.y),
                (panes.sidebar_divider.x, panes.sidebar_divider.y),
            ] {
                // Repeating a blank/border click must not double-click the
                // previously selected session or toggle a selected folder.
                for _ in 0..2 {
                    app.focus = ManageFocus::Session;
                    assert_eq!(app.on_mouse(MouseAction::Down, col, row), None);
                    assert_eq!(app.on_mouse(MouseAction::Up, col, row), None);
                    assert_eq!(app.focus, ManageFocus::Tree, "click at {col},{row}");
                    assert_eq!(app.cursor, cursor);
                    assert_eq!(app.active, active);
                    assert_eq!(app.sidebar_width, width);
                    assert!(!app.resizing_sidebar());
                }
            }
            for (col, row) in [
                (panes.session.x + 3, panes.session.y + 3),
                (panes.session.x, panes.session_outer.y),
                (panes.sidebar_divider.x + 1, panes.sidebar_divider.y),
            ] {
                app.focus = ManageFocus::Tree;
                assert_eq!(app.on_mouse(MouseAction::Down, col, row), None);
                assert_eq!(app.on_mouse(MouseAction::Up, col, row), None);
                assert_eq!(app.focus, ManageFocus::Session, "click at {col},{row}");
                assert_eq!(app.sidebar_width, width);
                assert!(!app.resizing_sidebar());
            }
        }
    }

    #[test]
    fn focusing_an_unconnected_thread_keeps_its_card_and_background_sessions_separate() {
        use crate::commands::cloud_agent::tui::{
            app::{ConsoleSession, Effect, MouseAction},
            session::Session,
        };
        use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
        let remote_thread = |name: &str| ConsoleSession {
            name: name.into(),
            kind: "SHELL".into(),
            command: None,
            running: true,
            attached: true,
            created_at: None,
            snapshot: None,
        };
        let mut app = app_with_tree();
        if let Load::Loaded(agents) = &mut app.tree[0].projects[0].envs[0].agents {
            agents[0].expanded = true;
            agents[0].sessions = LoadSessions::Loaded(vec![remote_thread("same-vm-thread")]);
            agents.push(Agent {
                id: "ca_2".into(),
                name: "quiet-harbor".into(),
                status: "running".into(),
                sessions: LoadSessions::Loaded(vec![remote_thread("other-vm-thread")]),
                expanded: true,
            });
        }
        let mut open = Session::for_test("ca_1", "nimble-otter").unwrap();
        open.durable_name = "open-thread".into();
        app.attach_session(open, "ca_1".into());

        for width in [None, Some(58)] {
            app.sidebar_width = width;
            for (name, agent_id) in [("same-vm-thread", "ca_1"), ("other-vm-thread", "ca_2")] {
                for on_edge in [false, true] {
                    app.focus = ManageFocus::Tree;
                    app.active = Some(0);
                    let cursor = app
                        .rows()
                        .iter()
                        .position(|row| row.label == format!("[S] {name}"))
                        .unwrap();
                    layout(&mut app, 140);
                    // Select a remote thread using the sidebar, as in the
                    // reported interaction, then click its displayed card.
                    let tree = app.panes.tree;
                    app.on_mouse(MouseAction::Down, tree.x + 2, tree.y + cursor as u16);
                    app.on_mouse(MouseAction::Up, tree.x + 2, tree.y + cursor as u16);
                    assert_eq!(app.cursor, cursor);
                    layout(&mut app, 140);
                    let pane = app.panes.session;
                    let col = if on_edge {
                        app.panes.sidebar_divider.x + 1
                    } else {
                        pane.x + 3
                    };
                    let row = pane.y + 2;
                    assert_eq!(app.on_mouse(MouseAction::Down, col, row), None);
                    assert_eq!(app.on_mouse(MouseAction::Up, col, row), None);
                    assert_eq!(app.focus, ManageFocus::Session);
                    assert_eq!(app.active, None, "no fallback to the open thread");
                    assert_eq!(app.cursor, cursor);
                    assert_eq!(app.sessions.len(), 1, "the open session stays connected");
                    assert_eq!(app.sessions[0].durable_name, "open-thread");
                    let screen = draw(&app, 140, 40);
                    assert!(
                        screen.contains("not connected — its output isn't shown here"),
                        "{screen}"
                    );
                    assert!(
                        !screen.contains("devtools / nimble-otter / open-thread"),
                        "{screen}"
                    );
                    assert!(!last_drawn_line(&screen).contains("stop typing"));
                    assert_eq!(
                        app.on_key(KeyEvent::new(KeyCode::Char('z'), KeyModifiers::NONE)),
                        None
                    );
                    assert_eq!(app.on_paste("do not send to the other VM".into()), None);
                    assert!(!app.sessions[0].input_within(std::time::Duration::from_secs(60)));
                    // Repeated clicks stay on the card; connecting still
                    // requires the explicit Enter action.
                    assert_eq!(app.on_mouse(MouseAction::Down, col, row), None);
                    assert_eq!(app.on_mouse(MouseAction::Up, col, row), None);
                    assert!(matches!(
                        app.on_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)),
                        Some(Effect::Reattach { agent_id: id, session_name, .. })
                            if id == agent_id && session_name == name
                    ));
                    app.on_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
                    assert_eq!(app.focus, ManageFocus::Tree);
                    // Keyboard focus changes follow the same rule.
                    app.active = Some(0);
                    app.on_key(KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE));
                    assert_eq!(app.focus, ManageFocus::Session);
                    assert_eq!(app.active, None);
                    app.on_key(KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE));
                    assert_eq!(app.focus, ManageFocus::Tree);
                }
            }
        }
        // Returning to the connected thread still focuses its existing pane.
        app.cursor = app
            .rows()
            .iter()
            .position(|row| row.label == "[S] open-thread")
            .unwrap();
        layout(&mut app, 140);
        let pane = app.panes.session;
        app.on_mouse(MouseAction::Down, pane.x + 3, pane.y + 2);
        app.on_mouse(MouseAction::Up, pane.x + 3, pane.y + 2);
        assert_eq!(app.active, Some(0));
        assert_eq!(app.focus, ManageFocus::Session);
    }

    #[test]
    fn wheel_scrolls_the_visible_terminal_after_focus_and_resize_gestures() {
        use crate::commands::cloud_agent::tui::{app::MouseAction, session::Session};
        let mut app = app_with_tree();
        let mut session = Session::for_test("ca_1", "nimble-otter").unwrap();
        session.resize(12, 80);
        for i in 0..100 {
            session.send(format!("scroll-line-{i:03}\r\n").as_bytes());
        }
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
        while !session
            .with_screen(|s| s.contents().contains("scroll-line-099"))
            .unwrap_or(false)
        {
            assert!(
                std::time::Instant::now() < deadline,
                "fixture output must arrive"
            );
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
        app.attach_session(session, "ca_1".into());
        for width in [None, Some(58)] {
            app.sidebar_width = width;
            layout(&mut app, 140);
            let pane = app.panes.session;
            for focus in [ManageFocus::Tree, ManageFocus::Session] {
                app.focus = focus;
                app.sessions[0].scroll_by(isize::MIN);
                let live = app.sessions[0].with_screen(|s| s.contents()).unwrap();
                assert_eq!(
                    app.on_mouse(MouseAction::ScrollUp, pane.x + 4, pane.y + 4),
                    None
                );
                assert!(app.sessions[0].scrolled_back());
                assert_ne!(app.sessions[0].with_screen(|s| s.contents()).unwrap(), live);
                assert_eq!(app.focus, focus, "scrolling must not take focus");
                app.on_mouse(MouseAction::ScrollDown, pane.x + 4, pane.y + 4);
                assert!(!app.sessions[0].scrolled_back());
            }
            // Mouse-up can be lost outside the window. A subsequent wheel
            // gesture must recover instead of being swallowed by resizing.
            let divider = app.panes.sidebar_divider;
            app.on_mouse(MouseAction::Down, divider.x, divider.y);
            app.on_mouse(MouseAction::Drag, divider.x + 4, divider.y);
            assert!(app.resizing_sidebar());
            layout(&mut app, 140);
            let pane = app.panes.session;
            app.on_mouse(MouseAction::ScrollUp, pane.x + 4, pane.y + 4);
            assert!(!app.resizing_sidebar());
            assert_eq!(app.sidebar_width, width);
            assert!(app.sessions[0].scrolled_back());

            // A displayed, connected row can be populated in the background
            // without changing active. The wheel follows what was drawn.
            app.focus = ManageFocus::Tree;
            app.active = None;
            app.sessions[0].scroll_by(isize::MIN);
            layout(&mut app, 140);
            let pane = app.panes.session;
            assert!(draw(&app, 140, 40).contains("scroll-line-099"));
            app.on_mouse(MouseAction::ScrollUp, pane.x + 4, pane.y + 4);
            assert!(app.sessions[0].scrolled_back());
            assert_eq!(
                app.active, None,
                "scrolling does not change the active connection"
            );
            app.active = Some(0);
            // The launcher shows no terminal: wheel input over it must not
            // scroll a hidden session.
            app.cursor = 0;
            app.sessions[0].scroll_by(isize::MIN);
            layout(&mut app, 140);
            app.on_mouse(MouseAction::ScrollUp, pane.x + 4, pane.y + 4);
            assert!(!app.sessions[0].scrolled_back());
            app.cursor = app
                .rows()
                .iter()
                .position(|row| matches!(row.kind, RowKind::Session(..)))
                .unwrap();
        }
    }

    #[test]
    fn a_fresh_panel_click_recovers_from_a_lost_resize_release() {
        use crate::commands::cloud_agent::tui::{app::MouseAction, session::Session};
        let mut app = app_with_tree();
        app.attach_session(
            Session::for_test("ca_1", "nimble-otter").unwrap(),
            "ca_1".into(),
        );
        for width in [None, Some(58)] {
            for target in [ManageFocus::Tree, ManageFocus::Session] {
                app.sidebar_width = width;
                app.focus = if target == ManageFocus::Tree {
                    ManageFocus::Session
                } else {
                    ManageFocus::Tree
                };
                layout(&mut app, 120);
                let divider = app.panes.sidebar_divider;
                app.on_mouse(MouseAction::Down, divider.x, divider.y);
                app.on_mouse(MouseAction::Drag, divider.x + 5, divider.y);
                assert!(app.resizing_sidebar());
                assert_ne!(app.sidebar_width, width);
                layout(&mut app, 120);
                let pane = if target == ManageFocus::Tree {
                    app.panes.tree_outer
                } else {
                    app.panes.session_outer
                };
                // No Up: simulate releasing outside the terminal window.
                assert_eq!(app.on_mouse(MouseAction::Down, pane.x + 3, pane.y), None);
                assert_eq!(app.on_mouse(MouseAction::Up, pane.x + 3, pane.y), None);
                assert!(!app.resizing_sidebar());
                assert_eq!(app.sidebar_width, width, "unfinished resize is canceled");
                assert_eq!(app.focus, target);
            }
        }
    }

    pub(super) fn draw(app: &App, w: u16, h: u16) -> String {
        let mut terminal = Terminal::new(TestBackend::new(w, h)).unwrap();
        terminal
            .draw(|f| {
                render_with_layout(app, f);
            })
            .unwrap();
        let buffer = terminal.backend().buffer().clone();
        (0..buffer.area.height)
            .map(|y| {
                (0..buffer.area.width)
                    .map(|x| buffer[(x, y)].symbol().to_string())
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    /// Every cell of a drawn frame, as `(symbol, background)`.
    fn cells(app: &App, w: u16, h: u16) -> Vec<Vec<(String, Color)>> {
        let mut terminal = Terminal::new(TestBackend::new(w, h)).unwrap();
        terminal
            .draw(|f| {
                render_with_layout(app, f);
            })
            .unwrap();
        let buffer = terminal.backend().buffer().clone();
        (0..buffer.area.height)
            .map(|y| {
                (0..buffer.area.width)
                    .map(|x| {
                        let cell = &buffer[(x, y)];
                        (cell.symbol().to_string(), cell.bg)
                    })
                    .collect()
            })
            .collect()
    }

    /// The rows a dialog covers, found by its border corners: the first row
    /// holding `╭` at or after `title`, through the matching `╰`.
    fn dialog_rows(grid: &[Vec<(String, Color)>], title: &str) -> (usize, usize, usize, usize) {
        let top = grid
            .iter()
            .position(|row| {
                let line: String = row.iter().map(|(s, _)| s.as_str()).collect();
                line.contains('') && line.contains(title)
            })
            .unwrap_or_else(|| panic!("no dialog titled {title}"));
        let left = grid[top].iter().position(|(s, _)| s == "").unwrap();
        let right = grid[top].iter().rposition(|(s, _)| s == "").unwrap();
        let bottom = (top + 1..grid.len())
            .find(|y| grid[*y][left].0 == "")
            .expect("a closed dialog");
        (top, bottom, left, right)
    }

    /// A dialog is a surface, not a window onto the screen behind it: every
    /// cell it covers carries its own background, so nothing underneath and no
    /// terminal wallpaper shows through.
    #[test]
    fn dialogs_are_filled_rather_than_transparent() {
        let mut app = app_with_tree();
        app.start_settings();
        let grid = cells(&app, 100, 40);
        let (top, bottom, left, right) = dialog_rows(&grid, "settings");
        let surface = app.theme.surface;
        for row in &grid[top..=bottom] {
            for (symbol, bg) in &row[left..=right] {
                // The key badges in the footer paint their own background;
                // everything else is the surface.
                assert!(
                    *bg == surface || *bg == app.theme.accent_dim,
                    "transparent cell {symbol:?} in the dialog: {bg:?}"
                );
            }
        }
    }

    /// The breathing room lives outside the boxes: a slim margin of untouched
    /// cells between the terminal's edges and everything the TUI draws, on
    /// every screen.
    #[test]
    fn the_page_keeps_clear_of_the_terminal_edges() {
        // Both faces of the Manage screen: the launcher pane, and the tree
        // with the detail pane beside it.
        for cursor in [0usize, 2] {
            let mut app = app_with_tree();
            app.screen = Screen::Manage;
            app.cursor = cursor;
            let grid = cells(&app, 100, 40);
            let blank = |cells: &[(String, Color)]| cells.iter().all(|(s, _)| s == " ");
            let h = grid.len();
            for y in 0..PAGE_MARGIN_Y as usize {
                assert!(blank(&grid[y]), "top margin row {y} has content");
                assert!(blank(&grid[h - 1 - y]), "bottom margin row has content");
            }
            for (y, row) in grid.iter().enumerate() {
                let w = row.len();
                assert!(
                    blank(&row[..PAGE_MARGIN_X as usize]),
                    "left margin has content at row {y}"
                );
                assert!(
                    blank(&row[w - PAGE_MARGIN_X as usize..]),
                    "right margin has content at row {y}"
                );
            }
        }
    }

    /// The last row the TUI actually draws on — the footer/key strip sits
    /// here, one page margin above the terminal's bottom edge.
    pub(super) fn last_drawn_line(out: &str) -> String {
        out.lines()
            .rev()
            .find(|l| !l.trim().is_empty())
            .unwrap_or_default()
            .to_string()
    }

    /// The prompt holds a paragraph's worth of writing room — six text rows
    /// inside the outline — and its breathing room sits outside the box:
    /// blank rows against the border, not padding within it.
    #[test]
    fn the_prompt_is_tall_with_its_room_outside() {
        let app = app_with_tree();
        let out = draw(&app, 100, 40);
        let lines: Vec<&str> = out.lines().collect();
        let top = lines
            .iter()
            .position(|l| l.contains(" Prompt "))
            .expect("the prompt box");
        let row: Vec<char> = lines[top].chars().collect();
        let left = row.iter().position(|&c| c == '').expect("a top border");
        let right = row.iter().rposition(|&c| c == '').expect("a top border");
        let bottom = (top + 1..lines.len())
            .find(|&y| lines[y].chars().nth(left) == Some(''))
            .expect("the prompt's bottom border");
        assert_eq!(bottom - top, 7, "six text rows inside the outline:\n{out}");
        // The gap rows are measured inside the box's own columns: the pane
        // the prompt now lives in draws its borders on the same rows.
        for y in [top - 1, bottom + 1] {
            let inside: String = lines[y].chars().skip(left).take(right - left + 1).collect();
            assert!(
                inside.trim().is_empty(),
                "row {y} should be the prompt's outside gap: {inside:?}"
            );
        }
    }

    /// The ⌥p composer is the launcher's prompt box opened elsewhere — the
    /// same writing room — so it reads as the same control. Width follows the
    /// host (the composer floats over the page; the launcher lives in a
    /// pane), but the height rule is shared.
    #[test]
    fn the_composer_matches_the_launcher_prompt_box() {
        fn box_of(out: &str, title: &str) -> usize {
            let lines: Vec<&str> = out.lines().collect();
            let top = lines
                .iter()
                .position(|l| l.contains(title))
                .unwrap_or_else(|| panic!("{title} not drawn"));
            let row: Vec<char> = lines[top].chars().collect();
            let left = row.iter().position(|&c| c == '').expect("a top border");
            // The closing corner is found by column, not line start: both
            // boxes sit over the manage screen, whose pane borders own the
            // starts of these rows.
            let bottom = (top + 1..lines.len())
                .find(|&y| lines[y].chars().nth(left) == Some(''))
                .expect("a closed box");
            bottom - top + 1
        }
        let launcher = box_of(&draw(&app_with_tree(), 100, 40), "╭ Prompt");
        let mut app = app_with_tree();
        app.screen = Screen::ManagePrompt;
        app.manage_prompt = Some(String::new());
        // Matched with its border corner: the launcher's own tree row also
        // says "New Session", and it is not a box.
        let composer = box_of(&draw(&app, 100, 40), "╭ New Session");
        assert_eq!(launcher, composer, "height of the two prompt boxes");
    }

    /// The title sits exactly two rows above the prompt box — the status line
    /// and one gap — however tall the pane is. It used to drift further apart
    /// on tall panes, which read as a hole in the layout.
    #[test]
    fn the_welcome_title_sits_two_rows_above_the_prompt() {
        let out = draw(&app_with_tree(), 100, 40);
        let lines: Vec<&str> = out.lines().collect();
        let title = lines
            .iter()
            .position(|l| l.contains("What should we build today?"))
            .expect("the title is drawn");
        let prompt = lines
            .iter()
            .position(|l| l.contains("╭ Prompt"))
            .expect("the prompt box is drawn");
        assert_eq!(
            prompt,
            title + 3,
            "two rows between title and prompt:\n{out}"
        );
    }

    /// The prompt box follows the CARET, not the tail: with a draft taller
    /// than the box and the cursor moved to the front, the caret (and the
    /// text being typed) must be on screen.
    #[test]
    fn the_prompt_scrolls_to_the_caret_not_the_tail() {
        let mut app = app_with_tree();
        app.screen = Screen::Manage;
        app.prompt_focused = true;
        app.cursor = 0;
        app.prompt = "word ".repeat(200);
        app.prompt_cursor = 0;
        let out = draw(&app, 100, 30);
        assert!(
            out.contains(''),
            "the caret stays in view at the front:\n{out}"
        );

        // And typing at the end still pins to the tail, as before.
        app.prompt_cursor = app.prompt.chars().count();
        let out = draw(&app, 100, 30);
        assert!(out.contains(''), "…and at the tail:\n{out}");
    }

    /// Submitting from the main screen carries the prompt box along: the
    /// loading pane echoes it in the same box (title, dialog surface, shared
    /// size rule), not a smaller "Task" card.
    #[test]
    fn the_loading_screen_echoes_the_prompt_in_its_own_box() {
        use crate::commands::cloud_agent::tui::app::Loading;

        let mut app = app_with_tree();
        app.screen = Screen::Manage;
        app.loading = Loading {
            active: true,
            target: "devtools/production".into(),
            harness: "claude".into(),
            prompt: Some("ship the release notes".into()),
            steps: Vec::new(),
            tick: 0,
        };
        let out = draw(&app, 100, 40);
        assert!(out.contains(" Prompt "), "the box keeps its name:\n{out}");
        assert!(!out.contains(" Task "), "the old card is gone:\n{out}");
        assert!(out.contains("ship the release notes"), "{out}");

        // A row of air separates the box from the steps below it.
        let lines: Vec<&str> = out.lines().collect();
        let top = lines.iter().position(|l| l.contains(" Prompt ")).unwrap();
        let col = lines[top].chars().position(|c| c == '').unwrap();
        let bottom = (top + 1..lines.len())
            .find(|&y| lines[y].chars().nth(col) == Some(''))
            .expect("a closed box");
        let right = lines[top]
            .chars()
            .collect::<Vec<_>>()
            .iter()
            .rposition(|&c| c == '')
            .expect("a top border");
        let below: String = lines[bottom + 1]
            .chars()
            .skip(col)
            .take(right - col + 1)
            .collect();
        assert!(
            below.trim().is_empty(),
            "the row under the prompt box should be clear: {below:?}"
        );
    }

    /// The wordmark must be full blocks and spaces only: box-drawing shadow
    /// glyphs render at a different weight in some monospace fonts and shear
    /// the whole thing.
    #[test]
    fn banner_uses_no_box_drawing_glyphs() {
        let stray: Vec<char> = BANNER
            .chars()
            .filter(|c| !matches!(c, '' | ' ' | '\n'))
            .collect();
        assert!(
            stray.is_empty(),
            "non-block glyphs in the banner: {stray:?}"
        );
        assert_eq!(BANNER.lines().count(), BANNER_H as usize);

        // Every rendered row is padded to one width, or ratatui centres them
        // independently and the letters drift out of column.
        let widths: std::collections::HashSet<usize> = banner_lines(Theme::default_theme())
            .iter()
            .map(|l| l.spans.iter().map(|s| s.content.chars().count()).sum())
            .collect();
        assert_eq!(
            widths,
            std::collections::HashSet::from([BANNER_W as usize]),
            "banner rows must all be {BANNER_W} wide, got {widths:?}"
        );
        // Nothing may exceed the declared width either — that would clip.
        assert!(
            BANNER
                .lines()
                .all(|l| l.chars().count() <= BANNER_W as usize),
            "a banner row is wider than BANNER_W"
        );

        // The Y's stem has to line up with the notch above it; an off-centre
        // join is what "not even" looks like.
        for line in BANNER.lines() {
            let padded = format!("{line:<width$}", width = BANNER_W as usize);
            let y: String = padded.chars().skip(47).collect();
            let mirrored: String = y.chars().rev().collect();
            assert_eq!(y, mirrored, "the Y must be symmetric: {y:?}");
        }
    }

    /// The launcher's footer uses the same chord badges as the rest of the
    /// manage screen, so the two read as one product rather than two
    /// conventions.
    #[test]
    fn the_launcher_footer_uses_chord_badges() {
        let app = app_with_tree();
        let out = draw(&app, 100, 40);
        let footer = out
            .lines()
            .rfind(|l| l.contains("launch"))
            .expect("the launcher footer");
        assert!(footer.contains("enter"), "{footer}");
        assert!(footer.contains("settings"), "{footer}");
        assert!(
            !footer.contains("theme"),
            "the theme moved onto the settings card: {footer}"
        );
        // The target shortcut moved onto the target line itself — see
        // `target_shortcut_sits_on_its_own_line`.
        assert!(!footer.contains("target"), "{footer}");
        assert!(!footer.contains("menu"), "the arrow hint is gone: {footer}");
        // The old run-on line separated with interpuncts; the badges do not.
        assert!(!footer.contains(" · "), "{footer}");
    }

    /// With shell selected the box stops being a prompt: it says what enter
    /// does instead of inviting text, and hides a draft typed for a real
    /// agent rather than showing words that would go nowhere.
    #[test]
    fn the_prompt_box_explains_itself_on_shell() {
        let mut app = app_with_tree();
        app.prompt = "fix the tests".into();
        while app.harness_name() != "shell" {
            app.on_key(crossterm::event::KeyEvent::new(
                crossterm::event::KeyCode::BackTab,
                crossterm::event::KeyModifiers::SHIFT,
            ));
        }
        let out = draw(&app, 100, 40);
        assert!(out.contains("A plain shell on the agent"), "{out}");
        assert!(
            !out.contains("fix the tests"),
            "the hidden draft must not show through: {out}"
        );
        let footer = out
            .lines()
            .find(|l| l.contains("shell") && l.contains("shift+tab"))
            .expect("the prompt box footer names the selection");
        assert!(footer.contains("shell"), "{footer}");
    }

    /// Where the prompt lands is its own line above the keys, not a chip inside
    /// the box being typed in.
    #[test]
    fn the_target_sits_above_the_shortcuts_not_in_the_prompt() {
        let app = app_with_tree();
        let out = draw(&app, 100, 40);
        let lines: Vec<&str> = out.lines().collect();

        let prompt_bottom = lines
            .iter()
            .position(|l| l.contains("claude") && l.contains("shift+tab"))
            .expect("the prompt box footer");
        assert!(
            !lines[prompt_bottom].contains("devtools"),
            "the target left the prompt box: {}",
            lines[prompt_bottom]
        );

        let target = lines
            .iter()
            .position(|l| l.contains("Target Project"))
            .expect("the target indicator");
        assert!(
            lines[target].contains("devtools (production)"),
            "{}",
            lines[target]
        );

        let footer = lines
            .iter()
            .position(|l| l.contains("launch"))
            .expect("the footer");
        assert!(target < footer, "the target sits above the shortcuts");
    }

    /// The shortcut for changing the target sits right on the field it acts
    /// on, not lumped into the footer's own chord list where it read like a
    /// command with no object.
    #[test]
    fn the_target_shortcut_sits_on_its_own_line() {
        let app = app_with_tree();
        let out = draw(&app, 100, 40);
        let target = out
            .lines()
            .find(|l| l.contains("Target Project"))
            .expect("the target indicator");
        let chord_at = target.find("⌥t").expect("the chord badge: {target}");
        let label_at = target.find("Target Project").unwrap();
        assert!(
            chord_at < label_at,
            "the chord badge comes before the label: {target}"
        );

        let footer = out
            .lines()
            .rfind(|l| l.contains("settings"))
            .expect("the menu footer");
        assert!(
            !footer.contains("⌥t"),
            "the chord moved out of the footer: {footer}"
        );
    }

    /// With nowhere to launch, the indicator says so rather than going blank.
    #[test]
    fn no_target_says_not_set() {
        let mut app = app_with_tree();
        app.target = None;
        let out = draw(&app, 100, 40);
        assert!(out.contains("Target Project  not set"), "{out}");
    }

    /// The recorded prompt box has to be where the prompt actually drew, or a
    /// click lands somewhere else — the only way to know is to read it out of
    /// a real frame.
    #[test]
    fn the_recorded_prompt_box_matches_the_drawn_rows() {
        use crate::commands::cloud_agent::tui::app::PaneRects;

        let app = app_with_tree();
        let mut terminal = Terminal::new(TestBackend::new(100, 44)).unwrap();
        let mut rects = PaneRects::default();
        terminal
            .draw(|f| {
                let (r, _) = render_with_layout(&app, f);
                rects = r;
            })
            .unwrap();
        let buffer = terminal.backend().buffer().clone();
        let out = (0..buffer.area.height)
            .map(|y| {
                (0..buffer.area.width)
                    .map(|x| buffer[(x, y)].symbol().to_string())
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n");
        let lines: Vec<&str> = out.lines().collect();

        let prompt = lines
            .iter()
            .position(|l| l.contains("╭ Prompt"))
            .expect("the prompt box");
        assert_eq!(rects.prompt.y as usize, prompt);
    }

    /// The pane renders history from any depth, not just the last screenful.
    /// This drives the real draw path — `render_session` → `screen_lines` →
    /// `Screen::cell` — with the view sitting several screens back, which the
    /// old emulator could not compose at all.
    #[test]
    fn a_deeply_scrolled_pane_draws_old_history() {
        use crate::commands::cloud_agent::tui::session::Session;

        let mut app = app_with_tree();
        app.screen = Screen::Manage;
        app.attach_session(
            Session::for_test("ca_1", "nimble-otter").unwrap(),
            "ca_1".into(),
        );

        let session = app.sessions.last_mut().expect("just attached");
        session.resize(6, 40);
        for i in 0..80 {
            session.send(format!("line-{i}\r\n").as_bytes());
        }
        for _ in 0..100 {
            std::thread::sleep(std::time::Duration::from_millis(20));
            let seen = session
                .with_screen(|screen| screen.contents().contains("line-79"))
                .unwrap_or(false);
            if seen {
                break;
            }
        }
        session.scroll_by(isize::MAX);
        assert!(session.scrolled_back());

        let out = draw(&app, 92, 20);
        assert!(
            out.contains("line-0"),
            "the top of history should be on screen:\n{out}"
        );
        assert!(
            !out.contains("line-79"),
            "the tail should be scrolled out of view:\n{out}"
        );
        assert!(
            out.contains("scrolled back"),
            "the pane should say where it is:\n{out}"
        );
    }

    /// A drag that reached the clipboard says so in the corner — the only other
    /// evidence is the clipboard itself, which is not on the screen.
    /// The PTY and the drawn pane are the same size. An emulator wrapping
    /// wider than its pane puts the tail of every row somewhere the screen
    /// never shows — four characters per fold of anything long enough to
    /// wrap, which sheared OAuth login URLs into invalid links.
    #[test]
    fn the_session_pty_matches_the_drawn_pane() {
        use crate::commands::cloud_agent::tui::session::Session;

        let mut app = app_with_tree();
        app.screen = Screen::Manage;
        app.attach_session(
            Session::for_test("ca_1", "nimble-otter").unwrap(),
            "ca_1".into(),
        );
        let mut terminal = Terminal::new(TestBackend::new(100, 40)).unwrap();
        let mut rects = crate::commands::cloud_agent::tui::app::PaneRects::default();
        terminal
            .draw(|f| {
                let (r, _) = render_with_layout(&app, f);
                rects = r;
            })
            .unwrap();
        let (rows, cols) =
            session_pane_size(Some(ratatui::layout::Size::new(100, 40)), false, None).unwrap();
        assert_eq!(
            (cols, rows),
            (rects.session.w, rects.session.h),
            "the PTY must be exactly the pane the emulator is drawn into"
        );
    }

    /// The ⌥s "Full-screen tabs" setting takes the header tabs out of the
    /// maximized layout: ⌥⇧[ ⌥⇧] stay the way between sessions, and the
    /// zeroed tab rects mean there is nothing stale to click.
    #[test]
    fn hidden_tabs_leave_the_maximized_header_bare() {
        use crate::commands::cloud_agent::tui::session::Session;

        let mut app = app_with_tree();
        app.screen = Screen::Manage;
        app.attach_session(
            Session::for_test("ca_1", "nimble-otter").unwrap(),
            "ca_1".into(),
        );
        app.maximized = true;

        let header = |out: &str| {
            out.lines()
                .find(|l| l.contains("RAILWAY CLOUD-AGENTS"))
                .unwrap_or_default()
                .to_string()
        };

        let out = draw(&app, 100, 30);
        assert!(header(&out).contains(" 1 "), "tabs show by default:\n{out}");

        app.hide_tabs = true;
        let mut terminal = Terminal::new(TestBackend::new(100, 30)).unwrap();
        let mut rects = crate::commands::cloud_agent::tui::app::PaneRects::default();
        terminal
            .draw(|f| {
                let (r, _) = render_with_layout(&app, f);
                rects = r;
            })
            .unwrap();
        let out = draw(&app, 100, 30);
        assert!(
            !header(&out).contains(" 1 "),
            "no tab row when hidden:\n{out}"
        );
        assert_eq!(rects.tabs[0].w, 0, "nothing stale to click");
    }

    /// An error toast sits front and center at the bottom of the session
    /// pane, where it can actually be read — not squeezed in beside the
    /// wordmark like a piece of header furniture.
    #[test]
    fn an_error_toast_centers_over_the_session_pane() {
        use crate::commands::cloud_agent::tui::session::Session;

        let mut app = app_with_tree();
        app.screen = Screen::Manage;
        app.attach_session(
            Session::for_test("ca_1", "nimble-otter").unwrap(),
            "ca_1".into(),
        );
        app.toast_error("Launch failed: boom");
        let mut terminal = Terminal::new(TestBackend::new(100, 30)).unwrap();
        let mut rects = crate::commands::cloud_agent::tui::app::PaneRects::default();
        terminal
            .draw(|f| {
                let (r, _) = render_with_layout(&app, f);
                rects = r;
            })
            .unwrap();
        let buffer = terminal.backend().buffer().clone();
        let out = (0..30)
            .map(|y| {
                (0..100)
                    .map(|x| buffer[(x, y)].symbol().to_string())
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n");
        let lines: Vec<&str> = out.lines().collect();
        let row = lines
            .iter()
            .position(|l| l.contains(""))
            .expect("the error toast");
        assert!(row > lines.len() * 2 / 3, "near the bottom: {row}");
        // Char positions, not byte offsets: the row is full of multi-byte
        // box-drawing cells, and columns are what centering is measured in.
        let line: Vec<char> = lines[row].chars().collect();
        let needle: Vec<char> = "Launch failed: boom".chars().collect();
        let start = line
            .windows(needle.len())
            .position(|w| w == needle.as_slice())
            .expect("the reason");
        let end = start + needle.len();
        // Centered within the session pane the frame actually drew.
        assert!(
            start > rects.session.x as usize,
            "inside the session pane: {start}"
        );
        let pane_mid = rects.session.x as usize + rects.session.w as usize / 2;
        let toast_mid = (start + end) / 2;
        assert!(
            toast_mid.abs_diff(pane_mid) <= 3,
            "centered in the pane: toast mid {toast_mid}, pane mid {pane_mid}\n{out}"
        );
    }

    #[test]
    fn a_toast_floats_in_the_bottom_corner() {
        use crate::commands::cloud_agent::tui::session::Session;

        let mut app = app_with_tree();
        app.screen = Screen::Manage;
        app.attach_session(
            Session::for_test("ca_1", "nimble-otter").unwrap(),
            "ca_1".into(),
        );
        app.toast("Copied 3 lines");
        let out = draw(&app, 92, 20);
        let lines: Vec<&str> = out.lines().collect();

        let row = lines
            .iter()
            .position(|l| l.contains("Copied 3 lines"))
            .expect("the toast");
        assert!(out.contains(""), "{out}");

        // Bottom right: below the middle, right of it, and clear of both the
        // key strip on the last row and the pane border above it.
        assert!(row > lines.len() / 2, "in the bottom half: {row}");
        let start = lines[row]
            .chars()
            .collect::<Vec<_>>()
            .windows(6)
            .position(|w| w.iter().collect::<String>() == "Copied")
            .expect("the toast text");
        assert!(start > 92 / 2, "on the right: {start}");
        let strip = last_drawn_line(&out);
        assert!(
            strip.contains("keys"),
            "the key strip is untouched: {strip}"
        );
        // The toast is a closed box: its bottom border sits under the text
        // (with the padding between them) and above the key strip.
        let closed = (row + 1..lines.len())
            .find(|y| lines[*y].contains(""))
            .expect("the toast's bottom border");
        assert!(
            closed < lines.len() - 1,
            "the toast should close above the key strip: {}",
            lines[closed]
        );
        assert!(
            lines[row + 1..=closed]
                .iter()
                .all(|l| !l.contains("Copied")),
            "the text is inside the box only once"
        );
    }

    /// A failure must not wear a tick.
    #[test]
    fn a_failed_copy_is_marked_as_one() {
        let mut app = app_with_tree();
        app.screen = Screen::Manage;
        app.toast_error("Couldn't copy: no clipboard");
        let out = draw(&app, 92, 20);
        assert!(out.contains(""), "{out}");
        assert!(!out.contains(""), "{out}");
    }

    /// And it leaves on its own rather than sitting there.
    #[test]
    fn an_expired_toast_is_not_drawn() {
        use crate::commands::cloud_agent::tui::app::{TOAST_LIFETIME, Toast};

        let mut app = app_with_tree();
        app.screen = Screen::Manage;
        app.toast = Some(Toast {
            text: "Copied 3 lines".into(),
            at: std::time::Instant::now() - TOAST_LIFETIME,
            ok: true,
        });
        let out = draw(&app, 92, 20);
        assert!(!out.contains("Copied 3 lines"), "{out}");
    }

    /// The way out of a focused session is a key, and the key strip already has
    /// it — the pane border does not need to say it twice.
    #[test]
    fn a_focused_pane_does_not_repeat_the_escape_chord() {
        use crate::commands::cloud_agent::tui::session::Session;

        let mut app = app_with_tree();
        app.screen = Screen::Manage;
        app.attach_session(
            Session::for_test("ca_1", "nimble-otter").unwrap(),
            "ca_1".into(),
        );
        let out = draw(&app, 92, 20);
        let border = out
            .lines()
            .find(|l| l.trim_start().starts_with(""))
            .expect("the pane's bottom border");
        assert!(!border.contains("to leave"), "{border}");
        assert!(
            last_drawn_line(&out).contains("stop typing"),
            "the key strip still has it:\n{out}"
        );
    }

    /// Maximized, the tree is gone and the session has the width.
    #[test]
    fn a_maximized_session_takes_the_whole_screen() {
        use crate::commands::cloud_agent::tui::session::Session;

        let mut app = app_with_tree();
        app.screen = Screen::Manage;
        app.attach_session(
            Session::for_test("ca_1", "nimble-otter").unwrap(),
            "ca_1".into(),
        );
        let before = draw(&app, 100, 30);
        assert!(before.contains("threads"), "the tree is there first");

        app.maximized = true;
        let out = draw(&app, 100, 30);
        assert!(!out.contains(" threads "), "the tree is gone:\n{out}");
        // The pane's own title still says `devtools / …` — the tree ROWS are
        // what must be gone, and the launcher heads those.
        assert!(!out.contains("+ New Agent"), "no tree rows:\n{out}");
        assert!(out.contains("restore the tree"), "the way back:\n{out}");

        // The session pane spans the width rather than starting at the old
        // tree boundary.
        let pane = out
            .lines()
            .find(|l| l.contains(""))
            .expect("the session pane");
        assert_eq!(
            pane.chars().position(|c| c == ''),
            Some(PAGE_MARGIN_X as usize),
            "the pane starts at the page's left edge: {pane}"
        );
    }

    /// The emulator is sized to whichever pane it is drawn into, or a maximized
    /// session would wrap where the tree used to be.
    #[test]
    fn the_emulator_follows_the_maximized_pane() {
        let size = Some(ratatui::layout::Size {
            width: 100,
            height: 30,
        });
        let (_, split) = session_pane_size(size, false, None).unwrap();
        let (_, full) = session_pane_size(size, true, None).unwrap();
        // Inside the page margin, like the panes it must agree with.
        assert_eq!(split, 100 - PAGE_MARGIN_X * 2 - TREE_W - 2);
        assert_eq!(full, 100 - PAGE_MARGIN_X * 2 - 2);

        // And a terminal too narrow for two panes is wide enough for one.
        let narrow = Some(ratatui::layout::Size {
            width: 50,
            height: 20,
        });
        assert!(session_pane_size(narrow, false, None).is_none());
        assert!(session_pane_size(narrow, true, None).is_some());
    }

    /// A terminal too narrow for anything else still keeps the launcher
    /// usable: the prompt is there and nothing runs off the edge.
    #[test]
    fn a_very_narrow_launcher_keeps_the_prompt() {
        let app = app_with_tree();
        let out = draw(&app, 46, 40);
        assert!(out.contains("Prompt"), "{out}");
        assert!(
            out.lines().all(|l| l.trim_end().chars().count() <= 46),
            "nothing runs off the edge:\n{out}"
        );
    }

    /// Below the banner threshold the screen still has to be usable — a
    /// terminal that small is common inside a split pane.
    #[test]
    fn the_launcher_degrades_to_a_wordmark_when_small() {
        let app = app_with_tree();
        let out = draw(&app, 50, 20);
        assert!(!out.contains(""), "banner should be dropped:\n{out}");
        assert!(out.contains("RAILWAY CLOUD-AGENTS"));
        assert!(out.contains("Prompt"));
    }

    #[test]
    fn manage_renders_the_tree_and_the_detail_pane() {
        let mut app = app_with_tree();
        app.screen = Screen::Manage;
        app.cursor = app
            .rows()
            .iter()
            .position(|r| r.label == "nimble-otter")
            .unwrap();
        let out = draw(&app, 100, 30);
        // The group header carries the project; the environment shows in the
        // detail pane rather than as a level of its own.
        assert!(out.contains("devtools"));
        assert!(out.contains("production"));
        assert!(out.contains("nimble-otter"));
        assert!(
            out.contains("running"),
            "status belongs in the detail pane:\n{out}"
        );
        assert!(
            out.contains("connect"),
            "the footer names the action:\n{out}"
        );
    }

    #[test]
    fn session_discovery_never_replaces_the_machine_status_icon() {
        let mut app = app_with_tree();
        app.screen = Screen::Manage;
        app.cursor = app
            .rows()
            .iter()
            .position(|r| r.label == "nimble-otter")
            .unwrap();
        if let Load::Loaded(agents) = &mut app.tree[0].projects[0].envs[0].agents {
            agents[0].sessions = LoadSessions::Loading;
        }
        app.loading.tick = 0;
        assert!(draw(&app, 100, 30).contains("● nimble-otter"));
        app.tick();
        let out = draw(&app, 100, 30);
        assert!(out.contains("● nimble-otter"));
        assert!(
            out.contains("running"),
            "the detail pane retains the VM status: {out}"
        );

        app.sessions_loaded((0, 0, 0, 0), "ca_1", Err("temporary failure".into()));
        let out = draw(&app, 100, 30);
        assert!(out.contains("● nimble-otter"));
        assert!(
            out.contains("couldn't load sessions"),
            "failure details remain available: {out}"
        );

        app.sessions_loaded((0, 0, 0, 0), "ca_1", Ok(Vec::new()));
        assert!(draw(&app, 100, 30).contains("● nimble-otter"));
    }

    /// One pane below 70 columns: two would leave the tree unreadable.
    #[test]
    fn manage_drops_the_detail_pane_when_narrow() {
        let mut app = app_with_tree();
        app.screen = Screen::Manage;
        // Off the launcher row, so the single pane is the tree.
        app.cursor = 2;
        let out = draw(&app, 60, 20);
        assert!(out.contains("nimble-otter"));
        // The pane's own title, not any line that happens to say "agent" —
        // the hint line mentions one.
        assert!(
            !out.contains("╭ agent "),
            "detail pane should be gone:\n{out}"
        );
    }

    /// The target chooser is the setup flow's card, floated over the tree —
    /// one list of places to run, not a trip through the management tree.
    #[test]
    fn the_target_picker_is_a_card_over_the_tree() {
        let mut app = app_with_tree();
        app.start_target_pick();
        let out = draw(&app, 100, 34);
        assert!(out.contains("target"), "{out}");
        assert!(out.contains("Where should Cloud Agents run?"), "{out}");
        assert!(out.contains("devtools (production)"), "{out}");
        assert!(out.contains("set target"), "{out}");
    }

    /// An open session takes over the right pane, and the agent row says how
    /// many are running on it.
    #[test]
    fn manage_shows_an_open_session_in_the_pane() {
        let mut app = app_with_tree();
        app.screen = Screen::Manage;
        app.attach_session(
            crate::commands::cloud_agent::tui::session::Session::for_test("ca_1", "nimble-otter")
                .unwrap(),
            "ca_1".into(),
        );
        let out = draw(&app, 100, 30);
        // The pane is titled by the agent and the session it is attached to.
        assert!(out.contains("nimble-otter"), "{out}");
        assert!(
            out.contains("test"),
            "the durable name in the title:\n{out}"
        );
        // And the old bottom-left list is gone for good.
        assert!(!out.contains("sessions ·"), "{out}");
    }

    /// While a launch runs, the wait belongs in the pane the session will
    /// appear in — with the tree still beside it.
    #[test]
    fn the_loading_state_renders_in_the_session_pane() {
        let mut app = app_with_tree();
        app.start_loading(&crate::commands::cloud_agent::tui::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: Some("fix the failing tests".into()),
            label: "devtools/production".into(),
            base: Default::default(),
        });
        app.loading_step("Creating a cloud agent".into());

        let out = draw(&app, 100, 30);
        assert!(out.contains("starting"), "pane title:\n{out}");
        assert!(out.contains("fix the failing tests"), "the task:\n{out}");
        assert!(out.contains("Creating a cloud agent"), "steps:\n{out}");
        // The tree is still there.
        assert!(out.contains("devtools"), "tree stays visible:\n{out}");

        // The block of steps is centred in its pane, not pinned to a border.
        // Measured between the borders either side of the text, since the tree
        // draws its own on the same rows — and entirely in `char` units: the
        // line is full of multi-byte box glyphs, so byte offsets would land
        // mid-character and the arithmetic would be quietly wrong.
        let line: Vec<char> = out
            .lines()
            .find(|l| l.contains("Creating a cloud agent"))
            .unwrap()
            .chars()
            .collect();
        let needle: Vec<char> = "Creating a cloud agent".chars().collect();
        let text_start = line
            .windows(needle.len())
            .position(|w| w == needle.as_slice())
            .expect("the step text");
        let text_end = text_start + needle.len() - 1;
        // Include the step's marker, which is part of the block being centred.
        let block_start = text_start.saturating_sub(2);
        let left_border = (0..block_start)
            .rev()
            .find(|i| line[*i] == '')
            .expect("a border to the left");
        let right_border = (text_end + 1..line.len())
            .find(|i| line[*i] == '')
            .expect("a border to the right");
        let gap_left = block_start - left_border - 1;
        let gap_right = right_border - text_end - 1;
        assert!(gap_left > 2, "hugging the left border: {gap_left}");
        assert!(
            gap_left.abs_diff(gap_right) <= 4,
            "left {gap_left} and right {gap_right} gaps should be close:\n{out}"
        );
    }

    /// …unless the tree was collapsed on the way in. `railway code` has
    /// already answered where and which harness, so there is nothing to
    /// navigate: the wait gets the whole window, and the session that replaces
    /// it inherits the same shape rather than jumping a pane's width sideways
    /// the moment it connects.
    #[test]
    fn a_collapsed_launch_gives_the_wait_the_whole_window() {
        let mut app = app_with_tree();
        app.maximized = true;
        app.start_loading(&crate::commands::cloud_agent::tui::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(),
        });
        app.loading_step("Creating a cloud agent".into());

        let out = draw(&app, 100, 30);
        assert!(out.contains("Creating a cloud agent"), "steps:\n{out}");
        assert!(
            !out.contains("cloud agents "),
            "the tree pane's title should be gone:\n{out}"
        );
        // ⌥f is how it comes back, and the footer has to say so.
        assert!(out.contains("restore the tree"), "footer:\n{out}");
    }

    /// The footer carries the actions that apply where the cursor is, with help
    /// pinned right; everything else is behind `?`.
    #[test]
    fn the_footer_shows_the_actions_for_the_selected_row() {
        let mut app = app_with_tree();
        app.screen = Screen::Manage;
        app.cursor = app
            .rows()
            .iter()
            .position(|r| r.label == "nimble-otter")
            .unwrap();

        let out = draw(&app, 120, 30);
        let footer = last_drawn_line(&out);
        let footer = footer.as_str();
        assert!(footer.contains("connect"), "{footer}");
        assert!(footer.contains("new VM"), "{footer}");
        assert!(footer.contains("delete"), "{footer}");
        assert!(footer.contains("save bootstrap"), "{footer}");
        // The agent is running, so it offers sleep and not wake.
        assert!(footer.contains("sleep"), "{footer}");
        assert!(!footer.contains("wake"), "{footer}");
        // Help is pinned to the right edge.
        assert!(footer.trim_end().ends_with("keys"), "{footer}");
        assert!(
            footer.find("keys").unwrap() > footer.find("connect").unwrap(),
            "help should be right of the actions:\n{footer}"
        );
    }

    /// A sleeping agent offers wake instead — never both, since only one of
    /// them does anything.
    #[test]
    fn the_footer_offers_wake_for_a_sleeping_agent() {
        let mut app = app_with_tree();
        app.screen = Screen::Manage;
        if let Load::Loaded(agents) = &mut app.tree[0].projects[0].envs[0].agents {
            agents[0].status = "sleeping".into();
        }
        app.cursor = app
            .rows()
            .iter()
            .position(|r| r.label == "nimble-otter")
            .unwrap();

        let footer = last_drawn_line(&draw(&app, 120, 30));
        assert!(footer.contains("wake"), "{footer}");
        assert!(!footer.contains("sleep"), "{footer}");
    }

    /// On a project there is nothing to sleep or delete, so it says less.
    #[test]
    fn the_footer_is_shorter_on_a_project() {
        let mut app = app_with_tree();
        app.screen = Screen::Manage;
        // A project with no agents lives in the tail — the only place project
        // rows still exist.
        app.tree[0].projects.push(ProjectNode {
            id: "proj_2".into(),
            name: "sandbox".into(),
            expanded: false,
            envs: vec![EnvNode {
                id: "env_sand".into(),
                name: "production".into(),
                expanded: false,
                agents: Load::NotLoaded,
            }],
        });
        app.others_expanded = Some(true);
        app.cursor = app
            .rows()
            .iter()
            .position(|r| r.label == "sandbox")
            .unwrap();
        let footer = last_drawn_line(&draw(&app, 120, 30));
        assert!(footer.contains("new VM"), "{footer}");
        assert!(!footer.contains("delete"), "{footer}");
        assert!(footer.trim_end().ends_with("keys"), "{footer}");
    }

    /// `?` still carries everything the footer leaves out.
    #[test]
    fn the_overlay_has_the_rest() {
        let mut app = app_with_tree();
        app.screen = Screen::Manage;
        app.keys_open = true;
        // Two rows taller than before: the page margin trims the overlay's
        // room, and this list is exactly long enough to notice.
        let out = draw(&app, 100, 34);
        assert!(out.contains("keys"));
        assert!(out.contains("refresh"), "{out}");
        assert!(out.contains("⌥esc"), "{out}");
        assert!(out.contains("any key closes"));
    }

    /// Standing on an agent shows its cards, even while one of its sessions is
    /// open — the pane follows the selection, not merely what is running.
    #[test]
    fn the_launcher_stays_up_while_a_session_runs() {
        let mut app = app_with_tree();
        app.screen = Screen::Manage;
        if let Load::Loaded(agents) = &mut app.tree[0].projects[0].envs[0].agents {
            agents[0].expanded = true;
            agents[0].sessions = LoadSessions::Loaded(vec![
                crate::commands::cloud_agent::tui::app::ConsoleSession {
                    name: "claude-one".into(),
                    kind: "SHELL".into(),
                    command: None,
                    running: true,
                    attached: true,
                    created_at: None,
                    snapshot: None,
                },
            ]);
        }
        let mut pane =
            crate::commands::cloud_agent::tui::session::Session::for_test("ca_1", "nimble-otter")
                .unwrap();
        pane.durable_name = "claude-one".into();
        app.sessions = vec![pane];
        app.active = Some(0);
        app.focus = ManageFocus::Tree;
        // On the launcher, the prompt owns the pane even while a session runs
        // in the background.
        app.cursor = 0;
        let out = draw(&app, 110, 30);
        assert!(
            out.contains("Prompt"),
            "the launcher holds the pane:\n{out}"
        );
        assert!(
            !out.contains("╭ devtools / nimble-otter / claude-one"),
            "the running pane must not take over:\n{out}"
        );

        // Move onto the thread itself and the pane takes over, titled like a
        // project reference: project / agent / session.
        app.cursor = app
            .rows()
            .iter()
            .position(|r| r.label == "[S] claude-one")
            .unwrap();
        let out = draw(&app, 110, 30);
        assert!(
            out.contains("devtools / nimble-otter / claude-one"),
            "the session pane's title:\n{out}"
        );
    }

    /// Standing on a session that has no pane says so and offers the way
    /// back, instead of leaving whichever pane was connected last on screen.
    #[test]
    fn a_dropped_pane_wears_a_banner_on_top() {
        let mut app = app_with_tree();
        app.screen = Screen::Manage;
        let pane =
            crate::commands::cloud_agent::tui::session::Session::for_test("ca_1", "nimble-otter")
                .unwrap();
        app.sessions = vec![pane];
        app.active = Some(0);
        app.focus = ManageFocus::Session;
        app.sessions[0].end_dropped_for_test();

        // Focused: the pane's own keys are the offer.
        let out = draw(&app, 110, 30);
        assert!(
            out.contains("✕ disconnected — press r to reconnect · x closes"),
            "the banner names the recovery keys:\n{out}"
        );
        // The banner sits on the pane's first row — right under its title
        // border — not down in whatever half-line ssh's goodbye landed on.
        let title_line = out
            .lines()
            .position(|l| l.contains("devtools / nimble-otter"))
            .unwrap();
        let banner_line = out
            .lines()
            .position(|l| l.contains("✕ disconnected"))
            .unwrap();
        assert_eq!(
            banner_line,
            title_line + 1,
            "the banner belongs at the top of the pane:\n{out}"
        );

        // Unfocused: the keys named are the ones that would actually work.
        // The cursor moves off the launcher (which would show the welcome
        // pane instead) onto the dropped pane's own session row — which the
        // platform still lists, since only our connection died.
        app.focus = ManageFocus::Tree;
        if let Load::Loaded(agents) = &mut app.tree[0].projects[0].envs[0].agents {
            agents[0].sessions = LoadSessions::Loaded(vec![
                crate::commands::cloud_agent::tui::app::ConsoleSession {
                    name: "test".into(),
                    kind: "SHELL".into(),
                    command: None,
                    running: true,
                    attached: false,
                    created_at: None,
                    snapshot: None,
                },
            ]);
        }
        app.cursor = app
            .rows()
            .iter()
            .position(|r| r.label == "[S] test")
            .unwrap();
        let out = draw(&app, 110, 30);
        assert!(
            out.contains("✕ disconnected — click here (or enter on its row) to reconnect"),
            "the unfocused banner points at the mouse and the row:\n{out}"
        );
    }

    #[test]
    fn a_disconnected_session_says_so() {
        let mut app = app_with_tree();
        app.screen = Screen::Manage;
        if let Load::Loaded(agents) = &mut app.tree[0].projects[0].envs[0].agents {
            agents[0].expanded = true;
            agents[0].sessions = LoadSessions::Loaded(vec![
                crate::commands::cloud_agent::tui::app::ConsoleSession {
                    name: "claude-one".into(),
                    kind: "SHELL".into(),
                    command: None,
                    running: true,
                    attached: true,
                    created_at: None,
                    snapshot: None,
                },
                crate::commands::cloud_agent::tui::app::ConsoleSession {
                    name: "claude-two".into(),
                    kind: "SHELL".into(),
                    command: None,
                    running: true,
                    attached: false,
                    created_at: None,
                    snapshot: None,
                },
            ]);
        }
        // One pane is open, for the *other* session.
        let mut pane =
            crate::commands::cloud_agent::tui::session::Session::for_test("ca_1", "nimble-otter")
                .unwrap();
        pane.durable_name = "claude-one".into();
        app.sessions = vec![pane];
        app.active = Some(0);
        app.focus = ManageFocus::Tree;
        app.cursor = app
            .rows()
            .iter()
            .position(|r| r.label == "[S] claude-two")
            .unwrap();

        let out = draw(&app, 110, 30);
        assert!(
            !out.contains("╭ devtools / nimble-otter / claude-one"),
            "the other session's pane must not linger:\n{out}"
        );
        assert!(
            out.contains("not connected"),
            "the card says the session is disconnected:\n{out}"
        );
        assert!(
            out.contains("enter / double-click connects"),
            "the card says how to get it back:\n{out}"
        );
    }

    /// Typing past the bottom of the prompt scrolls it, rather than quietly
    /// hiding what is being typed.
    #[test]
    fn a_long_prompt_scrolls_to_the_cursor() {
        let mut app = app_with_tree();
        // Far more than the box can show at once.
        app.prompt = "fix the failing retry tests in the worker service and then \
             update the changelog and open a pull request describing what changed"
            .repeat(3);
        let out = draw(&app, 100, 40);
        // The tail is what matters: the end of the draft has to be on screen.
        // The last words rather than a whole phrase — the box wraps, and where
        // a line breaks is the box's business.
        assert!(
            out.contains("what changed"),
            "the end of the prompt should be visible:\n{out}"
        );
    }

    /// Every text attribute the emulator tracks survives into the drawn
    /// pane. Dim is the one that regressed: Claude Code's ghost text is
    /// plain SGR 2 with no colour of its own, so dropping it rendered the
    /// suggestion as ordinary text.
    #[test]
    fn emulator_attributes_reach_the_pane() {
        let mut parser = vt100::Parser::new(4, 40, 0);
        parser.process(b"plain \x1b[2mghost\x1b[22m \x1b[3mslant\x1b[23m \x1b[1mloud\x1b[22m");
        let lines = screen_lines(parser.screen(), false);
        let style_of = |word: &str| {
            lines[0]
                .spans
                .iter()
                .find(|span| span.content.contains(word))
                .unwrap_or_else(|| panic!("{word} is on screen"))
                .style
        };
        assert!(style_of("ghost").add_modifier.contains(Modifier::DIM));
        assert!(style_of("slant").add_modifier.contains(Modifier::ITALIC));
        assert!(style_of("loud").add_modifier.contains(Modifier::BOLD));
        assert!(style_of("plain").add_modifier.is_empty());
    }

    #[test]
    fn codex_shaded_rows_keep_truecolor_and_blank_cell_backgrounds() {
        use ratatui::widgets::Widget;

        for (shade, rgb) in [("48;48;48", (48, 48, 48)), ("245;245;245", (245, 245, 245))] {
            let mut parser = vt100::Parser::new(3, 20, 0);
            // Codex shades the whole prompt/plan row, including its padding,
            // then resets for the next row. EL paints empty cells as well.
            parser.process(
                format!("\x1b[48;2;{shade}m\x1b[2K  plan\x1b[0m\r\n\x1b[38;2;0;95;135maccent\x1b[0m plain")
                    .as_bytes(),
            );
            let area = Rect::new(0, 0, 20, 3);
            let mut buffer = ratatui::buffer::Buffer::empty(area);
            Paragraph::new(screen_lines(parser.screen(), false)).render(area, &mut buffer);

            for col in 0..20 {
                assert_eq!(buffer[(col, 0)].bg, Color::Rgb(rgb.0, rgb.1, rgb.2));
                assert_eq!(buffer[(col, 1)].bg, Color::Reset);
            }
            assert_eq!(buffer[(10, 0)].symbol(), " ");
            assert_eq!(buffer[(0, 1)].fg, Color::Rgb(0, 95, 135));
            assert_eq!(buffer[(7, 1)].fg, Color::Reset);
        }
    }

    /// A wide character owns two columns but is one glyph: its continuation
    /// cell must not become a phantom space that shifts the rest of the line
    /// right.
    #[test]
    fn wide_characters_keep_their_columns() {
        let mut parser = vt100::Parser::new(2, 10, 0);
        parser.process("\u{65e5}x".as_bytes());
        let lines = screen_lines(parser.screen(), false);
        let text: String = lines[0]
            .spans
            .iter()
            .map(|span| span.content.clone().into_owned())
            .collect();
        assert_eq!(text, "\u{65e5}x       ");
    }

    /// Wrapping arithmetic the scroll depends on.
    #[test]
    fn wrapped_lines_counts_rows() {
        assert_eq!(wrapped_lines("", 10), 1);
        assert_eq!(wrapped_lines("short", 10), 1);
        assert_eq!(wrapped_lines("one two three", 8), 2);
        // A word longer than the box hard-wraps rather than vanishing.
        assert!(wrapped_lines(&"x".repeat(25), 10) >= 3);
        assert_eq!(wrapped_lines("anything", 0), 1, "no divide by zero");
    }

    /// The task box is a fixed third of the pane, so a long task cannot drag
    /// the panel open and shove the steps to the margin.
    #[test]
    fn a_long_task_does_not_widen_the_loading_panel() {
        let mut app = app_with_tree();
        app.start_loading(&crate::commands::cloud_agent::tui::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: Some(
                "fix the failing retry tests in the worker service and update the changelog".into(),
            ),
            label: "devtools/production".into(),
            base: Default::default(),
        });
        app.loading_step("Creating a cloud agent".into());

        let out = draw(&app, 120, 30);
        // In char units throughout: the row is full of multi-byte glyphs, so a
        // byte offset from `find` would land mid-character and the arithmetic
        // would be quietly wrong.
        let chars: Vec<char> = out
            .lines()
            .find(|l| l.contains("Creating a cloud agent"))
            .unwrap()
            .chars()
            .collect();
        let needle: Vec<char> = "Creating a cloud agent".chars().collect();
        let text_at = chars
            .windows(needle.len())
            .position(|w| w == needle.as_slice())
            .expect("the step text");
        // The spinner marker is part of the block being centred.
        let block_start = text_at.saturating_sub(2);
        let left = (0..block_start).rev().find(|i| chars[*i] == '').unwrap();
        let right = (text_at + needle.len()..chars.len())
            .find(|i| chars[*i] == '')
            .unwrap();
        let gap_left = block_start - left - 1;
        let gap_right = right - (text_at + needle.len());
        assert!(
            gap_left.abs_diff(gap_right) <= 6,
            "the steps should stay centred: left {gap_left}, right {gap_right}\n{out}"
        );
    }

    /// A list of names is a list of names: no blank row under each one.
    #[test]
    fn wizard_rows_without_a_description_have_no_gap() {
        let mut app = app_with_tree();
        // A second environment, so "adjacent" means something.
        app.tree[0].projects[0].envs.push(EnvNode {
            id: "env_stg".into(),
            name: "staging".into(),
            expanded: false,
            agents: Load::NotLoaded,
        });
        app.skills_source = None;
        app.start_wizard(false);
        if let Some(w) = app.wizard.as_mut() {
            w.step = crate::commands::cloud_agent::tui::wizard::Step::Target;
            // Expand the workspace's only project to reveal its environments
            // — leaf rows carry no description.
            w.workspaces[0].projects[0].expanded = true;
        }

        let out = draw(&app, 100, 30);
        let lines: Vec<&str> = out.lines().collect();
        let first = lines
            .iter()
            .position(|l| l.contains("production"))
            .expect("the environment row");
        assert!(
            lines[first + 1].contains("staging"),
            "rows should be adjacent:\n{out}"
        );
    }

    /// The settings card shows every value beside its name, and the
    /// highlighted one wears the cycle arrows.
    #[test]
    fn the_settings_card_shows_values_in_place() {
        let mut app = app_with_tree();
        app.skills_source = Some("claude".into());
        app.skills_enabled = true;
        app.start_settings();

        let out = draw(&app, 100, 40);
        assert!(out.contains("Cloud agent settings"), "{out}");
        assert!(
            out.contains("‹ claude ›"),
            "the highlighted row cycles in place:\n{out}"
        );
        assert!(out.contains("on · claude"), "{out}");
        assert!(out.contains("Railway"), "the theme's label:\n{out}");
        assert!(out.contains("Run first-time setup again"), "{out}");
        assert!(
            out.contains("not set"),
            "no default project reads as such:\n{out}"
        );
        let lines: Vec<_> = out.lines().collect();
        let positions: Vec<_> = [
            "Coding agent",
            "Default project",
            "Skills sync",
            "Theme",
            "Full-screen tabs",
            "Run first-time setup again",
        ]
        .iter()
        .map(|label| lines.iter().position(|line| line.contains(label)).unwrap())
        .collect();
        assert!(
            positions.windows(2).all(|pair| pair[1] == pair[0] + 1),
            "one line per setting: {out}"
        );
        assert!(!out.contains("Previews as you cycle"));
        assert!(!out.contains("Copied to the agent at launch"));
        assert!(!out.contains("Where new cloud agents are created"));
    }

    /// The project row opens the wizard's question as a sub-card and comes
    /// straight back, rather than walking the rest of a flow.
    #[test]
    fn the_settings_project_picker_is_the_setup_question() {
        let mut app = app_with_tree();
        app.start_settings();
        if let Some(settings) = app.settings.as_mut() {
            settings.down(); // the project row
            settings.select(); // opens the picker
        }

        let out = draw(&app, 100, 40);
        assert!(out.contains("Where should agents live?"), "{out}");
        assert!(out.contains("devtools (production)"), "{out}");
        assert!(out.contains("Decide later"), "{out}");
    }

    /// A tree with nothing in it must not panic the renderer.
    #[test]
    fn manage_survives_an_empty_tree() {
        let mut app = App::new(Vec::new(), None, None, None, None, true);
        app.screen = Screen::Manage;
        let out = draw(&app, 80, 24);
        assert!(out.contains("RAILWAY CLOUD-AGENTS"));
    }

    /// The gate card: name and fingerprint each on their own line (together
    /// they outrun the card and wrap mid-fingerprint), and the answers in the
    /// same badge-and-label chords as the footers.
    #[test]
    fn the_ssh_gate_card_lays_out_key_and_answers() {
        use crate::commands::cloud_agent::tui::app::{SshGate, SshKeyOffer};
        let mut app = app_with_tree();
        app.ssh_gate = Some(SshGate {
            offer: SshKeyOffer {
                name: "raildesk-deploy".into(),
                fingerprint: "SHA256:hlDEs7CV5clc1lMfsMxr/CPeuKuJNn9hJxjsy1e9zLc".into(),
                public_key: "ssh-ed25519 AAAA test".into(),
            },
            then: None,
        });
        let out = draw(&app, 80, 30);
        assert!(out.contains("Register your SSH key with Railway?"), "{out}");
        assert!(out.contains(" y "), "{out}");
        assert!(out.contains("Yes — register this key"), "{out}");
        assert!(out.contains("No, not now"), "{out}");

        let name_line = out
            .lines()
            .position(|l| l.contains("raildesk-deploy"))
            .expect("key name shown");
        let fp_line = out
            .lines()
            .position(|l| l.contains("SHA256:hlDEs7CV5clc1lMfsMxr/CPeuKuJNn9hJxjsy1e9zLc"))
            .expect("full fingerprint shown, unwrapped");
        assert_eq!(fp_line, name_line + 1, "fingerprint sits under the name");

        // The answers are centered under the copy, not left-aligned with it.
        let col = |needle: &str| {
            out.lines()
                .find_map(|l| l.find(needle))
                .unwrap_or_else(|| panic!("{needle} not shown"))
        };
        assert!(
            col("Yes — register this key") > col("raildesk-deploy"),
            "the answers should sit centered, right of the left-aligned copy"
        );
    }
}