trusty-mpm 1.8.2

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
//! Unit coverage for the `tm ls` session TUI (#7224).
//!
//! Why: a TUI's failure modes are silent — a selection that jumps after a
//! refresh, a confirm step a stray key skips, a column set that wraps at 80
//! columns. Every one of those is decidable from a pure function or a
//! `TestBackend` frame, so none of them needs a terminal to catch.
//!
//! What: the width-driven column layout, the scroll window, the whole state
//! machine (navigation, the delete confirm and its self-session guard, the
//! shared rename validator), the delete-outcome wording, the key mapping, and
//! `TestBackend` renders at 80x24, 200x50, and 20x5.

use std::path::{Path, PathBuf};

use ratatui::{Terminal, backend::TestBackend};
use trusty_mpm::client::ManagedSessionSummary;
use trusty_mpm::project::{Project, local_checkout_for};
use trusty_mpm::session_manager::rename::validate_session_name;

use super::layout::{self, Column};
use super::new_session::{
    self, NewProject, NewSessionFlow, NewSessionRequest, ProjectIdentity, Step, Target,
};
use super::render;
use super::state::{Action, Input, Mode, Severity, TuiState, is_self_session};
use super::{delete_outcome, map_key};
use crate::commands::picker_delete::DeleteReport;
use crate::commands::tmux_attach::AttachOutcome;

/// Minimal `ManagedSessionSummary` fixture.
fn session(name: &str, state: &str, slot: u32) -> ManagedSessionSummary {
    ManagedSessionSummary {
        id: format!("{name}-id"),
        name: name.to_string(),
        state: state.to_string(),
        persisted_state: None,
        workspace_path: None,
        repo_url: None,
        branch: None,
        created_at: None,
        last_activity_at: None,
        pending_decision: None,
        proposed_default: None,
        source_id: None,
        task: None,
        cwd: None,
        claude_session_id: None,
        deliverable_id: None,
        pane_id: None,
        injection_status: None,
        unresumable: false,
        stale_assets: false,
        stale_assets_unchecked: false,
        attached: false,
        slot,
        deleted: false,
        auto_resume_parked: None,
        kind: None,
    }
}

/// A three-row fleet: one active, one stopped, one attached.
fn fleet() -> Vec<ManagedSessionSummary> {
    let mut a = session("tm-alpha-01", "active", 1);
    a.source_id = Some("bobmatnyc/trusty-tools".to_string());
    a.pane_id = Some("%11".to_string());
    let b = session("tm-bravo-02", "stopped", 2);
    let mut c = session("tm-charlie-03", "active", 3);
    c.attached = true;
    vec![a, b, c]
}

/// A state browsing `fleet()`, outside any managed pane.
fn browsing() -> TuiState {
    let mut state = TuiState::new(None, None);
    state.sync(&fleet());
    state
}

// ── layout: which columns fit (#7224 requirement 2) ─────────────────────────

#[test]
fn layout_columns_full_set_at_wide_width() {
    assert_eq!(
        layout::visible_columns(200),
        vec![
            Column::Name,
            Column::Id,
            Column::Project,
            Column::State,
            Column::Tmux
        ]
    );
}

#[test]
fn layout_columns_drops_tmux_then_id_at_eighty() {
    // 80 columns fits name + state + project but neither id nor tmux, and the
    // survivors still come back in DISPLAY order, not priority order.
    assert_eq!(
        layout::visible_columns(80),
        vec![Column::Name, Column::Project, Column::State]
    );
    // The full set costs exactly 92 (marker 2 + 28 + 8 + 24 + 18 + 8 + four
    // gutters); one column short of that drops only TMUX, the lowest priority.
    assert_eq!(
        layout::visible_columns(91),
        vec![Column::Name, Column::Id, Column::Project, Column::State]
    );
    assert_eq!(
        layout::visible_columns(92),
        vec![
            Column::Name,
            Column::Id,
            Column::Project,
            Column::State,
            Column::Tmux
        ],
        "92 is the exact width the full set fits in"
    );
}

#[test]
fn layout_columns_keeps_name_at_absurdly_narrow_width() {
    // A row with no name is not a row anyone can act on, so NAME survives even
    // when it cannot be drawn in full.
    for width in [0u16, 1, 5, 20] {
        assert_eq!(
            layout::visible_columns(width),
            vec![Column::Name],
            "width {width}"
        );
    }
}

// ── layout: cell contents ───────────────────────────────────────────────────

#[test]
fn layout_cell_shortens_the_id_without_an_ellipsis() {
    let s = session("tm-alpha-01", "active", 1);
    let cell = layout::cell(Column::Id, &s);
    assert_eq!(cell.chars().count(), layout::SHORT_ID_LEN);
    assert!(
        !cell.contains('…'),
        "a short id must stay pasteable: {cell}"
    );
    assert!(s.id.starts_with(&cell));
}

#[test]
fn layout_cell_truncates_a_long_name_with_an_ellipsis() {
    let s = session(&"x".repeat(80), "active", 1);
    let cell = layout::cell(Column::Name, &s);
    assert_eq!(cell.chars().count(), layout::width(Column::Name) as usize);
    assert!(cell.ends_with('…'), "expected an ellipsis, got {cell}");
}

#[test]
fn layout_cell_placeholders_absent_project_and_pane() {
    let s = session("tm-alpha-01", "active", 1);
    assert_eq!(layout::cell(Column::Project, &s), "-");
    assert_eq!(layout::cell(Column::Tmux, &s), "-");
}

#[test]
fn layout_cell_state_uses_the_shared_annotations() {
    let mut s = session("tm-alpha-01", "stopped", 1);
    s.unresumable = true;
    assert!(layout::state_cell(&s).contains("[dead]"));
    let mut attached = session("tm-charlie-03", "active", 3);
    attached.attached = true;
    assert_eq!(layout::state_cell(&attached), "attached");
}

// ── layout: the scroll window ───────────────────────────────────────────────

#[test]
fn window_keeps_selection_visible_scrolling_down() {
    // 20 rows, a 5-row viewport, selection at 12: the window must contain 12.
    let (start, len) = layout::visible_window(20, 12, 5, 0);
    assert_eq!(len, 5);
    assert!((start..start + len).contains(&12), "start {start}");
}

#[test]
fn window_holds_still_while_the_selection_stays_visible() {
    // Selection moves from 7 to 6 inside the window [5,9]; the window must not
    // scroll, or the whole table jitters on every arrow key.
    assert_eq!(layout::visible_window(20, 6, 5, 5), (5, 5));
}

#[test]
fn window_clamps_to_the_end_of_the_list() {
    // A stale offset past the end (the list shrank) must not index out of range.
    let (start, len) = layout::visible_window(6, 5, 5, 99);
    assert_eq!((start, len), (1, 5));
    assert!(start + len <= 6);
}

#[test]
fn window_zero_height_is_empty() {
    assert_eq!(layout::visible_window(20, 3, 0, 0), (0, 0));
    assert_eq!(layout::visible_window(0, 0, 10, 0), (0, 0));
}

// ── state: navigation ───────────────────────────────────────────────────────

#[test]
fn state_navigation_moves_and_clamps_at_both_ends() {
    let sessions = fleet();
    let mut state = browsing();
    assert_eq!(state.selected(), 0);
    assert_eq!(state.apply(Input::Down, &sessions), Action::Redraw);
    assert_eq!(state.selected(), 1);
    assert_eq!(state.apply(Input::End, &sessions), Action::Redraw);
    assert_eq!(state.selected(), 2);
    // Already at the last row: nothing changed, so no redraw is owed.
    assert_eq!(state.apply(Input::Down, &sessions), Action::Ignore);
    assert_eq!(state.apply(Input::Home, &sessions), Action::Redraw);
    assert_eq!(state.selected(), 0);
    assert_eq!(state.apply(Input::Up, &sessions), Action::Ignore);
}

#[test]
fn state_vi_keys_mirror_the_arrows() {
    let sessions = fleet();
    let mut state = browsing();
    state.apply(Input::Char('j'), &sessions);
    assert_eq!(state.selected(), 1);
    state.apply(Input::Char('k'), &sessions);
    assert_eq!(state.selected(), 0);
    state.apply(Input::Char('G'), &sessions);
    assert_eq!(state.selected(), 2);
    state.apply(Input::Char('g'), &sessions);
    assert_eq!(state.selected(), 0);
}

#[test]
fn state_quit_keys_all_leave() {
    let sessions = fleet();
    for input in [Input::Char('q'), Input::Escape, Input::Cancel] {
        let mut state = browsing();
        assert_eq!(state.apply(input, &sessions), Action::Quit, "{input:?}");
    }
}

#[test]
fn state_enter_opens_the_selected_row() {
    let sessions = fleet();
    let mut state = browsing();
    state.apply(Input::Down, &sessions);
    assert_eq!(state.apply(Input::Enter, &sessions), Action::Open(1));
}

#[test]
fn state_enter_on_an_empty_fleet_does_nothing() {
    let mut state = TuiState::new(None, None);
    state.sync(&[]);
    assert_eq!(state.apply(Input::Enter, &[]), Action::Ignore);
}

#[test]
fn state_refresh_key_asks_for_a_refetch() {
    let sessions = fleet();
    let mut state = browsing();
    assert_eq!(state.apply(Input::Char('R'), &sessions), Action::Refresh);
}

#[test]
fn state_help_opens_and_any_key_closes_it() {
    let sessions = fleet();
    let mut state = browsing();
    state.apply(Input::Char('?'), &sessions);
    assert_eq!(state.mode(), &Mode::Help);
    state.apply(Input::Char('x'), &sessions);
    assert_eq!(state.mode(), &Mode::Browse);
}

// ── state: selection survives a refresh (#7224) ─────────────────────────────

#[test]
fn state_sync_follows_the_pinned_session_across_a_reorder() {
    let sessions = fleet();
    let mut state = browsing();
    state.apply(Input::Down, &sessions); // pin tm-bravo-02
    let reordered = vec![
        sessions[2].clone(),
        sessions[1].clone(),
        sessions[0].clone(),
    ];
    state.sync(&reordered);
    assert_eq!(state.selected(), 1);
    assert_eq!(reordered[state.selected()].name, "tm-bravo-02");
}

#[test]
fn state_sync_clamps_when_the_pinned_session_is_gone() {
    let sessions = fleet();
    let mut state = browsing();
    state.apply(Input::End, &sessions); // pin the third row
    let shrunk = vec![sessions[0].clone()];
    state.sync(&shrunk);
    assert_eq!(state.selected(), 0);
    // Re-pinned to what it landed on, so the next refresh follows THAT row.
    state.sync(&shrunk);
    assert_eq!(state.selected(), 0);
}

#[test]
fn state_sync_drops_an_overlay_whose_row_vanished() {
    let sessions = fleet();
    let mut state = browsing();
    state.apply(Input::End, &sessions);
    state.apply(Input::Char('r'), &sessions);
    assert!(matches!(state.mode(), Mode::Rename { .. }));
    state.sync(&sessions[..1]);
    assert_eq!(state.mode(), &Mode::Browse);
}

// ── state: delete (#7224 requirement 4) ─────────────────────────────────────

#[test]
fn state_delete_refuses_the_attached_self_session() {
    let sessions = fleet();
    // This terminal is inside tm-alpha-01, the row the selection starts on.
    let mut state = TuiState::new(Some("tm-alpha-01-id".to_string()), None);
    state.sync(&sessions);
    assert_eq!(state.apply(Input::Char('d'), &sessions), Action::Redraw);
    assert_eq!(state.mode(), &Mode::Browse, "no confirm dialog may open");
    let (text, severity) = state.message().expect("a visible refusal");
    assert_eq!(severity, Severity::Error);
    assert!(
        text.contains("tm-alpha-01") && text.contains("attached"),
        "refusal must name the session and why: {text}"
    );
}

#[test]
fn state_delete_on_a_stopped_row_confirms_with_yes() {
    let sessions = fleet();
    let mut state = browsing();
    state.apply(Input::Down, &sessions); // tm-bravo-02, stopped
    assert_eq!(state.apply(Input::Char('d'), &sessions), Action::Redraw);
    assert_eq!(
        state.mode(),
        &Mode::Confirm {
            index: 1,
            force: false,
            stop_first: false,
            typed: String::new()
        }
    );
    state.apply(Input::Char('y'), &sessions);
    assert_eq!(
        state.apply(Input::Enter, &sessions),
        Action::Delete {
            index: 1,
            force: false,
            stop_first: false
        }
    );
}

/// An ERRORED row confirms with a plain `y`, and the action it yields carries
/// `stop_first` — the runtime-stop leg the daemon's refusal used to send the
/// operator out to a shell to run (#7224). `force` stays false: the delete that
/// follows the stop is still unforced, so the daemon's tmux probe remains the
/// authority on whether the record may go.
#[test]
fn state_delete_on_an_errored_row_asks_to_stop_and_delete() {
    let mut sessions = fleet();
    sessions[1].state = "errored".to_string();
    let mut state = browsing();
    state.sync(&sessions);
    state.apply(Input::Down, &sessions); // tm-bravo-02, errored
    assert_eq!(state.apply(Input::Char('d'), &sessions), Action::Redraw);
    assert_eq!(
        state.mode(),
        &Mode::Confirm {
            index: 1,
            force: false,
            stop_first: true,
            typed: String::new()
        },
        "an errored row must open a stop-and-delete confirm, not a plain one"
    );
    state.apply(Input::Char('y'), &sessions);
    assert_eq!(
        state.apply(Input::Enter, &sessions),
        Action::Delete {
            index: 1,
            force: false,
            stop_first: true
        }
    );
}

