croft-software 0.2.232

VSCode-style TUI written in Rust
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
//! Remote work: SSH, the relay, ports, fleet, devcontainers and drop to
//! local.

use super::*;

#[test]
fn persistence_advisory_only_for_nonpersistent_remote_sessions() {
    // Remote session without dtach: warn on the status line. Remote-with-dtach
    // and any local session: nothing.
    assert!(super::remote_persistence_status(true, false).is_some());
    assert!(super::remote_persistence_status(true, true).is_none());
    assert!(super::remote_persistence_status(false, false).is_none());
    assert!(super::remote_persistence_status(false, true).is_none());
}

/// #862: leaving a remote croft for the local one ends this process like a
/// quit, so it asks the same way.
#[test]
fn drop_to_local_with_unsaved_edits_asks_first() {
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, a) = app_with_unsaved_file(tmp.path());
    app.session.is_remote = true;
    app.handle_key(key(KeyCode::Char('k'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('l'), KeyModifiers::NONE))
        .unwrap();
    assert!(!app.quit && !app.drop_to_local);
    assert_eq!(app.pending_unsaved, Some(UnsavedExit::DropToLocal));
    app.handle_key(key(KeyCode::Char('s'), KeyModifiers::NONE))
        .unwrap();
    assert!(app.drop_to_local && app.quit);
    assert_eq!(std::fs::read_to_string(&a).unwrap(), "xalpha\n");
}

/// The two install outcomes that hand this terminal to the remote croft:
/// one was already there (it launches while the reinstall runs on), or the
/// install just finished.
fn handoff_events() -> [crate::install_session::InstallEvent; 2] {
    use crate::install_session::InstallEvent;
    [InstallEvent::CanLaunch, InstallEvent::Done(Ok(()))]
}

/// #862: connecting to a remote croft ends this one once the remote side is
/// ready, which can be minutes after the connect was asked for. An edit
/// made meanwhile went with it: the handoff set `quit` without asking. It
/// asks now, and S saves before handing off.
#[test]
fn a_remote_handoff_asks_about_edits_made_during_the_install() {
    for event in handoff_events() {
        let tmp = tempfile::tempdir().unwrap();
        let mut app = app_with_open_file(tmp.path(), "a.txt", "alpha\n");
        // Nothing was unsaved when the connect was asked for; the edit
        // comes while the install runs.
        type_keys(&mut app, "x");
        ready_to_hand_off(&mut app, event);
        app.poll_install_session();
        assert!(!app.quit, "the unsaved a.txt must not go with the handoff");
        assert!(app.pending_unsaved.is_some(), "it asks");
        let screen = draw_screen(&mut app, 160, 40);
        assert!(screen.contains("ave all and connect"), "{screen}");
        app.handle_key(key(KeyCode::Char('s'), KeyModifiers::NONE))
            .unwrap();
        assert!(app.quit, "saved, so it hands off: {}", app.status);
        assert!(app.remote_launch.is_some(), "to the remote croft");
        let a = tmp.path().join("a.txt");
        assert_eq!(std::fs::read_to_string(&a).unwrap(), "xalpha\n");
    }
}

/// #862 negative: with nothing unsaved the handoff goes at once, as before.
#[test]
fn a_remote_handoff_with_nothing_unsaved_goes_at_once() {
    for event in handoff_events() {
        let tmp = tempfile::tempdir().unwrap();
        let mut app = app_with_open_file(tmp.path(), "a.txt", "alpha\n");
        ready_to_hand_off(&mut app, event);
        app.poll_install_session();
        assert!(app.quit);
        assert!(app.pending_unsaved.is_none(), "nothing to ask about");
        assert!(app.remote_launch.is_some());
    }
}

/// #862: Esc at the handoff prompt keeps this croft and the edits, and
/// drops the launch rather than leaving it armed for a later quit.
#[test]
fn cancelling_the_remote_handoff_stays_here_with_the_edits() {
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, a) = app_with_unsaved_file(tmp.path());
    ready_to_hand_off(&mut app, crate::install_session::InstallEvent::CanLaunch);
    app.poll_install_session();
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    assert!(!app.quit);
    assert!(app.remote_launch.is_none(), "the launch is dropped");
    assert!(app.install_session.is_none());
    assert!(app.editor.dirty && app.editor.lines[0] == "xalpha");
    assert_eq!(std::fs::read_to_string(&a).unwrap(), "alpha\n");
    assert!(app.status.contains("did not connect"), "{}", app.status);
}

/// A remote install whose thread crashed fails the connect and its dialog
/// says so, reading as failed and closing like any failed connect, even
/// while a helper of the install still holds its log (#2607 review). It used
/// to show the install as under way for good.
#[test]
fn a_remote_install_whose_thread_crashed_fails_the_connect() {
    // A failed install is remembered on disk: keep it off this machine's.
    let _serial = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let tmp = tempfile::tempdir().unwrap();
    let _restore = override_cache_dir(tmp.path().join("cache"));
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.connect_dialog = Some(crate::widgets::connect_dialog::ConnectDialog::new(
        String::from("devbox"),
    ));
    app.install_session = Some(crate::install_session::InstallSession::crashing("devbox"));
    crate::test_budget::await_spawned(
        std::time::Duration::from_secs(1),
        "the crashed install to end",
        || {
            app.poll_install_session();
            app.install_session.is_none()
        },
    );
    let dialog = app.connect_dialog.as_ref().expect("the dialog says why");
    assert_eq!(
        dialog.phase,
        crate::widgets::connect_dialog::DialogPhase::Failed
    );
    assert_eq!(
        dialog.error.as_deref(),
        Some(crate::install_session::CRASHED_DETAIL)
    );
    assert!(
        !app.status.contains("Remote install failed"),
        "the status line is left to the crash notice: {}",
        app.status
    );
    app.handle_connect_dialog_key(key(KeyCode::Esc, KeyModifiers::NONE));
    assert!(app.connect_dialog.is_none(), "Esc closes it");
}

/// #2610: a failed install closes the SSH connection it was handed, its
/// socket's private directory included, instead of leaving it open until
/// croft exits.
#[test]
fn a_failed_remote_install_closes_its_ssh_connection() {
    // A failed install is remembered on disk: keep it off this machine's.
    let _serial = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let tmp = tempfile::tempdir().unwrap();
    let _restore = override_cache_dir(tmp.path().join("cache"));
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let socket_dir = tmp.path().join("ctl");
    std::fs::create_dir(&socket_dir).unwrap();
    let adopted = crate::remote::AdoptedMaster {
        host: String::from("devbox"),
        socket_dir: socket_dir.clone(),
        socket_path: socket_dir.join("ctl"),
    };
    app.connect_dialog = Some(crate::widgets::connect_dialog::ConnectDialog::new(
        String::from("devbox"),
    ));
    app.install_session = Some(crate::install_session::InstallSession::with_events(
        "devbox",
        None,
        Some(adopted),
        vec![crate::install_session::InstallEvent::Done(Err(
            String::from("no space left on device"),
        ))],
    ));
    app.poll_install_session();
    assert!(app.install_session.is_none());
    assert!(
        !socket_dir.exists(),
        "the connection's socket directory is gone"
    );
}

/// #862 negative: S at the handoff prompt whose save is refused (the file
/// changed on disk) stays here, and drops the launch: left armed, the next
/// ordinary Ctrl+Q would have connected instead of quitting.
#[test]
fn a_refused_save_at_the_remote_handoff_drops_the_launch() {
    let tmp = tempfile::tempdir().unwrap();
    let (mut app, a) = app_with_unsaved_file(tmp.path());
    std::fs::write(&a, "changed elsewhere\n").unwrap();
    ready_to_hand_off(&mut app, crate::install_session::InstallEvent::CanLaunch);
    app.poll_install_session();
    app.handle_key(key(KeyCode::Char('s'), KeyModifiers::NONE))
        .unwrap();
    assert!(!app.quit);
    assert!(app.status.contains("Did not connect"), "{}", app.status);
    assert!(app.remote_launch.is_none(), "not left armed");
    assert_eq!(std::fs::read_to_string(&a).unwrap(), "changed elsewhere\n");
}

#[test]
fn ssh_empty_state_overlay_arms_image_clear_when_user_switches_off_remote_view() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // Simulate the post-emit state without actually writing OSC bytes.
    app.overlays.ssh.set_displayed(true);
    app.set_sidebar_view(SidebarView::Explorer);
    app.flush_ssh_empty_state_overlay(&ratatui::buffer::Buffer::empty(app.last_frame_area));
    assert!(
        app.consume_ssh_empty_state_image_clear(),
        "leaving the Remote view after the illustration was painted must arm one terminal.clear() so iTerm2 evicts the cached image cells — otherwise the server-rack PNG ghosts onto the Explorer tree the user just clicked to"
    );
    assert!(!app.overlays.ssh.is_displayed());
}

#[test]
fn ssh_empty_state_overlay_arms_image_clear_when_modal_opens_on_top() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.set_sidebar_view(SidebarView::Remote);
    app.overlays.ssh.set_displayed(true);
    app.handle_key(key(KeyCode::F(1), KeyModifiers::NONE))
        .unwrap();
    app.flush_ssh_empty_state_overlay(&ratatui::buffer::Buffer::empty(app.last_frame_area));
    assert!(
        app.consume_ssh_empty_state_image_clear(),
        "F1 opening the shortcuts modal over the SSH empty state must arm an image-clear so the illustration doesn't bleed through the modal text"
    );
}

#[test]
fn cmd_shift_r_jumps_to_remote_from_any_pane() {
    let mut app = editor_app_with_lines(&["x"]);
    app.focus_pane(Pane::Editor);
    app.handle_key(key(
        KeyCode::Char('r'),
        KeyModifiers::SUPER | KeyModifiers::SHIFT,
    ))
    .unwrap();
    assert_eq!(app.sidebar_view, SidebarView::Remote);
}

