railwayapp 5.34.0

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

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, Paragraph, Wrap,
};

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

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

/// The column a menu card's name occupies, so the descriptions line up.
const LABEL_W: usize = 20;

/// The marker column plus the spaces either side of a card's name.
const CARD_GUTTER: usize = 3;

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

/// Footer chords: an inverse badge for the key, dim text for what it does.
/// Shared so the menu 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(Span::styled(
            format!(" {chord} "),
            Style::default()
                .fg(theme.on_accent)
                .bg(theme.accent_dim)
                .add_modifier(Modifier::BOLD),
        ));
        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_toast(app, f);
}

/// The corner confirmation, over whatever is underneath it.
///
/// Bottom right, clear of the key strip on the left of the same row and of the
/// `? keys` badge on its right — it sits a line above both.
fn render_toast(app: &App, f: &mut Frame) {
    let Some(toast) = app.toast.as_ref().filter(|toast| !toast.expired()) else {
        return;
    };
    let theme = app.theme;
    let area = f.area();
    let text = format!(" {}  {}  ", if toast.ok { "" } else { "" }, toast.text);
    let w = (text.chars().count() as u16 + 2).min(area.width);
    let h = 3.min(area.height);
    // 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.
    let rect = Rect {
        x: area.width.saturating_sub(w + 2),
        y: area.height.saturating_sub(h + 2),
        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(
            Block::default()
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_style(Style::default().fg(accent)),
        ),
        rect,
    );
}

fn render_screen(app: &App, f: &mut Frame, rects: &mut PaneRects) {
    match app.screen {
        Screen::Setup => {
            render_menu(app, f, rects);
            render_wizard(app, f);
        }
        Screen::Menu => render_menu(app, f, rects),
        Screen::Manage => render_manage(app, f, rects),
        Screen::TargetPick => {
            render_menu(app, f, rects);
            render_target_pick(app, f);
        }
        Screen::AgentPick => {
            render_menu(app, f, rects);
            render_agent_pick(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,
    }
}

fn render_menu(app: &App, f: &mut Frame, rects: &mut PaneRects) {
    let theme = app.theme;
    let area = f.area();
    let big = area.width >= BANNER_W + 8 && area.height >= 26;
    let banner_h = if big { BANNER_H } else { 1 };
    let prompt_h = if area.height >= 30 { 6 } else { 4 };
    let panel_w = 74.min(area.width.saturating_sub(2)).max(40.min(area.width));
    let cards = app.cards();
    // Descriptions cost rows, and on a short screen those rows come out of the
    // prompt box. Names only, rather than a menu with no prompt on it.
    let chrome = banner_h + prompt_h + 12;
    let mut block = card_block(&cards, panel_w as usize, true);
    if chrome + block.height(cards.len()) > area.height {
        block = card_block(&cards, panel_w as usize, false);
    }
    let cards_h = block.height(cards.len());
    let panel_h = chrome + cards_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), // subtitle
        Constraint::Length(1), // gap
        Constraint::Length(prompt_h),
        Constraint::Length(1), // gap
        Constraint::Length(cards_h),
        Constraint::Min(0),
        Constraint::Length(1), // target
        Constraint::Length(1), // gap
        Constraint::Length(1), // hint
    ])
    .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]);
    rects.prompt = whole(rows[6]);
    render_cards(app, f, rows[8], &block, rects);

    // Where the prompt lands, on its own line above the keys. 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[10],
    );

    let chords: &[(&str, &str)] = match app.menu_focus {
        MenuFocus::Prompt => &[
            ("enter", "launch"),
            ("shift+tab", "agent"),
            ("^t", "target"),
            ("⌥t", "theme"),
            ("⌥s", "setup"),
        ],
        MenuFocus::Cards => &[
            ("↑↓", "select"),
            ("enter", "open"),
            ("^t", "target"),
            ("⌥t", "theme"),
            ("⌥s", "setup"),
            ("q", "quit"),
        ],
    };
    f.render_widget(
        Paragraph::new(Line::from(chord_spans(theme, chords))).alignment(Alignment::Center),
        rows[12],
    );
}

/// `Target Project  name (environment)`, or an invitation to set one.
fn target_line(app: &App) -> Line<'static> {
    let theme = app.theme;
    let label = Span::styled(
        "Target Project  ",
        Style::default().fg(theme.dim).add_modifier(Modifier::BOLD),
    );
    match app.target.as_ref() {
        Some(target) => Line::from(vec![
            label,
            Span::styled(
                format!("{} ({})", target.project_name, target.environment_name),
                Style::default().fg(theme.accent),
            ),
        ]),
        None => Line::from(vec![
            label,
            Span::styled("not set", Style::default().fg(theme.pending)),
        ]),
    }
}