/// The stop-first leg is scoped to `errored`: a `stopped` row has no runtime to
/// stop, and a running one takes the force-confirm path instead — neither may
/// pick up a stop request it does not need (#7224).
#[test]
fn state_delete_sets_stop_first_only_for_errored() {
    let sessions = fleet();
    for (index, expect_stop) in [(0usize, false), (1, false)] {
        let mut state = browsing();
        state.apply(
            if index == 0 { Input::Home } else { Input::Down },
            &sessions,
        );
        state.apply(Input::Char('d'), &sessions);
        match state.mode() {
            Mode::Confirm { stop_first, .. } => {
                assert_eq!(*stop_first, expect_stop, "row {index}");
            }
            other => panic!("row {index} must open a confirm, got {other:?}"),
        }
    }
}

#[test]
fn state_delete_on_a_running_row_requires_the_force_word() {
    let sessions = fleet();
    let mut state = browsing(); // tm-alpha-01, active
    state.apply(Input::Char('d'), &sessions);
    assert!(matches!(state.mode(), Mode::Confirm { force: true, .. }));
    // `y` is not enough for a running session — the CLI's own rule.
    for c in "y".chars() {
        state.apply(Input::Char(c), &sessions);
    }
    assert_eq!(state.apply(Input::Enter, &sessions), Action::Redraw);
    assert_eq!(state.mode(), &Mode::Browse);
    assert_eq!(
        state.message().expect("cancel notice").0,
        "delete cancelled"
    );

    let mut state = browsing();
    state.apply(Input::Char('d'), &sessions);
    for c in "force".chars() {
        state.apply(Input::Char(c), &sessions);
    }
    assert_eq!(
        state.apply(Input::Enter, &sessions),
        Action::Delete {
            index: 0,
            force: true,
            stop_first: false
        }
    );
}

#[test]
fn state_confirm_backspace_and_escape_both_step_back() {
    let sessions = fleet();
    let mut state = browsing();
    state.apply(Input::Down, &sessions);
    state.apply(Input::Char('d'), &sessions);
    state.apply(Input::Char('y'), &sessions);
    state.apply(Input::Backspace, &sessions);
    // The `y` is gone, so Enter cancels rather than deleting.
    assert_eq!(state.apply(Input::Enter, &sessions), Action::Redraw);

    let mut state = browsing();
    state.apply(Input::Down, &sessions);
    state.apply(Input::Char('d'), &sessions);
    assert_eq!(state.apply(Input::Escape, &sessions), Action::Redraw);
    assert_eq!(state.mode(), &Mode::Browse);
}

#[test]
fn is_self_session_matches_by_env_id() {
    let s = session("tm-alpha-01", "active", 1);
    assert!(is_self_session(&s, Some("tm-alpha-01-id"), None));
    assert!(!is_self_session(&s, Some("someone-else"), None));
}

#[test]
fn is_self_session_matches_by_tmux_name() {
    // The env var can be lost to a nested shell; the tmux session name IS the
    // managed session's identity name, so it answers on its own.
    let s = session("tm-alpha-01", "active", 1);
    assert!(is_self_session(&s, None, Some("tm-alpha-01")));
    assert!(!is_self_session(&s, None, Some("tm-other-09")));
}

#[test]
fn is_self_session_false_outside_a_managed_pane() {
    let s = session("tm-alpha-01", "active", 1);
    assert!(!is_self_session(&s, None, None));
}

// ── state: rename (#7224 requirement 5) ─────────────────────────────────────

#[test]
fn state_rename_seeds_the_overlay_with_the_current_name() {
    let sessions = fleet();
    let mut state = browsing();
    assert_eq!(state.apply(Input::Char('r'), &sessions), Action::Redraw);
    assert_eq!(
        state.mode(),
        &Mode::Rename {
            index: 0,
            typed: "tm-alpha-01".to_string()
        }
    );
}

#[test]
fn state_rename_rejects_an_invalid_name_with_the_shared_validator() {
    let sessions = fleet();
    let mut state = browsing();
    state.apply(Input::Char('r'), &sessions);
    // Clear the seeded name, then type one the daemon would reject.
    for _ in 0.."tm-alpha-01".len() {
        state.apply(Input::Backspace, &sessions);
    }
    for c in "bad name!".chars() {
        state.apply(Input::Char(c), &sessions);
    }
    assert_eq!(state.apply(Input::Enter, &sessions), Action::Redraw);
    // Still in the overlay, with the DAEMON'S own message — not a second
    // client-side spelling of the rule.
    assert!(matches!(state.mode(), Mode::Rename { .. }));
    let (text, severity) = state.message().expect("a validation error");
    assert_eq!(severity, Severity::Error);
    assert_eq!(
        text,
        validate_session_name("bad name!").expect_err("fixture must be invalid")
    );
}

#[test]
fn state_rename_sends_the_trimmed_validated_name() {
    let sessions = fleet();
    let mut state = browsing();
    state.apply(Input::Char('r'), &sessions);
    for _ in 0.."tm-alpha-01".len() {
        state.apply(Input::Backspace, &sessions);
    }
    for c in "tm-renamed ".chars() {
        state.apply(Input::Char(c), &sessions);
    }
    assert_eq!(
        state.apply(Input::Enter, &sessions),
        Action::Rename {
            index: 0,
            // The trailing space the validator trims never reaches the daemon.
            name: "tm-renamed".to_string()
        }
    );
    assert_eq!(state.mode(), &Mode::Browse);
}

#[test]
fn state_rename_to_the_same_name_is_not_a_round_trip() {
    let sessions = fleet();
    let mut state = browsing();
    state.apply(Input::Char('r'), &sessions);
    assert_eq!(state.apply(Input::Enter, &sessions), Action::Redraw);
    assert_eq!(state.message().expect("a notice").0, "name unchanged");
}

#[test]
fn state_rename_escape_cancels() {
    let sessions = fleet();
    let mut state = browsing();
    state.apply(Input::Char('r'), &sessions);
    assert_eq!(state.apply(Input::Escape, &sessions), Action::Redraw);
    assert_eq!(state.mode(), &Mode::Browse);
    assert_eq!(state.message().expect("a notice").0, "rename cancelled");
}

#[test]
fn state_rename_overlay_treats_action_keys_as_text() {
    // `d`, `q` and `r` are action keys while browsing and literal characters
    // while typing a name; only the mode can tell them apart.
    let sessions = fleet();
    let mut state = browsing();
    state.apply(Input::Char('r'), &sessions);
    for _ in 0.."tm-alpha-01".len() {
        state.apply(Input::Backspace, &sessions);
    }
    for c in "dqr".chars() {
        state.apply(Input::Char(c), &sessions);
    }
    assert_eq!(
        state.mode(),
        &Mode::Rename {
            index: 0,
            typed: "dqr".to_string()
        }
    );
}

// ── delete outcome wording ──────────────────────────────────────────────────

#[test]
fn delete_outcome_names_the_soft_delete() {
    let (text, severity) = delete_outcome(
        "tm-bravo-02",
        Ok(DeleteReport::Deleted {
            name: "tm-bravo-02".to_string(),
            prior_state: "stopped".to_string(),
            local: false,
            note: None,
        }),
    );
    assert_eq!(severity, Severity::Info);
    assert!(
        text.contains("--deleted--") && text.contains("still listed"),
        "a managed delete is soft and must say so: {text}"
    );
}

#[test]
fn delete_outcome_reports_the_local_store() {
    let (text, _) = delete_outcome(
        "local-01",
        Ok(DeleteReport::Deleted {
            name: "local-01".to_string(),
            prior_state: "stopped".to_string(),
            local: true,
            note: None,
        }),
    );
    assert!(text.contains("project store"), "{text}");
}

/// #8935: a delete that left a live tmux session with the record's name says
/// so in the status line.
#[test]
fn delete_outcome_says_a_live_session_was_left_running() {
    let note = "tmux session 'tm-x' is live but does not hold this record's pane %7; \
                it was left running";
    let (text, _) = delete_outcome(
        "tm-x",
        Ok(DeleteReport::Deleted {
            name: "tm-x".to_string(),
            prior_state: "stopped".to_string(),
            local: false,
            note: Some(note.to_string()),
        }),
    );
    assert!(
        text.contains("record only") && text.contains(note),
        "{text}"
    );
}

#[test]
fn delete_outcome_surfaces_a_refusal() {
    let (text, severity) = delete_outcome(
        "tm-alpha-01",
        Ok(DeleteReport::Refused("session is running\n".to_string())),
    );
    assert_eq!(severity, Severity::Error);
    assert_eq!(text, "delete refused: session is running");
}

/// A failed stop leg must read as "nothing was deleted", carrying the daemon's
/// own status and body — never as a delete that merely did not happen (#7224).
#[test]
fn delete_outcome_reports_a_failed_stop_as_not_deleted() {
    let (text, severity) = delete_outcome(
        "tm-bravo-02",
        Ok(DeleteReport::StopFailed(
            "stop returned HTTP 500 Internal Server Error: tmux driver unavailable".to_string(),
        )),
    );
    assert_eq!(severity, Severity::Error);
    assert!(text.contains("NOT deleted"), "{text}");
    assert!(text.contains("tmux driver unavailable"), "{text}");
    assert!(text.contains("500"), "{text}");
}

#[test]
fn delete_outcome_reports_not_found() {
    let (text, severity) = delete_outcome("gone-01", Ok(DeleteReport::NotFound));
    assert_eq!(severity, Severity::Info);
    assert!(text.contains("already gone"), "{text}");
}

#[test]
fn delete_outcome_reports_a_transport_error() {
    let (text, severity) =
        delete_outcome("tm-alpha-01", Err(anyhow::anyhow!("connection refused")));
    assert_eq!(severity, Severity::Error);
    assert!(text.contains("connection refused"), "{text}");
}

// ── key mapping ─────────────────────────────────────────────────────────────

#[test]
fn input_maps_ctrl_c_to_cancel() {
    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
    for c in ['c', 'd'] {
        let key = KeyEvent::new(KeyCode::Char(c), KeyModifiers::CONTROL);
        assert_eq!(map_key(key), Some(Input::Cancel), "ctrl-{c}");
    }
}

/// #8587: Ctrl-N reaches the state machine; before this `map_key` dropped it.
#[test]
fn input_maps_ctrl_n_to_name_new() {
    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
    let chords = [
        KeyEvent::new(KeyCode::Char('n'), KeyModifiers::CONTROL),
        KeyEvent::new(KeyCode::Char('N'), KeyModifiers::CONTROL),
        KeyEvent::new(
            KeyCode::Char('N'),
            KeyModifiers::CONTROL | KeyModifiers::SHIFT,
        ),
    ];
    for key in chords {
        assert_eq!(map_key(key), Some(Input::NameNew), "{key:?}");
    }
    // A bare `n` is still a character — the list filter and browse's `n`.
    let plain = KeyEvent::new(KeyCode::Char('n'), KeyModifiers::NONE);
    assert_eq!(map_key(plain), Some(Input::Char('n')));
}

#[test]
fn input_ignores_key_release() {
    use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyEventState, KeyModifiers};
    let key = KeyEvent::new_with_kind_and_state(
        KeyCode::Char('q'),
        KeyModifiers::NONE,
        KeyEventKind::Release,
        KeyEventState::NONE,
    );
    assert_eq!(map_key(key), None);
}

#[test]
fn input_passes_characters_through_unresolved() {
    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
    let key = KeyEvent::new(KeyCode::Char('d'), KeyModifiers::NONE);
    assert_eq!(map_key(key), Some(Input::Char('d')));
    let key = KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE);
    assert_eq!(map_key(key), Some(Input::Escape));
}

// ── TestBackend renders (#7224 requirement 2) ───────────────────────────────

/// Draw one frame at `w`x`h` and return the flattened screen text, one line
/// per terminal row.
fn draw(w: u16, h: u16, sessions: &[ManagedSessionSummary], state: &mut TuiState) -> Vec<String> {
    let mut terminal = Terminal::new(TestBackend::new(w, h)).expect("test terminal");
    terminal
        .draw(|frame| render::render(frame, sessions, state))
        .expect("render must not panic");
    let buffer = terminal.backend().buffer().clone();
    (0..h)
        .map(|y| {
            (0..w)
                .map(|x| buffer[(x, y)].symbol().to_string())
                .collect::<String>()
                .trim_end()
                .to_string()
        })
        .collect()
}