/// #2071: Drop to Local is `Cmd+K L`, the same on every pane, and the
/// palette's Remote: Drop to Local; on a remote session either ends it and
/// hands back to the local croft.
#[test]
fn cmd_k_l_on_remote_requests_drop_to_local() {
    let mut app = editor_app_with_lines(&["x"]);
    app.session.is_remote = true;
    app.handle_key(key(KeyCode::Char('k'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('l'), KeyModifiers::NONE))
        .unwrap();
    assert!(
        app.drop_to_local && app.quit,
        "Cmd+K L on a remote-launched croft must request a clean hand-back to the local croft"
    );
    let mut app = editor_app_with_lines(&["x"]);
    app.session.is_remote = true;
    app.run_command(crate::widgets::command_palette::Command::DropToLocal);
    assert!(
        app.drop_to_local && app.quit,
        "and so does the palette's row"
    );
}

/// #2071: Cmd+Shift+L selects all occurrences on a remote session, as it
/// does locally. It used to end the session instead, at once when nothing
/// was unsaved, leaving Select All Occurrences no key there.
#[test]
fn cmd_shift_l_selects_all_occurrences_on_remote_too() {
    for remote in [false, true] {
        let mut app = editor_app_with_lines(&["foo bar foo", "foo"]);
        app.session.is_remote = remote;
        app.handle_key(key(
            KeyCode::Char('l'),
            KeyModifiers::SUPER | KeyModifiers::SHIFT,
        ))
        .unwrap();
        assert!(!app.drop_to_local && !app.quit, "remote={remote}");
        assert!(
            app.status.contains("Selected 3 occurrences"),
            "remote={remote}: {}",
            app.status
        );
    }
}

/// #2071: on a local croft, Drop to Local has nothing to leave and says so.
#[test]
fn drop_to_local_on_local_says_there_is_nothing_to_leave() {
    let mut app = editor_app_with_lines(&["x"]);
    app.session.is_remote = false;
    app.handle_key(key(KeyCode::Char('k'), KeyModifiers::SUPER))
        .unwrap();
    app.handle_key(key(KeyCode::Char('l'), KeyModifiers::NONE))
        .unwrap();
    assert!(!app.drop_to_local && !app.quit);
    assert!(
        app.status.contains("not a remote session"),
        "{}",
        app.status
    );
}

#[test]
fn remote_launched_drop_queues_pull_request_via_relay_log() {
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    // The user dragged a Finder file onto a remote-launched croft. The Mac path
    // doesn't exist on the remote box, but the session is a `croft remote` child
    // (CROFT_REMOTE_AUTOUPDATE set) whose local parent runs a drop pump, so the
    // drop is recorded in the identity-derived relay log (no env path needed)
    // instead of being pasted into the editor.
    let workspace = tempfile::tempdir().unwrap();
    let home = tempfile::tempdir().unwrap();
    let mut app = App::new(workspace.path().to_path_buf()).unwrap();
    app.set_sidebar_view(SidebarView::Explorer);
    app.focus_pane(Pane::Tree);
    let (log, _) = with_relay_home(home.path(), || {
        let log = app.relay_log_path().expect("relay log path derivable");
        app.handle_paste("/Users/vitali/Documents/foo.txt\n");
        (log, ())
    });
    let written = std::fs::read_to_string(&log).expect("relay log was written");
    assert!(
        written.starts_with("pull\t"),
        "relay log entry must be a pull request, got: {written:?}",
    );
    assert!(
        written.contains("/Users/vitali/Documents/foo.txt"),
        "relay log must carry the foreign path, got: {written:?}",
    );
    assert_eq!(app.pending_remote_pulls.len(), 1);
}

/// #538, half two: what "the clipboard" means when croft runs on a remote box.
///
/// The user's clipboard is on the machine they are typing at, not on the Linux
/// box croft runs on. A copy there wrote the REMOTE box's clipboard (usually no
/// tool at all in an SSH session) and fell back to OSC 52, which the host
/// terminal may silently refuse — while the status line claimed success either
/// way. The drop relay already pulls the local clipboard for paste; this is the
/// same road in the other direction.
#[test]
fn copying_on_a_relay_session_pushes_the_text_to_the_local_clipboard() {
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let tmp = tempfile::tempdir().unwrap();
    let home = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // A silent child, so the grid holds exactly what the test feeds it.
    app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
        "/bin/sh",
        &[String::from("-c"), String::from("sleep 60")],
        tmp.path(),
    )
    .unwrap();
    app.show_terminal = true;
    app.focus_pane(Pane::Terminal);
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(160, 30)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let inner = app.terminals[0].last_inner;
    app.terminals[0].feed_bytes_for_test(b"copy-me-538\r\n");
    let (lines, top) = app.terminals[0].grid_lines();
    let vrow = (top
        + lines
            .iter()
            .position(|l| l.starts_with("copy-me-538"))
            .expect("the fed text reached the grid") as i32) as u16;
    app.terminals[0].start_selection_at(inner.x, inner.y + vrow);
    app.terminals[0].extend_selection_to(inner.x + 20, inner.y + vrow);
    let expected = app.terminals[0].selection_text();
    assert!(
        expected.contains("copy-me-538"),
        "precondition: the selection covers the fed text, got {expected:?}"
    );

    // Opt in explicitly. The flag is inert under cfg(test) precisely so that
    // this test's CROFT_RELAY_KEY cannot reroute a concurrent test's copy.
    app.session.relay_key = Some(String::from("testrelay"));
    let (log, inbox_for_assert) = with_relay_home(home.path(), || {
        let log = app.relay_log_path().expect("relay log path derivable");
        let inbox = app.relay_inbox_path().expect("relay inbox path derivable");
        app.handle_key(key(KeyCode::Char('c'), KeyModifiers::SUPER))
            .unwrap();
        (log, inbox)
    });

    let written = std::fs::read_to_string(&log).expect("relay log was written");
    assert!(
        written.starts_with("copy\t"),
        "a copy on a relay session must queue a copy request, got {written:?}"
    );
    // The line carries an ID ONLY: a path on the wire would let anything that
    // can write this log point the pump at a FIFO or outside the relay.
    let request_id = written
        .trim_end()
        .split('\t')
        .nth(1)
        .expect("the request carries an id");
    assert_eq!(
        written.trim_end().split('\t').count(),
        2,
        "no path belongs on the wire, got {written:?}"
    );
    let payload_path = inbox_for_assert.join(format!("{request_id}.txt"));
    let payload = std::fs::read_to_string(&payload_path).expect("the payload file was written");
    assert_eq!(
        payload, expected,
        "the payload must be exactly what was selected"
    );
    assert!(
        app.status.contains("local"),
        "and the status must say WHERE it went, got {:?}",
        app.status
    );
}

#[test]
fn remote_finder_drag_queues_pull_without_tree_focus() {
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    // A drop does not move keyboard focus to the Explorer tree, so a focus-only
    // gate dropped drags whenever the user had last clicked the terminal or
    // editor. A pure-path payload must be recognised regardless of focus.
    let workspace = tempfile::tempdir().unwrap();
    let home = tempfile::tempdir().unwrap();
    let mut app = App::new(workspace.path().to_path_buf()).unwrap();
    app.set_sidebar_view(SidebarView::Explorer);
    app.focus_pane(Pane::Editor); // focus is NOT on the tree
    let log = with_relay_home(home.path(), || {
        let log = app.relay_log_path().expect("relay log path derivable");
        app.handle_paste("/Users/vitali/Documents/dragged.txt\n");
        log
    });
    let written = std::fs::read_to_string(&log).expect("relay log was written");
    assert!(
        written.starts_with("pull\t") && written.contains("/Users/vitali/Documents/dragged.txt"),
        "a pure-path drag must queue a pull even without tree focus, got: {written:?}",
    );
    assert_eq!(app.pending_remote_pulls.len(), 1);
}

#[test]
fn drain_remote_pulls_imports_file_when_relay_signals_ok() {
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let workspace = tempfile::tempdir().unwrap();
    let home = tempfile::tempdir().unwrap();
    let mut app = App::new(workspace.path().to_path_buf()).unwrap();
    app.set_sidebar_view(SidebarView::Explorer);
    app.focus_pane(Pane::Tree);
    let request_dir = with_relay_home(home.path(), || {
        let inbox = app.relay_inbox_path().expect("relay inbox derivable");
        let request_dir = inbox.join("test-req-1");
        std::fs::create_dir_all(&request_dir).unwrap();
        std::fs::write(request_dir.join("foo.txt"), "payload").unwrap();
        std::fs::write(request_dir.join(".ok"), b"").unwrap();
        app.pending_remote_pulls.push(PendingRemotePull {
            request_id: String::from("test-req-1"),
            src_display: String::from("/Users/v/Docs/foo.txt"),
            basename: String::from("foo.txt"),
            dest_dir: workspace.path().to_path_buf(),
            started_at: std::time::Instant::now(),
            kind: RemotePullKind::File,
            open_after_forward: None,
            remote_ipv6: false,
        });
        let changed = app.drain_remote_pulls();
        assert!(changed);
        request_dir
    });
    assert!(app.pending_remote_pulls.is_empty());
    let landed = workspace.path().join("foo.txt");
    assert!(landed.exists(), "file should land in workspace");
    assert_eq!(std::fs::read_to_string(&landed).unwrap(), "payload");
    assert!(
        !request_dir.exists(),
        "relay request dir must be cleaned up after import",
    );
    assert!(app.status.contains("Pulled"));
}

#[test]
fn drain_remote_pulls_surfaces_relay_error_message() {
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let workspace = tempfile::tempdir().unwrap();
    let home = tempfile::tempdir().unwrap();
    let mut app = App::new(workspace.path().to_path_buf()).unwrap();
    with_relay_home(home.path(), || {
        let inbox = app.relay_inbox_path().expect("relay inbox derivable");
        let request_dir = inbox.join("req-2");
        std::fs::create_dir_all(&request_dir).unwrap();
        std::fs::write(request_dir.join(".err"), b"scp exited with 1").unwrap();
        app.pending_remote_pulls.push(PendingRemotePull {
            request_id: String::from("req-2"),
            src_display: String::from("/Users/v/missing.txt"),
            basename: String::from("missing.txt"),
            dest_dir: workspace.path().to_path_buf(),
            started_at: std::time::Instant::now(),
            kind: RemotePullKind::File,
            open_after_forward: None,
            remote_ipv6: false,
        });
        let changed = app.drain_remote_pulls();
        assert!(changed);
    });
    assert!(app.status.contains("scp exited with 1"));
}

#[test]
fn clicking_the_ports_tab_switches_the_panel_view() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let r = app.panel_hits.ports_tab;
    assert!(r.width > 0, "the PORTS tab must have a hit rect");
    left_click(&mut app, r.x, r.y);
    assert_eq!(
        app.bottom_panel_tab,
        BottomPanelTab::Ports,
        "a click on the PORTS tab activates that view",
    );
}

#[test]
fn a_detected_port_renders_in_the_ports_panel() {
    use crate::widgets::ports::PortOrigin;
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.bottom_panel_tab = BottomPanelTab::Ports;
    app.ports
        .upsert(3000, None, Some("node".into()), PortOrigin::Local);
    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let buf = term.backend().buffer().clone();
    let text: String = buf.content().iter().map(|c| c.symbol()).collect();
    assert!(text.contains("3000"), "the detected port is listed");
    assert!(text.contains("node"), "its process is listed");
}

/// #2568: a port poll whose thread crashed is no longer in flight. The
/// crash notice tells the user; the next poll then starts on cadence,
/// instead of no poll ever starting again until a restart.
#[test]
fn a_port_poll_whose_thread_crashed_lets_the_next_one_run() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    assert!(
        app.terminals.iter().any(|t| t.pid().is_some()),
        "setup: a pane with a shell to poll"
    );
    app.port_poll = Some(
        crate::jobs::Job::spawn("port-poll", crate::jobs::Start::Now, || -> PortPoll {
            panic!("the poll crashed (on purpose, in a test)")
        })
        .unwrap(),
    );
    // Not yet time for the next poll, so only the crashed one settles.
    app.last_port_poll = std::time::Instant::now();
    crate::test_budget::await_spawned(
        std::time::Duration::from_secs(1),
        "the crashed poll to settle",
        || {
            app.drain_ports_and_poll();
            app.port_poll.is_none()
        },
    );
    app.last_port_poll = std::time::Instant::now()
        .checked_sub(crate::app::bottom_panel::PORT_POLL_INTERVAL)
        .expect("the clock is past one poll interval");
    app.drain_ports_and_poll();
    assert!(app.port_poll.is_some(), "the next poll started");
}

#[test]
fn opening_a_forwarded_remote_port_routes_to_the_local_browser_via_relay() {
    use crate::widgets::ports::{PortOrigin, PortsPanel};
    // On a remote session the local opener would run on the headless remote, so
    // a forwarded port must re-open through the relay (lands on the local Mac).
    let mut p = PortsPanel::new();
    p.upsert(3000, None, None, PortOrigin::Remote("box".into()));
    p.mark_forwarded(3000, 3001);
    let entry = p.selected().unwrap();
    match super::plan_port_open(entry, true) {
        super::PortOpenAction::OpenViaRelay(url) => assert_eq!(url, "http://127.0.0.1:3001/"),
        other => panic!("expected relay open, got {other:?}"),
    }
}

#[test]
fn opening_an_unforwarded_remote_port_forwards_first() {
    use crate::widgets::ports::{PortOrigin, PortsPanel};
    let mut p = PortsPanel::new();
    p.upsert(3000, None, None, PortOrigin::Remote("box".into()));
    let entry = p.selected().unwrap();
    assert!(matches!(
        super::plan_port_open(entry, true),
        super::PortOpenAction::Forward(3000)
    ));
}

#[test]
fn opening_a_local_port_opens_directly_not_via_relay() {
    use crate::widgets::ports::{PortOrigin, PortsPanel};
    let mut p = PortsPanel::new();
    p.upsert(8000, None, None, PortOrigin::Local);
    let entry = p.selected().unwrap();
    match super::plan_port_open(entry, false) {
        super::PortOpenAction::OpenDirect(url) => assert!(url.contains("8000"), "{url}"),
        other => panic!("expected direct open, got {other:?}"),
    }
}