/// 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 = Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .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
    };

    const STEP_ROWS: u16 = 9;
    let task_h = match loading.prompt.as_deref() {
        // Three lines of task plus its border: a prompt is a sentence, and the
        // whole point of showing it is not making the user wonder what is
        // starting.
        Some(_) => 5,
        None => 0,
    };
    // Size the panel to its content and centre *that*, rather than letting it
    // span the pane: the steps read as a left-aligned block, and a block the
    // full width of the pane is a block pinned to its left border. The widest
    // line decides, so the group stays centred as steps arrive.
    let content_w = loading
        .steps
        .iter()
        .map(|step| step.chars().count() + 2)
        .chain(std::iter::once(loading.target.chars().count()))
        // The task is deliberately absent: it is a whole sentence, and letting
        // it set the width stretched the panel across the pane and pushed the
        // steps out to the left margin. It wraps inside a fixed box instead.
        .max()
        .unwrap_or(0)
        // A floor only so an empty panel is not a sliver; anything larger pads
        // the panel past its content and the centring visibly drifts left.
        .clamp(20, area.width.max(1) as usize) as u16;
    let panel = centered(content_w, (STEP_ROWS + task_h + 4).min(area.height), area);
    let rows = Layout::vertical([
        Constraint::Length(1), // title
        Constraint::Length(1), // target
        Constraint::Length(1), // gap
        Constraint::Length(task_h),
        Constraint::Length(STEP_ROWS),
        Constraint::Min(0),
        Constraint::Length(1), // hint
    ])
    .split(panel);

    f.render_widget(
        Paragraph::new(Line::from(vec![
            Span::styled(
                format!("{} ", spinner_frame(loading.tick)),
                Style::default().fg(theme.accent),
            ),
            Span::styled(
                loading.target.clone(),
                Style::default().fg(theme.fg).add_modifier(Modifier::BOLD),
            ),
        ]))
        .alignment(Alignment::Center),
        rows[0],
    );
    f.render_widget(
        Paragraph::new("preparing the agent")
            .alignment(Alignment::Center)
            .style(Style::default().fg(theme.dim)),
        rows[1],
    );

    if let Some(prompt) = loading.prompt.as_deref() {
        // A third of the pane, centred: a fixed frame the task wraps inside,
        // rather than a frame the task drags open.
        let task_area = centered((area.width / 3).max(24), task_h, rows[3]);
        f.render_widget(
            Paragraph::new(prompt.to_string())
                .block(
                    Block::default()
                        .borders(Borders::ALL)
                        .border_type(BorderType::Rounded)
                        .border_style(Style::default().fg(theme.accent_dim))
                        .title(Span::styled(" Task ", Style::default().fg(theme.dim))),
                )
                .style(Style::default().fg(theme.fg))
                .wrap(Wrap { trim: true }),
            task_area,
        );
    }

    f.render_widget(
        Paragraph::new(step_lines(app, rows[4].width)).wrap(Wrap { trim: false }),
        rows[4],
    );
}

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

/// Steps as lines: everything finished is ticked and dimmed, the newest is
/// live. Only the tail is kept, so the block never outgrows its box even on a
/// launch that reports a dozen things.
fn step_lines(app: &App, width: u16) -> Vec<Line<'static>> {
    let theme = app.theme;
    let steps = &app.loading.steps;
    const STEP_ROWS: usize = 9;

    // Each wrapped step costs more than one row; budget by estimated height so
    // the tail that is kept actually fits.
    let usable = width.saturating_sub(2).max(20) as usize;
    let mut budget = STEP_ROWS;
    let mut start = steps.len();
    for (i, step) in steps.iter().enumerate().rev() {
        let rows = step.chars().count().div_ceil(usable).max(1);
        if rows > budget {
            break;
        }
        budget -= rows;
        start = i;
    }

    let last = steps.len().saturating_sub(1);
    steps[start..]
        .iter()
        .enumerate()
        .map(|(offset, step)| {
            let i = start + offset;
            let (marker, style) = if i == last {
                (
                    format!("{} ", spinner_frame(app.loading.tick)),
                    Style::default().fg(theme.accent),
                )
            } else {
                ("".to_string(), Style::default().fg(theme.dim))
            };
            Line::from(vec![
                Span::styled(marker, style),
                Span::styled(step.clone(), style),
            ])
        })
        .collect()
}