#[test]
fn render_at_eighty_by_twentyfour_drops_the_widest_columns() {
    let sessions = fleet();
    let mut state = browsing();
    let screen = draw(80, 24, &sessions, &mut state);
    let joined = screen.join("\n");
    assert!(joined.contains("NAME"), "{joined}");
    assert!(joined.contains("PROJECT"), "{joined}");
    assert!(joined.contains("STATE"), "{joined}");
    // ID and TMUX do not fit at 80 columns and must be absent, not wrapped.
    assert!(!joined.contains("TMUX"), "{joined}");
    assert!(joined.contains("tm-alpha-01"), "{joined}");
    // Nothing may exceed the terminal width.
    for line in &screen {
        assert!(line.chars().count() <= 80, "overlong row: {line}");
    }
    // The footer key hints are always on screen.
    assert!(joined.contains("Enter open"), "{joined}");
    assert!(joined.contains("q quit"), "{joined}");
}

#[test]
fn render_at_two_hundred_by_fifty_shows_every_column() {
    let sessions = fleet();
    let mut state = browsing();
    let joined = draw(200, 50, &sessions, &mut state).join("\n");
    for header in ["NAME", "ID", "PROJECT", "STATE", "TMUX"] {
        assert!(joined.contains(header), "missing {header} in\n{joined}");
    }
    // Every row is drawn — a 50-row terminal has room for three sessions.
    for name in ["tm-alpha-01", "tm-bravo-02", "tm-charlie-03"] {
        assert!(joined.contains(name), "missing {name} in\n{joined}");
    }
    assert!(joined.contains("bobmatnyc/trusty-tools"), "{joined}");
    assert!(joined.contains("%11"), "{joined}");
}

/// The TUI overlay renders the SHARED errored question (#7224), so an operator
/// who learns what `y` does in the numbered fallback picker reads the same
/// promise here.
#[test]
fn confirm_overlay_asks_the_shared_errored_question() {
    let sessions = vec![session("tm-quiet-falcon", "errored", 4)];
    let mut state = TuiState::new(None, None);
    state.sync(&sessions);
    state.apply(Input::Char('d'), &sessions);
    let joined = draw(200, 50, &sessions, &mut state).join("\n");
    let ask = crate::commands::picker_delete::errored_confirm_ask("tm-quiet-falcon");
    assert!(joined.contains(&ask), "expected {ask:?} in\n{joined}");
}

#[test]
fn render_tiny_terminal_does_not_panic() {
    let sessions = fleet();
    // 20x5 and smaller, in every mode, including the overlays whose centered
    // popup is where a hand-rolled Rect would go out of bounds.
    for (w, h) in [(20u16, 5u16), (10, 3), (5, 2), (1, 1)] {
        for opener in ['?', 'd', 'r'] {
            let mut state = browsing();
            state.apply(Input::Char(opener), &sessions);
            let screen = draw(w, h, &sessions, &mut state);
            assert_eq!(screen.len(), h as usize, "{w}x{h} mode {opener}");
        }
    }
}

#[test]
fn render_empty_fleet_says_so() {
    let mut state = TuiState::new(None, None);
    state.sync(&[]);
    let joined = draw(80, 24, &[], &mut state).join("\n");
    assert!(joined.contains("no sessions"), "{joined}");
}

#[test]
fn render_scrolls_to_keep_the_selection_visible() {
    // 40 sessions in a 10-row terminal: the selected row must be on screen.
    let sessions: Vec<_> = (1..=40)
        .map(|i| session(&format!("tm-row-{i:02}"), "stopped", i))
        .collect();
    let mut state = TuiState::new(None, None);
    state.sync(&sessions);
    for _ in 0..30 {
        state.apply(Input::Down, &sessions);
    }
    let joined = draw(120, 10, &sessions, &mut state).join("\n");
    assert!(
        joined.contains("tm-row-31"),
        "selection off screen:\n{joined}"
    );
}

#[test]
fn render_confirm_overlay_names_the_word_it_wants() {
    let sessions = fleet();
    let mut state = browsing();
    state.apply(Input::Down, &sessions); // stopped row → plain confirm
    state.apply(Input::Char('d'), &sessions);
    let joined = draw(100, 24, &sessions, &mut state).join("\n");
    assert!(joined.contains("tm-bravo-02"), "{joined}");
    assert!(joined.contains("Type y"), "{joined}");

    let mut state = browsing(); // active row → force confirm
    state.apply(Input::Char('d'), &sessions);
    let joined = draw(100, 24, &sessions, &mut state).join("\n");
    assert!(joined.contains("force"), "{joined}");
}

#[test]
fn render_help_overlay_lists_every_action_key() {
    let sessions = fleet();
    let mut state = browsing();
    state.apply(Input::Char('?'), &sessions);
    let joined = draw(100, 30, &sessions, &mut state).join("\n");
    for token in ["rename", "delete", "refresh", "quit"] {
        assert!(joined.contains(token), "help omits {token}:\n{joined}");
    }
}

/// Every rendered row carries its session's name AND its state, on one line.
///
/// Why (#7224 requirement 1): the two cells an operator picks a row by are the
/// friendly name and the lifecycle state, and a table that draws them on
/// different lines — or drops the state column at a width that fits it — is
/// unusable for choosing what to resume. Asserting per ROW rather than
/// per-frame is what makes this fail if the columns ever come apart.
#[test]
fn render_rows_pair_each_name_with_its_state() {
    let sessions = fleet();
    let mut state = browsing();
    let lines = draw(140, 24, &sessions, &mut state);
    // `attached` outranks the raw state word — see `layout::state_cell`.
    for (name, expected_state) in [
        ("tm-alpha-01", "active"),
        ("tm-bravo-02", "stopped"),
        ("tm-charlie-03", "attached"),
    ] {
        let row = lines
            .iter()
            .find(|line| line.contains(name))
            .unwrap_or_else(|| panic!("no row for {name} in\n{}", lines.join("\n")));
        assert!(
            row.contains(expected_state),
            "row for {name} omits state {expected_state}: {row:?}"
        );
    }
}

/// A rename is visible in the list, and the selection follows the renamed row.
///
/// Why (#7224 requirement 5): the rename is only done when the operator can see
/// it. The overlay yields the validated name, the daemon applies it, and the
/// re-fetch that follows replaces the whole `Vec` — so this drives that exact
/// sequence and asserts the new name is on screen, the old one is gone, and
/// `sync` re-pointed the selection at the row by ID rather than by index.
#[test]
fn render_shows_a_rename_after_the_refetch() {
    let mut sessions = fleet();
    let mut state = browsing();
    state.apply(Input::Down, &sessions); // select tm-bravo-02
    state.apply(Input::Char('r'), &sessions);
    for _ in 0..11 {
        state.apply(Input::Backspace, &sessions); // clear the seeded name
    }
    for c in "tm-renamed-02".chars() {
        state.apply(Input::Char(c), &sessions);
    }
    let action = state.apply(Input::Enter, &sessions);
    let Action::Rename { index, name } = action else {
        panic!("expected a rename action, got {action:?}");
    };
    assert_eq!(name, "tm-renamed-02");

    // What the daemon does, then the re-fetch the driver performs after it.
    sessions[index].name = name.clone();
    let refetched: Vec<_> = sessions.iter().rev().cloned().collect(); // order churns
    state.sync(&refetched);

    let joined = draw(140, 24, &refetched, &mut state).join("\n");
    assert!(
        joined.contains("tm-renamed-02"),
        "rename not shown:\n{joined}"
    );
    assert!(
        !joined.contains("tm-bravo-02"),
        "old name still shown:\n{joined}"
    );
    assert_eq!(
        refetched[state.selected()].name,
        "tm-renamed-02",
        "selection must follow the renamed session across the re-fetch"
    );
}

// ── status-line wrapping: never cut a token in half (#7224) ─────────────────

/// The exact refusal the daemon's delete guard produces, for a session whose
/// friendly name and UUID are both realistic. This is the string the owner saw
/// cut off mid-UUID in the picker.
const GUARD_REFUSAL: &str = "delete refused: session 'tm-quiet-falcon' is errored — stop it first \
     with `tm session stop` (or `tm session decommission`), or pass --force to delete the record \
     anyway. Session id:\n8fc5db8f-b0a5-5c47-9a5b-59cd2a1e4f77";

/// The UUID in the guard refusal, which no wrap may split.
const GUARD_UUID: &str = "8fc5db8f-b0a5-5c47-9a5b-59cd2a1e4f77";

#[test]
fn wrap_message_keeps_a_uuid_whole_at_eighty_columns() {
    let lines = layout::wrap_message(GUARD_REFUSAL, 80, layout::STATUS_MAX_LINES);
    for line in &lines {
        assert!(
            line.chars().count() <= 80,
            "wrapped line exceeds the width: {line}"
        );
    }
    assert!(
        lines.iter().any(|l| l.contains(GUARD_UUID)),
        "the full session id must survive the wrap, got:\n{lines:#?}"
    );
}

#[test]
fn wrap_message_honours_explicit_newlines() {
    let lines = layout::wrap_message("first line\nsecond line", 80, 4);
    assert_eq!(lines, vec!["first line", "second line"]);
}

#[test]
fn wrap_message_elides_on_a_token_boundary() {
    // Ten five-character tokens at width 12 need five lines; capped at two, the
    // second must end in an ellipsis and never inside a token.
    let text = "aaaaa bbbbb ccccc ddddd eeeee fffff ggggg hhhhh iiiii jjjjj";
    let lines = layout::wrap_message(text, 12, 2);
    assert_eq!(lines.len(), 2);
    assert!(lines[1].ends_with('…'), "{lines:#?}");
    for line in &lines {
        assert!(line.chars().count() <= 12, "{line}");
        for token in line.trim_end_matches('…').split_whitespace() {
            assert_eq!(token.chars().count(), 5, "token cut mid-word: {token}");
        }
    }
}

/// #7224: the session id is the point of the refusal, so it has to survive the
/// wrap at the narrow widths a split pane actually has. Packing greedily from
/// the front filled all four lines with the first paragraph at 40 and 60
/// columns and dropped the id paragraph entirely.
#[test]
fn wrap_message_keeps_the_session_id_at_narrow_widths() {
    for width in [40usize, 60, 80] {
        let lines = layout::wrap_message(GUARD_REFUSAL, width, layout::STATUS_MAX_LINES);
        assert!(
            lines.len() <= layout::STATUS_MAX_LINES,
            "width {width} overflowed the status region:\n{lines:#?}"
        );
        for line in &lines {
            assert!(
                line.chars().count() <= width,
                "width {width}: line exceeds it: {line}"
            );
        }
        assert!(
            lines.iter().any(|l| l.contains(GUARD_UUID)),
            "width {width}: the full session id must survive, got:\n{lines:#?}"
        );
    }
}

/// A token longer than the width has no wrap that shows it whole, so it is
/// emitted alone and intact — splitting it is the exact failure the wrap exists
/// to prevent, and the elide helper must leave a line it cannot cut at a
/// whitespace boundary exactly as it is.
#[test]
fn wrap_message_keeps_an_overlong_token_whole() {
    let token = "z".repeat(200);
    let lines = layout::wrap_message(&token, 40, layout::STATUS_MAX_LINES);
    assert_eq!(lines, vec![token]);
}

#[test]
fn wrap_message_zero_width_is_empty() {
    assert!(layout::wrap_message("anything", 0, 4).is_empty());
    assert!(layout::wrap_message("anything", 80, 0).is_empty());
}

/// The regression the owner reported: at 80 columns the picker's status line
/// showed the delete refusal cut off inside the session UUID. The full id must
/// now appear somewhere on screen, unbroken (#7224).
#[test]
fn render_wraps_a_long_refusal_without_cutting_the_uuid() {
    let sessions = fleet();
    let mut state = browsing();
    state.set_message(GUARD_REFUSAL, Severity::Error);
    let screen = draw(80, 24, &sessions, &mut state);
    let joined = screen.join("\n");
    assert!(
        joined.contains(GUARD_UUID),
        "the session id was cut by the status line:\n{joined}"
    );
    for line in &screen {
        assert!(line.chars().count() <= 80, "overlong row: {line}");
    }
    // The table and the key footer must survive the taller status region.
    assert!(joined.contains("NAME"), "{joined}");
    assert!(joined.contains("q quit"), "{joined}");
}

#[test]
fn render_status_uses_one_row_when_there_is_no_message() {
    let sessions = fleet();
    let mut state = browsing();
    let screen = draw(80, 24, &sessions, &mut state);
    // Three sessions plus a header, a title, an empty status row and a footer —
    // the layout must not have grown a status region with nothing in it.
    assert_eq!(screen.len(), 24);
    assert!(screen.last().is_some_and(|l| l.contains("q quit")));
}

// ── new-session flow (#7395) ────────────────────────────────────────────────

/// A registry row fixture. Built through serde so every optional field takes
/// the same default the daemon's own listing gives it.
fn project(name: &str, repo_url: &str) -> Project {
    serde_json::from_value(serde_json::json!({
        "name": name,
        "repo_url": repo_url,
        "default_branch": "main",
    }))
    .expect("project fixture")
}

/// Two registered projects, plus the typed-path escape `targets_from` appends.
fn targets() -> Vec<Target> {
    new_session::targets_from_with(
        &[
            project("trusty-tools", "https://github.com/bobmatnyc/trusty-tools"),
            project("apex", "https://github.com/duetto/apex"),
        ],
        &[],
        stub_checkout,
    )
}