#[test]
fn double_clicking_a_port_row_opens_it() {
    use crate::widgets::ports::PortOrigin;
    // Opening a remote port forwards it through the drop relay whenever the
    // process-wide relay key is set, so a relay test running at the same
    // moment would receive this test's forward in its request log. Hold the
    // relay lock: no relay test runs alongside, and the relay stays off here.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.bottom_panel_tab = BottomPanelTab::Ports;
    // A remote, not-yet-forwarded port: opening it routes through the forward
    // path, which sets an observable status without spawning a real browser.
    app.ports
        .upsert(3000, None, None, PortOrigin::Remote("box".into()));
    draw(&mut app, 140, 50);
    let x = app.ports.last_area.x + 2;
    let y = app.ports.last_area.y + 1; // first data row
    // A single click selects the row but takes no open action.
    left_click(&mut app, x, y);
    assert!(
        !app.status.contains("orward"),
        "a single click must not open the port: {}",
        app.status
    );
    // A second click on the same row within the double-click window opens it.
    left_click(&mut app, x, y);
    assert!(
        app.status.contains("orward"),
        "a double click opens (forwards) the port: {}",
        app.status
    );
}

/// #317 beyond the terminal: the guard lives in `ClickTracker`, so every
/// surface that pairs clicks inherits it. The ports table is the cheapest one
/// to drive end to end, and it has a visible consequence - a double click
/// forwards the port - so a modified click that wrongly counted as half a
/// double would open something the user never double-clicked.
#[test]
fn a_modified_click_does_not_pair_with_a_plain_one_in_the_ports_table() {
    use crate::widgets::ports::PortOrigin;
    // Opening a remote port forwards it through the drop relay whenever the
    // process-wide relay key is set, so a relay test running at the same
    // moment would receive this test's forward in its request log. Hold the
    // relay lock: no relay test runs alongside, and the relay stays off here.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.bottom_panel_tab = BottomPanelTab::Ports;
    app.ports
        .upsert(3000, None, None, PortOrigin::Remote("box".into()));
    draw(&mut app, 140, 50);
    let x = app.ports.last_area.x + 2;
    let y = app.ports.last_area.y + 1;

    let click_with = |app: &mut App, modifiers| {
        app.handle_mouse(crossterm::event::MouseEvent {
            kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
            column: x,
            row: y,
            modifiers,
        });
    };

    // A modified click must not ARM the pair: the plain click after it is the
    // user's first ordinary click on that row, not the second half of a
    // gesture they never made.
    click_with(&mut app, KeyModifiers::CONTROL);
    click_with(&mut app, KeyModifiers::empty());
    assert!(
        !app.status.contains("orward"),
        "a plain click after a ctrl+click must not open the port: {}",
        app.status
    );

    // And a modified click must not COMPLETE one either.
    click_with(&mut app, KeyModifiers::empty());
    app.status.clear();
    click_with(&mut app, KeyModifiers::CONTROL);
    assert!(
        !app.status.contains("orward"),
        "a ctrl+click must not complete a double-click: {}",
        app.status
    );

    // The guard must not have cost the real gesture.
    app.status.clear();
    click_with(&mut app, KeyModifiers::empty());
    click_with(&mut app, KeyModifiers::empty());
    assert!(
        app.status.contains("orward"),
        "two ordinary clicks must still open the port: {}",
        app.status
    );
}

#[test]
fn clicking_the_port_toast_dismiss_button_clears_it() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.show_port_toast(3000, Some("node".into()));
    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    // The render records the toast's clickable button rects; find Dismiss.
    let dismiss = app
        .port_toast
        .as_ref()
        .expect("toast is showing")
        .buttons
        .iter()
        .find(|(_, a)| matches!(a, super::PortToastAction::Dismiss))
        .map(|(r, _)| *r)
        .expect("the toast has a dismiss button");
    left_click(&mut app, dismiss.x, dismiss.y);
    assert!(
        app.port_toast.is_none(),
        "clicking dismiss clears the toast"
    );
}

/// Croft Loch: the port toast is a raised card with the card edge (no line
/// box on the canvas, no title on its edge), its primary action in the
/// button fill without bold, and the dismiss cross a bare muted mark.
#[test]
fn croft_loch_port_toast_is_a_raised_card() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.theme = crate::theme::Theme::from_id("loch");
    let t = crate::theme::tones(app.theme).unwrap();
    app.show_port_toast(3000, Some("node".into()));
    let backend = ratatui::backend::TestBackend::new(140, 50);
    let mut term = ratatui::Terminal::new(backend).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let buf = term.backend().buffer();
    let buttons = app.port_toast.as_ref().unwrap().buttons.clone();
    let (open, _) = buttons[0];
    let (dismiss, _) = *buttons.last().unwrap();
    // The body line sits one row above the buttons, the edge one above it.
    let top = open.y - 2;
    let x0 = open.x - 2;
    assert_eq!(buf[(x0, top)].symbol(), "\u{2594}");
    assert_eq!(buf[(x0, top)].fg, t.accent(), "the lip");
    let edge: String = (x0..x0 + 20).map(|x| buf[(x, top)].symbol()).collect();
    assert!(!edge.contains("PORT"), "{edge}");
    assert_eq!(buf[(open.x - 1, open.y)].bg, t.raised());
    assert_eq!(buf[(open.x, open.y)].bg, app.theme.button());
    assert!(!buf[(open.x, open.y)].modifier.contains(Modifier::BOLD));
    assert_eq!(buf[(dismiss.x + 1, dismiss.y)].fg, t.muted());
    assert_eq!(buf[(dismiss.x + 1, dismiss.y)].bg, t.raised());
}

#[test]
fn relay_request_ids_are_unique_per_request() {
    // `Instant::now().elapsed()` measures the gap between an instant and
    // itself, so the id was `<kind>-<pid>-0` almost every time. The relay keys
    // its remote inbox directory by request id, so two requests raised in the
    // same second collided: the first reply satisfied both pending pulls and
    // deleted the directory out from under the second, which then timed out
    // 120s later - with its file already destroyed or its tunnel already up.
    let ids: Vec<String> = (0..64).map(|_| App::relay_request_id("forward")).collect();
    let unique: std::collections::HashSet<&String> = ids.iter().collect();
    assert_eq!(unique.len(), ids.len(), "every request id must be distinct");
    assert!(ids[0].starts_with("forward-"), "kind stays in the id");
}

/// Losing the relay link must not be silent: the app detects the dead
/// channel, drops the session, and reconnects through the normal backoff
/// path. Before detection existed, `is_live` stayed true forever and the
/// guest typed into a buffer whose ops reached nobody.
#[test]
fn losing_the_relay_reconnects_instead_of_typing_into_the_void() {
    use std::time::{Duration, Instant};
    let tmp = tempfile::tempdir().unwrap();
    let socket = tmp.path().join("collab.sock");
    // A hand-rolled "relay": accepts, then hangs up on command.
    let listener = std::os::unix::net::UnixListener::bind(&socket).unwrap();
    let mut guest = App::new(tmp.path().to_path_buf()).unwrap();
    guest.collab.config = Some((socket.clone(), crate::collab::CollabRole::Guest));
    guest.poll_collab();
    assert!(guest.collab.session.is_some(), "first connect");
    let (peer, _) = listener.accept().unwrap();
    drop(peer); // the relay dies

    // Detection: the dead session is dropped.
    let deadline = Instant::now() + Duration::from_secs(3);
    while guest.collab.session.is_some() {
        assert!(
            Instant::now() < deadline,
            "the dead session was never dropped"
        );
        guest.poll_collab();
        std::thread::sleep(Duration::from_millis(10));
    }
    // Recovery: a fresh session connects (the listener's backlog accepts).
    let deadline = Instant::now() + Duration::from_secs(5);
    while guest.collab.session.is_none() {
        assert!(Instant::now() < deadline, "never reconnected");
        guest.poll_collab();
        std::thread::sleep(Duration::from_millis(50));
    }
}

/// Relay startup failure is the spawn failure's sibling: the window has
/// already acquired the workspace host lock, cannot host without a relay,
/// and must release the lock on the way out so another window can try.
/// Holding it made every other window report "hosted by another croft
/// window" while nobody hosted anything.
#[test]
fn a_relay_failure_releases_the_host_lock() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.pair.record_path = tmp.path().join("x.pair.json");
    // A socket inside a directory that does not exist: the relay can never
    // bind it, so ensure_relay fails after its aliveness poll.
    app.pair.socket = tmp.path().join("missing-dir").join("collab.sock");
    app.pair.host_lock_path = tmp.path().join("x.host.lock");
    app.pair.spawn_override = Some(Box::new(|_| panic!("must not reach the spawn")));
    crate::session::write_pair_record(
        &app.pair.record_path,
        &crate::session::PairRecord {
            model: None,
            name: "nav".into(),
            enabled: true,
            task: None,
            provider: None,
            base_url: None,
        },
    )
    .unwrap();
    app.pair.last_check = None;
    app.maybe_seat_navigator();
    assert!(app.pair.host.is_none());
    assert!(
        app.status.contains("relay failed"),
        "the failure is announced: {}",
        app.status
    );
    assert!(
        app.pair.host_lock.is_none(),
        "a window without a relay cannot host; the lock must be released"
    );
}

/// #363: a fleet run does not block the event loop, and its results arrive
/// through the channel like every other background answer.
///
/// The blocking version is the tempting one — `run_on_hosts` returns a
/// `Vec`, so calling it inline reads naturally — and it freezes the editor
/// for up to `FLEET_TIMEOUT` while the network answers. The user could not
/// scroll, type, or cancel. This asserts the split: the command returns at
/// once, and a later drain reports.
#[test]
fn a_fleet_run_reports_through_the_channel_rather_than_blocking() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    // Nothing in flight: a drain finds nothing and says so, rather than
    // blocking or inventing an empty result.
    assert!(!app.drain_fleet_results(), "no run, nothing to report");

    // Feed a result as the worker thread would.
    let results = vec![
        crate::fleet::HostResult {
            host: String::from("a"),
            output: String::from("5.15.0"),
            exit: Some(0),
            elapsed: std::time::Duration::ZERO,
        },
        crate::fleet::HostResult {
            host: String::from("b"),
            output: String::from("5.15.0"),
            exit: Some(0),
            elapsed: std::time::Duration::ZERO,
        },
        crate::fleet::HostResult {
            host: String::from("odd"),
            output: String::from("6.1.0"),
            exit: Some(0),
            elapsed: std::time::Duration::ZERO,
        },
        crate::fleet::HostResult {
            host: String::from("down"),
            output: String::from("timed out"),
            exit: None,
            elapsed: std::time::Duration::ZERO,
        },
    ];
    app.fleet_run = Some(crate::jobs::Job::finished(results));

    assert!(app.drain_fleet_results(), "a delivered result must report");
    assert!(app.fleet_run.is_none(), "the run is no longer in flight");
    assert!(
        app.status.contains("2 identical") && app.status.contains("1 differ"),
        "the summary must reach the user: {}",
        app.status
    );
    assert!(app.status.contains("1 failed"), "status: {}", app.status);

    // And the channel is empty again, so a second drain is a no-op rather
    // than replaying the same run.
    assert!(!app.drain_fleet_results(), "results are consumed once");
}

#[test]
fn an_ssh_session_raises_the_offer_once_and_drops_it_when_the_session_ends() {
    // #364: the offer appears when a pane's foreground BECOMES `ssh <host>`
    // for a known host, not on every sample of the same session, and it
    // leaves with the session.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // The refusal memory is read from the real cache directory at startup;
    // this machine's must not decide the test.
    app.remote_offer_refused.clear();
    let pane = app.terminals[0].uid();
    app.consider_ssh_offer(pane, Some(String::from("db-1")));
    assert!(
        app.ssh_offer
            .as_ref()
            .is_some_and(|o| o.pane == pane && o.host == "db-1"),
        "a new session offers"
    );
    assert!(
        app.status.starts_with("Connected to db-1"),
        "{:?}",
        app.status
    );
    app.status = String::from("something else happened");
    app.consider_ssh_offer(pane, Some(String::from("db-1")));
    assert_eq!(
        app.status, "something else happened",
        "the same session sampled again does not re-prompt"
    );
    app.status = String::from("Connected to db-1 · Open workspace here?");
    app.consider_ssh_offer(pane, None);
    assert!(
        app.ssh_offer.is_none(),
        "the session ended: the offer is gone"
    );
    assert!(app.status.is_empty(), "and its status line with it");
    // A NEW session to the same host offers again.
    app.consider_ssh_offer(pane, Some(String::from("db-1")));
    assert!(app.ssh_offer.is_some());
}