fn render_prompt(app: &App, f: &mut Frame, area: Rect) {
    let theme = app.theme;
    let focused = app.menu_focus == MenuFocus::Prompt;
    let empty = app.prompt.is_empty();
    let (text, fg) = if empty && !focused {
        (
            "Fix a bug, scaffold a service, explain a repo…".to_string(),
            theme.dim,
        )
    } else if focused {
        (format!("{}", app.prompt), 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 {
        String::new()
    } else {
        format!(" {} ", app.prompt.chars().count())
    };

    let block = Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .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!(" {} ", app.harness_name()),
                Style::default()
                    .fg(if focused { theme.accent } else { theme.fg })
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled("shift+tab ", Style::default().fg(theme.dim)),
        ]))
        .title_bottom(
            Line::from(Span::styled(count, Style::default().fg(theme.dim))).right_aligned(),
        );

    // Keep the cursor line in view once the wrapped text outgrows the box.
    // Without this the box simply stops showing what is being typed, which is
    // the one thing it exists to do.
    let inner_w = area.width.saturating_sub(2).max(1) as usize;
    let inner_h = area.height.saturating_sub(2).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(Wrap { trim: false })
            .scroll((scroll_y, 0)),
        area,
    );
}

/// How many rows `text` occupies once wrapped at `width`, breaking on spaces
/// the way ratatui does and hard-wrapping a word that cannot fit.
fn wrapped_lines(text: &str, width: usize) -> usize {
    if width == 0 {
        return 1;
    }
    let mut rows = 1usize;
    let mut column = 0usize;
    for word in text.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
}

/// The menu's cards, centred as a block under the prompt.
///
/// Centred as a block, not line by line: each card is a name in a fixed column
/// followed by a sentence of a different length, so centring them individually
/// would leave the names in a ragged column down the middle.
/// The cards, laid out: how they wrap and how far in the block starts.
///
/// Computed before the layout as well as during the draw, because the number
/// of rows the cards need decides how much room the menu gives them.
struct CardBlock {
    /// Wrapped description lines, one list per card. Empty when the terminal is
    /// too narrow to carry the sentences at all.
    descriptions: Vec<Vec<String>>,
    indent: usize,
}

impl CardBlock {
    /// One line per description line, at least one per card, plus a blank
    /// between cards.
    fn height(&self, cards: usize) -> u16 {
        let text: usize = match self.descriptions.is_empty() {
            true => cards,
            false => self.descriptions.iter().map(|d| d.len().max(1)).sum(),
        };
        (text + cards) as u16
    }
}

/// Fit the cards to `width`.
///
/// Descriptions wrap into the column beside the name rather than widening the
/// block: the cards belong under the prompt box, and a block wider than the box
/// reads as a second, competing column. Where a wrapped sentence would be
/// shredded — or where the screen is too short to hold the extra rows, which
/// the caller decides with `descriptions` — the names stand alone.
fn card_block(
    cards: &[(&'static str, &'static str)],
    width: usize,
    descriptions: bool,
) -> CardBlock {
    let names = || CardBlock {
        descriptions: Vec::new(),
        indent: width
            .saturating_sub(
                cards
                    .iter()
                    .map(|(label, _)| 2 + label.chars().count())
                    .max()
                    .unwrap_or(0),
            )
            .div_euclid(2),
    };

    let desc_w = width.saturating_sub(LABEL_W + CARD_GUTTER);
    if !descriptions || desc_w < 24 {
        return names();
    }
    let descriptions: Vec<Vec<String>> = cards
        .iter()
        .map(|(_, desc)| wrap_words(desc, desc_w))
        .collect();
    let content = LABEL_W
        + CARD_GUTTER
        + descriptions
            .iter()
            .flatten()
            .map(|line| line.chars().count())
            .max()
            .unwrap_or(0);
    CardBlock {
        descriptions,
        indent: width.saturating_sub(content) / 2,
    }
}

/// Break `text` on spaces at `width`, hard-splitting nothing — a word longer
/// than the column simply overhangs, which cannot happen with the copy here and
/// is better than a name broken in half if it ever does.
fn wrap_words(text: &str, width: usize) -> Vec<String> {
    let mut lines: Vec<String> = Vec::new();
    let mut line = String::new();
    let mut column = 0usize;
    for word in text.split_whitespace() {
        let len = word.chars().count();
        if column > 0 && column + 1 + len > width {
            lines.push(std::mem::take(&mut line));
            column = 0;
        }
        if column > 0 {
            line.push(' ');
            column += 1;
        }
        line.push_str(word);
        column += len;
    }
    if !line.is_empty() {
        lines.push(line);
    }
    lines
}