/// Where the fixture row named `name` is checked out (#7887).
///
/// Why: the picker hands the create call a registered row's DIRECTORY and
/// refuses one that is not on this host, so a fixture row that a test confirms
/// needs a directory that really exists. This crate's own source tree supplies
/// them — which directory stands for which project is arbitrary; that two rows
/// differ, and that both exist, is the whole requirement.
fn fixture_checkout(name: &str) -> PathBuf {
    let here = Path::new(env!("CARGO_MANIFEST_DIR"));
    match name {
        "apex" => here.join("src").join("daemon"),
        "zeta" => here.join("src").join("client"),
        _ => here.join("src"),
    }
}

/// [`fixture_checkout`] as the picker's checkout resolver (#7887).
fn stub_checkout(project: &Project) -> Option<PathBuf> {
    Some(fixture_checkout(&project.name))
}

/// A checkout resolver naming a directory this host does not have (#7887).
fn missing_checkout(project: &Project) -> Option<PathBuf> {
    Some(PathBuf::from("/nonexistent/7887").join(&project.name))
}

/// Stand-in for the real git resolution, so the unregistered-path branch is
/// decidable without a checkout on disk.
fn stub_identity(typed: &str) -> Option<ProjectIdentity> {
    match typed {
        "/w/widgets" => Some(ProjectIdentity {
            name: "widgets".to_string(),
            repo_url: "https://github.com/acme/widgets".to_string(),
            root: "/w/widgets".to_string(),
        }),
        // The SAME project the registry already holds, reached by its checkout.
        "/w/trusty-tools" => Some(ProjectIdentity {
            name: "trusty-tools".to_string(),
            repo_url: "https://github.com/bobmatnyc/trusty-tools".to_string(),
            root: "/w/trusty-tools".to_string(),
        }),
        _ => None,
    }
}

/// A state browsing `fleet()` with the new-session flow already open.
fn creating() -> TuiState {
    let mut state = browsing();
    state.open_new_session(NewSessionFlow::with_resolver(targets(), stub_identity));
    state
}

#[test]
fn new_session_targets_from_puts_the_path_escape_last() {
    let targets = targets();
    assert_eq!(
        targets.first(),
        Some(&Target::Registered {
            name: "trusty-tools".to_string(),
            repo: "https://github.com/bobmatnyc/trusty-tools".to_string(),
            checkout: Some(fixture_checkout("trusty-tools")),
        })
    );
    assert_eq!(targets.last(), Some(&Target::Other));
    // An empty registry still offers the escape, or a fresh host could never
    // create anything from this surface.
    assert_eq!(new_session::targets_from(&[], &[]), vec![Target::Other]);
}

#[test]
fn new_session_key_opens_the_flow() {
    let sessions = fleet();
    let mut state = browsing();
    // `n` only ASKS — the registry read belongs to the driver, so the state
    // machine never issues one itself.
    assert_eq!(state.apply(Input::Char('n'), &sessions), Action::NewSession);
    assert_eq!(state.mode(), &Mode::Browse, "the flow opens on the answer");
    state.open_new_session(NewSessionFlow::with_resolver(targets(), stub_identity));
    assert!(matches!(state.mode(), Mode::New(_)));
}

/// Confirming a registered row creates in THAT project and registers nothing.
///
/// Why (#7395 requirement 3): this is the acceptance case for the
/// existing-project half — the create call has to receive the repo of the row
/// the operator moved onto, not the first row and not the cwd. Driving it from
/// the keystrokes, then through [`new_session::perform_with`] with fakes, is
/// what makes an implementation that creates something else fail here.
/// #7887: "the repo of the row" is that row's local checkout — the create call
/// takes a directory, never the registry's URL.
#[tokio::test]
async fn new_session_confirming_a_registered_project_creates_without_registering() {
    let sessions = fleet();
    let mut state = creating();
    // Move onto the SECOND registered project before confirming.
    assert_eq!(state.apply(Input::Down, &sessions), Action::Redraw);
    let action = state.apply(Input::Enter, &sessions);
    let Action::Create(request) = action else {
        panic!("expected a create action, got {action:?}");
    };
    let apex = fixture_checkout("apex").display().to_string();
    assert_eq!(
        request,
        NewSessionRequest {
            register: None,
            repo: apex.clone(),
            label: "apex".to_string(),
            name_hint: None,
        }
    );
    assert_eq!(state.mode(), &Mode::Browse, "the overlay closes on confirm");

    let calls = std::cell::RefCell::new(Vec::new());
    let outcome = new_session::perform_with(
        request,
        |p: NewProject| {
            calls.borrow_mut().push(format!("register:{}", p.name));
            async { anyhow::Ok(()) }
        },
        |repo: String, _: Option<String>| {
            calls.borrow_mut().push(format!("create:{repo}"));
            async { anyhow::Ok(AttachOutcome::Attached) }
        },
    )
    .await
    .expect("the create leg must succeed");
    assert_eq!(outcome, AttachOutcome::Attached);
    assert_eq!(
        calls.into_inner(),
        vec![format!("create:{apex}")],
        "a registered project must not be registered again"
    );
}

/// A registered row carries the directory a session in it runs in (#7887).
///
/// Why: the registry stores no path, so the row is where that answer has to be
/// resolved. This asserts the PRODUCTION wiring — `targets_from` asking
/// `local_checkout_for` — which the stub-driven tests below deliberately do not.
#[test]
fn new_session_registered_target_carries_its_local_checkout() {
    let rows =
        new_session::targets_from(&[project("cto", "https://github.com/bob-duetto/cto")], &[]);
    let Some(Target::Registered { repo, checkout, .. }) = rows.first() else {
        panic!("the registry row is not a target, got {rows:?}");
    };
    assert_eq!(
        repo, "https://github.com/bob-duetto/cto",
        "the row keeps its identity"
    );
    let checkout = checkout.as_ref().expect("a GitHub row names a directory");
    assert!(checkout.is_absolute(), "{checkout:?}");
    assert!(
        checkout.ends_with("bob-duetto/cto"),
        "not the managed clone path: {checkout:?}"
    );
}

/// Confirming a registered row sends its directory, never its URL (#7887).
///
/// Why: the owner's `tm ls` sent `https://github.com/bob-duetto/cto` as
/// `repo_url` and the daemon's ADR-0055 check refused it — trusty-mpm clones
/// nothing, so the only form it accepts is a directory that already exists.
/// Against the pre-fix picker this fails with that URL in `request.repo`.
#[test]
fn new_session_confirming_a_registered_project_sends_its_local_checkout() {
    let mut flow = NewSessionFlow::with_resolver(
        new_session::targets_from_with(
            &[project("cto", "https://github.com/bob-duetto/cto")],
            &[],
            stub_checkout,
        ),
        stub_identity,
    );
    match flow.apply(Input::Enter) {
        Step::Create(request) => {
            assert_eq!(request.register, None, "the project is already registered");
            assert_eq!(request.repo, fixture_checkout("cto").display().to_string());
            assert!(Path::new(&request.repo).is_dir(), "{request:?}");
        }
        other => panic!("the registered row was not confirmed, got {other:?}"),
    }
}

/// A registered project with no checkout names the path and the clone (#7887).
///
/// Why: falling back to the URL only moves the failure into the daemon's
/// background provisioning job, whose message names neither this project nor
/// where its checkout belongs. The refusal has to arrive here, with the step
/// that fixes it.
#[test]
fn new_session_registered_project_without_a_checkout_names_the_clone_step() {
    let mut flow = NewSessionFlow::with_resolver(
        new_session::targets_from_with(
            &[project("cto", "https://github.com/bob-duetto/cto")],
            &[],
            missing_checkout,
        ),
        stub_identity,
    );
    match flow.apply(Input::Enter) {
        Step::Reject(message) => {
            assert!(message.contains("/nonexistent/7887/cto"), "{message}");
            assert!(
                message
                    .contains("git clone https://github.com/bob-duetto/cto /nonexistent/7887/cto"),
                "{message}"
            );
        }
        other => panic!("a missing checkout was not refused, got {other:?}"),
    }
}

/// An unregistered path is registered FIRST, then created in.
///
/// Why (#7395 requirement 2): the daemon cannot spawn into a project it has
/// never heard of, so the ORDER is the requirement — asserting only that both
/// calls happened would pass for an implementation that registers afterwards.
#[tokio::test]
async fn new_session_unregistered_path_registers_before_creating() {
    let sessions = fleet();
    let mut state = creating();
    // Walk to the "other" row; two registered projects precede it.
    state.apply(Input::Down, &sessions);
    state.apply(Input::Down, &sessions);
    assert_eq!(
        state.apply(Input::Enter, &sessions),
        Action::Redraw,
        "the path entry opens rather than creating"
    );
    for c in "/w/widgets".chars() {
        state.apply(Input::Char(c), &sessions);
    }
    let action = state.apply(Input::Enter, &sessions);
    let Action::Create(request) = action else {
        panic!("expected a create action, got {action:?}");
    };
    assert_eq!(
        request,
        NewSessionRequest {
            register: Some(NewProject {
                name: "widgets".to_string(),
                repo_url: "https://github.com/acme/widgets".to_string(),
            }),
            // The local working-tree root, not the URL — that is what lets the
            // daemon resolve `source_id` for a checkout already on disk.
            repo: "/w/widgets".to_string(),
            label: "widgets".to_string(),
            name_hint: None,
        }
    );

    let calls = std::cell::RefCell::new(Vec::new());
    new_session::perform_with(
        request,
        |p: NewProject| {
            calls.borrow_mut().push(format!("register:{}", p.repo_url));
            async { anyhow::Ok(()) }
        },
        |repo: String, _: Option<String>| {
            calls.borrow_mut().push(format!("create:{repo}"));
            async { anyhow::Ok(AttachOutcome::Attached) }
        },
    )
    .await
    .expect("both legs must succeed");
    assert_eq!(
        calls.into_inner(),
        vec![
            "register:https://github.com/acme/widgets".to_string(),
            "create:/w/widgets".to_string(),
        ],
        "registration must land before the session is created"
    );
}

#[tokio::test]
async fn new_session_a_failed_registration_never_creates() {
    let request = NewSessionRequest {
        register: Some(NewProject {
            name: "widgets".to_string(),
            repo_url: "https://github.com/acme/widgets".to_string(),
        }),
        repo: "/w/widgets".to_string(),
        label: "widgets".to_string(),
        name_hint: None,
    };
    let created = std::cell::Cell::new(false);
    let err = new_session::perform_with(
        request,
        |_: NewProject| async { Err(anyhow::anyhow!("registry refused it")) },
        |_: String, _: Option<String>| {
            created.set(true);
            async { anyhow::Ok(AttachOutcome::Attached) }
        },
    )
    .await
    .expect_err("a failed registration must abort the flow");
    assert!(
        !created.get(),
        "nothing may be created after a failed register"
    );
    assert!(
        format!("{err:#}").contains("registry refused it"),
        "the daemon's own reason must survive: {err:#}"
    );
}

#[test]
fn new_session_known_path_skips_registration() {
    // The typed checkout resolves to a project the registry ALREADY holds, so
    // re-registering would replace its stored record with these two fields.
    let request = new_session::request_for_path("/w/trusty-tools", &targets(), stub_identity)
        .expect("a known checkout is usable");
    assert_eq!(request.register, None);
    assert_eq!(request.repo, "/w/trusty-tools");
}

#[test]
fn new_session_rejects_a_path_that_is_not_a_checkout() {
    let sessions = fleet();
    let mut state = creating();
    state.apply(Input::Down, &sessions);
    state.apply(Input::Down, &sessions);
    state.apply(Input::Enter, &sessions);
    for c in "/tmp/nope".chars() {
        state.apply(Input::Char(c), &sessions);
    }
    assert_eq!(state.apply(Input::Enter, &sessions), Action::Redraw);
    let (text, severity) = state.message().expect("a refusal must be shown");
    assert!(text.contains("/tmp/nope"), "{text}");
    assert_eq!(severity, Severity::Error);
    // The entry stays open with what was typed, so it can be corrected.
    match state.mode() {
        Mode::New(flow) => assert_eq!(flow.typed(), Some("/tmp/nope")),
        other => panic!("the flow must stay open, got {other:?}"),
    }
}

#[test]
fn new_session_rejects_an_empty_path() {
    let err = new_session::request_for_path("   ", &targets(), stub_identity)
        .expect_err("an empty path is not a project");
    assert!(err.contains("path"), "{err}");
}

#[test]
fn new_session_escape_cancels_from_both_steps() {
    let sessions = fleet();
    // From the project list.
    let mut state = creating();
    assert_eq!(state.apply(Input::Escape, &sessions), Action::Redraw);
    assert_eq!(state.mode(), &Mode::Browse);
    // From the path entry.
    let mut state = creating();
    state.apply(Input::Down, &sessions);
    state.apply(Input::Down, &sessions);
    state.apply(Input::Enter, &sessions);
    state.apply(Input::Char('/'), &sessions);
    assert_eq!(state.apply(Input::Escape, &sessions), Action::Redraw);
    assert_eq!(state.mode(), &Mode::Browse);
}