#[test]
fn the_offer_respects_the_global_switch_the_host_list_and_learned_refusals() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.remote_offer_refused.clear();
    let pane = app.terminals[0].uid();
    app.remote_offer_excluded = vec![String::from("DB-1")];
    app.consider_ssh_offer(pane, Some(String::from("db-1")));
    assert!(
        app.ssh_offer.is_none(),
        "per-host opt-out, case-insensitive"
    );
    app.remote_offer_excluded.clear();
    app.remote_offer_refused
        .insert(String::from("db-1"), std::time::SystemTime::now());
    app.consider_ssh_offer(pane, None);
    app.consider_ssh_offer(pane, Some(String::from("db-1")));
    assert!(
        app.ssh_offer.is_none(),
        "a host that refused provisioning is not offered"
    );
    app.remote_offer_refused.clear();
    app.remote_offer_disabled = true;
    app.consider_ssh_offer(pane, None);
    app.consider_ssh_offer(pane, Some(String::from("db-1")));
    assert!(app.ssh_offer.is_none(), "the global switch");
    app.remote_offer_disabled = false;
    app.consider_ssh_offer(pane, None);
    app.consider_ssh_offer(pane, Some(String::from("db-1")));
    assert!(
        app.ssh_offer.is_some(),
        "and with every gate open it offers"
    );
}

#[test]
fn accepting_or_dismissing_the_offer_clears_it() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    // The refusal memory is read from the real cache directory at startup;
    // this machine's must not decide the test.
    app.remote_offer_refused.clear();
    let pane = app.terminals[0].uid();
    app.consider_ssh_offer(pane, Some(String::from("db-1")));
    assert_eq!(
        app.accept_ssh_offer().map(|(host, _)| host).as_deref(),
        Some("db-1")
    );
    assert!(app.ssh_offer.is_none() && app.status.is_empty());
    assert_eq!(app.accept_ssh_offer(), None, "nothing to accept twice");

    app.consider_ssh_offer(pane, None);
    app.consider_ssh_offer(pane, Some(String::from("db-1")));
    assert!(app.ssh_offer.is_some());
    // Esc dismisses through the ordinary key path, whatever pane has focus.
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    assert!(app.ssh_offer.is_none(), "Esc dismissed the offer");
    assert!(app.status.is_empty());
}

#[test]
fn taking_a_host_off_the_exclusion_list_offers_the_session_already_on_it() {
    // A pane sampled on db-1 while db-1 was excluded is remembered as seen
    // there; the same host on the next sample would read as the same
    // session and never prompt. Un-excluding the host forgets that, so the
    // next sample offers it.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.remote_offer_refused.clear();
    let pane = app.terminals[0].uid();
    let mut prefs = crate::prefs::Prefs {
        remote_offer_excluded_hosts: vec![String::from("DB-1")],
        ..Default::default()
    };
    app.apply_merged_settings(&prefs);
    app.consider_ssh_offer(pane, Some(String::from("db-1")));
    assert!(app.ssh_offer.is_none(), "excluded: no offer");
    app.consider_ssh_offer(pane, Some(String::from("db-1")));
    assert!(
        app.ssh_offer.is_none(),
        "still the same session, still excluded"
    );
    prefs.remote_offer_excluded_hosts.clear();
    app.apply_merged_settings(&prefs);
    app.consider_ssh_offer(pane, Some(String::from("db-1")));
    assert!(
        app.ssh_offer
            .as_ref()
            .is_some_and(|o| o.pane == pane && o.host == "db-1"),
        "the live session is offered once its host is allowed again"
    );
    // A pane on a host that stayed excluded is untouched by the change.
    prefs.remote_offer_excluded_hosts = vec![String::from("jump"), String::from("db-1")];
    app.apply_merged_settings(&prefs);
    assert!(
        app.ssh_offer.is_none(),
        "re-excluding db-1 takes its offer down"
    );
    app.consider_ssh_offer(pane, Some(String::from("jump")));
    prefs.remote_offer_excluded_hosts = vec![String::from("jump")];
    app.apply_merged_settings(&prefs);
    app.consider_ssh_offer(pane, Some(String::from("jump")));
    assert!(
        app.ssh_offer.is_none(),
        "jump stayed excluded and stayed quiet"
    );
}

#[test]
fn cmd_k_g_with_no_offer_open_says_so_instead_of_connecting() {
    // The chord's guidance branch: nothing to accept, nothing launched, a
    // status that says where the offer comes from. (The accept branch runs
    // `request_remote_launch`, which spawns a real ssh; `accept_ssh_offer`
    // is covered directly instead of reaching the network from a test.)
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    assert!(app.ssh_offer.is_none());
    assert!(app.handle_cmd_k_chord(key(KeyCode::Char('g'), KeyModifiers::NONE)));
    assert!(
        app.status.starts_with("No ssh workspace offer is open"),
        "status: {}",
        app.status
    );
    assert!(app.connect_dialog.is_none(), "nothing was launched");
    assert!(app.pending_remote_launch_host.is_none());
}

#[test]
fn ssh_samples_from_the_label_thread_drive_the_offer_by_shell_pid() {
    // The label thread ships `(shell pid, host)`; the app maps the shell pid
    // to the pane's uid and feeds the same transition logic the direct tests
    // cover. An unknown shell pid is ignored.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.remote_offer_refused.clear();
    let shell = app.terminals[0]
        .shell_pid()
        .expect("the pane has a shell pid");
    let uid = app.terminals[0].uid();
    app.apply_ssh_samples(vec![
        (shell, Some(String::from("db-1"))),
        (-42, Some(String::from("x"))),
    ]);
    assert!(
        app.ssh_offer
            .as_ref()
            .is_some_and(|o| o.pane == uid && o.host == "db-1")
    );
    app.apply_ssh_samples(vec![(shell, None)]);
    assert!(
        app.ssh_offer.is_none(),
        "the session ended through the same path"
    );
}

#[test]
fn a_failed_provisioning_is_remembered_and_a_later_success_forgets_it() {
    // Drives the two notes the install session calls, against the cache-dir
    // override so nothing touches this machine's real memory.
    let _serial = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let tmp = tempfile::tempdir().unwrap();
    let _restore = override_cache_dir(tmp.path().join("cache"));
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    assert!(
        app.remote_offer_refused.is_empty(),
        "a fresh cache dir remembers nothing"
    );
    let pane = app.terminals[0].uid();

    app.note_provisioning_failed("DB-1", "refused");
    assert!(
        app.remote_offer_refused.contains_key("db-1"),
        "remembered in memory, lower-cased"
    );
    let refused_path = crate::remote::refused_hosts_path(&tmp.path().join("cache"));
    let on_disk = crate::remote::load_refused_hosts(&refused_path, std::time::SystemTime::now());
    assert!(on_disk.contains_key("db-1"), "and on disk: {on_disk:?}");
    app.consider_ssh_offer(pane, Some(String::from("db-1")));
    assert!(app.ssh_offer.is_none(), "a refused host is not offered");

    app.note_provisioning_succeeded("db-1");
    assert!(
        !app.remote_offer_refused.contains_key("db-1"),
        "a success forgets it in memory"
    );
    let on_disk = crate::remote::load_refused_hosts(&refused_path, std::time::SystemTime::now());
    assert!(!on_disk.contains_key("db-1"), "and on disk");
    app.consider_ssh_offer(pane, None);
    app.consider_ssh_offer(pane, Some(String::from("db-1")));
    assert!(app.ssh_offer.is_some(), "and the host is offered again");
}

#[test]
fn a_success_forgets_a_refusal_another_croft_recorded() {
    // The refusal file is shared by every croft on the machine. A refusal
    // this instance never loaded (recorded by another one after this one
    // started) must still be erased by a success here, or it outlives the
    // host that demonstrably works for its whole seven-day TTL.
    let _serial = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let tmp = tempfile::tempdir().unwrap();
    let cache = tmp.path().join("cache");
    let _restore = override_cache_dir(cache.clone());
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.remote_offer_refused.clear();
    let refused_path = crate::remote::refused_hosts_path(&cache);
    // "Another instance" writes the refusal behind this one's back.
    crate::remote::remember_refused_host(&refused_path, "db-1", std::time::SystemTime::now())
        .unwrap();
    assert!(
        crate::remote::load_refused_hosts(&refused_path, std::time::SystemTime::now())
            .contains_key("db-1")
    );
    app.note_provisioning_succeeded("DB-1");
    assert!(
        !crate::remote::load_refused_hosts(&refused_path, std::time::SystemTime::now())
            .contains_key("db-1"),
        "the disk refusal is gone even though this instance never held it"
    );
}

#[test]
fn provisioning_outcomes_are_logged_to_the_remote_output_channel() {
    // The cache-dir override is process-global; serialize with the
    // other tests that redirect it.
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    // #364: a host that gets croft through provisioning says so in OUTPUT >
    // Remote, success and failure alike, with the reason on failure.
    let home = tempfile::tempdir().unwrap();
    with_relay_home(home.path(), || {
        let tmp = tempfile::tempdir().unwrap();
        let mut app = App::new(tmp.path().to_path_buf()).unwrap();
        app.note_provisioning_failed("zz364-a.example", "no space left on device");
        app.note_provisioning_succeeded("zz364-b.example");
        let lines = crate::output::snapshot(crate::output::CHANNEL_REMOTE)
            .expect("the Remote channel exists");
        let failed = lines
            .iter()
            .find(|l| l.text.contains("zz364-a.example"))
            .expect("the failure is logged");
        assert!(
            failed.text.contains("no space left on device"),
            "{}",
            failed.text
        );
        assert_eq!(failed.level, crate::output::OutputLevel::Error);
        assert!(
            lines.iter().any(|l| l.text.contains("zz364-b.example")
                && l.level != crate::output::OutputLevel::Error),
            "the success is logged"
        );
    });
}

#[test]
fn fleet_output_shows_each_hosts_time_and_the_lines_that_differ() {
    // #363: a DIFFERS row says what differs, line by line, not just that
    // something did; every row says how long the host took.
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    let r = |host: &str, out: &str, ms: u64| crate::fleet::HostResult {
        host: String::from(host),
        output: String::from(out),
        exit: Some(0),
        elapsed: std::time::Duration::from_millis(ms),
    };
    app.fleet_run = Some(crate::jobs::Job::finished(vec![
        r("zz363-a", "Linux\n6.8.0-45", 120),
        r("zz363-b", "Linux\n6.8.0-45", 80),
        r("zz363-odd", "Linux\n6.8.0-31", 1500),
    ]));
    assert!(app.drain_fleet_results());
    let lines: Vec<String> = crate::output::snapshot(crate::output::CHANNEL_FLEET)
        .unwrap()
        .into_iter()
        .map(|l| l.text)
        .collect();
    let odd = lines
        .iter()
        .position(|l| l.starts_with("zz363-odd"))
        .expect("the odd host has a row");
    assert!(
        lines[odd].contains("[DIFFERS]") && lines[odd].contains("1.5s"),
        "{}",
        lines[odd]
    );
    assert_eq!(
        lines[odd + 1..odd + 3],
        ["    - 6.8.0-45", "    + 6.8.0-31"],
        "the reference's line and the host's, alone"
    );
    let a = lines.iter().find(|l| l.starts_with("zz363-a")).unwrap();
    assert!(a.contains("0.1s"), "{a}");
    assert!(
        !lines
            .iter()
            .any(|l| l.ends_with(" Linux") && l.starts_with("    ")),
        "an equal line is not marked"
    );
}

/// #2566: a fleet run whose thread crashed is no longer in flight. The
/// crash notice tells the user and FLEET says the run stopped; the next run
/// then starts instead of answering "A fleet run is already in flight".
#[test]
fn a_fleet_run_whose_thread_crashed_lets_the_next_one_run() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.fleet_run = Some(
        crate::jobs::Job::spawn("fleet-run", crate::jobs::Start::Now, || {
            panic!("the run crashed (on purpose, in a test)")
        })
        .unwrap(),
    );
    crate::test_budget::await_spawned(
        std::time::Duration::from_secs(1),
        "the crashed run to settle",
        || {
            app.drain_fleet_results();
            app.fleet_run.is_none()
        },
    );
    let lines: Vec<String> = crate::output::snapshot(crate::output::CHANNEL_FLEET)
        .unwrap_or_default()
        .into_iter()
        .map(|l| l.text)
        .collect();
    assert!(
        lines
            .iter()
            .any(|l| l == "the fleet run stopped without results"),
        "{lines:?}"
    );
    app.run_fleet_command("localhost: echo fleet-again");
    assert_eq!(app.status, "Fleet: running on 1 hosts…");
    assert!(app.fleet_run.is_some(), "the next run started");
}