fn render_cards(app: &App, f: &mut Frame, area: Rect, block: &CardBlock, rects: &mut PaneRects) {
    let theme = app.theme;
    let cards = app.cards();
    let indent = " ".repeat(block.indent);
    rects.cards = Default::default();

    let mut lines: Vec<Line> = Vec::new();
    for (i, (label, _)) in cards.iter().enumerate() {
        // The card's own rows, not the blank after it: a click in the gap
        // between two cards should pick neither.
        if let Some(slot) = rects.cards.get_mut(i) {
            let height = block
                .descriptions
                .get(i)
                .map(|d| d.len().max(1))
                .unwrap_or(1);
            *slot = PaneBox {
                x: area.x,
                y: area.y + lines.len() as u16,
                w: area.width,
                h: height as u16,
            };
        }
        let on = app.menu_focus == MenuFocus::Cards && i == app.card;
        let (fg, bg) = if on {
            (theme.on_accent, theme.accent)
        } else {
            (theme.fg, Color::Reset)
        };
        let desc = block.descriptions.get(i);
        let dim = Style::default().fg(if on { theme.fg } else { theme.dim });

        lines.push(Line::from(vec![
            Span::raw(indent.clone()),
            Span::styled(
                if on { "" } else { " " },
                Style::default().fg(theme.accent),
            ),
            Span::styled(
                match desc.is_some() {
                    true => format!(" {label:<LABEL_W$}"),
                    false => format!(" {label}"),
                },
                Style::default().fg(fg).bg(bg).add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                match desc.and_then(|lines| lines.first()) {
                    Some(first) => format!(" {first}"),
                    None => String::new(),
                },
                dim,
            ),
        ]));
        // Continuations line up under the first line of the description, not
        // under the name — the two columns stay two columns.
        for line in desc.map(|d| &d[1.min(d.len())..]).unwrap_or(&[]) {
            lines.push(Line::from(vec![
                Span::raw(format!(
                    "{indent}{:width$}",
                    "",
                    width = LABEL_W + CARD_GUTTER
                )),
                Span::styled(line.clone(), dim),
            ]));
        }
        lines.push(Line::from(""));
    }
    f.render_widget(Paragraph::new(lines), area);
}

/// 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,
) -> Option<(u16, u16)> {
    let area = area?;
    // Maximized there is no tree to leave room for, so no minimum width to
    // meet either.
    if !maximized && area.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 = area.height.saturating_sub(3).saturating_sub(2).max(1);
    let tree = if maximized { 0 } else { TREE_W };
    let cols = area.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 = f.area();
    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 header = Line::from(vec![
        Span::styled(
            " RAILWAY CLOUD-AGENTS ",
            Style::default()
                .fg(theme.on_accent)
                .bg(theme.accent)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            if app.status.is_empty() {
                String::new()
            } else {
                format!("  ·  {}", app.status)
            },
            Style::default().fg(theme.dim),
        ),
    ]);
    f.render_widget(Paragraph::new(header), chunks[0]);

    // Detail is fixed-width so the tree keeps the space it needs on a narrow
    // terminal; below that there is no room for two panes at all.
    // The tree is a fixed, narrow column and the right pane takes everything
    // else — the detail (and, later, a live session) is what you are actually
    // looking at, and a tree that grows with the window just pads names with
    // whitespace.
    // ⌥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 full = app.maximized && app.active_session().is_some();
    let two_pane = !full && chunks[2].width >= 70;
    let panes = if two_pane {
        Layout::horizontal([Constraint::Length(TREE_W), Constraint::Min(20)]).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();
        if let Some(session) = app.active_session() {
            render_session(app, session, f, pane);
        }
        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)))
        .collect();
    let mut state = ListState::default();
    state.select(if rows.is_empty() {
        None
    } else {
        Some(app.cursor)
    });
    f.render_stateful_widget(
        List::new(items)
            .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(" projects ", 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]);
        // 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. Typing in a session is the exception — the pane it has
        // the keyboard in cannot vanish from under it.
        let show_session = app.focus == ManageFocus::Session
            || matches!(
                app.selected_row().map(|row| row.kind),
                Some(RowKind::Session(..))
            );
        if app.loading.active {
            render_loading(app, f, panes[1]);
        } else {
            match app.active_session().filter(|_| show_session) {
                Some(session) => render_session(app, session, f, panes[1]),
                None => f.render_widget(
                    Paragraph::new(detail_lines(app)).block(
                        Block::default()
                            .borders(Borders::ALL)
                            .border_type(BorderType::Rounded)
                            .border_style(Style::default().fg(theme.accent_dim))
                            .title(Span::styled(" agent ", Style::default().fg(theme.dim))),
                    ),
                    panes[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;
    // 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.maximized {
        vec![
            ("⌥f", "restore the tree"),
            ("shift+esc / ^]", "stop typing"),
        ]
    } else if app.focus == ManageFocus::Session {
        let mut keys = vec![("shift+esc / ^]", "stop typing"), ("⌥f", "maximize")];
        // 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) {
            Some(RowKind::Session(..)) => vec![
                ("enter", "connect"),
                ("⌥f", "maximize"),
                ("shift+enter", "full screen"),
                ("c", "copy ssh"),
                ("x", "end session"),
                if sleeping {
                    ("w", "wake")
                } else {
                    ("s", "sleep")
                },
                ("d", "delete agent"),
            ],
            Some(RowKind::Agent(..)) => vec![
                ("enter", "connect"),
                ("n", "new session"),
                if sleeping {
                    ("w", "wake")
                } else {
                    ("s", "sleep")
                },
                ("d", "delete agent"),
            ],
            _ => vec![("enter", "open"), ("n", "new agent")],
        }
    };
    // 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(("⌥]", "next 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![
            Span::styled(
                " ? ",
                Style::default()
                    .fg(theme.on_accent)
                    .bg(theme.accent_dim)
                    .add_modifier(Modifier::BOLD),
            ),
            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 = 66.min(area.width.saturating_sub(4));
    let height = (body_h + dots_h + 7).min(area.height.saturating_sub(2));
    let outer = centered(width, height, area);
    f.render_widget(Clear, outer);

    let block = Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(theme.accent))
        .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],
        );
    }

    let mut lines: Vec<Line> = Vec::with_capacity(panel.rows.len() * 2);
    for (i, row) in panel.rows.iter().enumerate() {
        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),
                Style::default().fg(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,
        f.area(),
        Panel {
            title: "setup",
            heading: wizard.title(),
            position: wizard.position(),
            rows: &rows,
            cursor: wizard.cursor,
            footer,
        },
    );
}