/// Esc out of the flow leaves every observable part of the surface as it was.
///
/// Why (#7395 requirement 4): "returns to the list unchanged" is a claim about
/// the selection, the scroll offset and the status line, not just the mode — a
/// flow that reset the pinned row on the way out would still pass a mode-only
/// assertion.
#[test]
fn new_session_escape_leaves_the_state_identical() {
    let sessions = fleet();
    let mut state = browsing();
    state.apply(Input::Down, &sessions);
    let before = (
        state.mode().clone(),
        state.selected(),
        state.scroll(),
        state.message().map(|(t, s)| (t.to_string(), s)),
    );

    assert_eq!(state.apply(Input::Char('n'), &sessions), Action::NewSession);
    state.open_new_session(NewSessionFlow::with_resolver(targets(), stub_identity));
    state.apply(Input::Down, &sessions);
    state.apply(Input::Down, &sessions);
    state.apply(Input::Enter, &sessions);
    state.apply(Input::Char('/'), &sessions);
    state.apply(Input::Char('w'), &sessions);
    state.apply(Input::Escape, &sessions);

    let after = (
        state.mode().clone(),
        state.selected(),
        state.scroll(),
        state.message().map(|(t, s)| (t.to_string(), s)),
    );
    assert_eq!(after, before);
}

#[test]
fn new_session_rows_window_keeps_the_selection_visible() {
    // #7421: zero-padded so the alphabetical order the picker now applies is
    // also the numeric one, and the window arithmetic stays readable.
    let many: Vec<Project> = (0..12)
        .map(|i| {
            project(
                &format!("p{i:02}"),
                &format!("https://example.test/p{i:02}"),
            )
        })
        .collect();
    let mut flow =
        NewSessionFlow::with_resolver(new_session::targets_from(&many, &[]), stub_identity);
    // Eight rows is the whole window, so a short registry never scrolls.
    assert_eq!(flow.rows().len(), 8);
    assert!(flow.rows()[0].starts_with('▸'));
    for _ in 0..12 {
        flow.apply(Input::Down);
    }
    // Twelve projects plus the escape row: twelve `Down`s land on the escape.
    let rows = flow.rows();
    assert_eq!(rows.len(), 8);
    assert!(
        rows.last()
            .is_some_and(|r| r.starts_with('▸') && r.contains("other")),
        "the selection scrolled off the window: {rows:?}"
    );
    assert!(
        rows[0].contains("p05"),
        "the window did not follow the selection down: {rows:?}"
    );
}

#[test]
fn render_new_session_overlay_lists_the_registered_projects() {
    let sessions = fleet();
    let mut state = creating();
    let joined = draw(110, 30, &sessions, &mut state).join("\n");
    assert!(joined.contains("Start a new session in:"), "{joined}");
    // #7406: the row is the project's identity, not its stored URL.
    assert!(joined.contains("duetto/apex"), "{joined}");
    assert!(!joined.contains("https://"), "{joined}");
    assert!(joined.contains("other — type a project path"), "{joined}");
    assert!(joined.contains("Esc cancels"), "{joined}");
}

#[test]
fn render_new_session_overlay_shows_the_typed_path() {
    let sessions = fleet();
    let mut state = creating();
    state.apply(Input::Down, &sessions);
    state.apply(Input::Down, &sessions);
    state.apply(Input::Enter, &sessions);
    for c in "/w/widgets".chars() {
        state.apply(Input::Char(c), &sessions);
    }
    let joined = draw(110, 30, &sessions, &mut state).join("\n");
    assert!(joined.contains("/w/widgets"), "{joined}");
    assert!(joined.contains("registers it"), "{joined}");
}

/// The footer advertises the create key at the narrowest supported width.
///
/// Why (#7395 requirement 1): a key nobody can discover is not a feature, and
/// the footer is the only place it is visible without opening `?`. Asserting at
/// 80 columns is what catches a legend that has grown past the width it has to
/// fit in.
#[test]
fn render_footer_offers_the_new_session_key() {
    let sessions = fleet();
    let mut state = browsing();
    let screen = draw(80, 24, &sessions, &mut state);
    let footer = screen.last().expect("a footer row");
    assert!(footer.contains("n new"), "{footer}");
    assert!(
        footer.contains("q quit"),
        "the legend was clipped: {footer}"
    );
    // And the `?` reference says what the key does.
    state.apply(Input::Char('?'), &sessions);
    let joined = draw(110, 30, &sessions, &mut state).join("\n");
    assert!(joined.contains("new session"), "{joined}");
}

// ── new-session picker polish (#7406) ───────────────────────────────────────

/// The overlay's own rows, unwrapped from the border columns around them.
fn overlay_rows(screen: &[String]) -> Vec<String> {
    screen
        .iter()
        .filter_map(|line| {
            let mut parts = line.split('│');
            parts.next()?;
            Some(parts.next()?.trim_end().to_string())
        })
        .collect()
}

/// A registered row built straight, bypassing the offerable filter.
///
/// #7887: `checkout` is the production resolver's own answer for the row, so a
/// row built here compares equal to the one `targets_from` produces.
fn target(name: &str, repo: &str) -> Target {
    Target::Registered {
        name: name.to_string(),
        repo: repo.to_string(),
        checkout: local_checkout_for(&project(name, repo)),
    }
}

/// [`target`] carrying [`stub_checkout`]'s answer instead of the real resolver's.
///
/// #8582: pairs with `targets_from_with(.., stub_checkout)` so neither side of a
/// full `Target` comparison reads the projects-root env sibling tests `set_var`.
fn stub_target(name: &str, repo: &str) -> Target {
    Target::Registered {
        name: name.to_string(),
        repo: repo.to_string(),
        checkout: stub_checkout(&project(name, repo)),
    }
}

/// Three registered rows, in the alphabetical order #7421 renders them:
/// `acme/widgets`, `bobmatnyc/trusty-tools`, `duetto/apex`.
fn three_projects() -> Vec<Target> {
    new_session::targets_from(
        &[
            project("trusty-tools", "https://github.com/bobmatnyc/trusty-tools"),
            project("apex", "https://github.com/duetto/apex"),
            project("widgets", "https://github.com/acme/widgets"),
        ],
        &[],
    )
}

/// The overlay opens on the project of the row the cursor was on.
///
/// Why (#7406 requirement 1): opening on row 0 made the operator scroll past
/// the project they were already looking at on every create. The fixture puts
/// that project THIRD, so an implementation that keeps the old behaviour — or
/// that matches on the first row by accident — fails here.
#[test]
fn new_session_preselects_the_cursor_sessions_project() {
    let targets = three_projects();
    // The session spells the remote differently from the registry row; the
    // shared `repo_url_matches` is what makes the two agree.
    let mut cursor = session("a1", "Active", 1);
    cursor.repo_url = Some("git@github.com:duetto/apex.git".to_string());
    assert_eq!(new_session::preselect_index(&targets, Some(&cursor)), 2);

    let flow = NewSessionFlow::with_resolver(targets.clone(), stub_identity)
        .preselected_for(Some(&cursor));
    let rows = flow.rows();
    assert_eq!(rows[2], "▸ duetto/apex", "{rows:?}");
    assert!(!rows[0].starts_with('▸'), "{rows:?}");

    // A session with no `repo_url` is matched on its `owner/repo` source id.
    let mut by_source = session("t1", "Active", 2);
    by_source.source_id = Some("bobmatnyc/trusty-tools".to_string());
    assert_eq!(new_session::preselect_index(&targets, Some(&by_source)), 1);
}

#[test]
fn new_session_preselect_falls_back_to_the_first_row() {
    let targets = three_projects();
    // No cursor session at all.
    assert_eq!(new_session::preselect_index(&targets, None), 0);
    // A cursor session whose project is not registered.
    let mut stranger = session("s1", "Active", 1);
    stranger.repo_url = Some("https://github.com/other/thing".to_string());
    assert_eq!(new_session::preselect_index(&targets, Some(&stranger)), 0);
    // A cursor session that names no project at all.
    let bare = session("b1", "Active", 1);
    assert_eq!(new_session::preselect_index(&targets, Some(&bare)), 0);
}

/// Every row is `owner/repo` or `<basename> (local)` — never a URL or a path.
#[test]
fn new_session_rows_show_owner_repo_only() {
    let flow = NewSessionFlow::with_resolver(
        vec![
            target(
                "trusty-tools",
                "https://github.com/bobmatnyc/trusty-tools.git",
            ),
            target("widgets", "/Users/me/code/widgets"),
            target("nameless", ""),
            Target::Other,
        ],
        stub_identity,
    );
    assert_eq!(
        flow.rows(),
        vec![
            "▸ bobmatnyc/trusty-tools".to_string(),
            "  widgets (local)".to_string(),
            "  nameless (local)".to_string(),
            "  other — type a project path…".to_string(),
        ]
    );
}

/// The host appears only when two rows would otherwise read identically.
#[test]
fn new_session_labels_disambiguate_by_host() {
    let labels = new_session::row_labels(&[
        target("apex", "https://github.com/duetto/apex"),
        target("apex-gl", "https://gitlab.com/duetto/apex"),
        target("trusty-tools", "https://github.com/bobmatnyc/trusty-tools"),
    ]);
    assert_eq!(
        labels,
        vec![
            "github.com/duetto/apex".to_string(),
            "gitlab.com/duetto/apex".to_string(),
            // Unique on its own, so it keeps the short form.
            "bobmatnyc/trusty-tools".to_string(),
        ]
    );
}

/// A registration nobody can work in never reaches the picker.
///
/// Why (#7406 requirement 3): the owner's screen listed a probe registered at a
/// `/private/tmp/…/scratchpad/…` path. The fixture carries that row, a row
/// whose path is gone, and two rows that must survive.
///
/// #8582: `targets_from_with(.., stub_checkout)` and [`stub_target`], not
/// `targets_from` and [`target`]. Those resolve `checkout` through the real
/// `local_checkout_for` twice — once per side — reading `TRUSTY_MPM_REPOS_ROOT`
/// each time, so a sibling test's `set_var` between the reads failed the
/// comparison. The filter under test is the same one `targets_from` runs.
#[test]
fn new_session_targets_from_drops_a_scratchpad_registration() {
    let targets = new_session::targets_from_with(
        &[
            project(
                "mcp-probe-scratch-4181",
                "/private/tmp/claude-502/abc/scratchpad/mcp-probe-scratch-4181",
            ),
            project("gone", "/nonexistent/7406/no-such-checkout"),
            project("trusty-tools", "https://github.com/bobmatnyc/trusty-tools"),
            project("apex", "https://github.com/duetto/apex"),
        ],
        &[],
        stub_checkout,
    );
    assert_eq!(
        targets,
        vec![
            stub_target("trusty-tools", "https://github.com/bobmatnyc/trusty-tools"),
            stub_target("apex", "https://github.com/duetto/apex"),
            Target::Other,
        ]
    );
}

/// At 80 columns the rows are short, exact, and never wrap.
///
/// Why (#7406 requirement 2): the owner's screen wrapped a path onto a second
/// line, which is what made the list unreadable. Asserting the EXACT row text
/// at the narrowest supported width is what catches a row that grows back.
#[test]
fn render_new_session_rows_at_eighty_columns() {
    let sessions = fleet();
    let mut state = browsing();
    state.open_new_session(NewSessionFlow::with_resolver(
        vec![
            target("trusty-tools", "https://github.com/bobmatnyc/trusty-tools"),
            target("widgets", "/Users/me/code/widgets"),
            Target::Other,
        ],
        stub_identity,
    ));
    let screen = draw(80, 24, &sessions, &mut state);
    let rows = overlay_rows(&screen);
    // The popup is 80% of 80 columns; its inner width is what a row may use.
    for row in &rows {
        assert!(
            row.chars().count() <= 62,
            "row over the pane width: {row:?}"
        );
    }
    assert!(
        rows.contains(&"▸ bobmatnyc/trusty-tools".to_string()),
        "{rows:?}"
    );
    assert!(rows.contains(&"  widgets (local)".to_string()), "{rows:?}");
    let joined = screen.join("\n");
    assert!(
        !joined.contains("https://"),
        "a full URL reached a row: {joined}"
    );
    assert!(
        !joined.contains("/Users/me/code"),
        "an absolute path reached a row: {joined}"
    );
}

// ── new-session picker order, position and filter (#7421) ───────────────────

/// Six registrations, spelled in one order; the caller may reshuffle them.
fn six_projects() -> Vec<Project> {
    vec![
        project("apex", "https://github.com/duetto/apex"),
        project("widgets", "https://github.com/acme/widgets"),
        project("trusty-tools", "https://github.com/bobmatnyc/trusty-tools"),
        project("zeta", "https://github.com/zed/zeta"),
        project("mid", "https://github.com/mid/mid"),
        project("early", "https://github.com/early/early"),
    ]
}