/// #363 end to end: a fleet run's results open as tiles in the Fleet tab,
/// `s` saves the whole run to a file, `d` switches to full output, Enter
/// opens a shell pane on the selected host, and Esc closes the tab.
#[test]
fn a_fleet_run_opens_tiles_that_save_and_open_a_shell() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.run_fleet_command("localhost: echo fleet-ok");
    crate::test_budget::await_spawned(std::time::Duration::from_secs(10), "the fleet run", || {
        app.drain_fleet_results();
        app.editor.fleet.is_some()
    });
    let view = app.editor.fleet.as_ref().unwrap();
    assert_eq!(view.command, "echo fleet-ok");
    assert_eq!(view.results.len(), 1);
    assert_eq!(view.results[0].output, "fleet-ok");
    assert_eq!(app.editor.path.as_deref(), Some(Path::new("Fleet")));
    let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(120, 30)).unwrap();
    term.draw(|f| app.render(f)).unwrap();
    let screen: String = (0..30)
        .map(|y| {
            (0..120)
                .map(|x| term.backend().buffer()[(x, y)].symbol())
                .collect::<String>()
                + "\n"
        })
        .collect();
    assert!(screen.contains("localhost"), "{screen}");

    app.handle_key(key(KeyCode::Char('d'), KeyModifiers::NONE))
        .unwrap();
    assert!(!app.editor.fleet.as_ref().unwrap().diff_mode);
    app.handle_key(key(KeyCode::Char('s'), KeyModifiers::NONE))
        .unwrap();
    let saved = std::fs::read_dir(tmp.path())
        .unwrap()
        .filter_map(|e| e.ok().map(|e| e.path()))
        .find(|p| {
            p.file_name()
                .is_some_and(|n| n.to_string_lossy().starts_with("fleet-"))
        })
        .expect("a capture file");
    let text = std::fs::read_to_string(saved).unwrap();
    assert!(text.starts_with("$ echo fleet-ok\n"), "{text}");
    assert!(text.contains("== localhost (exit 0,"), "{text}");

    let panes = app.terminals.len();
    app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
        .unwrap();
    assert_eq!(
        app.terminals.len(),
        panes + 1,
        "a shell pane opened: {}",
        app.status
    );
    app.focus_pane(Pane::Editor);
    app.handle_key(key(KeyCode::Esc, KeyModifiers::NONE))
        .unwrap();
    assert!(app.editor.fleet.is_none());
}

#[test]
fn fleet_shell_commands_quote_the_target() {
    assert_eq!(fleet_shell_command("localhost"), None);
    assert_eq!(fleet_shell_command("db-1").as_deref(), Some("ssh 'db-1'"));
    assert_eq!(
        fleet_shell_command("docker:web").as_deref(),
        Some("docker exec -it 'web' sh")
    );
}

/// A second click on the same forwarded loopback link reuses the tunnel
/// instead of asking for another (each one was a new tunnel on a random port
/// and a new browser tab, #648); a click while one is in flight asks nothing.
#[test]
fn a_forwarded_port_is_reused_and_a_pending_forward_not_repeated() {
    use crate::widgets::ports::PortOrigin;
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let workspace = tempfile::tempdir().unwrap();
    let home = tempfile::tempdir().unwrap();
    let mut app = App::new(workspace.path().to_path_buf()).unwrap();
    let log = with_relay_home(home.path(), || {
        let log = app.relay_log_path().expect("relay log path derivable");
        app.request_remote_forward(3000, true);
        app.request_remote_forward(3000, true);
        let first = std::fs::read_to_string(&log).unwrap_or_default();
        assert_eq!(first.matches("forward\t").count(), 1, "{first:?}");
        // Once forwarded, a click opens the existing tunnel.
        app.pending_remote_pulls.clear();
        app.ports
            .upsert(3000, None, None, PortOrigin::Remote("box".into()));
        app.ports.mark_forwarded(3000, 3001);
        app.request_remote_forward(3000, true);
        log
    });
    let all = std::fs::read_to_string(&log).unwrap();
    assert_eq!(all.matches("forward\t").count(), 1, "{all:?}");
    assert!(all.contains("http://127.0.0.1:3001/"), "{all:?}");
}

/// A local croft (no update watcher) never pauses its servers, and the
/// marker is read at most once a second.
#[test]
fn only_a_remote_launched_croft_polls_the_build_marker() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    assert!(app.update_watch.is_none());
    assert!(!app.poll_source_build_marker());
    assert!(
        app.build_marker_checked.is_none(),
        "a local croft read the marker"
    );
    assert!(app.lsp.manager.is_some());

    app.update_watch = Some(crate::update_watch::UpdateWatch::start(
        tmp.path().to_path_buf(),
        String::new(),
    ));
    let just_now = std::time::Instant::now();
    app.build_marker_checked = Some(just_now);
    assert!(!app.poll_source_build_marker());
    assert_eq!(
        app.build_marker_checked,
        Some(just_now),
        "the marker was read again within the second"
    );
}

#[test]
fn the_output_ports_and_captures_tabs_are_announced_by_name_and_row() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.focus = Pane::Terminal;

    let channel = "a11y-1295-channel";
    crate::output::push(channel, crate::output::OutputLevel::Info, "hello");
    app.output.sync();
    assert!(app.output.select_by_name(channel));
    app.bottom_panel_tab = BottomPanelTab::Output;
    assert_eq!(app.a11y_snapshot().focus, format!("Output, {channel}"));

    app.bottom_panel_tab = BottomPanelTab::Ports;
    let snap = app.a11y_snapshot();
    assert_eq!((snap.focus.as_str(), snap.item), ("Ports, none", None));
    app.ports.upsert(
        3000,
        Some("http://localhost:3000".into()),
        Some("node".into()),
        crate::widgets::ports::PortOrigin::Local,
    );
    let snap = app.a11y_snapshot();
    assert_eq!(snap.focus, "Ports, 1 port");
    assert_eq!(
        snap.item.as_deref(),
        Some("Port 3000, node, http://localhost:3000")
    );

    app.bottom_panel_tab = BottomPanelTab::Captures;
    assert_eq!(app.a11y_snapshot().focus, "Captures, none");
    app.captures.push(crate::widgets::captures::CapturedLine {
        pane: "zsh".into(),
        shell_pid: None,
        message: "Build failed".into(),
        line: "error: build failed".into(),
        anchor: None,
    });
    let snap = app.a11y_snapshot();
    assert_eq!(snap.focus, "Captures, 1 capture");
    assert_eq!(snap.item.as_deref(), Some("Build failed, from zsh"));
}