/// Choosing which agent a new session goes on. Only drawn when there is more
/// than one to choose between.
fn render_agent_pick(app: &App, f: &mut Frame) {
    let Some(picker) = app.agent_pick.as_ref() else {
        return;
    };
    let theme = app.theme;
    let rows: Vec<PanelRow> = picker
        .rows()
        .into_iter()
        .map(|(label, tag)| PanelRow {
            label,
            tag,
            detail: String::new(),
        })
        .collect();
    let footer = Line::from(chord_spans(
        theme,
        &[
            ("↑↓", "choose"),
            ("enter", "new session"),
            ("esc", "cancel"),
        ],
    ));

    render_panel(
        f,
        theme,
        f.area(),
        Panel {
            title: "new session",
            heading: "Which cloud agent?",
            position: None,
            rows: &rows,
            cursor: picker.cursor,
            footer,
        },
    );
}

/// 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,
        f.area(),
        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 = f.area();

    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(
            format!(" {group}"),
            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 width = 52.min(area.width.saturating_sub(4));
    let height = (lines.len() as u16 + 2).min(area.height.saturating_sub(2));
    let panel = centered(width, height, area);
    f.render_widget(Clear, panel);
    f.render_widget(
        Paragraph::new(lines).block(
            Block::default()
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_style(Style::default().fg(theme.accent))
                .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;
    let title = format!(" {} · {} ", session.agent_name, session.durable_name);
    let block = Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .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() {
                " session ended "
            } 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);

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

/// 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 {
            let (text, mut style) = match screen.cell(row, col) {
                Some(cell) => (
                    {
                        let c = cell.contents();
                        if c.is_empty() { " ".to_string() } else { c }
                    },
                    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);
    }
    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.
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) -> Line<'static> {
    let indent = "  ".repeat(row.depth);
    let mut spans = vec![Span::raw(indent)];

    match (&row.kind, row.expanded) {
        (RowKind::Agent(..), _) => {
            let status = row.status.clone().unwrap_or_default();
            spans.push(Span::styled(
                format!("{} ", status_glyph(&status)),
                Style::default().fg(status_color(theme, &status)),
            ));
            spans.push(Span::styled(
                row.label.clone(),
                Style::default().fg(theme.fg),
            ));
        }
        (RowKind::Session(..), _) => {
            // The marker is the state: a filled dot when this UI has it open,
            // a quiet branch when it is only running on the agent.
            let connected = row.status.is_some();
            spans.push(Span::styled(
                if connected { "" } else { "" },
                Style::default().fg(if connected { theme.running } else { theme.dim }),
            ));
            spans.push(Span::styled(
                row.label.clone(),
                Style::default().fg(theme.fg),
            ));
        }
        (RowKind::Separator, _) => spans.push(Span::styled(
            "".repeat(TREE_W.saturating_sub(4) as usize),
            Style::default().fg(theme.accent_dim),
        )),
        (RowKind::Note(..), _) => spans.push(Span::styled(
            row.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(row.label.clone(), style));
        }
        _ => spans.push(Span::raw(row.label.clone())),
    }

    if !row.note.is_empty() && !matches!(row.kind, RowKind::Agent(..)) {
        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 {
        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(vec![
                    Span::styled(
                        format!("  {} {}", status_glyph(&status), status),
                        Style::default().fg(status_color(theme, &status)),
                    ),
                    Span::styled(
                        format!("  ·  {}/{}", proj.name, env.name),
                        Style::default().fg(theme.dim),
                    ),
                ]),
                Line::from(""),
            ];

            // A card per session: what it is, and the last thing it said. The
            // last line is only knowable for a session we have a pane for —
            // the platform reports state, not output — so an unattached one
            // says how to get its output rather than pretending to have it.
            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 sessions running",
                            Style::default().fg(theme.dim),
                        )));
                        lines.push(Line::from(""));
                        lines.push(Line::from(Span::styled(
                            "  n starts one",
                            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.name.clone(),
                                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 — enter 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 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(
                    "  → to load its sessions",
                    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()),
            ]
        }
        RowKind::Session(w, p, e, a, i) => {
            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.
            if let Load::Loaded(agents) = &app.tree[w].projects[p].envs[e].agents
                && let Some(agent) = agents.get(a)
                && let LoadSessions::Loaded(sessions) = &agent.sessions
                && let Some(session) = sessions.get(i)
            {
                lines.push(Line::from(""));
                lines.push(kv(
                    "state",
                    session_state(app, &session.name, session.running).to_string(),
                ));
                lines.push(kv("kind", session.kind.to_lowercase()));
                lines.push(Line::from(""));
                lines.push(Line::from(Span::styled(
                    format!(" {}", session.command_summary()),
                    Style::default().fg(theme.fg),
                )));
            }
            lines.push(Line::from(""));
            lines.push(Line::from(Span::styled(
                " enter reattaches in the pane",
                Style::default().fg(theme.dim),
            )));
            lines
        }
        RowKind::Separator | RowKind::Note(..) => 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 {
            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,
        )
    }

    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")
    }

    /// 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 menu's footer uses the same chord badges as the manage screen, so
    /// the two read as one product rather than two conventions.
    #[test]
    fn the_menu_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 menu footer");
        assert!(footer.contains("enter"), "{footer}");
        assert!(footer.contains("target"), "{footer}");
        assert!(footer.contains("theme"), "{footer}");
        assert!(footer.contains("setup"), "{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}");
    }

    /// The cards are a place to point at, not a list of commands: no key
    /// badges, and nothing that reads like one.
    #[test]
    fn the_menu_cards_carry_no_key_badges() {
        let app = app_with_tree();
        let out = draw(&app, 100, 40);
        let card = out
            .lines()
            .find(|l| l.contains("New Session"))
            .expect("the New Session card");
        assert!(!card.contains(" n "), "no key badge: {card}");

        let card = out
            .lines()
            .find(|l| l.contains("Manage Cloud Agents"))
            .expect("the Manage card");
        assert!(!card.contains(" m "), "no key badge: {card}");
    }

    /// Every card, including the first-run Setup one.
    const CARD_LINES: &[&str] = &[
        "New Session",
        "New Cloud Agent",
        "Manage Cloud Agents",
        "Setup",
    ];

    /// The cards sit under the middle of the prompt box, as a block — the names
    /// stay in one column rather than being centred line by line.
    #[test]
    fn the_menu_cards_are_centred_as_a_block() {
        let mut app = app_with_tree();
        app.configured = false;
        let width = 100u16;
        let out = draw(&app, width, 40);

        let starts: Vec<usize> = out
            .lines()
            .filter(|l| CARD_LINES.iter().any(|card| l.contains(card)))
            .map(|l| l.len() - l.trim_start().len())
            .collect();
        assert_eq!(starts.len(), 4, "three cards plus setup");
        assert!(
            starts.iter().all(|s| *s == starts[0]),
            "one left edge, not three: {starts:?}"
        );

        // And the block as a whole sits on the middle of the screen.
        let right_edge = out
            .lines()
            .filter(|l| CARD_LINES.iter().any(|card| l.contains(card)))
            .map(|l| l.trim_end().chars().count())
            .max()
            .expect("a card");
        let middle = (starts[0] + right_edge) / 2;
        assert!(
            middle.abs_diff(width as usize / 2) <= 2,
            "the block should be centred: {starts:?}..{right_edge} on {width}"
        );
    }

    /// Setup is on the menu only while there is nothing set up; after that it
    /// is the ⌥s in the footer, which is there either way.
    #[test]
    fn setup_is_a_card_only_on_a_first_run() {
        let mut app = app_with_tree();
        let out = draw(&app, 100, 40);
        assert!(!out.contains("Default agent, skills"), "{out}");
        assert!(out.contains("setup"), "the chord is still offered:\n{out}");

        app.configured = false;
        let out = draw(&app, 100, 40);
        assert!(out.contains("Default agent, skills"), "{out}");
    }

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

    /// 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 clickable boxes have to be where the cards actually drew, or a click
    /// lands on the wrong one — the only way to know is to read them out of a
    /// real frame.
    #[test]
    fn the_recorded_card_boxes_match_the_drawn_rows() {
        use crate::commands::cloud_agent::tui::app::PaneRects;

        let mut app = app_with_tree();
        app.configured = false; // all four cards
        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();

        for (i, (label, _)) in app.cards().iter().enumerate() {
            let drawn = lines
                .iter()
                .position(|l| l.contains(label))
                .unwrap_or_else(|| panic!("{label} was not drawn"));
            let box_ = rects.cards[i];
            assert_eq!(
                box_.y as usize, drawn,
                "{label}: recorded at {}, drawn at {drawn}",
                box_.y
            );
            assert!(box_.h >= 1, "{label} has no clickable height");
            // A wrapped description is part of the same card.
            let wrapped = out
                .lines()
                .nth(drawn + 1)
                .is_some_and(|l| !l.trim().is_empty() && !CARD_LINES.iter().any(|c| l.contains(c)));
            assert_eq!(
                box_.h >= 2,
                wrapped,
                "{label}: height {} does not match its wrapping",
                box_.h
            );
        }

        // And the prompt box is where it was drawn.
        let prompt = lines
            .iter()
            .position(|l| l.contains("╭ Prompt"))
            .expect("the prompt box");
        assert_eq!(rects.prompt.y as usize, prompt);
    }

    /// 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.
    #[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}");
        assert!(
            lines[lines.len() - 1].contains("keys"),
            "the key strip is untouched: {}",
            lines[lines.len() - 1]
        );
        assert!(
            lines[row + 1].contains("") && !lines[row + 1].contains("Copied"),
            "the toast is closed above the pane border: {}",
            lines[row + 1]
        );
    }

    /// 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.starts_with(""))
            .expect("the pane's bottom border");
        assert!(!border.contains("to leave"), "{border}");
        assert!(
            out.lines().next_back().unwrap().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("projects"), "the tree is there first");

        app.maximized = true;
        let out = draw(&app, 100, 30);
        assert!(!out.contains(" projects "), "the tree is gone:\n{out}");
        assert!(!out.contains("devtools"), "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(0),
            "the pane starts at the 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).unwrap();
        let (_, full) = session_pane_size(size, true).unwrap();
        assert_eq!(split, 100 - TREE_W - 2);
        assert_eq!(full, 98);

        // 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).is_none());
        assert!(session_pane_size(narrow, true).is_some());
    }

    /// Choosing which agent a new session goes on is the same card, so the two
    /// questions look like one flow.
    #[test]
    fn the_agent_picker_lists_the_agents_with_their_status() {
        use crate::commands::cloud_agent::tui::app::AgentPicker;

        let mut app = app_with_tree();
        app.agent_pick = Some(AgentPicker {
            options: vec![
                ("ca_1".into(), "nimble-otter".into(), "running".into()),
                ("ca_2".into(), "brisk-heron".into(), "sleeping".into()),
            ],
            cursor: 0,
        });
        app.screen = Screen::AgentPick;
        let out = draw(&app, 100, 34);
        assert!(out.contains("Which cloud agent?"), "{out}");
        assert!(out.contains("nimble-otter"), "{out}");
        assert!(out.contains("sleeping"), "the status rides along: {out}");
        assert!(out.contains("new session"), "{out}");
    }

    /// The descriptions are longer than the prompt box is wide, so they wrap
    /// into the column beside the name — the block never grows past the box.
    #[test]
    fn card_descriptions_wrap_inside_the_prompt_box() {
        let app = app_with_tree();
        for width in [120u16, 100, 90, 80, 60] {
            let out = draw(&app, width, 44);
            let lines: Vec<&str> = out.lines().collect();

            let box_left = lines
                .iter()
                .find(|l| l.contains("╭ Prompt"))
                .map(|l| l.chars().position(|c| c == '').unwrap())
                .expect("the prompt box");
            let box_right = lines
                .iter()
                .find(|l| l.contains("╭ Prompt"))
                .map(|l| l.chars().position(|c| c == '').unwrap())
                .expect("the prompt box");

            // Every card line, continuations included, lives inside the box.
            for line in lines
                .iter()
                .filter(|l| CARD_LINES.iter().any(|card| l.contains(card)) || l.contains("project"))
            {
                let start = line.len() - line.trim_start().len();
                let end = line.trim_end().chars().count();
                assert!(
                    start >= box_left && end <= box_right + 1,
                    "at {width}: {start}..{end} outside {box_left}..{box_right}\n{line}"
                );
            }

            // And the sentence still arrives in full, across however many lines
            // it took.
            let text: String = lines
                .join(" ")
                .split_whitespace()
                .collect::<Vec<_>>()
                .join(" ");
            assert!(
                text.contains("Create a new session on a Cloud Agent in your default project"),
                "at {width}: the description was lost\n{out}"
            );
        }
    }

    /// Below the width where even a wrapped sentence would be shredded, the
    /// names stand alone.
    #[test]
    fn very_narrow_cards_keep_their_names_and_lose_the_descriptions() {
        let app = app_with_tree();
        let out = draw(&app, 46, 40);
        assert!(out.contains("New Session"), "{out}");
        assert!(out.contains("Manage Cloud Agents"), "{out}");
        assert!(!out.contains("Create a new"), "{out}");
        assert!(
            out.lines().all(|l| l.trim_end().chars().count() <= 46),
            "nothing runs off the edge:\n{out}"
        );
    }

    #[test]
    fn wrap_words_breaks_on_spaces_and_keeps_every_word() {
        let wrapped = wrap_words("Create a new Cloud Agent in your default project", 20);
        assert!(wrapped.len() > 1, "{wrapped:?}");
        assert!(
            wrapped.iter().all(|l| l.chars().count() <= 20),
            "{wrapped:?}"
        );
        assert_eq!(
            wrapped.join(" "),
            "Create a new Cloud Agent in your default project"
        );
        assert_eq!(wrap_words("", 20), Vec::<String>::new());
    }

    /// Below the banner threshold the screen still has to be usable — a
    /// terminal that small is common inside a split pane.
    #[test]
    fn menu_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);
        assert!(out.contains("Railway"));
        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}"
        );
    }

    /// 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;
        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, over the menu — one list of
    /// places to run, not a trip through the management tree.
    #[test]
    fn the_target_picker_is_a_card_over_the_menu() {
        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}");
        assert!(
            !out.contains("╭ agents"),
            "the management tree must not be behind it:\n{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(),
        });
        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}"
        );
    }

    /// 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 = out.lines().last().unwrap();
        assert!(footer.contains("connect"), "{footer}");
        assert!(footer.contains("new session"), "{footer}");
        assert!(footer.contains("delete agent"), "{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 = draw(&app, 120, 30).lines().last().unwrap().to_string();
        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;
        app.cursor = app
            .rows()
            .iter()
            .position(|r| r.label == "devtools")
            .unwrap();
        let footer = draw(&app, 120, 30).lines().last().unwrap().to_string();
        assert!(footer.contains("new agent"), "{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;
        let out = draw(&app, 100, 30);
        assert!(out.contains("keys"));
        assert!(out.contains("refresh"), "{out}");
        assert!(out.contains("shift+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 an_agent_shows_its_cards_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,
                },
            ]);
        }
        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 == "nimble-otter")
            .unwrap();

        let out = draw(&app, 110, 30);
        assert!(
            out.contains("claude-one"),
            "the card names the session:\n{out}"
        );
        assert!(
            out.contains("running") || out.contains("attached"),
            "the card carries its state:\n{out}"
        );

        // Move onto the session itself and the pane takes over.
        app.cursor = app
            .rows()
            .iter()
            .position(|r| r.label == "claude-one")
            .unwrap();
        let out = draw(&app, 110, 30);
        assert!(
            out.contains("nimble-otter · claude-one"),
            "the session pane's title:\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.
        assert!(
            out.contains("describing what changed"),
            "the end of the prompt should be visible:\n{out}"
        );
    }

    /// 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(),
        });
        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 project, so "adjacent" means something.
        app.tree[0].projects.push(ProjectNode {
            id: "proj_2".into(),
            name: "mono".into(),
            expanded: false,
            envs: vec![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::ProjectPick;
        }

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