/// The same registry contents render the same rows, whatever order they arrive
/// in.
///
/// Why (#7421 acceptance 1 and 5): the registry is a `HashMap`, so
/// `registry_list_projects` hands back `values()` in an order that varies run to
/// run. Against the pre-#7421 `targets_from` — which mapped the input straight
/// through — a permuted input produced a permuted row list, so this fails there.
///
/// #7989: uses `targets_from_with(..., stub_checkout)` rather than
/// `targets_from`, which resolves each row's checkout through the real
/// `local_checkout_for` — `repos_root()` → `$TRUSTY_MPM_REPOS_ROOT` /
/// `$TRUSTY_MPM_WORKSPACE_ROOT` / config / real `$HOME`. Sibling tests in this
/// binary `set_var` those keys, so under the parallel harness a full-bin run
/// could race a `Target::Registered.checkout` in the middle of this
/// comparison. The stub removes that dependence; the assertions below are
/// unaffected since they only ever compared the label order.
#[test]
fn new_session_order_is_independent_of_registry_iteration_order() {
    let forward = new_session::targets_from_with(&six_projects(), &[], stub_checkout);
    let mut shuffled = six_projects();
    shuffled.reverse();
    shuffled.swap(0, 3);
    let reversed = new_session::targets_from_with(&shuffled, &[], stub_checkout);
    assert_eq!(forward, reversed, "the row order followed the input order");
    // And the order is the alphabetical one the labels spell, escape hatch last.
    assert_eq!(
        new_session::row_labels(&forward),
        vec![
            "acme/widgets".to_string(),
            "bobmatnyc/trusty-tools".to_string(),
            "duetto/apex".to_string(),
            "early/early".to_string(),
            "mid/mid".to_string(),
            "zed/zeta".to_string(),
            "other — type a project path…".to_string(),
        ]
    );
}

/// A project with a live session outranks every project without one.
///
/// Why (#7421 acceptance 1 and 5): the owner's four projects with running
/// sessions were the ones scrolling out of the eight-row window. `zed/zeta`
/// sorts LAST alphabetically, so an implementation that only sorts by label —
/// the pre-#7421 behaviour plus a plain sort — fails here.
#[test]
fn new_session_order_puts_a_live_session_project_first() {
    let mut live = session("z1", "active", 1);
    live.repo_url = Some("git@github.com:zed/zeta.git".to_string());
    live.last_activity_at = Some("2026-09-11T10:00:00Z".to_string());
    // A second session, older and merely stopped, in a project that would
    // otherwise sort first.
    let mut older = session("w1", "stopped", 2);
    older.source_id = Some("acme/widgets".to_string());
    older.last_activity_at = Some("2026-09-01T10:00:00Z".to_string());

    let rows = new_session::targets_from(&six_projects(), &[live, older]);
    let labels = new_session::row_labels(&rows);
    assert_eq!(
        labels.first().map(String::as_str),
        Some("zed/zeta"),
        "the live-session project did not sort first: {labels:?}"
    );
    assert_eq!(
        labels.get(1).map(String::as_str),
        Some("acme/widgets"),
        "the stopped-session project did not outrank the session-less ones: {labels:?}"
    );
    assert_eq!(
        labels.get(2).map(String::as_str),
        Some("bobmatnyc/trusty-tools"),
        "the session-less rows lost their alphabetical order: {labels:?}"
    );
}

/// Typing narrows the rows; Esc clears the filter before it cancels the flow.
///
/// Why (#7421 acceptance 3): a twenty-project registry is unusable by arrow key
/// alone, and an Esc that threw the whole flow away on a mistyped filter would
/// make typing more expensive than scrolling.
#[test]
fn new_session_typing_filters_the_rows() {
    let mut flow = NewSessionFlow::with_resolver(
        new_session::targets_from(&six_projects(), &[]),
        stub_identity,
    );
    assert_eq!(flow.rows().len(), 7);

    assert_eq!(flow.apply(Input::Char('z')), Step::Redraw);
    assert_eq!(flow.filter(), "z");
    // The matching row, plus the typed-path escape, which never filters away.
    assert_eq!(
        flow.rows(),
        vec![
            "▸ zed/zeta".to_string(),
            "  other — type a project path…".to_string(),
        ],
        "the filter did not narrow the rows"
    );

    // Matching is case-insensitive and runs over the whole label.
    assert_eq!(flow.apply(Input::Backspace), Step::Redraw);
    assert_eq!(flow.apply(Input::Char('A')), Step::Redraw);
    assert_eq!(flow.apply(Input::Char('C')), Step::Redraw);
    assert_eq!(flow.rows().len(), 2, "{:?}", flow.rows());
    assert!(flow.rows()[0].contains("acme/widgets"), "{:?}", flow.rows());

    // Esc clears the filter; a second Esc, with nothing left to clear, cancels.
    assert_eq!(flow.apply(Input::Escape), Step::Redraw);
    assert_eq!(flow.filter(), "");
    assert_eq!(flow.rows().len(), 7);
    assert_eq!(flow.apply(Input::Escape), Step::Cancel);
}

/// A filter that hides the highlighted row re-seats it on the first match.
#[test]
fn new_session_filter_keeps_the_selection_valid() {
    let mut flow = NewSessionFlow::with_resolver(
        // #7887: Enter below sends a directory, so the rows need one.
        new_session::targets_from_with(&six_projects(), &[], stub_checkout),
        stub_identity,
    );
    // Move onto `bobmatnyc/trusty-tools`, then filter it away.
    assert_eq!(flow.apply(Input::Down), Step::Redraw);
    assert_eq!(flow.apply(Input::Char('z')), Step::Redraw);
    let rows = flow.rows();
    assert!(
        rows[0].starts_with("▸ zed/zeta"),
        "the highlight stayed on a hidden row: {rows:?}"
    );
    // And Enter confirms the row the highlight is actually on.
    assert_eq!(
        flow.apply(Input::Enter),
        Step::Create(NewSessionRequest {
            register: None,
            repo: fixture_checkout("zeta").display().to_string(),
            label: "zeta".to_string(),
            name_hint: None,
        })
    );
}

/// The overlay says where in the list the eight-row window sits.
///
/// Why (#7421 acceptance 2): with twenty-seven registrations and no indicator,
/// a project below the fold was indistinguishable from one that is not
/// registered at all.
#[test]
fn new_session_position_indicator_reports_the_window() {
    let many: Vec<Project> = (0..26)
        .map(|i| {
            project(
                &format!("p{i:02}"),
                &format!("https://ex.test/o{i:02}/p{i:02}"),
            )
        })
        .collect();
    let mut flow =
        NewSessionFlow::with_resolver(new_session::targets_from(&many, &[]), stub_identity);
    // Twenty-six projects plus the typed-path escape.
    assert_eq!(flow.position(), Some("1–8 of 27".to_string()));
    for _ in 0..9 {
        flow.apply(Input::Down);
    }
    assert_eq!(flow.position(), Some("3–10 of 27".to_string()));
    // A short list needs no indicator at all.
    let short = NewSessionFlow::with_resolver(new_session::targets_from(&[], &[]), stub_identity);
    assert_eq!(short.position(), None);
}

/// The rendered overlay carries both the position and the typed filter.
#[test]
fn render_new_session_overlay_shows_the_position_and_filter() {
    let sessions = fleet();
    let many: Vec<Project> = (0..26)
        .map(|i| {
            project(
                &format!("p{i:02}"),
                &format!("https://ex.test/o{i:02}/p{i:02}"),
            )
        })
        .collect();
    let mut state = browsing();
    state.open_new_session(NewSessionFlow::with_resolver(
        new_session::targets_from(&many, &[]),
        stub_identity,
    ));
    let joined = draw(110, 30, &sessions, &mut state).join("\n");
    assert!(joined.contains("1–8 of 27"), "{joined}");
    assert!(joined.contains("Type to filter"), "{joined}");

    state.apply(Input::Char('o'), &sessions);
    state.apply(Input::Char('1'), &sessions);
    let joined = draw(110, 30, &sessions, &mut state).join("\n");
    assert!(joined.contains("filter: o1"), "{joined}");
}

/// A row wider than the pane is cut with `…` rather than wrapped.
#[test]
fn render_new_session_overlay_truncates_a_long_row() {
    let sessions = fleet();
    let mut state = browsing();
    let long = format!("https://github.com/{}/{}", "o".repeat(40), "r".repeat(40));
    state.open_new_session(NewSessionFlow::with_resolver(
        vec![target("long", &long), Target::Other],
        stub_identity,
    ));
    let screen = draw(80, 24, &sessions, &mut state);
    let joined = screen.join("\n");
    assert!(joined.contains('…'), "the long row was not cut: {joined}");
    assert!(
        !joined.contains(&"r".repeat(40)),
        "the long row wrapped instead of being cut: {joined}"
    );
}

// ── new-session picker grouping and free-text entry (#7488) ─────────────────

/// A registry spanning two GitHub owners, a self-hosted forge, a GitLab owner
/// and one registration with no remote at all.
///
/// Why: the four cases the grouping has to tell apart, in one fixture — and
/// `alpha.example.com` deliberately hosts a `zed/infra` whose LABEL sorts near
/// the end, so a plain label sort cannot produce the expected order by accident.
fn grouped_projects() -> Vec<Project> {
    vec![
        project("api", "https://github.com/acme/api"),
        project("charts", "https://gitlab.com/zeta/charts"),
        project("infra", "https://alpha.example.com/zed/infra"),
        project("notes", ""),
        project("tools", "git@gitlab.com:zeta/tools.git"),
        project("trusty-tools", "https://github.com/bobmatnyc/trusty-tools"),
        project("widgets", "https://github.com/acme/widgets"),
    ]
}

/// Rows group by owner-or-domain, then by name, whatever order they arrive in.
///
/// Why (#7488 acceptance 1): the owner asked for the list to be structured by
/// who owns the project. `zed/infra` is on a self-hosted host, so it groups
/// under `alpha.example.com` — between `acme` and `bobmatnyc` — while a plain
/// alphabetical sort of the LABELS would put it second from last. That gap is
/// what makes this fail against #7421's ordering.
///
/// #7989: uses `targets_from_with(..., stub_checkout)` throughout, not
/// `targets_from` — this test compares full `Vec<Target>` equality, which
/// includes each row's `checkout`, resolved through the real
/// `local_checkout_for` under `targets_from`. That path reads
/// `TRUSTY_MPM_REPOS_ROOT` / `TRUSTY_MPM_WORKSPACE_ROOT` / config / real
/// `$HOME`, which sibling tests in this binary `set_var` — a race under the
/// parallel harness. The stub removes that dependence.
#[test]
fn new_session_order_groups_by_owner_then_domain() {
    let forward = new_session::targets_from_with(&grouped_projects(), &[], stub_checkout);
    assert_eq!(
        new_session::row_labels(&forward),
        vec![
            // github.com → the owner is the group.
            "acme/api".to_string(),
            "acme/widgets".to_string(),
            // Not a known forge → the host is the group, so it sorts under `a`.
            "zed/infra".to_string(),
            "bobmatnyc/trusty-tools".to_string(),
            "zeta/charts".to_string(),
            "zeta/tools".to_string(),
            // No remote → one fixed group, always last.
            "notes (local)".to_string(),
            "other — type a project path…".to_string(),
        ]
    );

    // Two differently shuffled inputs, one order (#7488 acceptance 1).
    let mut shuffled = grouped_projects();
    shuffled.reverse();
    shuffled.swap(0, 4);
    shuffled.swap(1, 5);
    assert_eq!(
        new_session::targets_from_with(&shuffled, &[], stub_checkout),
        forward,
        "the row order followed the input order"
    );
    let mut other = grouped_projects();
    other.rotate_left(3);
    other.swap(2, 6);
    assert_eq!(
        new_session::targets_from_with(&other, &[], stub_checkout),
        forward,
        "a second shuffle produced a third order"
    );
}

/// A live session lifts its whole OWNER, and stays first inside it.
///
/// Why (#7488 acceptance 1): #7421's "the projects I am working in come first"
/// has to survive the grouping, and the least surprising way to keep both is to
/// move the group rather than pull one row out of it. `zeta` sorts last of the
/// remote groups, so an implementation that ignores sessions fails here, and one
/// that hoists the single project out of its group fails on the second row.
#[test]
fn new_session_order_lifts_the_whole_group_of_a_live_session() {
    let mut live = session("z1", "active", 1);
    live.source_id = Some("zeta/tools".to_string());
    live.last_activity_at = Some("2026-09-11T10:00:00Z".to_string());

    let rows = new_session::targets_from(&grouped_projects(), &[live]);
    assert_eq!(
        new_session::row_labels(&rows),
        vec![
            "zeta/tools".to_string(),
            "zeta/charts".to_string(),
            "acme/api".to_string(),
            "acme/widgets".to_string(),
            "zed/infra".to_string(),
            "bobmatnyc/trusty-tools".to_string(),
            "notes (local)".to_string(),
            "other — type a project path…".to_string(),
        ]
    );
}

/// Group keys: the owner on a known forge, the host anywhere else, one fixed
/// key with no remote.
#[test]
fn new_session_order_group_of_reads_owner_then_domain() {
    use super::new_session_order::group_of;
    assert_eq!(
        group_of("https://github.com/Acme/api"),
        (0, "acme".to_string())
    );
    assert_eq!(
        group_of("git@gitlab.com:zeta/tools.git"),
        (0, "zeta".to_string())
    );
    assert_eq!(
        group_of("https://alpha.example.com/zed/infra"),
        (0, "alpha.example.com".to_string())
    );
    // A local path and an empty registration are the same, always-last group.
    assert_eq!(
        group_of("/Users/me/code/widgets"),
        (1, "(local)".to_string())
    );
    assert_eq!(group_of(""), (1, "(local)".to_string()));
}