/// #2070: on a relay session every copy goes home to the clipboard of the
/// machine the user types at, not only the terminal's (#1667). The editor's
/// Copy and Delete Line, Copy Path and the Ports view's copy all wrote the
/// remote box's clipboard, so pasting at home gave the old text.
#[test]
fn every_copy_on_a_relay_session_reaches_the_local_clipboard() {
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("a.txt");
    std::fs::write(&p, "alpha beta\nsecond\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.editor.open(&p).unwrap();
    app.focus_pane(Pane::Editor);

    app.handle_key(key(KeyCode::Char('a'), KeyModifiers::SUPER))
        .unwrap();
    let sent = relay_copied(&mut app, |app| {
        app.handle_key(key(KeyCode::Char('c'), KeyModifiers::SUPER))
            .unwrap();
    });
    assert_eq!(sent.as_deref(), Some("alpha beta\nsecond"), "editor Copy");
    assert!(app.status.contains("local clipboard"), "{}", app.status);

    let sent = relay_copied(&mut app, |app| app.copy_path_to_clipboard(p.clone()));
    assert_eq!(sent, Some(p.display().to_string()), "Copy Path");
    assert!(
        app.status.ends_with("sent to the local clipboard"),
        "{}",
        app.status
    );

    app.editor.clear_selection();
    app.editor.cursor_row = 0;
    let sent = relay_copied(&mut app, |app| app.delete_current_line());
    assert_eq!(sent.as_deref(), Some("alpha beta\n"), "Delete Line");

    app.ports
        .upsert(3000, None, None, crate::widgets::ports::PortOrigin::Local);
    let sent = relay_copied(&mut app, |app| app.ports_copy_selected());
    assert_eq!(
        sent.as_deref(),
        Some("http://127.0.0.1:3000/"),
        "Ports copy"
    );
}

/// #2070: a copy on a relay session goes home and leaves this box's
/// clipboard alone, so a paste inside croft must not read that clipboard
/// first. Cut then Paste put back what was on it before the cut.
#[test]
fn a_cut_then_paste_on_a_relay_session_puts_back_the_cut_text() {
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let tmp = tempfile::tempdir().unwrap();
    let p = tmp.path().join("a.txt");
    std::fs::write(&p, "alpha beta\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.clipboard_reader = || Some(String::from("stale remote text"));
    app.editor.open(&p).unwrap();
    app.focus_pane(Pane::Editor);
    app.editor.selection = Some(crate::widgets::editor::EditorSelection {
        anchor: (0, 0),
        head: (0, 5),
    });
    app.editor.cursor_col = 5;

    let sent = relay_copied(&mut app, |app| {
        app.handle_key(key(KeyCode::Char('x'), KeyModifiers::SUPER))
            .unwrap();
    });
    assert_eq!(sent.as_deref(), Some("alpha"), "the cut went home");
    assert_eq!(app.editor.lines[0], " beta");

    app.editor.cursor_col = app.editor.lines[0].chars().count();
    app.handle_key(key(KeyCode::Char('v'), KeyModifiers::SUPER))
        .unwrap();
    assert_eq!(app.editor.lines[0], " betaalpha", "{}", app.status);
}

/// #2070: when the local machine has no clipboard to write, its pump
/// answers the copy with `.err`, and the copy goes by OSC 52 from here, as
/// it did before copies went home. A copy with no answer sends nothing.
#[test]
fn a_relay_copy_the_local_machine_could_not_take_goes_by_osc52() {
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let tmp = tempfile::tempdir().unwrap();
    let home = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.session.relay_key = Some(String::from("testrelay"));
    let _ = crate::clipboard::test_clip::take_osc52_sent();
    with_relay_home(home.path(), || {
        let inbox = app.relay_inbox_path().expect("relay inbox derivable");
        assert_eq!(app.copy_where_pasted("landed"), CopyLanding::Local);
        assert_eq!(app.copy_where_pasted("refused"), CopyLanding::Local);
        let ids: Vec<String> = app
            .pending_relay_copies
            .iter()
            .map(|c| c.request_id.clone())
            .collect();
        assert_eq!(ids.len(), 2, "both copies wait for an answer");

        assert!(!app.drain_relay_copies(), "no answer yet");
        assert!(crate::clipboard::test_clip::take_osc52_sent().is_empty());

        let refused = inbox.join(&ids[1]);
        std::fs::create_dir_all(&refused).unwrap();
        std::fs::write(refused.join(".err"), "no clipboard to write").unwrap();
        assert!(app.drain_relay_copies());
        assert_eq!(
            crate::clipboard::test_clip::take_osc52_sent(),
            vec![String::from("refused")]
        );
        assert!(app.status.contains("via OSC 52"), "{}", app.status);
        assert!(!refused.exists(), "the answer is cleared");
        assert_eq!(app.pending_relay_copies.len(), 1, "the other still waits");

        app.pending_relay_copies[0].started_at -= RELAY_COPY_ANSWER_WAIT;
        assert!(!app.drain_relay_copies());
        assert!(
            app.pending_relay_copies.is_empty(),
            "silence means it landed"
        );
        assert!(crate::clipboard::test_clip::take_osc52_sent().is_empty());
    });
}

/// #2965: external links in a PDF must pass the same web-only scheme and
/// control-character checks as LSP document links rather than handing
/// arbitrary URIs straight to the OS opener.
#[test]
fn pdf_external_links_refuse_non_web_and_malformed_schemes() {
    let tmp = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    for hostile in [
        "file:///etc/hosts",
        "vscode://file/etc/passwd",
        "javascript:alert(1)",
        "mailto:a@b.c",
    ] {
        app.follow_pdf_link(crate::pdf::LinkTarget::Url(String::from(hostile)));
        assert!(
            app.status.starts_with("Refused to open non-web link:"),
            "{hostile} must be refused, got {:?}",
            app.status
        );
    }
    for malformed in [
        "https://example.com\nopen\tevil",
        "https://exa\u{0}mple.com",
    ] {
        app.follow_pdf_link(crate::pdf::LinkTarget::Url(String::from(malformed)));
        assert!(
            app.status.starts_with("Refused to open malformed link:"),
            "{malformed:?} must be refused, got {:?}",
            app.status
        );
    }
}

/// #2965: on a remote session, clicking a PDF web link routes through the drop
/// relay (trust confirm, direct relay open, or loopback port forward) and
/// refuses cleanly on a plain SSH session without a relay rather than trying
/// to launch a browser on the headless remote host.
#[test]
fn pdf_external_links_route_through_relay_and_refuse_plain_remote() {
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let tmp = tempfile::tempdir().unwrap();
    let home = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.session.is_remote = true;

    // Without a relay, a remote session refuses rather than invoking the OS opener.
    app.follow_pdf_link(crate::pdf::LinkTarget::Url(String::from(
        "https://example.com/spec.pdf",
    )));
    assert!(
        app.status.contains("Running remotely"),
        "plain remote session must refuse browser open, got {:?}",
        app.status
    );
    assert!(app.pending_local_open.is_none());

    // With a relay active: untrusted prompts for confirmation; trusted queues
    // an open request; a loopback URL queues a port forward.
    with_relay_home(home.path(), || {
        app.trust_local_browser = false;
        app.follow_pdf_link(crate::pdf::LinkTarget::Url(String::from(
            "https://example.com/spec.pdf",
        )));
        assert_eq!(
            app.pending_local_open.as_deref(),
            Some("https://example.com/spec.pdf")
        );

        // Public lookalike hosts starting with "localhost" must NOT be treated
        // as loopback forwards: they follow the external-link confirm path.
        app.pending_local_open = None;
        app.pending_remote_pulls.clear();
        app.follow_pdf_link(crate::pdf::LinkTarget::Url(String::from(
            "https://localhost.run/docs",
        )));
        assert_eq!(
            app.pending_local_open.as_deref(),
            Some("https://localhost.run/docs")
        );
        assert!(
            app.pending_remote_pulls.is_empty(),
            "public lookalike host must not queue a port forward"
        );

        app.pending_local_open = None;
        app.trust_local_browser = true;
        let log = app.relay_log_path().expect("relay log path derivable");
        app.follow_pdf_link(crate::pdf::LinkTarget::Url(String::from(
            "https://example.com/manual",
        )));
        let written = std::fs::read_to_string(&log).expect("relay log written");
        assert!(
            written.contains("open\t") && written.contains("https://example.com/manual"),
            "trusted relay open should queue open request, got {written:?}"
        );

        app.pending_remote_pulls.clear();
        app.follow_pdf_link(crate::pdf::LinkTarget::Url(String::from(
            "https://localhost:8443/docs/spec.pdf?download=1#page=3",
        )));
        let written = std::fs::read_to_string(&log).expect("relay log updated");
        let fwd_req = app
            .pending_remote_pulls
            .iter()
            .find(|p| matches!(p.kind, RemotePullKind::Forward { remote_port: 8443 }))
            .expect("loopback PDF link should queue port 8443 forward")
            .request_id
            .clone();
        assert!(
            written.contains(&format!("forward\t{fwd_req}\t8443\t0\n")),
            "loopback PDF link must forward without auto-opening bare http root, got {written:?}"
        );

        // Once the relay answers with the chosen local port, drain_remote_pulls
        // registers the forwarded port in PORTS even when it was never scraped
        // from a terminal pane, and opens the original HTTPS URL rewritten to
        // 127.0.0.1:<local_port>, keeping scheme, path, query and fragment intact.
        let inbox = app.relay_inbox_path().expect("relay inbox derivable");
        let fwd_dir = inbox.join(&fwd_req);
        std::fs::create_dir_all(&fwd_dir).unwrap();
        std::fs::write(fwd_dir.join(".ok"), "51234").unwrap();
        assert!(app.drain_remote_pulls());
        assert_eq!(
            app.ports.forwarded_local_port(8443),
            Some(51234),
            "completed PDF port forward must register in PORTS even without prior detection"
        );
        let written = std::fs::read_to_string(&log).expect("relay log updated after forward");
        assert!(
            written.contains("open\t")
                && written.contains("https://127.0.0.1:51234/docs/spec.pdf?download=1#page=3"),
            "forwarded PDF link must preserve scheme, path, query and fragment, got {written:?}"
        );

        // A second PDF link to the same port reuses the tunnel recorded above
        // (no manual PORTS upsert) and immediately opens the rewritten URL.
        let before_len = written.len();
        app.follow_pdf_link(crate::pdf::LinkTarget::Url(String::from(
            "https://localhost:8443/other?v=2#top",
        )));
        let written = std::fs::read_to_string(&log).expect("relay log updated on reuse");
        let appended = &written[before_len..];
        assert!(
            !appended.contains("forward\t"),
            "already-forwarded port must reuse existing tunnel, got {appended:?}"
        );
        assert!(
            appended.contains("open\t")
                && appended.contains("https://127.0.0.1:51234/other?v=2#top"),
            "reused tunnel must open rewritten destination URL, got {appended:?}"
        );
        // An IPv6 loopback PDF link on the SAME port number carries `[::1]`
        // and stays distinct from the IPv4 tunnel on port 8443.
        let before_v6_len = written.len();
        app.follow_pdf_link(crate::pdf::LinkTarget::Url(String::from(
            "http://[::1]:8443/v6docs?k=1#top",
        )));
        let written = std::fs::read_to_string(&log).expect("relay log updated for ipv6");
        let appended_v6 = &written[before_v6_len..];
        let v6_req = app
            .pending_remote_pulls
            .iter()
            .find(|p| {
                matches!(p.kind, RemotePullKind::Forward { remote_port: 8443 }) && p.remote_ipv6
            })
            .expect("IPv6 loopback PDF link should queue its own [::1] forward")
            .request_id
            .clone();
        assert!(
            appended_v6.contains(&format!("forward\t{v6_req}\t8443\t0\t[::1]\n")),
            "IPv6 forward request must name remote [::1], got {appended_v6:?}"
        );
        let v6_dir = inbox.join(&v6_req);
        std::fs::create_dir_all(&v6_dir).unwrap();
        std::fs::write(v6_dir.join(".ok"), "51235").unwrap();
        assert!(app.drain_remote_pulls());
        assert_eq!(app.ports.forwarded_local_port_for(8443, false), Some(51234));
        assert_eq!(app.ports.forwarded_local_port_for(8443, true), Some(51235));
        let written = std::fs::read_to_string(&log).expect("relay log updated after ipv6 open");
        assert!(
            written.contains("open\t") && written.contains("http://127.0.0.1:51235/v6docs?k=1#top"),
            "completed IPv6 forward must open rewritten URL on its local port, got {written:?}"
        );

        // Stopping the IPv6 row via `x` leaves the IPv4 tunnel intact; pressing
        // `f` or Enter on the stopped IPv6 row restarts it as IPv6 (`[::1]`),
        // and dismissing the stopped IPv6 row via `x` removes only the IPv6 row.
        app.ports.select_index(1);
        assert!(app.ports.selected().is_some_and(|e| e.remote_ipv6));
        let before_stop_len = written.len();
        app.ports_stop_selected();
        let written = std::fs::read_to_string(&log).expect("relay log updated after ipv6 stop");
        assert!(
            written[before_stop_len..].contains("\t51235\t8443\t[::1]\n"),
            "stopping selected IPv6 row must send [::1] unforward, got {:?}",
            &written[before_stop_len..]
        );
        assert_eq!(
            app.ports.forwarded_local_port_for(8443, false),
            Some(51234),
            "stopping IPv6 row must keep IPv4 tunnel intact"
        );
        assert_eq!(app.ports.forwarded_local_port_for(8443, true), None);

        // Restarting the stopped IPv6 row via `f` preserves `[::1]`.
        let before_restart_len = written.len();
        app.pending_remote_pulls.clear();
        app.ports_forward_selected();
        let written = std::fs::read_to_string(&log).expect("relay log updated after ipv6 restart");
        assert!(
            written[before_restart_len..].contains("\t8443\t0\t[::1]\n"),
            "restarting stopped IPv6 row via `f` must forward [::1], got {:?}",
            &written[before_restart_len..]
        );
        assert!(
            app.pending_remote_pulls.iter().any(|p| matches!(
                p.kind,
                RemotePullKind::Forward { remote_port: 8443 }
            ) && p.remote_ipv6),
            "restarted IPv6 forward pull must carry remote_ipv6=true"
        );

        // Restarting the stopped IPv6 row via Enter (`ports_open_selected`)
        // also preserves `[::1]`.
        let before_open_len = written.len();
        app.pending_remote_pulls.clear();
        app.ports_open_selected();
        let written = std::fs::read_to_string(&log).expect("relay log updated after ipv6 open");
        assert!(
            written[before_open_len..].contains("\t8443\t1\t[::1]\n"),
            "restarting stopped IPv6 row via Enter must forward [::1], got {:?}",
            &written[before_open_len..]
        );

        // Dismissing the unforwarded IPv6 row via `x` removes only the IPv6 row
        // and keeps the live IPv4 tunnel on the same port untouched.
        app.ports_stop_selected();
        assert_eq!(app.ports.len(), 1);
        assert_eq!(
            app.ports.forwarded_local_port_for(8443, false),
            Some(51234),
            "dismissing IPv6 row must leave IPv4 tunnel on same port intact"
        );
        assert_eq!(app.ports.forwarded_local_port_for(8443, true), None);
    });
}

/// #2966: in a plain SSH remote session without a drop relay, every web-link
/// opener must refuse cleanly instead of trying to start a browser on the
/// headless remote host; with a relay active, all of them route through it.
#[test]
fn plain_remote_session_refuses_browser_open_across_all_link_paths() {
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let tmp = tempfile::tempdir().unwrap();
    let home = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.session.is_remote = true;

    app.open_detected_url("https://example.com/term");
    assert!(
        app.status.contains("Running remotely"),
        "open_detected_url must refuse on plain remote, got {:?}",
        app.status
    );

    app.open_ssh_learn_more();
    assert!(
        app.status.contains("Running remotely"),
        "open_ssh_learn_more must refuse on plain remote, got {:?}",
        app.status
    );

    app.open_document_link("https://example.com/doc");
    assert!(
        app.status.contains("Running remotely"),
        "open_document_link must refuse on plain remote, got {:?}",
        app.status
    );

    assert!(
        !app.try_open_url_for_user("https://example.com/release"),
        "try_open_url_for_user must report false on plain remote"
    );
    assert!(
        app.status.contains("Running remotely"),
        "try_open_url_for_user must explain refusal, got {:?}",
        app.status
    );

    // Positive: once a relay is active, all four route to the local prompt.
    with_relay_home(home.path(), || {
        app.trust_local_browser = false;

        app.pending_local_open = None;
        app.open_detected_url("https://example.com/term");
        assert_eq!(
            app.pending_local_open.as_deref(),
            Some("https://example.com/term")
        );

        app.pending_local_open = None;
        app.open_ssh_learn_more();
        assert_eq!(
            app.pending_local_open.as_deref(),
            Some("https://man.openbsd.org/ssh_config")
        );

        app.pending_local_open = None;
        app.open_document_link("https://example.com/doc");
        assert_eq!(
            app.pending_local_open.as_deref(),
            Some("https://example.com/doc")
        );

        app.pending_local_open = None;
        assert!(app.try_open_url_for_user("https://example.com/release"));
        assert_eq!(
            app.pending_local_open.as_deref(),
            Some("https://example.com/release")
        );

        // A local App must stay inert inside `with_relay_home` even while
        // `CROFT_RELAY_KEY` is set in the process environment.
        let mut local_app = App::new(tmp.path().to_path_buf()).unwrap();
        assert!(local_app.try_open_url_for_user("https://example.com/local"));
        assert_eq!(local_app.status, "Open https://example.com/local");
        assert!(local_app.pending_local_open.is_none());
    });
}

/// #2967: terminal paste on a relay session must request the user's local
/// clipboard through the relay first instead of reading the remote host's
/// clipboard, and local terminal paste must read through `clipboard_reader`.
#[test]
fn terminal_paste_requests_relay_clipboard_before_remote_host_clipboard() {
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let workspace = tempfile::tempdir().unwrap();
    let home = tempfile::tempdir().unwrap();
    let mut app = App::new(workspace.path().to_path_buf()).unwrap();
    app.focus_pane(Pane::Terminal);

    // Local session (no relay): reads through `clipboard_reader`, and falls
    // back to `last_copy()` when the host clipboard cannot be read.
    app.clipboard_reader = || Some(String::from("local-one\nlocal-two"));
    app.paste_clipboard_into_terminal();
    let pending = app
        .pending_terminal_paste
        .take()
        .expect("local terminal paste should read from clipboard_reader");
    assert_eq!(pending, b"local-one\nlocal-two");

    crate::clipboard::remember_copy("copied-a\ncopied-b");
    app.clipboard_reader = || None;
    app.paste_clipboard_into_terminal();
    let fallback = app
        .pending_terminal_paste
        .take()
        .expect("local terminal paste should fall back to last_copy()");
    assert_eq!(fallback, b"copied-a\ncopied-b");

    // Relay session: even when the remote host's clipboard returns stale text,
    // terminal paste must ask the relay for the user's local clipboard instead.
    // Opt in explicitly via `session.relay_key` (inert under cfg(test)) so
    // ambient `CROFT_RELAY_KEY` from `with_relay_home` never diverts parallel
    // local terminal-paste tests.
    app.clipboard_reader = || Some(String::from("stale-remote-one\nstale-remote-two"));
    with_relay_home(home.path(), || {
        // Without opting into a relay session, a local App inside
        // `with_relay_home` still pastes via `clipboard_reader`.
        app.paste_clipboard_into_terminal();
        assert_eq!(
            app.pending_terminal_paste.take().as_deref(),
            Some(b"stale-remote-one\nstale-remote-two".as_slice())
        );

        app.session.relay_key = Some(String::from("testrelay"));
        let pane_uid = app.terminals[app.active_terminal].uid();
        let log = app.relay_log_path().expect("relay log path derivable");
        app.paste_clipboard_into_terminal();
        assert!(
            app.pending_terminal_paste.is_none(),
            "relay terminal paste must not paste stale remote clipboard"
        );
        assert!(
            app.pending_remote_pulls.iter().any(|p| matches!(
                p.kind,
                RemotePullKind::Clipboard { terminal_uid } if terminal_uid == Some(pane_uid)
            )),
            "relay terminal paste must queue a clipboard pull targeting the requesting pane"
        );
        let written = std::fs::read_to_string(&log).expect("relay log written");
        assert!(
            written.contains("clipboard\t"),
            "relay log must contain clipboard request, got {written:?}"
        );
    });
}

/// #2967: an asynchronous relay clipboard reply must land only in the terminal
/// pane that requested it, even if the user switched panes (or opened the
/// multiline confirm popup) before the reply arrived, and must cancel cleanly
/// if the requesting pane was closed.
#[test]
fn relay_terminal_paste_targets_requesting_pane_and_cancels_when_closed() {
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let workspace = tempfile::tempdir().unwrap();
    let home = tempfile::tempdir().unwrap();
    let mut app = App::new(workspace.path().to_path_buf()).unwrap();
    app.split_terminal().unwrap();
    app.focus_pane(Pane::Terminal);
    app.session.relay_key = Some(String::from("testrelay"));

    let stage_reply = |inbox: &std::path::Path, req_id: &str, payload: &[u8]| {
        let dir = inbox.join(req_id);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("clipboard.txt"), payload).unwrap();
        std::fs::write(dir.join(".ok"), b"").unwrap();
    };

    with_relay_home(home.path(), || {
        let inbox = app.relay_inbox_path().expect("relay inbox path derivable");

        // 1. Single-line relay paste requested in pane 0, user switches to
        //    pane 1 before reply lands: bytes go ONLY to pane 0.
        app.active_terminal = 0;
        let pane0_uid = app.terminals[0].uid();
        app.paste_clipboard_into_terminal();
        let req_id = app.pending_remote_pulls.last().unwrap().request_id.clone();
        app.active_terminal = 1;
        stage_reply(&inbox, &req_id, b"hello-pane-0");
        assert!(app.drain_remote_pulls());
        assert_eq!(app.terminals[0].written_bytes_for_test(), b"hello-pane-0");
        assert!(
            app.terminals[1].written_bytes_for_test().is_empty(),
            "pane 1 must not receive pane 0's relay paste"
        );

        // 2. Multi-line relay paste requested in pane 0, user switches to
        //    pane 1 before reply lands and before confirming: confirmed bytes
        //    still land ONLY in pane 0.
        app.active_terminal = 0;
        app.paste_clipboard_into_terminal();
        let req_id = app.pending_remote_pulls.last().unwrap().request_id.clone();
        app.active_terminal = 1;
        stage_reply(&inbox, &req_id, b"line-one\nline-two");
        assert!(app.drain_remote_pulls());
        assert_eq!(
            app.pending_terminal_paste.as_deref(),
            Some(b"line-one\nline-two".as_slice())
        );
        app.confirm_pending_terminal_paste(false);
        assert_eq!(
            app.terminals[0].written_bytes_for_test(),
            b"hello-pane-0line-one\nline-two"
        );
        assert!(
            app.terminals[1].written_bytes_for_test().is_empty(),
            "pane 1 must not receive pane 0's confirmed multiline paste"
        );

        // 3. Requesting pane closed before reply lands: paste is cancelled and
        //    pane 1 receives nothing.
        app.active_terminal = 0;
        app.paste_clipboard_into_terminal();
        let req_id = app.pending_remote_pulls.last().unwrap().request_id.clone();
        app.terminals.retain(|t| t.uid() != pane0_uid);
        app.active_terminal = 0; // remaining pane is old pane 1
        stage_reply(&inbox, &req_id, b"must-not-paste");
        assert!(app.drain_remote_pulls());
        assert!(
            app.terminals[0].written_bytes_for_test().is_empty(),
            "remaining pane must not receive a closed pane's paste"
        );
        assert!(
            app.status.contains("requesting terminal closed"),
            "expected closed-terminal status, got {:?}",
            app.status
        );
    });
}

/// #2062: local/remote session origin, relay key, persistence and update-check
/// environment variables must be read once through `HostSession::from_env` in
/// `src/app/remote_sessions.rs`, never scattered across feature files.
#[test]
fn session_origin_env_vars_are_read_only_in_host_session() {
    let app_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/app");
    let mut violations = Vec::new();

    fn walk(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
        for entry in std::fs::read_dir(dir).unwrap().flatten() {
            let p = entry.path();
            if p.is_dir() {
                if p.file_name().is_some_and(|n| n == "tests") {
                    continue;
                }
                walk(&p, out);
            } else if p.extension().is_some_and(|e| e == "rs") {
                out.push(p);
            }
        }
    }

    let mut files = Vec::new();
    walk(&app_dir, &mut files);
    files.sort();
    assert!(!files.is_empty());

    let env_keys = [
        "CROFT_RELAY_KEY",
        "CROFT_SESSION_PERSISTENT",
        "CROFT_REMOTE_AUTOUPDATE",
        "CROFT_NO_UPDATE_CHECK",
        "SSH_CONNECTION",
        "SSH_TTY",
        "SSH_CLIENT",
    ];
    for file in files {
        if file.ends_with("src/app/remote_sessions.rs") {
            continue;
        }
        let text = std::fs::read_to_string(&file).unwrap();
        for (idx, line) in text.lines().enumerate() {
            let trimmed = line.trim_start();
            if trimmed.starts_with("//") {
                continue;
            }
            let calls_env =
                trimmed.contains("env::var") && env_keys.iter().any(|k| trimmed.contains(k));
            let calls_remote_fn =
                trimmed.contains("running_over_ssh") || trimmed.contains("is_remote_session");
            if calls_env || calls_remote_fn {
                violations.push(format!("{}:{}: {}", file.display(), idx + 1, trimmed));
            }
        }
    }
    assert!(
        violations.is_empty(),
        "session-origin env reads must live in HostSession (src/app/remote_sessions.rs):\n{}",
        violations.join("\n")
    );
}

/// #2062: setting `app.session` directly drives remote media-open refusal and
/// update-check refusals without touching process environment variables.
#[test]
fn host_session_drives_remote_media_and_update_refusals() {
    let tmp = tempfile::tempdir().unwrap();
    let media = tmp.path().join("clip.md");
    std::fs::write(&media, "# clip\n").unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();
    app.session.is_remote = true;
    app.editor.open_pinned(&media).unwrap();
    app.toggle_markdown_preview();
    app.editor.markdown_preview.as_mut().unwrap().media = true;

    app.run_command(crate::widgets::command_palette::Command::MediaOpenExternal);
    assert!(
        app.status.contains("Running remotely: copy"),
        "MediaOpenExternal should read app.session.is_remote, got {:?}",
        app.status
    );

    app.session.remote_autoupdate = true;
    app.update_croft();
    assert!(
        app.status.contains("updated by the croft that launched it"),
        "update_croft should read app.session.remote_autoupdate, got {:?}",
        app.status
    );
    assert!(app.manual_update_check.is_none());

    app.session.remote_autoupdate = false;
    app.session.no_update_check = true;
    app.update_croft();
    assert!(
        app.status.contains("CROFT_NO_UPDATE_CHECK"),
        "update_croft should read app.session.no_update_check, got {:?}",
        app.status
    );
    assert!(app.manual_update_check.is_none());
}

/// #2062: every web-URL opener in `src/app/` must go through
/// `App::open_web_url` in `src/app/remote_sessions.rs` rather than calling
/// `open_url(...)` directly and drifting on scheme or remote-session checks.
#[test]
fn web_links_route_through_one_opener() {
    let app_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/app");
    let mut violations = Vec::new();

    fn walk(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
        for entry in std::fs::read_dir(dir).unwrap().flatten() {
            let p = entry.path();
            if p.is_dir() {
                if p.file_name().is_some_and(|n| n == "tests") {
                    continue;
                }
                walk(&p, out);
            } else if p.extension().is_some_and(|e| e == "rs") {
                out.push(p);
            }
        }
    }

    let mut files = Vec::new();
    walk(&app_dir, &mut files);
    files.sort();
    for file in files {
        // Allowed outside remote_sessions.rs: the local media-file player
        // (commands.rs) and the planned port opener (bottom_panel.rs).
        if file.ends_with("src/app/commands.rs") || file.ends_with("src/app/bottom_panel.rs") {
            continue;
        }
        let in_remote_sessions = file.ends_with("src/app/remote_sessions.rs");
        let text = std::fs::read_to_string(&file).unwrap();
        let mut current_fn = String::new();
        for (idx, line) in text.lines().enumerate() {
            let trimmed = line.trim_start();
            if let Some(rest) = trimmed
                .find("fn ")
                .map(|pos| &trimmed[pos + 3..])
                .filter(|_| !trimmed.starts_with("//"))
            {
                let name: String = rest
                    .chars()
                    .take_while(|c| c.is_ascii_alphanumeric() || *c == '_')
                    .collect();
                if !name.is_empty() {
                    current_fn = name;
                }
            }
            if trimmed.starts_with("//") || trimmed.starts_with("fn open_url(") {
                continue;
            }
            if trimmed.contains("open_url(") && !trimmed.contains(".open_url(") {
                // Inside remote_sessions.rs only the unified opener itself and
                // the local port-toast button may call `open_url`.
                if in_remote_sessions
                    && matches!(
                        current_fn.as_str(),
                        "open_web_url" | "handle_port_toast_click"
                    )
                {
                    continue;
                }
                violations.push(format!(
                    "{}:{} (in fn {}): {}",
                    file.display(),
                    idx + 1,
                    current_fn,
                    trimmed
                ));
            }
        }
    }
    assert!(
        violations.is_empty(),
        "web URL opens must go through App::open_web_url in src/app/remote_sessions.rs:\n{}",
        violations.join("\n")
    );
}

#[test]
fn open_web_url_validates_and_routes_consistently_across_callers() {
    let _guard = relay_test_lock().lock().unwrap_or_else(|e| e.into_inner());
    let tmp = tempfile::tempdir().unwrap();
    let home = tempfile::tempdir().unwrap();
    let mut app = App::new(tmp.path().to_path_buf()).unwrap();

    // Non-web and control-char URLs are refused everywhere, even via
    // try_open_url_for_user on a local session (returning false).
    assert!(!app.try_open_url_for_user("javascript:alert(1)"));
    assert_eq!(
        app.status,
        "Refused to open non-web link: javascript:alert(1)"
    );
    assert!(!app.try_open_url_for_user("https://example.com/\nboom"));
    assert!(
        app.status.starts_with("Refused to open malformed link:"),
        "got {:?}",
        app.status
    );

    // Valid web URL stays inert in tests when called via try_open_url_for_user.
    assert!(app.try_open_url_for_user("  https://example.com/docs  "));
    assert_eq!(app.status, "Open https://example.com/docs");

    // Relay active: non-web URL still returns false; trusted web URL routes
    // through the relay with custom label preserved; loopback forwards port.
    with_relay_home(home.path(), || {
        // Local App inside `with_relay_home` must remain inert on
        // `try_open_url_for_user` despite ambient `CROFT_RELAY_KEY`.
        let mut local_app = App::new(tmp.path().to_path_buf()).unwrap();
        assert!(local_app.try_open_url_for_user("https://example.com/local"));
        assert_eq!(local_app.status, "Open https://example.com/local");
        assert!(local_app.pending_local_open.is_none());

        app.session.is_remote = true;
        app.session.relay_key = Some(String::from("web-opener-test"));
        app.trust_local_browser = true;
        let log_path = app.relay_log_path().unwrap();

        assert!(!app.try_open_url_for_user("file:///etc/passwd"));
        assert_eq!(
            app.status,
            "Refused to open non-web link: file:///etc/passwd"
        );

        app.pending_remote_pulls.clear();
        app.open_ssh_learn_more();
        assert_eq!(app.status, "Opening ssh_config(5) on your local Mac");
        assert!(
            app.pending_remote_pulls.iter().any(|p| {
                p.kind == RemotePullKind::Open
                    && p.src_display == "https://man.openbsd.org/ssh_config"
            }),
            "ssh_config docs should queue one relay open"
        );
        let relay_log = std::fs::read_to_string(&log_path).unwrap();
        assert!(
            relay_log.contains("open\t")
                && relay_log.contains("https://man.openbsd.org/ssh_config"),
            "relay log should record the open request, got {relay_log:?}"
        );

        app.pending_remote_pulls.clear();
        assert!(app.try_open_url_for_user("http://127.0.0.1:4321/app"));
        assert!(
            app.pending_remote_pulls
                .iter()
                .any(|p| matches!(p.kind, RemotePullKind::Forward { remote_port: 4321 })),
            "loopback URL should forward port 4321 via relay"
        );
    });
}

/// Cross-platform parity check (#2062): a persistent, relay-backed remote
/// session and a local session must render cell-for-cell identical frames
/// across core views (welcome, workbench with code open, command palette,
/// quick open, settings editor), while a non-persistent remote session MUST
/// visibly diverge by drawing its persistence warning in the status bar.
#[test]
fn local_and_remote_render_byte_identical_frames_across_core_views() {
    struct PlainHostGuard;
    impl PlainHostGuard {
        fn enter() -> Self {
            crate::iterm2_inline::PLAIN_HOST_FRAMES.with(|f| f.set(true));
            Self
        }
    }
    impl Drop for PlainHostGuard {
        fn drop(&mut self) {
            crate::iterm2_inline::PLAIN_HOST_FRAMES.with(|f| f.set(false));
        }
    }

    fn make_app(root: &std::path::Path, session: HostSession) -> App {
        let mut app = App::new(root.to_path_buf()).unwrap();
        app.color_depth = crate::color_depth::ColorDepth::TrueColor;
        app.underline_colors = true;
        app.inline_protocol = crate::iterm2_inline::InlineImageProtocol::None;
        app.sixel_supported = false;
        app.cell_pixel = None;
        app.osk_auto = false;
        app.status = String::from("Ready");
        app.bottom_panel_tab = BottomPanelTab::Problems;
        app.persistence_warning = remote_persistence_status(session.is_remote, session.persistent);
        app.terminal_restore_respawns = session.is_remote;
        app.session = session;
        app.welcome
            .set_test_notes(vec![crate::release_notes::ReleaseNote {
                kind: crate::release_notes::NoteKind::Feature,
                summary: "Local and remote share one renderer",
            }]);
        app
    }

    fn draw_buf(app: &mut App, width: u16, height: u16) -> ratatui::buffer::Buffer {
        for _ in 0..8 {
            let started = std::time::Instant::now();
            let backend = ratatui::backend::TestBackend::new(width, height);
            let mut terminal = ratatui::Terminal::new(backend).unwrap();
            app.cursor_blink.poke();
            terminal.draw(|f| app.render_for_terminal(f)).unwrap();
            if started.elapsed() < super::cursor_blink::HALF && app.cursor_visible_phase() {
                return terminal.backend().buffer().clone();
            }
        }
        panic!("frame did not draw inside the visible blink half-period");
    }

    fn remote_persistent() -> HostSession {
        HostSession {
            is_remote: true,
            relay_key: Some(String::from("parity-relay")),
            persistent: true,
            remote_autoupdate: true,
            no_update_check: false,
        }
    }

    fn pair(root: &std::path::Path) -> (App, App) {
        (
            make_app(root, HostSession::default()),
            make_app(root, remote_persistent()),
        )
    }

    let _plain = PlainHostGuard::enter();
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path().join("parity");
    std::fs::create_dir_all(root.join("src")).unwrap();
    let main_rs = root.join("src/main.rs");
    std::fs::write(&main_rs, "fn main() {\n    println!(\"hello\");\n}\n").unwrap();
    std::fs::write(root.join("README.md"), "# parity\n").unwrap();

    // 1. Welcome page
    {
        let (mut local, mut remote) = pair(&root);
        assert_eq!(
            draw_buf(&mut local, 120, 40),
            draw_buf(&mut remote, 120, 40),
            "welcome frame must match between local and persistent remote"
        );
    }

    // 2. Workbench with file open
    {
        let (mut local, mut remote) = pair(&root);
        assert!(local.open_file_at_launch(&main_rs));
        assert!(remote.open_file_at_launch(&main_rs));
        assert_eq!(
            draw_buf(&mut local, 120, 40),
            draw_buf(&mut remote, 120, 40),
            "workbench frame must match between local and persistent remote"
        );
    }

    // 3. Command palette with query
    {
        let (mut local, mut remote) = pair(&root);
        assert!(local.open_file_at_launch(&main_rs));
        assert!(remote.open_file_at_launch(&main_rs));
        for app in [&mut local, &mut remote] {
            app.open_command_palette();
            for ch in "toggle side".chars() {
                app.handle_key(key(KeyCode::Char(ch), KeyModifiers::NONE))
                    .unwrap();
            }
        }
        assert_eq!(
            draw_buf(&mut local, 120, 40),
            draw_buf(&mut remote, 120, 40),
            "command palette frame must match between local and persistent remote"
        );
    }

    // 4. Quick Open with indexed query
    {
        let (mut local, mut remote) = pair(&root);
        for app in [&mut local, &mut remote] {
            crate::test_budget::await_spawned(
                std::time::Duration::from_millis(500),
                "the Go to File index to be built",
                || {
                    app.poll_file_finder_index();
                    app.file_finder_index.is_some()
                },
            );
            app.run_command(crate::widgets::command_palette::Command::QuickOpen);
            for ch in "main".chars() {
                app.handle_key(key(KeyCode::Char(ch), KeyModifiers::NONE))
                    .unwrap();
            }
        }
        assert_eq!(
            draw_buf(&mut local, 120, 40),
            draw_buf(&mut remote, 120, 40),
            "quick-open frame must match between local and persistent remote"
        );
    }

    // 5. Settings Editor
    {
        let (mut local, mut remote) = pair(&root);
        local.run_command(crate::widgets::command_palette::Command::OpenSettingsEditor);
        remote.run_command(crate::widgets::command_palette::Command::OpenSettingsEditor);
        assert_eq!(
            draw_buf(&mut local, 120, 40),
            draw_buf(&mut remote, 120, 40),
            "settings editor frame must match between local and persistent remote"
        );
    }

    // 6. Negative check: non-persistent remote MUST visibly diverge in status bar.
    {
        let (mut local, mut remote) = pair(&root);
        assert!(local.open_file_at_launch(&main_rs));
        assert!(remote.open_file_at_launch(&main_rs));
        remote.session.persistent = false;
        remote.persistence_warning =
            remote_persistence_status(remote.session.is_remote, remote.session.persistent);
        let local_buf = draw_buf(&mut local, 120, 40);
        let remote_buf = draw_buf(&mut remote, 120, 40);
        assert_ne!(
            remote_buf, local_buf,
            "non-persistent remote session must visibly differ from local workbench"
        );
        let status_row: String = (0..120).map(|x| remote_buf[(x, 39)].symbol()).collect();
        assert!(
            status_row.contains("Persistence off: install dtach"),
            "status bar should show persistence warning, got {status_row:?}"
        );
    }
}

/// Contract test for every intentional behavioral difference between local and
/// remote sessions (#2062). Any drift from this explicit list is a bug.
#[test]
fn intentional_remote_session_differences_follow_one_contract() {
    use crate::widgets::ports::PortOrigin;

    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("note.txt");
    std::fs::write(&file, "hello\n").unwrap();

    // 1. Persistence warning is only raised for non-persistent remote sessions.
    assert_eq!(remote_persistence_status(false, false), None);
    assert_eq!(remote_persistence_status(false, true), None);
    assert_eq!(remote_persistence_status(true, true), None);
    assert_eq!(
        remote_persistence_status(true, false),
        Some("Persistence off: install dtach")
    );

    // 2. Drop to Local: refused locally, sets drop_to_local + quit remotely.
    let mut local = App::new(tmp.path().to_path_buf()).unwrap();
    local.session = HostSession::default();
    local.drop_to_local_if_remote();
    assert!(!local.drop_to_local);
    assert!(!local.quit);
    assert_eq!(
        local.status,
        "Drop to Local: this croft is not a remote session"
    );

    let mut remote = App::new(tmp.path().to_path_buf()).unwrap();
    remote.session = HostSession {
        is_remote: true,
        relay_key: Some(String::from("contract-relay")),
        persistent: true,
        remote_autoupdate: true,
        no_update_check: false,
    };
    remote.drop_to_local_if_remote();
    assert!(remote.drop_to_local);
    assert!(remote.quit);

    // 3. New Window: refused on remote sessions (no local window server).
    remote.drop_to_local = false;
    remote.quit = false;
    assert!(remote.open_file_at_launch(&file));
    assert!(!remote.open_tab_in_new_window(0));
    assert_eq!(remote.status, "New Window: not available over SSH");

    // 4. PORTS origin: Local vs Remote(host).
    assert_eq!(local.port_origin(), PortOrigin::Local);
    assert!(matches!(remote.port_origin(), PortOrigin::Remote(_)));

    // 5. macOS Finder reveal menu item is shown locally and hidden remotely.
    #[cfg(target_os = "macos")]
    {
        assert!(local.open_file_at_launch(&file));
        let local_items = build_tab_context_menu_items(
            0,
            local.editor.tab_count(),
            false,
            Some(&file),
            !local.session.is_remote && cfg!(target_os = "macos"),
            false,
            true,
        );
        let remote_items = build_tab_context_menu_items(
            0,
            remote.editor.tab_count(),
            false,
            Some(&file),
            !remote.session.is_remote && cfg!(target_os = "macos"),
            false,
            true,
        );
        let has_finder = |items: &[MenuEntry]| {
            items.iter().any(
                |entry| matches!(entry, MenuEntry::Item { label, .. } if label.contains("Finder")),
            )
        };
        assert!(has_finder(&local_items), "local macOS menu includes Finder");
        assert!(!has_finder(&remote_items), "remote macOS menu omits Finder");
    }
}