/// The three spellings the picker accepts as a project it can clone.
#[test]
fn new_session_entry_parses_the_three_shapes() {
    use super::new_session_entry::{ProjectEntry, parse_project_entry};
    let expect = |text: &str, name: &str, repo_url: &str| {
        assert_eq!(
            parse_project_entry(text),
            Some(ProjectEntry {
                name: name.to_string(),
                repo_url: repo_url.to_string(),
            }),
            "{text}"
        );
    };
    // (a) a full clone URL, kept verbatim so an ssh entry still clones over ssh.
    expect(
        "https://github.com/acme/widgets",
        "widgets",
        "https://github.com/acme/widgets",
    );
    expect(
        "https://github.com/acme/widgets.git",
        "widgets",
        "https://github.com/acme/widgets.git",
    );
    expect(
        "git@github.com:acme/widgets.git",
        "widgets",
        "git@github.com:acme/widgets.git",
    );
    expect(
        "ssh://git@git.example.com/ops/infra",
        "infra",
        "ssh://git@git.example.com/ops/infra",
    );
    // (b) `owner/repo` means github.com.
    expect("acme/widgets", "widgets", "https://github.com/acme/widgets");
    expect(
        "acme/widgets.git",
        "widgets",
        "https://github.com/acme/widgets",
    );
    // (c) `domain/owner/repo` spells the host.
    expect(
        "git.example.com/ops/infra",
        "infra",
        "https://git.example.com/ops/infra",
    );
    expect(
        "localhost/ops/infra",
        "infra",
        "https://localhost/ops/infra",
    );
}

/// Text that names no project is refused, never guessed at.
#[test]
fn new_session_entry_rejects_malformed_text() {
    use super::new_session_entry::parse_project_entry;
    for bad in [
        "",
        "   ",
        "widgets",
        "acme/",
        "/acme/widgets",
        "acme widgets",
        "acme/widgets/extra/deep",
        // A path is the checkout resolver's job, not a clone target.
        "/Users/me/code/widgets",
        "~/code/widgets",
        "./widgets",
        // Two segments whose first is a domain names no owner.
        "example.com/widgets",
        // A URL shape the one remote parser refuses.
        "https://github.com/acme",
    ] {
        assert_eq!(parse_project_entry(bad), None, "{bad:?} was accepted");
    }
}

/// Where an unregistered project's clone URL is checked out (#7898).
///
/// Why: the production resolver (`local_checkout_for_url`) reads this host's
/// projects root — the same env sibling tests `set_var` (#7989). `acme/widgets`
/// stands for a project already cloned; any other URL stands for one that is
/// not on this host at all.
fn stub_checkout_for_url(repo_url: &str) -> Option<PathBuf> {
    if repo_url == "https://github.com/acme/widgets" {
        return Some(fixture_checkout("widgets"));
    }
    Some(PathBuf::from("/nonexistent/acme/missing"))
}

/// An unregistered entry carries the register leg AND the LOCAL CHECKOUT.
///
/// Why (#7898): the create leg used to carry `entry.repo_url` — a clone URL.
/// Since ADR-0055 the daemon takes only a directory that already exists, so
/// that request registered the project and was then refused by the spawn. This
/// asserts the create argument is the checkout, and asserts against the URL by
/// name so the pre-#7898 request cannot satisfy it.
#[test]
fn new_session_entry_builds_a_clone_and_register_request() {
    let request = super::new_session_entry::request_for_entry_with(
        "acme/widgets",
        &targets(),
        stub_checkout_for_url,
    )
    .expect("owner/repo is a project");
    assert_eq!(
        request,
        NewSessionRequest {
            register: Some(NewProject {
                name: "widgets".to_string(),
                repo_url: "https://github.com/acme/widgets".to_string(),
            }),
            // The directory the daemon can actually start a session in.
            repo: fixture_checkout("widgets").display().to_string(),
            label: "widgets".to_string(),
            name_hint: None,
        }
    );
    assert_ne!(request.repo, "https://github.com/acme/widgets");
}

/// A project that is not cloned yet is refused BEFORE anything is registered.
///
/// Why (#7898): registering first and failing at the spawn left a registration
/// behind for a session that never existed. The refusal names the same
/// `git clone <url> <path>` step the registered-row path prints (#7887), so
/// both ways in say the same thing.
#[test]
fn new_session_entry_without_a_checkout_names_the_clone_step() {
    let err = super::new_session_entry::request_for_entry_with(
        "acme/missing",
        &targets(),
        stub_checkout_for_url,
    )
    .expect_err("a project with no checkout cannot be started");
    assert!(
        err.contains("git clone https://github.com/acme/missing /nonexistent/acme/missing"),
        "{err}"
    );
}

/// #9285: a registered row with no project directory names its stored URL,
/// which can carry a `user:password@`, so the refusal prints it masked.
#[test]
fn new_session_registered_row_without_a_directory_masks_the_stored_password_9285() {
    let err = super::new_session::request_for_registered(
        "cto",
        "https://u:pa'ss9285@github.com/acme/cto",
        None,
    )
    .expect_err("a row with no project directory cannot be started");
    assert!(
        !err.contains("ss9285"),
        "a password fragment survived: {err}"
    );
    assert!(
        !err.contains("u:pa"),
        "the user:password pair survived: {err}"
    );
    assert!(
        err.contains("cto is registered as https://***@github.com/acme/cto,"),
        "{err}"
    );
}

/// #9285: the clone step for an uncloned registered row names the stored URL
/// masked; a masked URL is no `git clone` command, so the step is worded as
/// prose. A clean URL keeps the pasteable command
/// (`new_session_entry_without_a_checkout_names_the_clone_step`).
#[test]
fn new_session_registered_row_without_a_checkout_masks_the_stored_password_9285() {
    let err = super::new_session::request_for_registered(
        "cto",
        "https://u:pa'ss9285@github.com/acme/cto",
        Some(Path::new("/nonexistent/9285/cto")),
    )
    .expect_err("a row with no checkout cannot be started");
    assert!(
        !err.contains("ss9285"),
        "a password fragment survived: {err}"
    );
    assert!(
        !err.contains("u:pa"),
        "the user:password pair survived: {err}"
    );
    assert!(!err.contains("git clone"), "{err}");
    assert!(
        err.contains(
            "clone it first from https://***@github.com/acme/cto into /nonexistent/9285/cto"
        ),
        "{err}"
    );
}

/// #9285: the "names no checkout directory" refusal echoes the typed clone URL,
/// which a `user:password@` can ride in on, so it prints the URL masked.
#[test]
fn new_session_entry_with_no_checkout_masks_the_typed_password_9285() {
    fn no_checkout(_: &str) -> Option<PathBuf> {
        None
    }
    let err = super::new_session_entry::request_for_entry_with(
        "https://u:pa'ss9285@github.com/acme/gadget",
        &targets(),
        no_checkout,
    )
    .expect_err("a URL with no checkout directory cannot be started");
    assert!(
        !err.contains("ss9285"),
        "a password fragment survived: {err}"
    );
    assert!(
        !err.contains("u:pa"),
        "the user:password pair survived: {err}"
    );
    assert!(
        err.starts_with("https://***@github.com/acme/gadget names no checkout"),
        "{err}"
    );
}

/// An entry naming a project the registry already holds never re-registers it.
///
/// Why: `register` is an unqualified upsert, so a redundant call would replace
/// the stored record's optional fields with the two this flow can supply.
/// #7887: and it starts the session in that row's CHECKOUT — typing a
/// registered `owner/repo` must send what picking its row sends.
#[test]
fn new_session_entry_reuses_a_registered_project() {
    let request = super::new_session_entry::request_for_entry("bobmatnyc/trusty-tools", &targets())
        .expect("a registered project is still a project");
    assert_eq!(request.register, None);
    assert_eq!(
        request.repo,
        fixture_checkout("trusty-tools").display().to_string()
    );
    assert_ne!(request.repo, "https://github.com/bobmatnyc/trusty-tools");
    assert_eq!(request.label, "trusty-tools");
}

/// Typing an uncloned project in the filter is refused with the clone step.
///
/// Why (#7488 acceptance 2): the filter box is where the operator already types
/// a project's name; before this, a name matching nothing emptied the list and
/// Enter only opened a blank path prompt.
/// #7898: `acme/widgets` is not cloned under this host's projects root, and the
/// create leg needs a directory that exists — so Enter now refuses inline with
/// the `git clone` step rather than registering the project and failing at the
/// spawn. That the text is RECOGNISED (not "is not a project") is the half this
/// pins; the payload of a recognised, cloned project is
/// `new_session_entry_builds_a_clone_and_register_request`.
#[test]
fn new_session_entry_from_the_filter_creates_a_clone_request() {
    let mut flow = NewSessionFlow::with_resolver(targets(), stub_identity);
    for c in "acme/widgets".chars() {
        assert_eq!(flow.apply(Input::Char(c)), Step::Redraw);
    }
    match flow.apply(Input::Enter) {
        Step::Reject(msg) => assert!(
            msg.contains("git clone https://github.com/acme/widgets"),
            "{msg}"
        ),
        other => panic!("an uncloned project must be refused, got {other:?}"),
    }
}

/// A filter that still matches a row keeps Enter meaning "open that row".
#[test]
fn new_session_entry_does_not_hijack_a_matching_filter() {
    let mut flow = NewSessionFlow::with_resolver(targets(), stub_identity);
    for c in "duetto".chars() {
        flow.apply(Input::Char(c));
    }
    assert_eq!(
        flow.apply(Input::Enter),
        Step::Create(NewSessionRequest {
            register: None,
            repo: fixture_checkout("apex").display().to_string(),
            label: "apex".to_string(),
            name_hint: None,
        })
    );
}

/// Malformed free text is refused inline, with the flow and the filter intact.
///
/// Why (#7488 acceptance 3): nothing may be silently dropped, and no session
/// may be created from text the picker could not read.
#[test]
fn new_session_entry_from_the_filter_rejects_malformed_text() {
    let sessions = fleet();
    let mut state = creating();
    for c in "nope!!".chars() {
        state.apply(Input::Char(c), &sessions);
    }
    assert_eq!(
        state.apply(Input::Enter, &sessions),
        Action::Redraw,
        "malformed text created a session"
    );
    let (text, severity) = state.message().expect("a refusal must be shown");
    assert!(text.contains("nope!!"), "{text}");
    assert_eq!(severity, Severity::Error);
    match state.mode() {
        Mode::New(flow) => assert_eq!(flow.filter(), "nope!!"),
        other => panic!("the flow must stay open, got {other:?}"),
    }
}

/// The typed-path entry takes a clone URL too, not only a checkout path.
///
/// #7898: a clone URL for a project that is not on this host is RECOGNISED and
/// answered with the clone step. The generic "is not a git checkout, a clone
/// URL, or an owner/repo project" wording is reserved for text the recogniser
/// actually refused — overwriting the actionable message with it would send the
/// operator hunting for a typo that is not there.
#[test]
fn new_session_entry_path_step_accepts_a_clone_url() {
    let err =
        new_session::request_for_path("https://github.com/acme/widgets", &targets(), stub_identity)
            .expect_err("the project is not cloned on this host");
    assert!(
        err.contains("git clone https://github.com/acme/widgets"),
        "{err}"
    );
    assert!(!err.contains("is not a git checkout"), "{err}");
}

// ── #8506: whole-row state colors ───────────────────────────────────────────

/// A fleet with one row per state the owner's mapping names, behind a first
/// row that takes the selection highlight so every row under test is drawn in
/// its own style.
fn state_color_fleet() -> Vec<ManagedSessionSummary> {
    let selected = session("tm-selected-00", "active", 1);
    let active = session("tm-active-01", "active", 2);
    let stopped = session("tm-stopped-02", "stopped", 3);
    let errored = session("tm-errored-03", "errored", 4);
    let mut dead = session("tm-dead-04", "stopped", 5);
    dead.unresumable = true;
    let mut attached = session("tm-attached-05", "active", 6);
    attached.attached = true;
    let provisioning = session("tm-provisioning-06", "provisioning", 7);
    let decommissioned = session("tm-decommissioned-07", "decommissioned", 8);
    vec![
        selected,
        active,
        stopped,
        errored,
        dead,
        attached,
        provisioning,
        decommissioned,
    ]
}

/// Draw `sessions` and return, per row, the foreground color of the first
/// cell of its name.
fn row_foregrounds(
    sessions: &[ManagedSessionSummary],
    state: &mut TuiState,
) -> Vec<(String, ratatui::style::Color, ratatui::style::Modifier)> {
    let (w, h) = (200, 30);
    let mut terminal = Terminal::new(TestBackend::new(w, h)).expect("test terminal");
    terminal
        .draw(|frame| render::render(frame, sessions, state))
        .expect("render must not panic");
    let buffer = terminal.backend().buffer().clone();
    sessions
        .iter()
        .map(|s| {
            let (x, y) = (0..h)
                .find_map(|y| {
                    let line: String = (0..w).map(|x| buffer[(x, y)].symbol()).collect();
                    line.find(&s.name)
                        .map(|byte| (line[..byte].chars().count() as u16, y))
                })
                .unwrap_or_else(|| panic!("{} not drawn", s.name));
            let cell = &buffer[(x, y)];
            (s.name.clone(), cell.fg, cell.modifier)
        })
        .collect()
}

/// Why (#8506): the TUI redesign (#7248) kept only attached (cyan) and
/// unresumable (red), so an active and a stopped row drew identically. The
/// owner's mapping is active=green, stopped=yellow, dead=red, and (owner
/// ruling) decommissioned=dim.
/// Test: this test.
#[test]
fn render_paints_each_row_in_its_state_color() {
    use ratatui::style::{Color, Modifier};
    let sessions = state_color_fleet();
    let mut state = TuiState::new(None, None);
    state.sync(&sessions);
    let got = row_foregrounds(&sessions, &mut state);
    let want = [
        ("tm-active-01", Color::Green, Modifier::empty()),
        ("tm-stopped-02", Color::Yellow, Modifier::empty()),
        ("tm-errored-03", Color::Red, Modifier::empty()),
        ("tm-dead-04", Color::Red, Modifier::empty()),
        ("tm-attached-05", Color::Cyan, Modifier::BOLD),
        ("tm-provisioning-06", Color::Blue, Modifier::empty()),
        ("tm-decommissioned-07", Color::Reset, Modifier::DIM),
    ];
    for (name, color, modifier) in want {
        let cell = got
            .iter()
            .find(|(n, _, _)| n == name)
            .map(|(_, fg, m)| (*fg, *m));
        assert_eq!(cell, Some((color, modifier)), "row {name}");
    }
}

/// Why (#8506): `NO_COLOR` must turn the state colors off in the TUI as it does
/// in the static table; the gate is injected through `TuiState::with_color`.
/// Test: this test.
#[test]
fn render_draws_no_state_color_when_color_is_off() {
    use ratatui::style::{Color, Modifier};
    let sessions = state_color_fleet();
    let mut state = TuiState::new(None, None).with_color(false);
    state.sync(&sessions);
    for (name, fg, modifier) in row_foregrounds(&sessions, &mut state).into_iter().skip(1) {
        assert_eq!(fg, Color::Reset, "row {name} must be uncolored");
        assert_eq!(modifier, Modifier::empty(), "row {name} must be unstyled");
    }
}

// ── new-session name step (#8587) ───────────────────────────────────────────

/// The open new-session flow, or a panic naming the mode that is open instead.
fn open_flow(state: &TuiState) -> &NewSessionFlow {
    match state.mode() {
        Mode::New(flow) => flow,
        other => panic!("the new-session flow is not open: {other:?}"),
    }
}

/// `creating()`, moved onto `apex`, with the name step open and `name` typed.
fn naming_apex(name: &str) -> TuiState {
    let sessions = fleet();
    let mut state = creating();
    state.apply(Input::Down, &sessions);
    assert_eq!(state.apply(Input::NameNew, &sessions), Action::Redraw);
    for c in name.chars() {
        state.apply(Input::Char(c), &sessions);
    }
    state
}

/// The request Enter on `apex` produces, named `name_hint`.
fn apex_request(name_hint: Option<&str>) -> NewSessionRequest {
    NewSessionRequest {
        register: None,
        repo: fixture_checkout("apex").display().to_string(),
        label: "apex".to_string(),
        name_hint: name_hint.map(str::to_string),
    }
}

#[test]
fn new_session_name_ctrl_n_opens_the_name_step() {
    let sessions = fleet();
    let mut state = creating();
    assert!(open_flow(&state).naming().is_none());
    assert_eq!(state.apply(Input::NameNew, &sessions), Action::Redraw);
    let naming = open_flow(&state)
        .naming()
        .expect("Ctrl-N on a registered row opens the name step");
    assert_eq!(naming.label(), "trusty-tools");
    assert_eq!(naming.typed(), "");
    // Ctrl-N while browsing does nothing; only the project list offers it.
    let mut browse = browsing();
    assert_eq!(browse.apply(Input::NameNew, &sessions), Action::Ignore);
    assert_eq!(browse.mode(), &Mode::Browse);
}

#[test]
fn new_session_name_ctrl_n_rejects_the_path_row() {
    let sessions = fleet();
    let mut state = creating();
    state.apply(Input::Down, &sessions);
    state.apply(Input::Down, &sessions);
    assert_eq!(state.apply(Input::NameNew, &sessions), Action::Redraw);
    assert_eq!(
        state.message(),
        Some((super::new_session_name::NOT_A_PROJECT, Severity::Error))
    );
    assert!(open_flow(&state).naming().is_none(), "no name step opened");
}

/// A row Enter refuses is refused at the Ctrl-N keypress, with Enter's words.
#[test]
fn new_session_name_ctrl_n_rejects_a_row_without_a_checkout() {
    let flow = || {
        NewSessionFlow::with_resolver(
            new_session::targets_from_with(
                &[project("cto", "https://github.com/bob-duetto/cto")],
                &[],
                missing_checkout,
            ),
            stub_identity,
        )
    };
    let Step::Reject(on_enter) = flow().apply(Input::Enter) else {
        panic!("Enter must refuse a row with no checkout");
    };
    let mut named = flow();
    assert_eq!(named.apply(Input::NameNew), Step::Reject(on_enter));
    assert!(named.naming().is_none(), "no name step opened");
}

#[test]
fn new_session_name_enter_creates_with_the_slug() {
    let sessions = fleet();
    let mut state = naming_apex("Auth Refactor");
    assert_eq!(
        state.apply(Input::Enter, &sessions),
        Action::Create(apex_request(Some("auth-refactor")))
    );
    assert_eq!(state.mode(), &Mode::Browse, "the overlay closes on create");
}

#[test]
fn new_session_name_rejects_an_empty_slug() {
    let sessions = fleet();
    for typed in ["", "!!!"] {
        let mut state = naming_apex(typed);
        assert_eq!(state.apply(Input::Enter, &sessions), Action::Redraw);
        let (message, severity) = state.message().expect("the refusal is shown");
        assert_eq!(severity, Severity::Error);
        assert!(message.contains("no letters or digits"), "{message}");
        let naming = open_flow(&state)
            .naming()
            .expect("the name step stays open after a refusal");
        assert_eq!(naming.typed(), typed);
    }
}

/// Esc in the name step goes back ONE step: the filter and highlight survive.
///
/// Why: the flow's Esc arm clears a non-empty filter before anything else, so
/// a name step routed after it would lose the filter instead of closing.
#[test]
fn new_session_name_escape_returns_to_the_list_intact() {
    let sessions = fleet();
    let mut state = creating();
    for c in "ap".chars() {
        state.apply(Input::Char(c), &sessions);
    }
    let before = open_flow(&state).clone();
    assert!(
        before
            .rows()
            .iter()
            .any(|r| r.starts_with('▸') && r.contains("duetto/apex")),
        "{:?}",
        before.rows()
    );
    state.apply(Input::NameNew, &sessions);
    state.apply(Input::Char('x'), &sessions);
    assert_eq!(state.apply(Input::Escape, &sessions), Action::Redraw);
    assert_eq!(open_flow(&state), &before, "filter and selection intact");
    assert_eq!(open_flow(&state).filter(), "ap");
}

#[test]
fn new_session_name_preview_shows_the_slug() {
    let named = naming_apex("Auth Refactor");
    let naming = open_flow(&named).naming().expect("name step open");
    assert_eq!(naming.preview().as_deref(), Some("tm-auth-refactor-NN"));
    let symbols = naming_apex("!!!");
    let naming = open_flow(&symbols).naming().expect("name step open");
    assert_eq!(naming.preview(), None);
}

#[test]
fn new_session_name_overlay_shows_the_text_and_preview() {
    let sessions = fleet();
    let mut picker = creating();
    let joined = draw(110, 30, &sessions, &mut picker).join("\n");
    assert!(
        joined.contains("Ctrl-N"),
        "the list must offer Ctrl-N:\n{joined}"
    );

    let mut state = naming_apex("Auth Refactor");
    let joined = draw(110, 30, &sessions, &mut state).join("\n");
    assert!(joined.contains("in apex"), "{joined}");
    assert!(joined.contains("> Auth Refactor"), "{joined}");
    assert!(joined.contains("tm-auth-refactor-NN"), "{joined}");
    assert!(joined.contains("Esc goes back"), "{joined}");
}

#[test]
fn render_help_overlay_lists_ctrl_n() {
    let sessions = fleet();
    let mut state = browsing();
    state.apply(Input::Char('?'), &sessions);
    let joined = draw(100, 30, &sessions, &mut state).join("\n");
    assert!(joined.contains("Ctrl-N"), "help omits Ctrl-N:\n{joined}");
}

#[test]
fn new_session_name_status_line_names_the_session() {
    use super::new_session_name::created_message;
    assert_eq!(created_message(&apex_request(None)), "new session in apex");
    assert_eq!(
        created_message(&apex_request(Some("auth-refactor"))),
        "new session named auth-refactor in apex"
    );
}

/// Backspace removes one CHARACTER, so a multi-byte letter goes whole.
#[test]
fn new_session_name_backspace_removes_a_whole_character() {
    let sessions = fleet();
    let mut state = naming_apex("café");
    assert_eq!(state.apply(Input::Backspace, &sessions), Action::Redraw);
    let naming = open_flow(&state).naming().expect("name step open");
    assert_eq!(naming.typed(), "caf");
}

/// A name past the slug cap previews exactly what `leaf_slug_from_hint` sends.
#[test]
fn new_session_name_long_name_preview_matches_the_capped_slug() {
    let name = "authentication refactor phase two";
    let slug = trusty_common::session_naming::leaf_slug_from_hint(name);
    assert!(!slug.ends_with('-'), "{slug}");
    assert!(slug.len() < name.len(), "the cap must have cut: {slug}");
    let state = naming_apex(name);
    let naming = open_flow(&state).naming().expect("name step open");
    let preview = naming.preview().expect("a long name still slugs");
    assert_eq!(preview, format!("tm-{slug}-NN"));
    assert!(!preview.trim_end_matches("-NN").ends_with('-'), "{preview}");
}

/// Arrow keys while naming move nothing: the step owns the keys.
#[test]
fn new_session_name_arrows_are_ignored_while_naming() {
    let sessions = fleet();
    let mut state = naming_apex("auth");
    let before = open_flow(&state).clone();
    assert_eq!(state.apply(Input::Down, &sessions), Action::Ignore);
    assert_eq!(state.apply(Input::Up, &sessions), Action::Ignore);
    assert_eq!(open_flow(&state), &before, "selection unchanged");
}

/// The typed name reaches the create leg — the fail-open check (#8587).
///
/// Why: a `name_hint` field can exist on the request and still be dropped by
/// `perform_with`, which then creates a default-named session. Driven from the
/// keystrokes, so the request is the one the TUI really builds.
#[tokio::test]
async fn new_session_name_reaches_the_create_leg() {
    let sessions = fleet();
    let mut state = naming_apex("Auth Refactor");
    let Action::Create(request) = state.apply(Input::Enter, &sessions) else {
        panic!("Enter in the name step must create");
    };
    let received = std::cell::RefCell::new(None);
    new_session::perform_with(
        request,
        |_: NewProject| async { anyhow::Ok(()) },
        |repo: String, name_hint: Option<String>| {
            *received.borrow_mut() = Some((repo, name_hint));
            async { anyhow::Ok(AttachOutcome::Attached) }
        },
    )
    .await
    .expect("the create leg must succeed");
    assert_eq!(
        received.into_inner(),
        Some((
            fixture_checkout("apex").display().to_string(),
            Some("auth-refactor".to_string())
        ))
    );
}

/// `perform` puts the name on the daemon POST as `name_hint` (#8587).
///
/// Why: `perform_with` takes its legs as closures, so its test cannot see
/// whether `perform`'s own create closure forwards the name. This one runs
/// `perform` against a local server that records the POST body and answers
/// 500, so the call stops after the POST.
#[tokio::test]
async fn new_session_name_reaches_the_daemon_post() {
    use axum::{Json, Router, routing::post};
    type Captured = std::sync::Arc<std::sync::Mutex<Option<serde_json::Value>>>;
    let captured: Captured = std::sync::Arc::default();
    let sink = std::sync::Arc::clone(&captured);
    let handler = move |Json(body): Json<serde_json::Value>| {
        let sink = std::sync::Arc::clone(&sink);
        async move {
            *sink.lock().expect("capture mutex") = Some(body);
            axum::http::StatusCode::INTERNAL_SERVER_ERROR
        }
    };
    let router = Router::new().route("/api/v1/sessions/managed", post(handler));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
        .await
        .expect("bind ephemeral port");
    let url = format!("http://{}", listener.local_addr().expect("local_addr"));
    tokio::spawn(async move { axum::serve(listener, router).await.ok() });

    let result = new_session::perform(
        &reqwest::Client::new(),
        &url,
        apex_request(Some("auth-refactor")),
    )
    .await;
    assert!(result.is_err(), "the server answers 500: {result:?}");
    let body = captured
        .lock()
        .expect("capture mutex")
        .clone()
        .expect("perform must POST the create request");
    assert_eq!(body["name_hint"], "auth-refactor", "{body}");
}