filament-cli 0.6.3

P2P file transfer between terminals and browsers, no upload, no account. The terminal end of filament.autumated.com.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
// L2, ssh / raw TCP tunnelled over the Filament WebRTC data channel.
//
// Productionizes docs/L2-tunnel-design.md (spike: cli/spike/l2spike.rs). L2
// multiplexes logical TCP streams over the SAME data channel that moves files
// today, reusing the `Transport` trait verbatim, no transport changes.
//
// SCOPE: single-stream (ssh / one forward at a time is the supported case and
// what ships first). Multiple *concurrent heavy* streams over one link need
// per-stream credit flow control (design §4) to stay deadlock-free; that is a
// follow-up, see TODO(credits) below. l2-open-ack is mandatory here (it closes
// the early-frame-drop race and the open/deny ambiguity); the `credit` field it
// will eventually carry is the only piece deferred.
//
// Three surfaces, smallest-primitive-first (each is sugar over the one below):
//   * `filament netcat <peer> <rport>`            stdio  <-> one L2 stream
//   * `filament forward <lport> <peer> <rport>`   local TCP listener; conn=stream
//   * `filament ssh <peer> [args...]`             real ssh -o ProxyCommand=netcat
//
// The ACCEPTOR (the side that dials the localhost target) is NOT a subcommand:
// it lives inside `filament up` / `filament recv`, gated on the existing
// proof-verified `trusted` flag (the capability placeholder) + localhost-only
// dialing (the SSRF defense). See `Mux::on_open` and main.rs's recv loop.

use crate::net::{self, Ev, Peer, Transport};
use anyhow::{anyhow, bail, Result};
use bytes::Bytes;
use serde_json::{json, Value};
use std::collections::{HashMap, VecDeque};
use std::sync::atomic::{AtomicU32, AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::{mpsc, Mutex};
use tokio::task::AbortHandle;

/// L2 stream ids live in the HIGH half of the u32 sid space (`sid | 0x8000_0000`)
/// so they can NEVER collide with file-transfer sids (which start at 0 and count
/// up). A single link can therefore carry file transfers (low sids) and L2
/// streams (high sids) at once; the read loop in net.rs hands both to `Ev::Chunk`
/// and the dispatcher splits on this bit.
pub const L2_SID_BASE: u32 = 0x8000_0000;

/// Is this a high-half (L2) stream id? The hot-path discriminator the recv loop
/// uses to route an `Ev::Chunk` to the mux vs. the file-transfer logic.
#[inline]
pub fn is_l2_sid(sid: u32) -> bool {
    sid & L2_SID_BASE != 0
}

/// Per-stream pipe item: `Some(bytes)` = data; `None` = clean half-close/EOF
/// (an empty 4-byte data frame). A RST/abort is signalled out-of-band by
/// dropping the whole stream entry (writer wakes on a closed channel), distinct
/// from `None` so a reset is never mistaken for an orderly EOF.
type PipeItem = Option<Bytes>;
type StreamTx = mpsc::Sender<PipeItem>;

/// Liveness handle for one stream's two pumps. Holding the read-pump's
/// `AbortHandle` is what makes teardown actually work: `socket_to_dc` parks in
/// `rd.read()` and will NOT wake just because we drop its peer channel, so on
/// data-channel death / l2-close we must abort it explicitly (design §3.5).
struct StreamHandle {
    tx: StreamTx,
    read_pump: Option<AbortHandle>,
}

/// H-1 (DoS): per-link cap on concurrently live streams (file + L2 + PTY share
/// the `streams` table). Beyond this an `l2-open`/`pty-open` is refused. A
/// generous bound, interactive use needs only a handful, that still stops a
/// flaky/hostile paired device from spawning unbounded threads/sockets.
pub const MAX_STREAMS_PER_LINK: usize = 8;

/// H-1 (DoS): process-wide cap on concurrently live PTYs across ALL links. Each
/// PTY is a login shell + threads, so this bounds total resource use even if many
/// links each stay under the per-link cap. Refused opens get an `l2-close`.
pub const MAX_PTYS_GLOBAL: usize = 32;

/// Process-wide live-PTY counter (incremented just before a PTY session task is
/// spawned, decremented when it ends, see `PtyGuard`). The acceptor checks it
/// against `MAX_PTYS_GLOBAL` before granting a `pty-open`.
pub static LIVE_PTYS: AtomicUsize = AtomicUsize::new(0);

/// RAII guard that decrements `LIVE_PTYS` on drop, so the global PTY count is
/// freed on EVERY PTY session exit path (shell exit, browser FIN, error return).
pub struct PtyGuard;
impl PtyGuard {
    /// Reserve a global PTY slot if one is free. Returns `None` (and reserves
    /// nothing) when `MAX_PTYS_GLOBAL` live PTYs already exist.
    pub fn try_acquire() -> Option<PtyGuard> {
        // Optimistic CAS loop so the check + increment is atomic across links.
        let mut cur = LIVE_PTYS.load(Ordering::Relaxed);
        loop {
            if cur >= MAX_PTYS_GLOBAL {
                return None;
            }
            match LIVE_PTYS.compare_exchange_weak(cur, cur + 1, Ordering::AcqRel, Ordering::Relaxed) {
                Ok(_) => return Some(PtyGuard),
                Err(actual) => cur = actual,
            }
        }
    }
}
impl Drop for PtyGuard {
    fn drop(&mut self) {
        LIVE_PTYS.fetch_sub(1, Ordering::AcqRel);
    }
}

/// The multiplexer: routes inbound control/data frames to per-stream pipes and
/// owns stream-id allocation. Transport-agnostic, it rides above the trait.
pub struct Mux {
    transport: Arc<dyn Transport>,
    streams: Mutex<HashMap<u32, StreamHandle>>,
    next_sid: AtomicU32,
    /// Acceptor only: sids we have seen `l2-open` for and accepted, so a late
    /// duplicate open is ignored. (Initiator allocates, so it can't double-open.)
    accepted: Mutex<HashMap<u32, ()>>,
    /// web-shell: per-sid PTY resize senders. H-1: owning these HERE (rather than
    /// in the main event loop) guarantees they are dropped on EVERY teardown path:
    /// inbound `l2-close` (`on_close`), the session task exit (`drop_pty`), and
    /// link/mux death (`shutdown_all`), closing the resizer-map leak.
    resizers: Mutex<HashMap<u32, mpsc::UnboundedSender<(u16, u16)>>>,
    /// mount: per-sid oneshot senders for delivering mount-open-ack caps back to
    /// the caller that issued open_mount_stream. pump_initiator receives the ack
    /// control message, resolves the sid, and sends the caps; open_mount_stream
    /// awaits the receiver. Cleaned up on stream teardown.
    mount_ack_tx: Mutex<HashMap<u32, tokio::sync::oneshot::Sender<serde_json::Value>>>,
}

impl Mux {
    pub fn new(t: Arc<dyn Transport>) -> Arc<Self> {
        Arc::new(Mux {
            transport: t,
            streams: Mutex::new(HashMap::new()),
            next_sid: AtomicU32::new(0),
            accepted: Mutex::new(HashMap::new()),
            resizers: Mutex::new(HashMap::new()),
            mount_ack_tx: Mutex::new(HashMap::new()),
        })
    }

    pub fn transport(&self) -> Arc<dyn Transport> {
        self.transport.clone()
    }

    fn alloc_sid(&self) -> u32 {
        // Mask the counter to the low 30 bits so a long-lived link never escapes
        // into the L2 flag (0x80000000) OR the answerer-role bit (0x40000000).
        // The role bit keeps the two ends' sid spaces DISJOINT: each end allocates
        // with its own bit (opposite the peer's, via the deterministic `polite`
        // role), so a sid this end allocates can never equal one the peer
        // allocated - preventing cross-tunnel frame collisions when both ends open
        // L2 streams on one link (pty + warm-reuse forward, etc.).
        let n = self.next_sid.fetch_add(1, Ordering::Relaxed) & 0x3FFF_FFFF;
        let role = if self.transport.sid_answerer() { 0x4000_0000 } else { 0 };
        n | L2_SID_BASE | role
    }

    /// Register a stream's inbound pipe and return the receiver the socket-writer
    /// task drains. The read-pump handle is attached later via `set_read_pump`.
    async fn register(&self, sid: u32) -> mpsc::Receiver<PipeItem> {
        let (tx, rx) = mpsc::channel::<PipeItem>(256);
        self.streams
            .lock()
            .await
            .insert(sid, StreamHandle { tx, read_pump: None });
        rx
    }

    async fn set_read_pump(&self, sid: u32, h: AbortHandle) {
        if let Some(s) = self.streams.lock().await.get_mut(&sid) {
            s.read_pump = Some(h);
        } else {
            // Stream already gone (raced with teardown), kill the orphan pump.
            h.abort();
        }
    }

    /// Register a stream's inbound pipe (public, for the PTY acceptor which
    /// registers BEFORE spawning the shell, same pre-registration race fix as
    /// l2-open's dial path).
    pub async fn register_stream(&self, sid: u32) -> mpsc::Receiver<PipeItem> {
        self.register(sid).await
    }

    /// Number of currently live streams on this link (file + L2 + PTY share the
    /// table). H-1: the acceptor checks this against `MAX_STREAMS_PER_LINK`
    /// before accepting a new `l2-open`/`pty-open`.
    pub async fn live_streams(&self) -> usize {
        self.streams.lock().await.len()
    }

    /// True if accepting one more stream would exceed `MAX_STREAMS_PER_LINK`.
    pub async fn at_stream_cap(&self) -> bool {
        self.live_streams().await >= MAX_STREAMS_PER_LINK
    }

    /// Drop a stream and abort its read pump. Idempotent. Also drops any PTY
    /// resize sender for this sid (H-1: no resizer outlives its stream).
    async fn drop_stream(&self, sid: u32) {
        self.resizers.lock().await.remove(&sid);
        if let Some(s) = self.streams.lock().await.remove(&sid) {
            if let Some(h) = s.read_pump {
                h.abort();
            }
            // Dropping `s.tx` closes the pipe; the writer pump (dc_to_socket)
            // sees `recv()` return None and shuts the socket down.
        }
    }

    /// Register a PTY's resize sender (acceptor). Stored in the mux so it is freed
    /// on every teardown path with the stream, see `resizers`.
    pub async fn register_resizer(&self, sid: u32, tx: mpsc::UnboundedSender<(u16, u16)>) {
        self.resizers.lock().await.insert(sid, tx);
    }

    /// Deliver a `pty-resize` to the PTY task for `sid`, if it is still live.
    pub async fn resize_pty(&self, sid: u32, cols: u16, rows: u16) {
        if let Some(tx) = self.resizers.lock().await.get(&sid) {
            let _ = tx.send((cols, rows));
        }
    }

    /// Free a PTY's stream + resize sender on a session task exit (the teardown path
    /// that does NOT come from an inbound `l2-close`). Idempotent.
    pub async fn drop_pty(&self, sid: u32) {
        self.resizers.lock().await.remove(&sid);
        self.streams.lock().await.remove(&sid);
    }

    /// Route an inbound data frame to its stream. Empty payload = clean EOF/FIN.
    pub async fn on_frame(&self, sid: u32, payload: Bytes) {
        let tx = self.streams.lock().await.get(&sid).map(|s| s.tx.clone());
        if let Some(tx) = tx {
            let msg = if payload.is_empty() { None } else { Some(payload) };
            let _ = tx.send(msg).await; // receiver gone => stream already torn down
        }
    }

    /// Deliver a liveness marker for `sid` when the acceptor's `l2-open-ack` lands.
    /// Warm-reuse verification (`verify_first_frame`) needs proof the held link still
    /// delivers BEFORE it commits the client. A server-speaks-first protocol supplies
    /// that proof itself (sshd's banner), but a CLIENT-speaks-first one (HTTP, most DB
    /// clients) sends no app bytes until the client does - so without this the verify
    /// window expired and a HEALTHY link was wrongly dropped as a zombie, making every
    /// `forward` connection fall to a fresh cold link (the "no extra presence" promise
    /// broke). The ack is an empty `Some`: `on_frame` maps real empty payloads to
    /// `None`/EOF, so `Some(empty)` never occurs organically and is an unambiguous
    /// marker; replaying it writes zero bytes to the client.
    pub async fn on_open_ack(&self, sid: u32) {
        let tx = self.streams.lock().await.get(&sid).map(|s| s.tx.clone());
        if let Some(tx) = tx {
            let _ = tx.send(Some(Bytes::new())).await;
        }
    }

    /// Inbound l2-close. `err` set = RST/abort (drop, do NOT deliver clean EOF);
    /// no `err` = the peer is done, also a drop (its data direction already
    /// EOF'd via the empty frame). Either way: abort pumps, close the socket.
    async fn on_close(&self, sid: u32, _err: Option<&str>) {
        // Drop any pending mount-open-ack waiter for this sid so the caller
        // gets a clean error rather than hanging on a oneshot that will never fire.
        self.mount_ack_tx.lock().await.remove(&sid);
        self.drop_stream(sid).await;
    }

    /// Data-channel died (or a send errored): tear down EVERY live stream so no
    /// pump hangs forever waiting on a peer that will never speak again.
    pub async fn shutdown_all(&self) {
        self.resizers.lock().await.clear(); // H-1: no resizer outlives the mux
        self.mount_ack_tx.lock().await.clear();
        let mut map = self.streams.lock().await;
        for (_, s) in map.drain() {
            if let Some(h) = s.read_pump {
                h.abort();
            }
        }
    }
}

// ----------------------------------------------------------- stream plumbing --

/// Pump local TCP reads -> data-channel frames. On local EOF, send a 4-byte
/// empty frame (clean half-close / FIN). `send_frame` carries the per-link
/// aggregate backpressure, so a slow peer naturally stalls us here. Returns the
/// kind of ending so the caller can pick FIN vs. RST in the trailing l2-close.
///
/// TODO(credits): single-stream only relies on send_frame's per-link
/// backpressure. With >1 concurrent heavy stream this needs a per-stream credit
/// window (design §4) or one slow stream head-of-line-blocks the others.
async fn socket_to_dc<R: AsyncRead + Unpin>(
    transport: Arc<dyn Transport>,
    sid: u32,
    mut rd: R,
) -> Result<()> {
    let cap = transport.max_payload();
    let mut buf = vec![0u8; cap];
    loop {
        let n = rd.read(&mut buf).await?;
        if n == 0 {
            transport.send_frame(sid, 0, &[]).await?; // local FIN -> empty frame
            return Ok(());
        }
        transport.send_frame(sid, 0, &buf[..n]).await?;
    }
}

/// Pump data-channel frames -> local TCP writes. `None` = peer FIN: shutdown the
/// write half so the local app sees a clean EOF, then end. A dropped pipe
/// (channel closed without a `None`) = abort: shutdown anyway and end.
async fn dc_to_socket<W: AsyncWrite + Unpin>(
    mut rx: mpsc::Receiver<PipeItem>,
    mut wr: W,
    first: Option<PipeItem>,
) -> Result<()> {
    // A warm-reuse verify already pulled the FIRST inbound frame off the wire to
    // confirm the link is live; replay it here so no peer bytes are lost.
    if let Some(item) = first {
        match item {
            Some(bytes) => wr.write_all(&bytes).await?,
            None => {
                let _ = wr.shutdown().await;
                return Ok(());
            }
        }
    }
    while let Some(item) = rx.recv().await {
        match item {
            Some(bytes) => wr.write_all(&bytes).await?,
            None => {
                let _ = wr.shutdown().await; // clean half-close to local app
                return Ok(());
            }
        }
    }
    let _ = wr.shutdown().await; // pipe dropped (teardown/abort)
    Ok(())
}

/// Wire a connected socket to stream `sid` whose inbound pipe (`rx`) is already
/// registered. Spawns the write pump, stores the read pump's abort handle so
/// teardown can wake it, and runs the read pump to completion. On exit, drops
/// the stream and (optionally) sends a trailing l2-close (FIN or, on read error,
/// RST with `err`).
async fn serve_stream<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(
    mux: Arc<Mux>,
    sid: u32,
    sock: S,
    rx: mpsc::Receiver<PipeItem>,
    send_close: bool,
    first: Option<PipeItem>,
) {
    // Caller sets TCP_NODELAY where applicable (a unix socket has none); split
    // generically so the same plumbing serves a TcpStream OR a local UnixStream
    // (the warm-link reuse path bridges a unix socket to an L2 stream).
    let (rd, wr) = tokio::io::split(sock);
    // `first`: a warm-reuse verify already pulled the first inbound frame off the
    // wire to PROVE the link is live before the client was committed; replay it
    // here so no peer bytes are lost.
    let mut writer = tokio::spawn(dc_to_socket(rx, wr, first));
    let reader_task = tokio::spawn(socket_to_dc(mux.transport.clone(), sid, rd));
    mux.set_read_pump(sid, reader_task.abort_handle()).await;
    let mut reader = Some(reader_task);

    // Half-close semantics: reader-done (client stdin-EOF) is NON-TERMINAL.
    // The reader finishing means the client closed its write-half (stdin-EOF /
    // socket write-half closed). On a Unix socket, closing the write-half sends
    // EOF to the reader (socket_to_dc sees it and sends FIN to daemon transport),
    // but the read-half stays open. The daemon keeps the pty open until the
    // command exits, then dc_to_socket finishes and the socket closes.
    //
    // Writer-done (dc_to_socket done = remote command exited / pty output pipe
    // closed) IS terminal: this is when the command has finished and all output
    // has been delivered. Only then do we send l2-close and tear down.
    //
    // Ticker+transport-dead is also terminal: a dead peer must not hang the
    // bridge. The 2s poll tears down in ~2s (kept short so a dead peer doesn't
    // leave the warm pty hung).
    //
    // read_result: Some = reader finished (Ok=FIN sent); None = we tore down
    // because the peer/link ended (writer-done or transport-dead).
    let mut ticker = tokio::time::interval(Duration::from_secs(2));
    ticker.tick().await; // consume the immediate tick
    let mut reader_done = false;
    let mut read_result = None;
    loop {
        tokio::select! {
            r = async { reader.as_mut().unwrap().await }, if !reader_done => {
                // Client-side finished: record result, disarm the arm, but DO
                // NOT break. The writer (dc_to_socket) is still waiting for the
                // remote command to exit. l2-close is sent only after the writer
                // finishes (command exit), not here.
                read_result = Some(r);
                reader = None;   // disarm - must not re-poll a resolved future
                reader_done = true;
            }
            _ = &mut writer => {
                // Terminal: remote command exited / pty output pipe closed.
                // All output delivered; safe to tear down.
                if let Some(r) = reader.take() { r.abort(); }
                read_result = None;
                break;
            }
            _ = ticker.tick() => {
                if !mux.transport.is_alive() {
                    // Terminal: transport dead. Abort both directions.
                    if let Some(r) = reader.take() { r.abort(); }
                    writer.abort();
                    read_result = None;
                    break;
                }
            }
        }
    }
    // The stream may already be gone (teardown). Remove if still present.
    mux.streams.lock().await.remove(&sid);
    if send_close {
        let close = match read_result {
            Some(Ok(Ok(()))) => json!({ "type": "l2-close", "sid": sid }), // clean FIN
            Some(Ok(Err(e))) => json!({ "type": "l2-close", "sid": sid, "err": e.to_string() }),
            Some(Err(_aborted)) => return, // teardown owns the close; don't double-send
            // Peer FIN or link death: ack a close so the peer reaps its half (a
            // no-op if the transport is already gone).
            None => json!({ "type": "l2-close", "sid": sid }),
        };
        let _ = mux.transport.send_control(&close).await;
    }
}

// ----------------------------------------------------- PERSISTENT PTY SESSIONS --
//
// Issue #4 (disconnects lose progress): a PTY must OUTLIVE the data channel that
// opened it. A link-bound bridge would tie the shell's lifetime to one link, so a
// dropped channel would kill the shell. The session model below decouples them:
//
//   * A `PtySession` owns the shell (child + master + reader/writer threads) and
//     a long-lived task. It is keyed by a STABLE `session id` chosen by the
//     browser, NOT by the per-link sid (which changes on every reconnect).
//   * While ATTACHED, PTY output is framed to the current link's transport+sid
//     AND mirrored into a bounded ring buffer. While DETACHED (channel dropped),
//     output only accrues in the ring (capped: oldest bytes evicted).
//   * On reconnect the browser re-opens with the SAME session id; the acceptor
//     calls `attach`, which rebinds the new transport+sid and REPLAYS the ring,
//     so the user sees the same shell and its missed output (tmux/mosh-style).
//   * Caps: the ring is bounded (`SESSION_BUFFER_CAP`); a detached session is
//     reaped after `SESSION_DETACHED_IDLE` with no reattach; ANY session is
//     reaped after `SESSION_MAX_LIFETIME` regardless. The shell exiting always
//     ends the session immediately.

/// Bytes of recent PTY output retained while detached, for replay on reattach.
/// 256 KiB covers a full-screen TUI redraw plus a scrollback's worth of context
/// without letting an abandoned-but-not-reaped session hoard memory.
pub const SESSION_BUFFER_CAP: usize = 256 * 1024;

/// Terminal-mode reset emitted to the client right AFTER a reattach replay.
/// A TUI that gets cut off mid-run (link drop, then the app dies before it can
/// emit its own disable) leaves the client terminal stuck in mouse-reporting
/// mode: every trackpad move then spews escape codes onto the shell line, which
/// also wedges readline so Ctrl-U / Alt-Backspace stop parsing. Clearing the
/// mouse modes after the replay heals that; a TUI that is STILL alive re-enables
/// the mouse on its next redraw. Deliberately ONLY mouse modes (X10/normal/
/// button/any-motion + SGR + urxvt ext), never cursor-key or keypad modes, so a
/// reattach never disturbs arrow keys.
pub const PTY_REATTACH_RESET: &[u8] = b"\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?1015l";

/// Scan a PTY output chunk for DEC private-mode SET/RST sequences that
/// affect mouse tracking. Returns (modes_set, modes_reset) from this chunk.
///
/// CSI `ESC [ ? <num> h` = DECSET (enable); `l` = DECRST (disable).
/// Multiple mode numbers separated by `;` are each evaluated.
fn mouse_mode_changes(data: &[u8]) -> (Vec<u16>, Vec<u16>) {
    let mut sets: Vec<u16> = Vec::new();
    let mut resets: Vec<u16> = Vec::new();
    let mut i = 0;
    while i < data.len() {
        if data[i] != b'\x1b' || i + 3 >= data.len() || data[i + 1] != b'[' || data[i + 2] != b'?' {
            i += 1;
            continue;
        }
        let start = i + 3;
        let mut j = start;
        while j < data.len() && (data[j].is_ascii_digit() || data[j] == b';') {
            j += 1;
        }
        if j > start && j < data.len() && matches!(data[j], b'h' | b'l') {
            let set = data[j] == b'h';
            let nums: &str = std::str::from_utf8(&data[start..j]).unwrap_or("");
            for part in nums.split(';') {
                if let Ok(n) = part.parse::<u16>() {
                    if matches!(n, 1000 | 1002 | 1003 | 1006 | 1015) {
                        if set {
                            if !sets.contains(&n) { sets.push(n); }
                        } else {
                            if !resets.contains(&n) { resets.push(n); }
                        }
                    }
                }
            }
        }
        i = j + 1;
    }
    (sets, resets)
}

/// A detached session (channel dropped, nobody reattached) is reaped after this.
/// Long enough to ride out a mobile network handoff / tab suspend, short enough
/// that a closed laptop does not leave a root shell alive for hours.
pub const SESSION_DETACHED_IDLE: Duration = Duration::from_secs(180);

/// Hard lifetime cap on ANY persistent PTY session, attached or not. A backstop
/// so a wedged or forgotten session cannot live forever.
pub const SESSION_MAX_LIFETIME: Duration = Duration::from_secs(8 * 3600);

/// Where a session sends its PTY output right now: a link's transport + the sid
/// the browser allocated for THIS attach. `None` = detached (buffer only).
struct OutBind {
    transport: Arc<dyn Transport>,
    sid: u32,
}

/// Commands to a session's task: (re)bind output to a new link, detach, or end.
enum SessionCmd {
    Attach { transport: Arc<dyn Transport>, sid: u32 },
    Detach,
    End,
}

/// Handle to one persistent PTY session, stored in the `PtySessions` map. Cloning
/// is cheap (channels + Arcs); the actual shell lives in the spawned task.
#[derive(Clone)]
pub struct PtySessionHandle {
    /// Bytes typed by the user -> PTY master writer thread.
    input_tx: std::sync::mpsc::Sender<Vec<u8>>,
    /// Window-size changes -> PTY master resize.
    resize_tx: mpsc::UnboundedSender<(u16, u16)>,
    /// Attach/detach control -> the session task.
    cmd_tx: mpsc::UnboundedSender<SessionCmd>,
    /// Set once the task observes the shell exit OR a reap, so a stale handle in
    /// the map is recognized as dead and replaced by a fresh spawn.
    dead: Arc<std::sync::atomic::AtomicBool>,
}

impl PtySessionHandle {
    pub fn is_dead(&self) -> bool {
        self.dead.load(Ordering::Acquire)
    }
    pub fn feed_input(&self, bytes: Vec<u8>) {
        let _ = self.input_tx.send(bytes);
    }
    pub fn resize(&self, cols: u16, rows: u16) {
        let _ = self.resize_tx.send((cols, rows));
    }
    /// Rebind output to a new link (transport + sid) and replay the buffer.
    pub fn attach(&self, transport: Arc<dyn Transport>, sid: u32) {
        let _ = self.cmd_tx.send(SessionCmd::Attach { transport, sid });
    }
    /// Drop the current binding; output accrues in the ring until the next attach
    /// or the detached-idle reaper fires.
    pub fn detach(&self) {
        let _ = self.cmd_tx.send(SessionCmd::Detach);
    }
    /// End the session now: kill the shell and tear the task down (the explicit
    /// `pty-close` / user-closed path, NOT a transient channel drop).
    pub fn end(&self) {
        let _ = self.cmd_tx.send(SessionCmd::End);
    }
}

/// Process-wide store of persistent PTY sessions, keyed by the browser-chosen
/// stable session id. Lives for the whole `up`/`recv` process so a session
/// survives any number of link drops/reconnects.
#[derive(Default)]
pub struct PtySessions {
    map: Mutex<HashMap<String, PtySessionHandle>>,
}

impl PtySessions {
    pub fn new() -> Arc<Self> {
        Arc::new(Self::default())
    }

    /// Look up a LIVE session by id (a dead/exited one is treated as absent so a
    /// re-open spawns fresh).
    pub async fn get_live(&self, id: &str) -> Option<PtySessionHandle> {
        let mut map = self.map.lock().await;
        match map.get(id) {
            Some(h) if !h.is_dead() => Some(h.clone()),
            Some(_) => {
                map.remove(id);
                None
            }
            None => None,
        }
    }

    /// Insert a freshly spawned session under `id`.
    pub async fn insert(&self, id: String, h: PtySessionHandle) {
        self.map.lock().await.insert(id, h);
    }

    /// Remove a session by id (the reaper / shell-exit path calls this).
    pub async fn remove(&self, id: &str) {
        self.map.lock().await.remove(id);
    }
}

/// Spawn a brand-new persistent PTY session bound to `(transport, sid)`. Returns
/// a handle to store in `PtySessions`; the shell runs in a detached task that
/// outlives the link. `pty_guard` holds the global PTY slot for the session's
/// whole life. On any failure an `l2-close{err}` is sent on the opening link and
/// `None` is returned (nothing to store).
pub async fn spawn_pty_session(
    sessions: Arc<PtySessions>,
    session_id: String,
    transport: Arc<dyn Transport>,
    sid: u32,
    cols: u16,
    rows: u16,
    term: &str,
    argv: Vec<String>,
    pty_guard: PtyGuard,
) -> Option<PtySessionHandle> {
    use portable_pty::{native_pty_system, CommandBuilder, PtySize};
    use std::io::{Read as _, Write as _};

    let size = PtySize { rows: rows.max(1), cols: cols.max(1), pixel_width: 0, pixel_height: 0 };
    let pair = match native_pty_system().openpty(size) {
        Ok(p) => p,
        Err(e) => {
            let _ = transport.send_control(&json!({ "type": "l2-close", "sid": sid, "err": format!("pty: {e}") })).await;
            return None;
        }
    };
    let mut cmd = CommandBuilder::new(&argv[0]);
    for a in &argv[1..] {
        cmd.arg(a);
    }
    cmd.env("TERM", if term.is_empty() { "xterm-256color" } else { term });
    // Advertise 24-bit color. opentui-based TUIs (e.g. opencode) downgrade to a
    // 256-color palette when COLORTERM is unset; the web-shell xterm.js renders
    // truecolor fine, so set this to get full-color output (verified: opencode
    // emits 38;2;R;G;B with this set, 38;5;N without).
    cmd.env("COLORTERM", "truecolor");
    cmd.cwd(crate::platform::Paths::home_dir());
    let mut child = match pair.slave.spawn_command(cmd) {
        Ok(c) => c,
        Err(e) => {
            let _ = transport.send_control(&json!({ "type": "l2-close", "sid": sid, "err": format!("spawn: {e}") })).await;
            return None;
        }
    };
    drop(pair.slave); // close our copy so the shell owns the only slave
    let master = pair.master;
    let mut reader = match master.try_clone_reader() {
        Ok(r) => r,
        Err(_) => return None,
    };
    let mut writer = match master.take_writer() {
        Ok(w) => w,
        Err(_) => return None,
    };

    // Blocking PTY-master reads -> async output channel.
    let (otx, mut orx) = mpsc::channel::<Vec<u8>>(128);
    std::thread::spawn(move || {
        let mut buf = [0u8; 8192];
        loop {
            match reader.read(&mut buf) {
                Ok(0) | Err(_) => break, // shell exited / PTY closed
                Ok(n) => {
                    if otx.blocking_send(buf[..n].to_vec()).is_err() {
                        break;
                    }
                }
            }
        }
    });
    // Async input -> blocking PTY-master writes (dedicated thread).
    let (input_tx, wrx) = std::sync::mpsc::channel::<Vec<u8>>();
    std::thread::spawn(move || {
        while let Ok(b) = wrx.recv() {
            if writer.write_all(&b).is_err() {
                break;
            }
            let _ = writer.flush();
        }
    });

    let (resize_tx, mut resize_rx) = mpsc::unbounded_channel::<(u16, u16)>();
    let (cmd_tx, mut cmd_rx) = mpsc::unbounded_channel::<SessionCmd>();
    let dead = Arc::new(std::sync::atomic::AtomicBool::new(false));

    let handle = PtySessionHandle {
        input_tx,
        resize_tx,
        cmd_tx,
        dead: dead.clone(),
    };

    // The long-lived session task: it owns the PTY output, the current binding,
    // the replay ring, and the lifetime/idle caps. It outlives every link.
    let sessions_for_task = sessions.clone();
    let session_id_for_task = session_id.clone();
    tokio::spawn(async move {
        let _guard = pty_guard; // freed when the task ends (any exit path)
        let mut bind: Option<OutBind> = Some(OutBind { transport, sid });
        let mut ring: VecDeque<u8> = VecDeque::new();
        let started = Instant::now();
        let mut detached_since: Option<Instant> = None;
        let mut active_mouse_modes: Vec<u16> = Vec::new();
        // 5s tick to enforce the idle/lifetime caps without busy-waiting.
        let mut reaper = tokio::time::interval(Duration::from_secs(5));
        reaper.tick().await; // consume the immediate first tick

        loop {
            tokio::select! {
                out = orx.recv() => match out {
                    Some(bytes) => {
                        let (sets, resets) = mouse_mode_changes(&bytes);
                        for m in sets {
                            if !active_mouse_modes.contains(&m) { active_mouse_modes.push(m); }
                        }
                        active_mouse_modes.retain(|m| !resets.contains(m));
                        push_ring(&mut ring, &bytes, SESSION_BUFFER_CAP);
                        if let Some(b) = &bind {
                            for chunk in bytes.chunks(b.transport.max_payload().max(1)) {
                                if b.transport.send_frame(b.sid, 0, chunk).await.is_err() {
                                    // The link died under us; treat as a detach so
                                    // output keeps buffering for a reattach.
                                    detached_since = Some(Instant::now());
                                    bind = None;
                                    break;
                                }
                            }
                        }
                    }
                    None => break, // shell exited
                },
                cmd = cmd_rx.recv() => match cmd {
                    Some(SessionCmd::Attach { transport, sid }) => {
                        // Replay the buffered output to the freshly attached link
                        // so the user sees the shell exactly as it stands now.
                        let snapshot: Vec<u8> = ring.iter().copied().collect();
                        let mp = transport.max_payload().max(1);
                        let mut ok = true;
                        for chunk in snapshot.chunks(mp) {
                            if transport.send_frame(sid, 0, chunk).await.is_err() {
                                ok = false;
                                break;
                            }
                        }
                        // Heal stuck mouse modes from a cut-off TUI, then
                        // restore any modes the live PTY app had active so
                        // the wheel still scrolls after a reconnect.
                        if ok {
                            // Always flush stuck modes first (safety net)
                            if transport.send_frame(sid, 0, PTY_REATTACH_RESET).await.is_err() {
                                ok = false;
                            }
                            // Re-enable modes the PTY app had on before detach
                            for m in &active_mouse_modes {
                                let seq = format!("\x1b[?{m}h");
                                if ok && transport.send_frame(sid, 0, seq.as_bytes()).await.is_err() {
                                    ok = false;
                                    break;
                                }
                            }
                        }
                        if ok {
                            bind = Some(OutBind { transport, sid });
                            detached_since = None;
                        } else {
                            detached_since = Some(Instant::now());
                            bind = None;
                        }
                    }
                    Some(SessionCmd::Detach) => {
                        bind = None;
                        detached_since = Some(Instant::now());
                    }
                    Some(SessionCmd::End) => break, // explicit close: kill the shell
                    None => break, // all handles dropped (store removed): tear down
                },
                rs = resize_rx.recv() => {
                    if let Some((c, r)) = rs {
                        let _ = master.resize(PtySize { rows: r.max(1), cols: c.max(1), pixel_width: 0, pixel_height: 0 });
                    }
                }
                _ = reaper.tick() => {
                    let lifetime_up = started.elapsed() >= SESSION_MAX_LIFETIME;
                    let idle_up = detached_since
                        .map(|t| t.elapsed() >= SESSION_DETACHED_IDLE)
                        .unwrap_or(false);
                    if lifetime_up || idle_up {
                        break;
                    }
                }
            }
        }

        // Teardown (shell exit, reap, or store removal): kill the shell, tell the
        // currently-attached link (if any) the session ended, drop from the store.
        let _ = child.kill();
        let _ = child.wait();
        dead.store(true, Ordering::Release);
        if let Some(b) = &bind {
            let _ = b.transport.send_control(&json!({ "type": "l2-close", "sid": b.sid })).await;
        }
        sessions_for_task.remove(&session_id_for_task).await;
    });

    sessions.insert(session_id, handle.clone()).await;
    Some(handle)
}

/// Append `bytes` to the replay ring, evicting from the front so it never exceeds
/// `cap`. A single write larger than `cap` keeps only its trailing `cap` bytes
/// (the most recent screen state is what matters for replay).
fn push_ring(ring: &mut VecDeque<u8>, bytes: &[u8], cap: usize) {
    if bytes.len() >= cap {
        ring.clear();
        ring.extend(&bytes[bytes.len() - cap..]);
        return;
    }
    ring.extend(bytes);
    while ring.len() > cap {
        ring.pop_front();
    }
}

// ------------------------------------------------------------- ACCEPTOR side --

/// Decision for an inbound `l2-open`, made synchronously in the event loop
/// BEFORE any await, so the pipe is registered before a data frame for this sid
/// can be processed (closes the early-frame-drop race, design §3.4).
pub enum OpenVerdict {
    /// Accepted: dial this localhost target and relay. Carries the pre-registered
    /// inbound pipe.
    Accept { sid: u32, host: String, port: u16, rx: mpsc::Receiver<PipeItem> },
    /// Refused: send l2-close{err} and forget it.
    Deny { sid: u32, err: &'static str },
    /// Not an l2-open / malformed, ignore.
    Ignore,
}

impl Mux {
    /// Handle an inbound L2 *control* message on the acceptor side. `trusted` is
    /// the proof-verified capability flag for this link (the placeholder gate).
    /// Registers the pipe synchronously for an accepted open, then returns the
    /// verdict for the caller to act on (the dial is async and must NOT block the
    /// event loop). Returns `Ignore` for non-l2 control.
    /// `allow_nonloopback`: the caller (main.rs, where the peer's device name is
    /// known) decided this specific non-loopback target is permitted by the
    /// operator's opt-in `l2-allow.json` allowlist. Loopback is always allowed; a
    /// non-loopback host is refused UNLESS this is set, keeping the SSRF default.
    pub async fn accept_control(&self, v: &Value, trusted: bool, allow_nonloopback: bool) -> OpenVerdict {
        match v["type"].as_str() {
            Some("l2-open") => {
                let Some(sid) = v["sid"].as_u64().map(|s| s as u32) else {
                    return OpenVerdict::Ignore;
                };
                if !is_l2_sid(sid) {
                    return OpenVerdict::Ignore; // not in the high half, not ours
                }
                // Idempotency: a duplicate open for a live sid is ignored.
                {
                    let mut acc = self.accepted.lock().await;
                    if acc.contains_key(&sid) {
                        return OpenVerdict::Ignore;
                    }
                    acc.insert(sid, ());
                }
                // ---- CAPABILITY GATE (placeholder; see TODO below) ----
                // Today: the peer must be a remembered/trusted device (its
                // pair-proof verified on this link, main.rs ~3111). That is the
                // coarse stand-in for L1-a's per-cap model.
                if !trusted {
                    return OpenVerdict::Deny { sid, err: "denied" };
                }
                // TODO(L1-a caps): replace the bare `trusted` check above with the
                // real capability decision once l1-a-pake merges. L1-a gives each
                // device a record {name, secret, caps[]}; here we must require the
                // `forward` cap (and `shell` for port 22) carried/proved in
                // `v["cap"]` and bound to the DTLS fingerprints, deny-by-default.
                // The whole L2 acceptor stays OFF unless FILAMENT_L2=1 (opt-in).

                let host = v["host"].as_str().unwrap_or("127.0.0.1").to_string();
                let port = v["rport"].as_u64().or_else(|| v["port"].as_u64()).unwrap_or(0) as u16;
                if port == 0 {
                    return OpenVerdict::Deny { sid, err: "bad port" };
                }
                // ---- SSRF defense: localhost-only by default ----
                // Stricter than is_private_addr (which ALLOWS LAN/RFC1918): the
                // dial target must resolve to loopback. A non-loopback host is
                // refused UNLESS the caller's opt-in per-device allowlist
                // (l2-allow.json) authorized this exact target (`allow_nonloopback`).
                if !host_is_loopback(&host) && !allow_nonloopback {
                    return OpenVerdict::Deny { sid, err: "non-loopback denied (not in l2-allow.json)" };
                }
                // H-1 (DoS): cap concurrent streams per link. A flaky/hostile
                // paired device can otherwise flood `l2-open` and exhaust
                // sockets/threads. We drop the `accepted` marker so the same sid
                // can be retried once others free up.
                if self.at_stream_cap().await {
                    self.accepted.lock().await.remove(&sid);
                    return OpenVerdict::Deny { sid, err: "too many streams" };
                }
                let rx = self.register(sid).await; // BEFORE the async dial
                OpenVerdict::Accept { sid, host, port, rx }
            }
            Some("l2-close") => {
                if let Some(sid) = v["sid"].as_u64() {
                    self.on_close(sid as u32, v["err"].as_str()).await;
                }
                OpenVerdict::Ignore
            }
            _ => OpenVerdict::Ignore,
        }
    }

    /// Acceptor: dial the localhost target for an accepted open and relay. Sends
    /// l2-open-ack on success, l2-close{err} on dial failure. Runs as its own
    /// task (the event loop spawns it) so the dial never blocks routing.
    pub async fn dial_and_serve(self: Arc<Self>, sid: u32, host: String, port: u16, rx: mpsc::Receiver<PipeItem>) {
        match TcpStream::connect((host.as_str(), port)).await {
            Ok(sock) => {
                let _ = sock.set_nodelay(true);
                // l2-open-ack is mandatory (design §3.4/O2): it tells the
                // initiator the stream is live. credit-in-ack is the follow-up
                // (TODO(credits)); 0 here means "no per-stream window yet".
                let _ = self
                    .transport
                    .send_control(&json!({ "type": "l2-open-ack", "sid": sid, "credit": 0 }))
                    .await;
                serve_stream(self.clone(), sid, sock, rx, true, None).await;
                self.accepted.lock().await.remove(&sid);
            }
            Err(e) => {
                self.drop_stream(sid).await;
                self.accepted.lock().await.remove(&sid);
                let _ = self
                    .transport
                    .send_control(&json!({ "type": "l2-close", "sid": sid, "err": e.to_string() }))
                    .await;
            }
        }
    }
}

/// True if `host` is a loopback address/name. We accept the literal "localhost"
/// and any address that parses to a loopback IP. (DNS for arbitrary names is
/// deliberately NOT performed here, the default contract is localhost-only and
/// a name that isn't "localhost" is treated as non-loopback.)
fn host_is_loopback(host: &str) -> bool {
    if host.eq_ignore_ascii_case("localhost") {
        return true;
    }
    host.parse::<std::net::IpAddr>().map(|ip| ip.is_loopback()).unwrap_or(false)
}

// ------------------------------------------------------------ INITIATOR side --

/// Holds the signaling client + WebRTC peer that back a brought-up link so the
/// CALLER decides their fate. A long-lived consumer (netcat/forward) calls
/// `forget()` to keep the link alive for the process lifetime (byte-identical to
/// the old `std::mem::forget`). A short-lived consumer (the shell bootstrap)
/// calls `close().await` to TEAR THE LINK DOWN before opening a second link to
/// the same device, otherwise the acceptor sees two same-device peers at once
/// and its C6 supersede/adopt logic churns (one link gets dropped mid-use).
pub struct LinkGuard {
    sio: Option<rust_socketio::asynchronous::Client>,
    peer: Option<Arc<Peer>>,
}

impl LinkGuard {
    /// Keep the link alive forever (leaks sio+peer, as the long-lived tunnels
    /// want). Consumes the guard.
    fn forget(mut self) {
        if let Some(sio) = self.sio.take() {
            std::mem::forget(sio);
        }
        if let Some(p) = self.peer.take() {
            std::mem::forget(p);
        }
    }

    /// Cleanly close the link: drop the WebRTC peer connection and disconnect
    /// signaling, so the acceptor reaps this peer promptly. Consumes the guard.
    async fn close(mut self) {
        if let Some(p) = self.peer.take() {
            p.close().await;
        }
        if let Some(sio) = self.sio.take() {
            let _ = sio.disconnect().await;
        }
    }
}

/// Minimal identity-mode link bring-up to a *known* device, mirroring the
/// production send/recv path but stripped to exactly what L2 needs: join a solo
/// room, subscribe to the device's presence channel, dial it when it appears,
/// and prove our identity (pair-proof) so its `up`/`recv` marks us trusted,
/// which is what unlocks the acceptor's capability gate. Returns the ready
/// Transport, the event receiver, and a `LinkGuard` the caller must either
/// `forget()` (keep alive) or `close().await` (tear down).
async fn bring_up_to_known(
    server: &str,
    peer_name: &str,
    relay: bool,
    role: &'static str,
) -> Result<(Arc<dyn Transport>, mpsc::UnboundedReceiver<Ev>, LinkGuard, crate::diag::Attempt)> {
    let secret = crate::devices_load()
        .into_iter()
        .find(|(n, _)| n.eq_ignore_ascii_case(peer_name))
        .map(|(_, s)| s)
        .ok_or_else(|| anyhow!("no known device named '{peer_name}', run `filament pair` first (see `filament devices`)"))?;
    let channel = crate::channel_of(&secret);

    // Establishment telemetry: a connect span, peer tagged by SHORT HASH (never
    // the petname). The Attempt is returned to the caller so it can record the
    // L2Open round trip and the final `up`. We start in Signaling (socket + the
    // first `welcome`); the loop drives the phase transitions below.
    let mut diag = crate::diag::Attempt::new(server, &crate::diag::peer_hash_from_secret(&secret), role);
    // Latch so we record the Presence->Establishing transition exactly once
    // (the loop dequeues a candidate every time `peer` is idle, but the connect
    // lifecycle's "establishing" begins at the FIRST candidate).
    let mut entered_establishing = false;

    let cfg = net::fetch_config(server).await?;
    let (tx, mut rx) = mpsc::unbounded_channel::<Ev>();
    let mut sio = net::connect_signaling(server, tx.clone()).await?;

    let my_uid = crate::mk_uid("l2");
    // A solo room keeps strangers out; presence-channel subscription is how we
    // actually find the known device (same as `--to` identity mode).
    let solo = format!("l2-{}", crate::fresh_secret());
    let join_payload =
        json!({ "room": solo, "uid": my_uid, "name": crate::display_name() });
    sio.emit("join", join_payload.clone()).await.ok();
    // NOTE: subscribe is emitted on Ev::Welcome (below), not here, `welcome` is
    // the proof the socket.io connection is fully established, so the subscribe
    // can't be lost in the connect->emit race that intermittently left the client
    // unsubscribed and "waiting for known device" forever (harness finding).
    //
    // The `join` ABOVE has the SAME connect->emit race: fired the instant
    // `connect_signaling` returns, it can land before the socket.io connection is
    // fully ready and be silently dropped, the server then never runs `_do_join`,
    // never emits `welcome`, and this loop waits for a Welcome that never comes,
    // stranding `filament ssh` in "waiting for known device" (~30% of attempts in
    // the isolated repro). So we RE-EMIT join on the same cadence as the
    // re-subscribe below until Welcome lands (idempotent: a repeat join to the
    // same solo room is a no-op server-side once it took).

    let mut my_id: Option<String> = None;
    let mut peer: Option<Arc<Peer>> = None;
    let mut peer_uid: Option<String> = None;
    let mut generation: u32 = 0;
    // Ghost tolerance: the channel can hold DEAD sids (a SIGKILL'd process
    // lingers until the server's ping-timeout) and WRONG peers (our own up
    // subscribes the same pair channel). Locking onto the first known-peer
    // forever was the dominant stall. Instead: one candidate AT A TIME (a
    // parallel race glares, proven, see multicandidate-attempt.patch), a
    // short per-candidate timer, and rotation through everything seen.
    let mut queue: VecDeque<(String, Option<String>)> = VecDeque::new();
    // Per-candidate establish budget for the INTERACTIVE L2/ssh path: how long a
    // single candidate gets to complete (WebRTC + direct-QUIC race) before it is
    // declared Stuck and we rotate to the next. This is a TIMEOUT, not the
    // connect time: a healthy candidate completes in 1.7-3.3s regardless, so a
    // larger budget never slows a good path, it only stops abandoning a real one
    // too early.
    //
    // It was briefly tightened to 4s chasing Tailscale's sub-5s connect, but 4s
    // is BELOW the time a legitimately slow-but-real ICE needs (~5s, e.g. a
    // cross-NAT path that nominates a srflx/relay pair): the budget fired before
    // the real candidate finished, every rotation got cut at 4s, and the link
    // never came up ("establishment timed out", reproduced live as a consistent
    // pop-os -> do-vm failure that 7s/12s established cleanly). Back to 7s, which
    // clears the real ICE time with margin; field-overridable via
    // FILAMENT_L2_CANDIDATE_SECS.
    let candidate_secs: u64 = std::env::var("FILAMENT_L2_CANDIDATE_SECS")
        .ok()
        .and_then(|v| v.parse::<u64>().ok())
        .filter(|n| *n > 0)
        .unwrap_or(7);
    // Item 3: the L2 initiator races a DIRECT-QUIC dial against WebRTC. On
    // KnownPeer we bind a quinn endpoint + advertise our candidates (mirrors
    // `start_direct` in main.rs); when the peer's transport-offer arrives we
    // consume this endpoint into the race. UNCONDITIONAL here: `bring_up_to_known`
    // only ever serves L2 (netcat/ssh/forward), which always wants direct, and
    // `filament ssh`/`netcat` do NOT set FILAMENT_L2 in their own env, so gating
    // on `direct_enabled()` would kill the direct dial on the live path. main.rs
    // gates because it ALSO serves file transfer; this function never does.
    let mut endpoint: Option<quinn::Endpoint> = None;
    // Candidates gathered once at first bind; re-advertised to each new
    // candidate peer we rotate to (the endpoint accepts from any of them,
    // the QUIC race is pair-secret-authenticated either way).
    let mut direct_cands: Option<Vec<String>> = None;
    // The acceptor re-sends its transport-offer (a late initiator can miss the
    // first). Race only the FIRST offer we get; later re-sends are duplicates.
    let mut direct_racing = false;

    let spawn_timer = |pid: String, g: u32| {
        let tx = tx.clone();
        tokio::spawn(async move {
            tokio::time::sleep(std::time::Duration::from_secs(candidate_secs)).await;
            let _ = tx.send(Ev::Stuck(pid, g));
        });
    };

    // Distinct wording for the shell-auth pre-flight so the two sequential
    // bring-ups of `filament ssh` (the bootstrap link, then the netcat data link)
    // do not read as a flap/retry of one connection. "bootstrap" has its own
    // wording; "reconnect" is silent (post-warm resume check — the link was
    // already up; re-reporting it after a clean logout is noise).
    let silent = role.starts_with("reconnect");
    if !silent {
        crate::ui::say(&match role {
            "bootstrap" => format!("filament: authenticating with '{peer_name}'..."),
            _ => format!("\rfilament: waiting for known device '{peer_name}'..."),
        });
    }

    // Presence re-subscribe cadence: while we have NOT yet discovered a candidate
    // (empty queue, no live peer), re-emit the ack'd subscribe every ~2s. This
    // recovers the inverse of the ack-roster race, the acceptor that subscribes
    // AFTER us, whose single async `known-peer` push to us is lost. The `up`
    // acceptor gets this self-healing free from its `sync` tick; the one-shot L2
    // initiator needs it explicitly or a lost push strands it in "presence"
    // forever. Cheap (one emit) and idempotent, and it STOPS the instant a
    // candidate is queued/dialing, so a healthy connect never re-subscribes.
    let mut resubscribe = tokio::time::interval(Duration::from_millis(2000));
    resubscribe.tick().await; // consume the immediate first tick (we just subscribed on Welcome)
    // How many re-join ticks we've waited with NO Welcome. rust_socketio's
    // websocket client occasionally finishes `.connect().await` in a state where
    // it can SEND but silently never DELIVERS inbound events to our handlers: the
    // server receives our `join` (and re-emits `welcome` on every retry, verified
    // in the backend telemetry) but this loop never sees `Ev::Welcome`, so it
    // hangs in "waiting for known device" no matter how many times we re-join the
    // SAME dead socket (the residual ~30% rapid-`ssh` failure). Re-emitting can't
    // fix a socket that won't receive, so after a couple of silent ticks we tear
    // the socket DOWN and dial a FRESH one (reconnect_signaling) on the same `tx`.
    let mut welcome_silent_ticks: u32 = 0;

    // Heartbeat so a slow establish never reads as a silent hang: every 7s while
    // still connecting, emit elapsed progress (skipped for `doctor`, which renders
    // its own per-phase ladder). The overall deadline lives at the call site.
    let connect_started = tokio::time::Instant::now();
    let mut heartbeat = tokio::time::interval(Duration::from_secs(7));
    heartbeat.tick().await; // consume the immediate first tick

    loop {
        // One candidate at a time: start the next attempt whenever idle.
        if peer.is_none() {
            if let Some((pid, uid)) = queue.pop_front() {
                // A candidate appeared and we are dialing it: presence is done,
                // we are now in the Establishing (WebRTC + direct-QUIC race)
                // phase. Latched so re-dials of later candidates don't re-emit.
                if !entered_establishing {
                    diag.enter(crate::diag::Phase::Establishing);
                    entered_establishing = true;
                }
                let mine = my_id.clone().unwrap_or_default();
                let polite = net::polite_role(&my_uid, uid.as_deref(), &mine, &pid);
                generation += 1;
                spawn_timer(pid.clone(), generation);
                let p = Peer::connect(
                    pid.clone(), polite, cfg.ice_servers.clone(), relay,
                    sio.clone(), tx.clone(), generation,
                )
                .await?;
                peer_uid = uid;
                peer = Some(p);

                // Item 3: also start a DIRECT-QUIC attempt racing the WebRTC
                // dial. Bind once, advertise to whichever candidate is current
                // (mirrors `start_direct`); the peer's own offer drives the
                // race (handled in Ev::Signal below). Gated on
                // `direct_enabled()` — when `FILAMENT_DIRECT=0` (e.g. macOS
                // hyperkit CI), the L2 establish skips direct-quic entirely and
                // uses WebRTC (srflx / relay candidates), exercising the relay
                // fallback path.
                if !direct_racing && crate::direct::direct_enabled() {
                    if endpoint.is_none() {
                        match crate::direct::bind_endpoint() {
                            Ok((ep, port)) => {
                                direct_cands =
                                    Some(crate::direct::gather_candidates(server, port).await);
                                endpoint = Some(ep);
                                // TRACE, direct-offer detail.
                                crate::ui::trace(&format!("filament: DIRECT-OFFER sent to '{peer_name}', port {port}"));
                            }
                            Err(e) => {
                                crate::ui::trace(&format!("filament: direct disabled (endpoint bind failed: {e}), WebRTC only"));
                            }
                        }
                    }
                    if endpoint.is_some() {
                        if let Some(c) = &direct_cands {
                            let offer =
                                json!({ "type": "transport-offer", "v": 1, "addrs": c });
                            sio.emit("signal", json!({ "to": pid, "data": offer })).await.ok();
                        }
                    }
                }
            }
        }
        let ev = tokio::select! {
            ev = rx.recv() => match ev {
                Some(ev) => ev,
                None => break,
            },
            _ = heartbeat.tick() => {
                if role != "doctor" {
                    crate::ui::say(&format!(
                        "filament: still reaching '{peer_name}'... ({}s)",
                        connect_started.elapsed().as_secs()
                    ));
                }
                continue;
            }
            _ = resubscribe.tick() => {
                if my_id.is_none() {
                    // No Welcome yet. Re-emit the `join` once (it may have raced the
                    // socket-ready and been dropped server-bound); but if the socket
                    // stays silent across a couple of ticks the socket itself is
                    // RECEIVE-dead, so dial a fresh one and re-join on it.
                    welcome_silent_ticks += 1;
                    if welcome_silent_ticks >= 2 {
                        welcome_silent_ticks = 0;
                        if let Ok(fresh) = net::reconnect_signaling(server, tx.clone()).await {
                            let _ = sio.disconnect().await;
                            sio = fresh;
                        }
                    }
                    sio.emit("join", join_payload.clone()).await.ok();
                } else if peer.is_none() && queue.is_empty() {
                    // Welcome landed but no candidate found yet: re-subscribe so a
                    // lost `known-peer` push / a late-appearing acceptor is still
                    // discovered. Stops the instant a candidate is queued/dialing.
                    net::subscribe_with_ack(&sio, vec![channel.clone()], tx.clone()).await;
                }
                continue;
            }
        };
        match ev {
            Ev::Welcome(v) => {
                my_id = v["id"].as_str().map(|s| s.to_string());
                // Signaling is live (socket + welcome); we now subscribe and wait
                // for the known device to appear, that is the Presence phase.
                diag.enter(crate::diag::Phase::Presence);
                // Subscribe now that the connection is confirmed (see the note at
                // the join site). DETERMINISTIC discovery: emit-with-ack and read
                // the roster the server returns synchronously, so a known device
                // already present is found even if its one-shot async `known-peer`
                // push is lost (the dominant presence stall, see
                // `net::subscribe_with_ack`). The periodic re-subscribe below
                // covers the inverse race (the acceptor appearing AFTER us).
                net::subscribe_with_ack(&sio, vec![channel.clone()], tx.clone()).await;
            }
            Ev::KnownPeer(v) => {
                if v["channel"].as_str() != Some(channel.as_str()) {
                    continue;
                }
                let pid = match v["id"].as_str() {
                    Some(p) => p.to_string(),
                    None => continue,
                };
                if Some(pid.as_str()) == my_id.as_deref() {
                    continue;
                }
                // #9: never dial our OWN install (the up subscribes this pair
                // channel too). Pair secrets are symmetric, so a self-connect
                // can pass the pair-proof and tunnel into the WRONG host's
                // sshd, the local daemon answering as the remote device.
                if crate::is_self_uid(&my_uid, v["uid"].as_str()) {
                    continue;
                }
                // Queue every distinct sid; the loop top rotates through them.
                if peer.as_ref().is_some_and(|p| p.id == pid)
                    || queue.iter().any(|(q, _)| *q == pid)
                {
                    continue;
                }
                queue.push_back((pid, v["uid"].as_str().map(|s| s.to_string())));
            }
            Ev::Signal(v) => {
                let data = v["data"].clone();
                // Item 3: a relayed `transport-offer` carries the peer's direct
                // candidates. Do NOT hand it to the WebRTC `Peer`; instead consume
                // our endpoint and spawn the simultaneous-open + auth race
                // (`race_connect_labeled`, the same primitive `start_direct`
                // drives). The winner posts Ev::DirectReady into THIS loop's tx,
                // so the DirectTransport's reader funnels Chunk/Control/PcState to
                // the rx the caller hands to `pump_initiator`.
                if data["type"].as_str() == Some("transport-offer") {
                    if direct_racing {
                        continue; // already racing the first offer; ignore re-sends
                    }
                    // Bind on-demand if the offer beat our own KnownPeer: on real
                    // WAN the already-running acceptor fires its offer the instant
                    // we appear, which can arrive BEFORE our presence event sets
                    // `endpoint`. The old `if let Some` silently DROPPED it and we
                    // never dialed (the cross-machine stall). We DIAL the peer's
                    // candidates, so we don't need to have sent our own offer first.
                    let ep = endpoint
                        .take()
                        .or_else(|| crate::direct::bind_endpoint().ok().map(|(ep, _)| ep));
                    if let Some(ep) = ep {
                        direct_racing = true;
                        let peer_cands: Vec<String> = data["addrs"]
                            .as_array()
                            .map(|a| a.iter().filter_map(|x| x.as_str().map(String::from)).collect())
                            .unwrap_or_default();
                        // DEBUG, resilience/direct internal (racing a direct path).
                        crate::ui::debug(&format!(
                            "filament: got transport-offer ({} cand), racing direct-quic",
                            peer_cands.len()
                        ));
                        let secret = secret.clone();
                        let pid = v["from"].as_str().unwrap_or_default().to_string();
                        let tx = tx.clone();
                        tokio::spawn(async move {
                            if let Some(t) = crate::direct::race_connect_labeled(
                                // answerer=false: this is bring_up (the connector
                                // side), so it allocates the low L2 sid half.
                                ep, peer_cands, &secret, pid.clone(), tx.clone(), "direct-quic", false,
                            )
                            .await
                            {
                                let _ = tx.send(Ev::DirectReady(pid, t, "direct-quic"));
                            }
                            // On None the WebRTC path (Ev::ChannelReady) continues.
                        });
                    }
                    continue;
                }
                // Route by sender: the channel is multi-party (our own up
                // subscribes it too, plus lingering dead sids), a stray offer
                // applied to the current pc was a reliable glare generator.
                let from = v["from"].as_str().unwrap_or_default();
                let Some(p) = &peer else { continue };
                if p.id != from {
                    continue;
                }
                match p.handle_signal(data).await {
                    Ok(net::SignalOutcome::Handled) => {}
                    Ok(net::SignalOutcome::Glare(offer)) => {
                        // Both sides offered (role confusion). Yield: rebuild
                        // this attempt as a pure responder answering theirs.
                        let old = peer.take().unwrap();
                        let pid = old.id.clone();
                        old.mark_closed();
                        tokio::spawn(async move { old.close().await });
                        generation += 1;
                        spawn_timer(pid.clone(), generation);
                        let p = Peer::connect(
                            pid, true, cfg.ice_servers.clone(), relay,
                            sio.clone(), tx.clone(), generation,
                        )
                        .await?;
                        if let Err(e) = p.handle_signal(offer).await {
                            crate::ui::trace(&format!("filament: signal: {e}"));
                        }
                        peer = Some(p);
                    }
                    Err(e) => crate::ui::trace(&format!("filament: signal: {e}")),
                }
            }
            Ev::DirectReady(_pid, t, route) => {
                // Item 3: the DIRECT-QUIC race won before WebRTC. The acceptor's
                // `adopt_direct` (main.rs) is born `trusted: true` + identity-bound
                // `verified_name`, its pair-secret MAC already proved who we are,
                // so the cap gate is satisfied WITHOUT a pair-proof. We deliberately
                // do NOT replicate the ChannelReady proof here: that MAC is built
                // from the WebRTC DTLS fingerprints, which a direct QUIC link does
                // not have, and the acceptor's direct link (`peer: None`) has none
                // to verify against. (design-l2-direct-ladder.md §NOTE: pre-trust
                // OR pair-proof, we confirmed pre-trust holds for the L2 acceptor.)
                // INFO, tunnel established (with its route label). Silent for the
                // bootstrap pre-flight (internal; the data link reports the route)
                // and for reconnect roles (post-warm resume noise suppression).
                if !role.starts_with("reconnect") && role != "bootstrap" {
                    crate::ui::debug(&format!("\rfilament: tunnel up to '{peer_name}' (route: {route})"));
                }
                // Transport is up: the Establishing race is won. Record Ready;
                // the caller records the L2Open round trip and the final `up`.
                diag.enter(crate::diag::Phase::Ready);
                // The WebRTC `peer` is now superfluous; the guard owns it (its
                // teardown/forget semantics are unchanged, no extra teardown).
                let guard = LinkGuard { sio: Some(sio), peer: peer.take() };
                return Ok((t, rx, guard, diag));
            }
            Ev::Stuck(pid, g) => {
                // Per-candidate timer (or the 15s watchdog) fired for the
                // CURRENT attempt: drop it and rotate. The sid goes to the
                // back of the queue, a slow-but-real peer gets retried, a
                // ghost just cycles until the server evicts it.
                if g == generation && peer.as_ref().is_some_and(|p| p.id == pid) {
                    let p = peer.take().unwrap();
                    p.mark_closed();
                    tokio::spawn(async move { p.close().await });
                    // The per-candidate establish budget fired: this candidate
                    // wedged and we rotate. Record a stall (the "burns the budget
                    // then succeeds on retry" signal we are hunting).
                    diag.stall(crate::diag::Phase::Establishing, candidate_secs * 1000);
                    crate::ui::debug("filament: candidate unresponsive, rotating");
                    queue.push_back((pid, peer_uid.take()));
                }
            }
            Ev::ChannelReady(pid, t) if peer.as_ref().is_some_and(|p| p.id == pid) => {
                // Prove identity so the peer's up/recv marks this link trusted,
                // the acceptor's capability gate keys on exactly that.
                if let Some(p) = &peer {
                    if let Some((my_fp, their_fp)) = p.fingerprints().await {
                        let mac = crate::proof_for(
                            &secret, &my_uid, &my_uid,
                            peer_uid.as_deref().unwrap_or(""), &my_fp, &their_fp,
                        );
                        t.send_control(&json!({ "type": "pair-proof", "mac": mac })).await?;
                    }
                }
                // Hand sio + peer to the caller via a guard: a long-lived tunnel
                // `forget()`s it (keep alive); the bootstrap `close().await`s it
                // (tear down before the second link).
                if !role.starts_with("reconnect") && role != "bootstrap" {
                    crate::ui::say(&format!("filament: tunnel up to '{peer_name}'"));
                }
                // Transport is up via WebRTC: Establishing race won. Record Ready;
                // the caller records the L2Open round trip and the final `up`.
                diag.enter(crate::diag::Phase::Ready);
                let guard = LinkGuard { sio: Some(sio), peer: peer.take() };
                return Ok((t, rx, guard, diag));
            }
            Ev::PcState(pid, s) if s == "failed" || s == "closed" => {
                // Was fatal; now just rotate, the overall command timeout
                // (or the user) bounds how long we keep trying.
                if peer.as_ref().is_some_and(|p| p.id == pid) {
                    let p = peer.take().unwrap();
                    p.mark_closed();
                    tokio::spawn(async move { p.close().await });
                    crate::ui::debug(&format!("filament: connection {s}, rotating"));
                    queue.push_back((pid, peer_uid.take()));
                }
            }
            _ => {}
        }
    }
    diag.fail("signaling ended before a data channel came up");
    Err(anyhow!("signaling ended before a data channel came up"))
}

// ------------------------------------------------------------- DOCTOR PROBE --
//
// `filament doctor <device>` drives this: an "establish then drop" probe that
// runs the EXACT same bring-up as netcat (`bring_up_to_known` with role
// "doctor"), opens one L2 stream so the L2Open round trip is exercised, then
// IMMEDIATELY tears the link down. It never opens a shell or moves payload. The
// point is to surface WHERE establishment is slow or stalls, using the same
// `Attempt` instrumentation (phases + budgets) a real connect uses, so the
// ladder a probe prints matches what a live ssh would have hit.

/// The result of one `establish_probe`: the per-phase ladder (reused verbatim
/// from the `Attempt`), the total span time, and the terminal verdict.
pub struct ProbeOutcome {
    /// Per-phase timings, in completion order (signaling, presence, ...). Each
    /// carries its over-budget flag, computed by `diag::over_budget`.
    pub timings: Vec<crate::diag::PhaseTiming>,
    /// Total establish time, signaling start to link usable.
    pub total_ms: u64,
    /// True iff the link came up. On `false`, `failed_phase` says where it died.
    pub established: bool,
    /// On failure, the phase the bring-up was IN when it gave up.
    pub failed_phase: Option<crate::diag::Phase>,
    /// On failure, the error string.
    pub error: Option<String>,
    /// On success, the path the probe link actually took (interface, address
    /// class, endpoints) - so `filament doctor` shows the route in the same fine
    /// detail as `filament ping`. `None` when the link never came up.
    pub path: Option<crate::net::PathInfo>,
}

/// Establish a link to `peer` exactly as netcat would, then drop it. Returns the
/// per-phase timings + verdict. Reuses `bring_up_to_known` (role "doctor"), so
/// the phases/budgets are identical to a real connect, and cleans up BOTH the
/// link (LinkGuard::close) and the mux (no leaked streams/pumps).
pub async fn establish_probe(server: &str, peer: &str, relay: bool) -> Result<ProbeOutcome> {
    // Overall safety bound so a wedged candidate cannot hang the probe forever
    // (the per-candidate rotation already re-races inside bring_up_to_known; this
    // is the outer wall). Generous: a slow-but-real ICE lands around 5s and we
    // want to OBSERVE that, not abort it prematurely. Overridable for the field.
    let probe_secs: u64 = std::env::var("FILAMENT_DOCTOR_PROBE_SECS")
        .ok()
        .and_then(|v| v.parse::<u64>().ok())
        .filter(|n| *n > 0)
        .unwrap_or(30);
    let deadline = std::time::Duration::from_secs(probe_secs);

    match tokio::time::timeout(deadline, bring_up_to_known(server, peer, relay, "doctor")).await {
        Ok(Ok((t, rx, guard, mut diag))) => {
            // The link is up (Ready recorded). Exercise the L2Open round trip the
            // same way netcat does: pump inbound events, open one stream (sends
            // l2-open), record `up`. We do NOT wait on payload; the open is the
            // last establishment rung we care about.
            let mux = Mux::new(t);
            let pump = tokio::spawn(pump_initiator(rx, mux.clone()));

            diag.enter(crate::diag::Phase::L2Open);
            // rport is irrelevant for the timing: the acceptor dials localhost:0
            // and refuses, but the l2-open / l2-close round trip is what we time.
            // Use a benign port and tear the stream down immediately afterwards.
            let probe_rport: u16 = 9; // discard
            let (sid, _rx_pipe) = open_stream(&mux, probe_rport).await?;
            diag.up("tunnel", "datachannel-or-direct");

            // Capture the path BEFORE teardown: the transport (direct) or the
            // guard's webrtc peer (relay) still holds the live endpoints here.
            let path = Some(
                crate::net::describe_path(mux.transport().as_ref(), guard.peer.as_deref()).await,
            );

            // Tear DOWN, no leak: drop the stream, tell the peer, stop the pump,
            // and close the link (peer + signaling), so the acceptor reaps us.
            mux.drop_stream(sid).await;
            let _ = mux
                .transport()
                .send_control(&json!({ "type": "l2-close", "sid": sid }))
                .await;
            mux.shutdown_all().await;
            pump.abort();
            guard.close().await;

            Ok(ProbeOutcome {
                timings: diag.timings().to_vec(),
                total_ms: diag.total_ms(),
                established: true,
                failed_phase: None,
                error: None,
                path,
            })
        }
        Ok(Err(e)) => {
            // bring_up_to_known recorded `fail` on its (now-consumed) Attempt and
            // wrote the partial ladder to the JSONL. Read it back so the verdict
            // can name where it died, the SAME timings a live connect recorded.
            let (timings, failed_phase) = match crate::diag::latest_span_ladder() {
                Some((t, p)) => (t, Some(p)),
                None => (Vec::new(), None),
            };
            Ok(ProbeOutcome {
                timings,
                total_ms: 0,
                established: false,
                failed_phase,
                error: Some(e.to_string()),
                path: None,
            })
        }
        Err(_elapsed) => {
            // The outer wall fired: the bring-up is still running (the Attempt was
            // never returned). Recover whatever ladder it logged so far.
            let (timings, failed_phase) = match crate::diag::latest_span_ladder() {
                Some((t, p)) => (t, Some(p)),
                None => (Vec::new(), None),
            };
            Ok(ProbeOutcome {
                timings,
                total_ms: probe_secs * 1000,
                established: false,
                failed_phase,
                error: Some(format!("establishment timed out after {probe_secs}s")),
                path: None,
            })
        }
    }
}

/// Drive the initiator's inbound event pump: route L2 control/data into the mux
/// and tear everything down on data-channel death. The initiator never accepts
/// inbound opens (it allocates ids); an l2-open-ack is delivered to the stream as a
/// liveness marker so warm-reuse verification passes even for a client-speaks-first
/// protocol (see `Mux::on_open_ack`).
async fn pump_initiator(mut rx: mpsc::UnboundedReceiver<Ev>, mux: Arc<Mux>) {
    while let Some(ev) = rx.recv().await {
        match ev {
            Ev::Control(_pid, v) => match v["type"].as_str() {
                Some("l2-close") => {
                    if let Some(sid) = v["sid"].as_u64() {
                        mux.on_close(sid as u32, v["err"].as_str()).await;
                    }
                }
                Some("l2-open-ack") => {
                    if let Some(sid) = v["sid"].as_u64() {
                        mux.on_open_ack(sid as u32).await;
                    }
                }
                Some("mount-open-ack") => {
                    if let Some(sid) = v["sid"].as_u64() {
                        let mut ack_map = mux.mount_ack_tx.lock().await;
                        if let Some(tx) = ack_map.remove(&(sid as u32)) {
                            let caps = v.get("caps").cloned().unwrap_or(serde_json::Value::Null);
                            let _ = tx.send(caps);
                        }
                    }
                }
                _ => {}
            },
            Ev::Chunk(_pid, sid, _offset, data) if is_l2_sid(sid) => {
                mux.on_frame(sid, data).await;
            }
            Ev::PcState(_, s) if s == "failed" || s == "closed" || s == "disconnected" => {
                crate::ui::debug(&format!("filament: tunnel {s}, closing streams"));
                mux.shutdown_all().await;
            }
            _ => {}
        }
    }
    mux.shutdown_all().await;
}

/// Open one stream to `peer:rport`, sending l2-open and waiting (briefly) until
/// the inbound pipe is wired. Returns the registered receiver. The initiator
/// registers its OWN pipe up front so a server-speaks-first protocol (ssh
/// banner) can't lose bytes.
pub(crate) async fn open_stream(mux: &Arc<Mux>, rport: u16) -> Result<(u32, mpsc::Receiver<PipeItem>)> {
    let sid = mux.alloc_sid();
    let rx = mux.register(sid).await;
    // The dial target is ALWAYS 127.0.0.1 in production (localhost-only is the
    // contract). FILAMENT_L2_DIALHOST is a TEST-ONLY override so the SSRF gate
    // can drive a non-loopback open and observe the acceptor refuse it.
    let host = std::env::var("FILAMENT_L2_DIALHOST").unwrap_or_else(|_| "127.0.0.1".to_string());
    mux.transport
        .send_control(&json!({ "type": "l2-open", "sid": sid, "host": host, "rport": rport }))
        .await?;
    Ok((sid, rx))
}

/// How long warm-reuse waits for the first inbound frame proving a held link
/// still delivers, before treating it as a zombie. A healthy link answers in ~1
/// RTT; for ssh that frame is sshd's banner and for pty the shell prompt, both of
/// which the peer sends UNPROMPTED, so the wait overlaps work we needed anyway.
/// Only a black-holed link burns the whole window. Override with
/// FILAMENT_WARM_VERIFY_MS.
#[cfg(unix)]
pub(crate) fn warm_verify_window() -> std::time::Duration {
    let ms = std::env::var("FILAMENT_WARM_VERIFY_MS")
        .ok()
        .and_then(|s| s.parse::<u64>().ok())
        .filter(|n| *n > 0)
        .unwrap_or(2500);
    std::time::Duration::from_millis(ms)
}

/// Confirm a just-opened warm stream (`sid` + its inbound `rx`) actually delivers,
/// BEFORE the caller commits the client to it. Waits up to `verify` for the first
/// inbound frame - data OR an l2-close (a real refusal): either proves the link is
/// alive. Returns the frame so the caller can replay it (no bytes lost). `Err` if
/// nothing arrives in time: a ZOMBIE link, up at the QUIC layer but black-holing
/// new streams, so the caller drops it and falls back to a fresh establish rather
/// than handing the client a dead connection (which would stall until ITS own
/// timeout - the 25s ssh ConnectTimeout we measured). Verifying first means the
/// fallback is immediate and the client never sends bytes into a black hole.
#[cfg(unix)]
async fn verify_first_frame(
    mux: &Arc<Mux>,
    sid: u32,
    mut rx: mpsc::Receiver<PipeItem>,
    verify: std::time::Duration,
) -> Result<(PipeItem, mpsc::Receiver<PipeItem>)> {
    match tokio::time::timeout(verify, rx.recv()).await {
        Ok(Some(first)) => Ok((first, rx)),
        Ok(None) => Err(anyhow!("warm stream closed before any frame")),
        Err(_) => {
            // Best-effort tear-down of the half-open sid on the peer, then bail so
            // the caller drops this zombie link and establishes fresh.
            mux.streams.lock().await.remove(&sid);
            let _ = mux
                .transport
                .send_control(&json!({ "type": "l2-close", "sid": sid }))
                .await;
            Err(anyhow!("warm link unresponsive after {}ms (zombie)", verify.as_millis()))
        }
    }
}

/// Open an L2 stream over a warm link and CONFIRM the peer responds before the
/// caller commits the client. Returns (sid, first_frame, remaining_rx) once the
/// first inbound frame lands. `Err` on a zombie link (see `verify_first_frame`).
#[cfg(unix)]
pub(crate) async fn open_stream_verified(
    mux: &Arc<Mux>,
    rport: u16,
    verify: std::time::Duration,
) -> Result<(u32, PipeItem, mpsc::Receiver<PipeItem>)> {
    let (sid, rx) = open_stream(mux, rport).await?;
    let (first, rx) = verify_first_frame(mux, sid, rx, verify).await?;
    Ok((sid, first, rx))
}

/// Bridge a verified warm stream to the client `sock`, replaying the already-read
/// `first` frame so no peer bytes are lost.
#[cfg(unix)]
pub(crate) async fn serve_verified_stream<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(
    mux: Arc<Mux>,
    sid: u32,
    sock: S,
    first: PipeItem,
    rx: mpsc::Receiver<PipeItem>,
) {
    serve_stream(mux, sid, sock, rx, true, Some(first)).await;
}

/// Open a mesh-native mount stream to the peer, sending `mount-open` with the
/// encoded root path. Waits for the `mount-open-ack` control message carrying
/// server capabilities, then sends `mount-cap-ack` to confirm the negotiated
/// protocol. Returns sid + inbound pipe + the server's MountCaps.
/// No sshd, no sshfs.
pub(crate) async fn open_mount_stream(
    mux: &Arc<Mux>,
    root: &str,
) -> Result<(u32, mpsc::Receiver<PipeItem>, crate::mount_proto::MountCaps)> {
    let sid = mux.alloc_sid();
    let rx = mux.register(sid).await;
    let (tx, caps_rx) = tokio::sync::oneshot::channel();
    mux.mount_ack_tx.lock().await.insert(sid, tx);
    let encoded = crate::mount_proto::path_encode(std::path::Path::new(root));
    mux.transport
        .send_control(&json!({ "type": "mount-open", "sid": sid, "root": encoded }))
        .await?;
    let caps_value = tokio::time::timeout(
        std::time::Duration::from_secs(10),
        caps_rx,
    )
    .await
    .map_err(|_| anyhow::anyhow!("mount-open-ack not received (timed out)"))?
    .map_err(|_| anyhow::anyhow!("mount-open-ack channel closed"))?;
    let caps = crate::mount_proto::parse_mount_caps(caps_value)?;
    // Send mount-cap-ack: the client confirms it accepts the server's caps.
    let _ = mux.transport.send_control(&json!({
        "type": "mount-cap-ack", "sid": sid,
        "binary_frames": caps.protocol_version >= 2
    })).await;
    Ok((sid, rx, caps))
}

/// WARM pty (daemon side): open a PTY on the peer over an EXISTING link's `mux`,
/// sending `pty-open` (vs `open_stream`'s `l2-open`). Returns the sid + inbound
/// pipe; the caller bridges with `serve_opened_stream` and relays `pty-resize` by
/// the sid. `session` keys the peer's persistent PTY so a reconnect reattaches.
/// The remote acceptor serves this exactly as a cold `pty-open`.
pub(crate) async fn open_pty_stream(
    mux: &Arc<Mux>,
    session: &str,
    cols: u16,
    rows: u16,
    term: &str,
    cmd: &str,
) -> Result<(u32, mpsc::Receiver<PipeItem>)> {
    let sid = mux.alloc_sid();
    let rx = mux.register(sid).await;
    let mut ctl = json!({
        "type": "pty-open", "sid": sid, "session": session, "cols": cols, "rows": rows, "term": term
    });
    if !cmd.is_empty() {
        ctl["cmd"] = json!(cmd);
    }
    mux.transport.send_control(&ctl).await?;
    Ok((sid, rx))
}

/// Warm PTY open that CONFIRMS the held link delivers before the caller commits
/// the terminal - the pty twin of `open_stream_verified`. A fresh PTY's shell
/// prompt (or a reattach's replayed buffer) is the first inbound frame and the
/// peer sends it unprompted, so a healthy link costs nothing here; a zombie link
/// yields nothing within `verify` and we `Err` so the caller drops it + falls
/// back to a cold pty instead of handing the user a dead terminal.
#[cfg(unix)]
pub(crate) async fn open_pty_stream_verified(
    mux: &Arc<Mux>,
    session: &str,
    cols: u16,
    rows: u16,
    term: &str,
    cmd: &str,
    verify: std::time::Duration,
) -> Result<(u32, PipeItem, mpsc::Receiver<PipeItem>)> {
    let (sid, rx) = open_pty_stream(mux, session, cols, rows, term, cmd).await?;
    let (first, rx) = verify_first_frame(mux, sid, rx, verify).await?;
    Ok((sid, first, rx))
}

/// Bridge an already-opened L2 stream (`sid` + its inbound `rx`) to a local
/// `stream` (the warm pty client's unix socket), running to completion (stream
/// EOF or peer FIN). The daemon's warm-pty path uses this after a verified open.
#[cfg(unix)]
pub(crate) async fn serve_opened_stream<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(
    mux: Arc<Mux>,
    sid: u32,
    stream: S,
    rx: mpsc::Receiver<PipeItem>,
) {
    serve_stream(mux, sid, stream, rx, true, None).await;
}

/// Pump this process's stdio over a connected warm-reuse socket: stdin -> sock,
/// sock -> stdout. Exit when the remote half closes (sock read EOF), the same
/// "session over" semantics the cold netcat path has. Its OWN `tokio::io::stdin()`
/// is fine here because netcat is a single-shot ProxyCommand (one process, one
/// attach, no reconnect): the singleton is created once and never handed off.
#[cfg(unix)]
async fn pump_stdio_over(sock: tokio::net::UnixStream) -> Result<()> {
    let (mut rd, mut wr) = tokio::io::split(sock);
    let writer = tokio::spawn(async move {
        let mut stdin = tokio::io::stdin();
        let _ = tokio::io::copy(&mut stdin, &mut wr).await; // local EOF
        let _ = wr.shutdown().await; // half-close so the remote sees our EOF
    });
    let mut stdout = tokio::io::stdout();
    tokio::io::copy(&mut rd, &mut stdout).await?;
    let _ = stdout.flush().await;
    writer.abort();
    Ok(())
}

/// Warm-pty variant of `pump_stdio_over` that draws input from the SHARED,
/// invocation-long stdin reader instead of its own `tokio::io::stdin()`. The pty
/// client can hand off warm->cold on a drop, so both halves MUST consume the one
/// fd0 reader or a stale singleton swallows input after the handoff (see
/// `spawn_stdin_reader`). `pending` preserves an input chunk pulled just as the
/// warm socket died so the cold reattach re-sends it. Returns when the socket's
/// remote half closes (warm session over: a drop OR a clean shell exit).
#[cfg(unix)]
async fn pump_warm_pty_stdio(
    sock: tokio::net::UnixStream,
    stdin_rx: &mut tokio::sync::mpsc::UnboundedReceiver<Vec<u8>>,
    pending: &mut Option<Vec<u8>>,
) -> Result<()> {
    let (mut rd, mut wr) = tokio::io::split(sock);
    if let Some(buf) = pending.take() {
        if wr.write_all(&buf).await.is_err() {
            *pending = Some(buf);
            return Ok(());
        }
        let _ = wr.flush().await;
    }
    let mut stdout = tokio::io::stdout();
    let mut buf = [0u8; 16 * 1024];
    loop {
        tokio::select! {
            r = rd.read(&mut buf) => match r {
                Ok(0) | Err(_) => break, // remote half closed: warm session over
                Ok(n) => { stdout.write_all(&buf[..n]).await?; stdout.flush().await?; }
            },
            chunk = stdin_rx.recv() => match chunk {
                Some(c) if c.is_empty() => { let _ = wr.shutdown().await; } // fd0 EOF
                Some(c) => {
                    if wr.write_all(&c).await.is_err() { *pending = Some(c); break; }
                    let _ = wr.flush().await;
                }
                None => { let _ = wr.shutdown().await; }
            },
        }
    }
    let _ = stdout.flush().await;
    Ok(())
}

/// Pump a one-shot warm pty: stream output to stdout until the command exits.
/// No raw mode, no SIGWINCH, no interactive features. Forwards stdin to match
/// cold path parity (supports `echo hi | filament pty peer -- cat`).
#[cfg(unix)]
async fn pump_warm_pty_one_shot(
    sock: tokio::net::UnixStream,
    stdin_rx: &mut tokio::sync::mpsc::UnboundedReceiver<Vec<u8>>,
    pending: &mut Option<Vec<u8>>,
) -> Result<()> {
    let (mut rd, mut wr) = tokio::io::split(sock);
    if let Some(buf) = pending.take() {
        if wr.write_all(&buf).await.is_err() {
            *pending = Some(buf);
            return Ok(());
        }
        let _ = wr.flush().await;
    }
    // For scripted one-shot: on stdin-EOF, shut down the write-half to signal
    // stdin-EOF to the daemon (cat etc. will see stdin EOF and exit), but do
    // NOT let serve_stream tear down the pty session yet. The daemon's
    // socket_to_dc sees the read-EOF and sends an empty frame (FIN) to the
    // daemon transport, which closes the pty stdin. The daemon keeps the pty
    // open until the command exits, then closes the socket (dc_to_socket
    // finishes as the pty output pipe closes), which we see as read-EOF.
    //
    // Key insight: on a Unix socket, closing the write-half sends FIN to the
    // reader, but the reader half stays open. socket_to_dc sees the FIN and
    // returns Ok(()), but the writer (dc_to_socket) is NOT aborted until the
    // daemon's pty output pipe closes. serve_stream's select! picks up the
    // writer finishing AFTER the reader, not before.
    let mut stdin_done = false;
    let mut stdout = tokio::io::stdout();
    let mut buf = [0u8; 16 * 1024];
    loop {
        tokio::select! {
            r = rd.read(&mut buf) => match r {
                Ok(0) | Err(_) => break, // command exited / link closed
                Ok(n) => {
                    stdout.write_all(&buf[..n]).await?;
                    stdout.flush().await?;
                }
            },
            chunk = stdin_rx.recv(), if !stdin_done => match chunk {
                Some(c) if c.is_empty() => {
                    // stdin-EOF: shut down write-half to signal the daemon.
                    // socket_to_dc sees read-EOF, sends FIN to daemon transport.
                    // Daemon keeps pty open until command exits, then closes socket.
                    let _ = wr.shutdown().await;
                    stdin_done = true;
                }
                Some(c) => {
                    if wr.write_all(&c).await.is_err() { *pending = Some(c); break; }
                    let _ = wr.flush().await;
                }
                None => {
                    // Shared reader gone (only at shutdown) - don't close socket.
                    stdin_done = true;
                }
            },
        }
    }
    let _ = stdout.flush().await;
    Ok(())
}

/// `filament dial <peer> <port>`: wire this process's stdio to a service the peer
/// EXPOSED on its overlay address, over L3 (the overlay-port counterpart of
/// `netcat`; also an ssh ProxyCommand for an overlay-exposed sshd). Goes through the
/// local daemon, which resolves the peer to its verified overlay address and dials
/// it, so it works from a userspace node with no kernel route.
#[cfg(unix)]
pub async fn dial_cmd(peer: &str, port: u16) -> Result<()> {
    match crate::ctl::try_dial(peer, port).await {
        Some(sock) => pump_stdio_over(sock).await,
        None => bail!(
            "could not dial {peer}.mesh:{port} over the overlay (is the daemon up, the peer paired, and the port expose'd on it?)"
        ),
    }
}

#[cfg(not(unix))]
pub async fn dial_cmd(_peer: &str, _port: u16) -> Result<()> {
    bail!("filament dial needs the local daemon's control socket (unix only)")
}

/// `filament netcat <peer> <rport>`: wire this process's stdio to one L2 stream.
/// This is the ssh ProxyCommand primitive.
pub async fn netcat_cmd(server: &str, peer: &str, rport: u16, relay: bool) -> Result<()> {
    // WARM-LINK FAST PATH: if a local `up` daemon already holds a link to `peer`,
    // ride it (no signaling, no establishment, ~1s saved). Skipped under --relay
    // (the user forced a relay path; a warm link may be direct) and self-heals: any
    // miss / no daemon / dead stream falls through to a fresh establish below.
    // Unix-only: the control socket is a unix-domain socket (no-op elsewhere).
    #[cfg(unix)]
    if !relay {
        if let Some(sock) = crate::ctl::try_open(peer, rport).await {
            crate::ui::trace(&format!("filament: reusing warm link to '{peer}' (no establish)"));
            return pump_stdio_over(sock).await;
        }
    }
    // Bound the connect so an unreachable peer fails with a clear message
    // instead of hanging forever. Override with FILAMENT_CONNECT_SECS.
    let connect_secs: u64 = std::env::var("FILAMENT_CONNECT_SECS")
        .ok()
        .and_then(|s| s.parse().ok())
        .filter(|n| *n > 0)
        .unwrap_or(45);
    let (t, rx, guard, mut diag) = match tokio::time::timeout(
        std::time::Duration::from_secs(connect_secs),
        bring_up_to_known(server, peer, relay, "init"),
    )
    .await
    {
        Ok(inner) => inner?,
        Err(_) => {
            crate::ui::problem(
                &format!("filament netcat: can't reach '{peer}'"),
                &format!(
                    "couldn't establish a link to '{peer}' in {connect_secs}s - it may be offline or unreachable from here."
                ),
                &[
                    format!("check it's reachable: {}", crate::ui::paint(crate::ui::Tone::Brand, &format!("filament ping {peer}"))),
                    format!("diagnose the connect: {}", crate::ui::paint(crate::ui::Tone::Brand, &format!("filament doctor {peer}"))),
                ],
            );
            std::process::exit(1);
        }
    };
    guard.forget(); // long-lived tunnel, keep the link alive for the process
    let mux = Mux::new(t);
    let pump = tokio::spawn(pump_initiator(rx, mux.clone()));

    // L2Open round trip: open the stream and wait for the acceptor's l2-open-ack
    // (the stream-is-live confirmation) before declaring the link Up. The ack is
    // consumed by pump_initiator, so we instead wait for the FIRST inbound byte
    // or a bounded grace, the practical "stream usable" signal for stdio netcat.
    diag.enter(crate::diag::Phase::L2Open);
    let (sid, mut rx_pipe) = open_stream(&mux, rport).await?;
    // The link is now usable end to end (the ssh handshake will flow). Record
    // `up` with the route label we can infer (the transport carries no route()
    // for a direct link, so we report the generic tunnel transport here).
    diag.up("tunnel", "datachannel-or-direct");

    // stdin -> dc
    let t_in = mux.transport();
    let reader = tokio::spawn(async move {
        let mut stdin = tokio::io::stdin();
        let cap = t_in.max_payload();
        let mut buf = vec![0u8; cap];
        loop {
            match stdin.read(&mut buf).await {
                Ok(0) | Err(_) => {
                    let _ = t_in.send_frame(sid, 0, &[]).await; // local EOF -> FIN
                    break;
                }
                Ok(n) => {
                    if t_in.send_frame(sid, 0, &buf[..n]).await.is_err() {
                        break;
                    }
                }
            }
        }
    });

    // dc -> stdout
    let mut stdout = tokio::io::stdout();
    while let Some(item) = rx_pipe.recv().await {
        match item {
            Some(bytes) => {
                stdout.write_all(&bytes).await?;
                stdout.flush().await?;
            }
            None => break, // peer FIN
        }
    }
    let _ = reader.await;
    mux.drop_stream(sid).await;
    let _ = mux
        .transport()
        .send_control(&json!({ "type": "l2-close", "sid": sid }))
        .await;
    pump.abort();
    Ok(())
}

/// RAII guard: put the local terminal in raw mode for an interactive PTY and
/// ALWAYS restore cooked mode on drop (normal exit, error, or `?`). Without raw
/// mode the local tty line-buffers + echoes and swallows control keys, so a
/// remote TUI (claude/opencode/vim/htop) can't receive keystrokes or escape
/// sequences and renders unusable.
struct RawGuard {
    active: bool,
}
impl RawGuard {
    fn enable() -> Result<Self> {
        crossterm::terminal::enable_raw_mode()?;
        Ok(RawGuard { active: true })
    }
}
impl Drop for RawGuard {
    fn drop(&mut self) {
        if self.active {
            let _ = crossterm::terminal::disable_raw_mode();
            crossterm::execute!(std::io::stderr(), crossterm::cursor::Show).ok();
            eprint!("\r\n");
        }
    }
}

/// Why a single PTY attach ended.
enum PtyOutcome {
    /// The remote shell exited (acceptor sent `l2-close` while the link was
    /// healthy) - we are DONE, do not reconnect.
    Exited,
    /// The link died under us (transport not alive) - the remote PTY session may
    /// still be alive on the acceptor; reconnect and REATTACH the same session.
    Dropped,
}

/// A single, process-lifetime reader of fd0 for the resumable pty client.
///
/// tokio's `io::stdin()` is a GLOBAL singleton backed by an UNCANCELLABLE blocking
/// read thread. The resumable client re-attaches on every link drop (and hands off
/// warm->cold), and the old code spawned a fresh stdin reader per attach then
/// `abort()`ed the previous one. Aborting a task parked in that shared blocking
/// read does NOT stop the read: a stale reader keeps draining fd0 and routing bytes
/// to a DEAD stream, so after a real reattach every keystroke is silently swallowed
/// (observed live: a 30s outage closes QUIC, forces a true reattach, input dies -
/// the read even shows up in strace, it just goes nowhere). Fix: read fd0 exactly
/// ONCE, on a dedicated thread that lives for the whole invocation, and fan chunks
/// to whichever attach is current over an mpsc channel. An empty Vec is the EOF
/// sentinel (matches the `send_frame(sid, &[])` FIN convention). The thread ends on
/// EOF/error; on a clean session exit the process exits right after, reaping it.
fn spawn_stdin_reader() -> tokio::sync::mpsc::UnboundedReceiver<Vec<u8>> {
    let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<Vec<u8>>();
    std::thread::spawn(move || {
        use std::io::Read;
        let mut stdin = std::io::stdin().lock();
        let mut buf = [0u8; 16 * 1024];
        loop {
            match stdin.read(&mut buf) {
                Ok(0) | Err(_) => {
                    let _ = tx.send(Vec::new()); // EOF sentinel
                    break;
                }
                Ok(n) => {
                    if tx.send(buf[..n].to_vec()).is_err() {
                        break; // the client hung up
                    }
                }
            }
        }
    });
    rx
}

/// Send `data` to the peer over one L2 stream, split into transport-sized frames.
/// `Err(())` means a frame was rejected (the link is gone); the caller stashes the
/// unsent input for the next attach so a keystroke typed at the drop is not lost.
async fn send_frames_chunked(t: &Arc<dyn Transport>, sid: u32, data: &[u8]) -> std::result::Result<(), ()> {
    let cap = t.max_payload().max(1);
    for chunk in data.chunks(cap) {
        if t.send_frame(sid, 0, chunk).await.is_err() {
            return Err(());
        }
    }
    Ok(())
}

/// One attach to the peer's PTY over a freshly-established link: open/reattach the
/// `session_id`, bridge stdio, and return why it ended. Raw mode is owned by the
/// caller (held across reconnects), so this only does size/resize/IO. `stdin_rx`
/// is the shared, invocation-long stdin source (see `spawn_stdin_reader`); `pending`
/// carries input pulled-but-unsent when the previous attach dropped, so a keystroke
/// at the seam survives the reconnect.
#[allow(clippy::too_many_arguments)]
async fn pty_attach_once(
    server: &str,
    peer: &str,
    relay: bool,
    role: &'static str,
    session_id: &str,
    term: &str,
    cmd: &str,
    interactive: bool,
    resume: bool,
    raw: &mut Option<RawGuard>,
    stdin_rx: &mut tokio::sync::mpsc::UnboundedReceiver<Vec<u8>>,
    pending: &mut Option<Vec<u8>>,
) -> Result<PtyOutcome> {
    // Bound the connect so an unreachable peer fails with a clear message
    // instead of hanging forever. Override with FILAMENT_CONNECT_SECS.
    let connect_secs: u64 = std::env::var("FILAMENT_CONNECT_SECS")
        .ok()
        .and_then(|s| s.parse().ok())
        .filter(|n| *n > 0)
        .unwrap_or(45);
    let (t, rx, guard, mut diag) = match tokio::time::timeout(
        std::time::Duration::from_secs(connect_secs),
        bring_up_to_known(server, peer, relay, role),
    )
    .await
    {
        Ok(inner) => inner?,
        Err(_) => {
            bail!("connect timeout: couldn't reach '{peer}' in {connect_secs}s");
        }
    };
    guard.forget();
    let mux = Mux::new(t);
    let pump = tokio::spawn(pump_initiator(rx, mux.clone()));

    diag.enter(crate::diag::Phase::L2Open);
    let sid = mux.alloc_sid();
    let mut rx_pipe = mux.register(sid).await;

    // Real terminal: query the ACTUAL tty size (crossterm asks the tty via
    // ioctl), NOT the COLUMNS/LINES shell vars which are usually unexported and
    // leave a TUI rendering at a stale size. Fall back to env/defaults for a pipe.
    let (cols, rows) = if interactive {
        crossterm::terminal::size().unwrap_or((80, 24))
    } else {
        (
            std::env::var("COLUMNS").ok().and_then(|s| s.parse().ok()).unwrap_or(80u16),
            std::env::var("LINES").ok().and_then(|s| s.parse().ok()).unwrap_or(24u16),
        )
    };
    // `session` makes reconnects REATTACH the same shell (acceptor keys it per
    // verified device); a fresh per-invocation id means two `filament pty` runs
    // never collide. `term` is forwarded so the remote matches THIS terminal.
    mux.transport()
        .send_control(&{
            let mut ctl = json!({
                "type": "pty-open", "sid": sid, "session": session_id,
                "cols": cols, "rows": rows, "term": term, "resume": resume,
            });
            if !cmd.is_empty() {
                ctl["cmd"] = json!(cmd);
            }
            ctl
        })
        .await?;
    diag.up("tunnel", "datachannel-or-direct");

    // Enable raw mode LAZILY, AFTER the establishment status lines have printed in
    // cooked mode (so `\n` still does CR+LF and they don't "staircase"). Held in
    // the caller's scope so it persists across reconnects and is restored on exit.
    // On a reconnect raw is already on; the acceptor's buffer replay redraws the
    // screen cleanly anyway.
    if interactive && raw.is_none() {
        *raw = Some(RawGuard::enable()?);
    }

    // Forward terminal resizes to the remote PTY (acceptor handles `pty-resize`).
    #[cfg(unix)]
    let winch = if interactive {
        let t_resize = mux.transport();
        Some(tokio::spawn(async move {
            use tokio::signal::unix::{signal, SignalKind};
            let mut sig = match signal(SignalKind::window_change()) {
                Ok(s) => s,
                Err(_) => return,
            };
            while sig.recv().await.is_some() {
                if let Ok((c, r)) = crossterm::terminal::size() {
                    let _ = t_resize
                        .send_control(&json!({ "type": "pty-resize", "sid": sid, "cols": c, "rows": r }))
                        .await;
                }
            }
        }))
    } else {
        None
    };

    let t_in = mux.transport();
    // Input buffered-but-unsent by the PREVIOUS (dropped) attach goes out first, so
    // a keystroke typed right at the seam survives the reconnect. If this link is
    // already dead, keep it stashed and report a drop so the loop reattaches again.
    if let Some(buf) = pending.take() {
        if send_frames_chunked(&t_in, sid, &buf).await.is_err() {
            *pending = Some(buf);
            #[cfg(unix)]
            if let Some(w) = winch {
                w.abort();
            }
            mux.drop_stream(sid).await;
            pump.abort();
            return Ok(PtyOutcome::Dropped);
        }
    }

    // Stream remote output to stdout AND forward local input, driven by the SHARED
    // stdin reader (see `spawn_stdin_reader`) so reconnects never spawn a second
    // fd0 consumer. End when the pipe closes (shell exit OR link death) - disambiguated
    // by the transport's liveness. A 2s liveness poll is the backstop for a silent
    // black-hole that never closes the pipe.
    let mut stdout = tokio::io::stdout();
    let mut ticker = tokio::time::interval(Duration::from_secs(2));
    ticker.tick().await; // consume the immediate tick
    let mut stdin_done = false; // fd0 hit EOF: stop reading it, keep pumping stdout
    let dropped;
    loop {
        tokio::select! {
            item = rx_pipe.recv() => match item {
                Some(Some(bytes)) => {
                    stdout.write_all(&bytes).await?;
                    stdout.flush().await?;
                }
                // Pipe closed: clean exit (l2-close, link still alive) vs drop.
                _ => { dropped = !mux.transport().is_alive(); break; }
            },
            chunk = stdin_rx.recv(), if !stdin_done => match chunk {
                // Empty Vec = fd0 EOF: send the FIN once, then stop reading stdin but
                // keep draining remote output until the shell actually closes.
                Some(c) if c.is_empty() => { let _ = t_in.send_frame(sid, 0, &[]).await; stdin_done = true; }
                Some(c) => {
                    if send_frames_chunked(&t_in, sid, &c).await.is_err() {
                        // Link died mid-send: stash the input for the next attach and
                        // reconnect rather than lose it.
                        *pending = Some(c);
                        dropped = true;
                        break;
                    }
                }
                None => { stdin_done = true; } // shared reader gone (only at shutdown)
            },
            _ = ticker.tick() => {
                if !mux.transport().is_alive() { dropped = true; break; }
            }
        }
    }

    #[cfg(unix)]
    if let Some(w) = winch {
        w.abort();
    }
    mux.drop_stream(sid).await;
    // Only send our own l2-close on a CLEAN exit. On a drop the link is gone and,
    // crucially, an l2-close would tell the acceptor to END the session we want
    // to reattach - so we stay silent and let it buffer for the reattach.
    if !dropped {
        let _ = mux.transport().send_control(&json!({ "type": "l2-close", "sid": sid })).await;
    }
    pump.abort();
    Ok(if dropped { PtyOutcome::Dropped } else { PtyOutcome::Exited })
}

/// Warm fast path for `filament pty`: if the local daemon already holds a link to
/// `peer`, open the PTY over it (via the control socket) and bridge this process's
/// stdio to it - raw mode + SIGWINCH forwarded as a `resize` op. Returns
/// `Some(result)` once it has handled the session (stdio EOF = shell exit or a
/// warm-link drop -> we exit), or `None` when there is no warm link, so the caller
/// falls through to the cold resumable path. Unix-only (the control socket is unix).
#[cfg(unix)]
async fn try_warm_pty(
    peer: &str,
    session: &str,
    term: &str,
    cmd: &str,
    interactive: bool,
    raw: &mut Option<RawGuard>,
    stdin_rx: &mut tokio::sync::mpsc::UnboundedReceiver<Vec<u8>>,
    pending: &mut Option<Vec<u8>>,
) -> Option<Result<()>> {
    let (cols, rows) = crossterm::terminal::size().unwrap_or((80, 24));
    let sock = crate::ctl::try_pty(peer, session, cols, rows, term, cmd).await?; // None = no warm link
    if interactive {
        crate::ui::trace(&format!("filament: reusing warm link to '{peer}' for pty (no establish)"));
        if raw.is_none() {
            match RawGuard::enable() {
                Ok(g) => *raw = Some(g),
                Err(e) => return Some(Err(e)),
            }
        }
        // Forward SIGWINCH as a `resize` control op (a fresh short connection each time).
        let session_owned = session.to_string();
        let winch = tokio::spawn(async move {
            use tokio::signal::unix::{signal, SignalKind};
            let mut sig = match signal(SignalKind::window_change()) {
                Ok(s) => s,
                Err(_) => return,
            };
            while sig.recv().await.is_some() {
                if let Ok((c, r)) = crossterm::terminal::size() {
                    crate::ctl::try_resize(&session_owned, c, r).await;
                }
            }
        });
        let r = pump_warm_pty_stdio(sock, stdin_rx, pending).await;
        winch.abort();
        Some(r)
    } else {
        // One-shot (scripted): no raw mode, no SIGWINCH, just stream output.
        crate::ui::trace(&format!("filament: reusing warm link to '{peer}' for one-shot pty"));
        // NOTE: neither the cold path nor this warm path propagates the remote
        // command's exit status - both return Ok(()) regardless. This is a known
        // limitation / future enhancement.
        Some(pump_warm_pty_one_shot(sock, stdin_rx, pending).await)
    }
}

/// `filament pty <peer>`: open a PTY shell on the peer and bridge it to this
/// terminal (the CLI sibling of the browser web-shell). On a real terminal it is
/// a FULL interactive client - real tty size, raw mode, SIGWINCH, $TERM - AND
/// RESUMABLE: a per-invocation random session id lets a dropped link reconnect
/// and reattach the SAME live shell (mosh/tmux-style, the acceptor replays its
/// output buffer), so a flaky link (e.g. a Coder workspace reconnecting every
/// ~90s) no longer loses the session. The session id lives only in THIS process,
/// so a separate `filament pty` run always gets a fresh shell, never this one.
/// A non-tty stdio (a pipe) keeps the plain cooked, non-resuming bridge.
pub async fn pty_cmd(server: &str, peer: &str, relay: bool, cmd: Vec<String>) -> Result<()> {
    let one_shot = cmd.join(" ");
    use std::io::IsTerminal;
    let interactive = std::io::stdin().is_terminal() && std::io::stdout().is_terminal();
    // Random, per-invocation, in-memory only: distinct runs never collide; only
    // THIS process's reconnects reattach (see the user's "same client" concern).
    let session_id = crate::fresh_secret();
    let term = std::env::var("TERM").ok().filter(|s| !s.is_empty()).unwrap_or_else(|| "xterm-256color".into());

    // Raw mode is held for the WHOLE invocation (enabled lazily inside the first
    // attach, AFTER its status lines, so they don't staircase), persists across
    // reconnects, and is restored on every exit path by this guard's Drop.
    let mut raw: Option<RawGuard> = None;

    // ONE fd0 reader for the whole invocation, shared across the warm bridge and
    // every cold reattach. tokio's stdin singleton can't be cancelled, so a
    // per-attach reader leaks and swallows input after a reconnect (see
    // `spawn_stdin_reader`). `pending` carries input pulled just as a link died so
    // the reattach re-sends it instead of losing the keystroke.
    let mut stdin_rx = spawn_stdin_reader();
    let mut pending: Option<Vec<u8>> = None;

    // WARM FAST PATH: if the local `up` daemon already holds a (verified, direct)
    // link to `peer`, open the PTY over it - no signaling, no establishment, ~0.2s
    // instead of seconds. A miss / no daemon / no warm link falls through to the
    // cold resumable path below. Skipped under --relay (the user forced relay; a
    // warm link may be direct) and for non-tty stdio (scripted). Resumability
    // lives on the cold path, where flaky peers (no warm link) need it anyway.
    // Loop state up front so the warm path can hand off INTO the resumable loop
    // instead of returning (the old behavior, which re-logged-in on a warm drop).
    let mut ever_connected = false;
    let mut last_up = std::time::Instant::now();
    let mut backoff = Duration::from_millis(300);
    let mut role: &'static str = "init";
    // Set when a WARM session ended (a drop OR a clean shell exit - the warm bridge
    // can't tell). The first cold attach after that is RESUME-ONLY: a warm drop
    // reattaches the SAME live shell/TUI (seamless, no re-login); a clean warm exit
    // finds no session and the acceptor closes it, so we exit cleanly.
    // TODO: distinguish clean-exit from transport-drop at the warm layer.
    //   Currently the bridge sees an opaque socket close for both cases.
    //   A `ctl::session_alive(peer)` probe before the cold loop would skip
    //   unnecessary transport establishment after a clean logout.
    let mut warm_ended = false;

    #[cfg(unix)]
    if !relay && (interactive || !one_shot.is_empty()) {
        match try_warm_pty(peer, &session_id, &term, &one_shot, interactive, &mut raw, &mut stdin_rx, &mut pending).await {
            Some(Err(e)) => return Err(e),
            Some(Ok(())) => {
                // For one-shot exec: the warm bridge already streamed the command's
                // output and waited for exit. Return immediately - do NOT enter the
                // reconnect/resume loop which would cold-establish redundantly.
                if !one_shot.is_empty() {
                    return Ok(());
                }
                warm_ended = true;
                role = "reconnect";
            }
            None => {} // no warm link -> normal cold path below
        }
    }

    loop {
        // Resume-only after any prior connection (warm or cold). If the session
        // is gone (shell exited cleanly on a prior drop), the acceptor returns
        // "no such session" and we exit cleanly instead of spawning a fresh shell.
        let resume = ever_connected || warm_ended;
        match pty_attach_once(server, peer, relay, role, &session_id, &term, &one_shot, interactive, resume, &mut raw, &mut stdin_rx, &mut pending).await {
            Ok(PtyOutcome::Exited) => return Ok(()),
            Ok(PtyOutcome::Dropped) => {
                // Non-tty (scripted) sessions don't resume; a drop is the end.
                if !interactive {
                    return Ok(());
                }
                ever_connected = true;
                last_up = std::time::Instant::now();
                backoff = Duration::from_millis(300);
                role = "reconnect";
                eprint!("\r\n\x1b[2m[filament: link dropped, reconnecting...]\x1b[0m\r\n");
                continue;
            }
            Err(e) => {
                // A first COLD connect (no warm session) failing is fatal. But if a
                // warm session just ended, a failed reattach should RETRY (the mesh
                // may be mid-repair) until the reaper window, not bail.
                if !ever_connected && !warm_ended {
                    let connect_secs: u64 = std::env::var("FILAMENT_CONNECT_SECS")
                        .ok()
                        .and_then(|s| s.parse().ok())
                        .filter(|n| *n > 0)
                        .unwrap_or(45);
                    crate::ui::problem(
                        &format!("filament pty: can't reach '{peer}'"),
                        &format!(
                            "couldn't establish a link to '{peer}' in {connect_secs}s - it may be offline or unreachable from here."
                        ),
                        &[
                            format!("check it's reachable: {}", crate::ui::paint(crate::ui::Tone::Brand, &format!("filament ping {peer}"))),
                            format!("diagnose the connect: {}", crate::ui::paint(crate::ui::Tone::Brand, &format!("filament doctor {peer}"))),
                        ],
                    );
                    std::process::exit(1);
                }
                // A reconnect attempt failed. Keep trying until the acceptor would
                // have reaped the detached session (SESSION_DETACHED_IDLE = 180s);
                // stop a bit under that so we don't reattach into a fresh shell.
                if last_up.elapsed() > Duration::from_secs(150) {
                    eprint!("\r\n\x1b[2m[filament: session expired, reconnect window passed]\x1b[0m\r\n");
                    return Ok(());
                }
                tokio::time::sleep(backoff).await;
                backoff = (backoff * 2).min(Duration::from_secs(5));
                role = "reconnect";
                continue;
            }
        }
    }
}

/// Build the user-facing message for the case where `filament forward` could
/// not bind its local listener because the requested port is in use. The
/// tunnel itself is healthy; only the local bind failed. We suggest
/// lport+1 with a saturating increment so the suggestion is always a valid
/// u16 (the helper is pure so the unit test below can pin the message shape
/// without touching the network).
fn port_in_use_msg(lport: u16, peer: &str, rport: u16) -> String {
    let suggested = lport.saturating_add(1);
    format!(
        "filament: local port {lport} is already in use, pick another (e.g. filament forward {suggested} {peer} {rport})"
    )
}

/// Bidirectionally copy an accepted local TCP connection and a warm-reuse unix
/// socket (the daemon bridges the unix socket to an L2 stream over its existing
/// link). One copy per direction; either side's EOF ends the pair. Unix-only.
#[cfg(unix)]
async fn bridge_streams(mut tcp: TcpStream, mut unix: tokio::net::UnixStream) -> std::io::Result<()> {
    tokio::io::copy_bidirectional(&mut tcp, &mut unix).await.map(|_| ())
}

/// `filament forward <lport> <peer> <rport>`: local TCP listener; every accepted
/// connection opens a fresh L2 stream to `peer:127.0.0.1:rport`.
///
/// WARM-LINK FAST PATH: when a local daemon already holds a link to `peer`, each
/// accepted connection rides it (no establishment) via the control socket. If the
/// daemon can't serve it (no daemon / no warm link / --relay), we fall back to
/// establishing ONE cold link lazily and multiplexing connections over it, the
/// original behavior. The warm path also sidesteps the single-link credit caveat:
/// each connection is an independent stream over the daemon's link.
/// Normalize a device name for self-comparison: lowercase, alphanumerics only, so
/// "pop-os", "popos", and "Pop_OS" all compare equal.
fn norm_device_name(s: &str) -> String {
    s.chars().filter(|c| c.is_ascii_alphanumeric()).map(|c| c.to_ascii_lowercase()).collect()
}

/// True when `peer` names THIS device (its configured name, that name's host part,
/// or the system hostname), so the forward would just loop back to this machine.
fn forward_target_is_self(peer: &str) -> bool {
    let p = norm_device_name(peer);
    if p.is_empty() {
        return false;
    }
    let dn = crate::display_name();
    let host_part = dn.rsplit('@').next().unwrap_or("").to_string();
    let hostname = std::fs::read_to_string("/etc/hostname").unwrap_or_default();
    [dn.as_str(), host_part.as_str(), hostname.trim()]
        .iter()
        .any(|c| !c.is_empty() && norm_device_name(c) == p)
}

/// Live per-connection accounting for `forward`, so the user can SEE it working
/// instead of staring at a static "ready" line. Increments on accept, decrements on
/// close (RAII), keeps one updating status line ("N active, M total"), and prints a
/// one-time confirmation on the very first forwarded connection.
struct ForwardActivity {
    active: std::sync::Arc<std::sync::atomic::AtomicU64>,
    total: std::sync::Arc<std::sync::atomic::AtomicU64>,
    first: std::sync::Arc<std::sync::atomic::AtomicBool>,
    peer: String,
    rport: u16,
}

impl ForwardActivity {
    fn new(peer: &str, rport: u16) -> Self {
        Self {
            active: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)),
            total: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)),
            first: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
            peer: peer.to_string(),
            rport,
        }
    }
    fn line(&self) {
        use std::sync::atomic::Ordering::Relaxed;
        crate::ui::status(&format!(
            "filament: forwarding to {}:{} - {} active, {} total",
            self.peer,
            self.rport,
            self.active.load(Relaxed),
            self.total.load(Relaxed)
        ));
    }
    /// Register a newly accepted connection; the returned guard decrements on drop.
    fn begin(&self) -> ConnGuard {
        use std::sync::atomic::Ordering::Relaxed;
        self.total.fetch_add(1, Relaxed);
        self.active.fetch_add(1, Relaxed);
        if !self.first.swap(true, Relaxed) {
            crate::ui::say(&format!(
                "filament: first connection forwarded to {}:{} - the link is live",
                self.peer, self.rport
            ));
        }
        self.line();
        ConnGuard {
            active: self.active.clone(),
            total: self.total.clone(),
            peer: self.peer.clone(),
            rport: self.rport,
        }
    }
}

struct ConnGuard {
    active: std::sync::Arc<std::sync::atomic::AtomicU64>,
    total: std::sync::Arc<std::sync::atomic::AtomicU64>,
    peer: String,
    rport: u16,
}

impl Drop for ConnGuard {
    fn drop(&mut self) {
        use std::sync::atomic::Ordering::Relaxed;
        self.active.fetch_sub(1, Relaxed);
        crate::ui::status(&format!(
            "filament: forwarding to {}:{} - {} active, {} total",
            self.peer,
            self.rport,
            self.active.load(Relaxed),
            self.total.load(Relaxed)
        ));
    }
}

/// `filament mount <peer> <remote>`: open a mesh-native mount stream to the
/// peer and serve the remote filesystem over the mount protocol. No sshd,
/// no sshfs — the server runs the mount handler on the peer's side of the
/// authenticated mesh stream, and the client drives it via `MountClient`.
///
/// Returns a `MountClient` ready for FUSE or direct operations.
pub async fn mount_cmd(
    server: &str,
    peer: &str,
    relay: bool,
    root: &str,
) -> Result<crate::mount_proto::MountClient> {
    let (t, rx, guard, _diag) = bring_up_to_known(server, peer, relay, "mount").await?;
    guard.forget();
    let mux = Mux::new(t.clone());
    let _pump = tokio::spawn(pump_initiator(rx, mux.clone()));
    let (sid, pipe_rx, caps) = open_mount_stream(&mux, root).await?;
    let client = crate::mount_proto::MountClient::from_mux_v2(t.clone(), sid, pipe_rx, caps);
    Ok(client)
}

pub async fn forward_cmd(server: &str, lport: u16, peer: &str, rport: u16, relay: bool) -> Result<()> {
    // Refuse a forward to THIS device before doing anything: it would just loop back,
    // and the generic "no known device" error hides what actually happened.
    if forward_target_is_self(peer) {
        bail!(
            "filament: '{peer}' is this device - a forward reaches a DIFFERENT machine. \
             Whatever runs on this host's :{rport} is already here as 127.0.0.1:{rport}; \
             point the forward at another peer (see `filament devices`)."
        );
    }
    // Resolve the peer against the paired devices UP FRONT, so an unknown/typo'd
    // target fails immediately with a clear message instead of after a premature
    // "ready" (the warm path used to announce success before ever reaching the peer).
    if !crate::devices_load().iter().any(|(n, _)| n.eq_ignore_ascii_case(peer)) {
        bail!(
            "filament: no known device named '{peer}'. Pair it first with `filament pair`, \
             then `filament devices` shows who you can reach."
        );
    }
    // Bind first so a port conflict fails fast, before any network work.
    let listener = match TcpListener::bind(("127.0.0.1", lport)).await {
        Ok(l) => l,
        Err(e) if e.kind() == std::io::ErrorKind::AddrInUse => {
            bail!("{}", port_in_use_msg(lport, peer, rport));
        }
        Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
            bail!(
                "filament: cannot bind 127.0.0.1:{lport}: permission denied. Local ports below \
                 1024 need root; pick a higher local port (e.g. `filament forward 8{lport:0>3} {peer} {rport}`) \
                 or run with sudo."
            );
        }
        Err(e) => {
            return Err(anyhow::Error::new(e).context(format!(
                "filament: failed to bind 127.0.0.1:{lport} for forward to {peer}:127.0.0.1:{rport}"
            )));
        }
    };
    crate::ui::say(&format!("filament: forwarding 127.0.0.1:{lport} -> {peer}:127.0.0.1:{rport}"));

    // Ride a local `up` daemon's warm link when one exists (unix control socket):
    // connections are then instant and open NO new presence on the peer (the
    // daemon is the one connected), and the daemon reports its own link state.
    // Probed once, up front.
    #[cfg(unix)]
    let via_daemon = !relay && crate::ctl::daemon_present().await;
    #[cfg(not(unix))]
    let via_daemon = false;
    let warm = via_daemon; // per-connection warm attempts (unix only)

    // Cold link (no daemon): managed by a background task that establishes it,
    // WATCHES its liveness, and reconnects on loss, reporting lost/recovered so a
    // network blip is never silent (the old code held one link and never noticed).
    // Published via a watch channel the accept loop reads. Not started on the warm
    // path (that would create the extra presence we are avoiding).
    let mut cold_rx = if via_daemon {
        // Report the ACTUAL peer link state, not a blanket "ready". The daemon may
        // hold a live warm link (then connections really are instant) or none yet
        // (then it opens on the first connection) - saying "ready, instant" in the
        // second case is what left the user unsure whether it was forwarding.
        match crate::ctl::try_ping(peer).await {
            Some(facts) => {
                let route = facts["route"].as_str().unwrap_or("link");
                crate::ui::say(&format!(
                    "filament: ready - 127.0.0.1:{lport} -> {peer}:{rport} over the daemon's live {route} link (no extra presence on {peer})"
                ));
            }
            None => {
                crate::ui::say(&format!(
                    "filament: listening on 127.0.0.1:{lport} -> {peer}:{rport} via the local daemon; no live link to {peer} yet - it opens on the first connection (check with `filament ping {peer}`)"
                ));
            }
        }
        None
    } else {
        crate::ui::status(&format!("filament: bringing up the link to {peer} ..."));
        let (tx, mut rx) = tokio::sync::watch::channel::<Option<Arc<Mux>>>(None);
        {
            let (server, peer_s) = (server.to_string(), peer.to_string());
            tokio::spawn(async move { manage_cold_link(server, peer_s, relay, tx).await });
        }
        // Wait for the first link so "ready" is honest.
        while rx.borrow().is_none() {
            if rx.changed().await.is_err() {
                bail!("filament: could not establish the link to {peer}; is it online? check with `filament ping {peer}` (or `filament devices`)");
            }
        }
        crate::ui::say(&format!(
            "filament: ready, listening on 127.0.0.1:{lport} -> {peer}:{rport} (connect to it to forward; run `filament up` here to avoid a separate presence on {peer})"
        ));
        Some(rx)
    };

    let activity = ForwardActivity::new(peer, rport);
    loop {
        // A transient accept error (e.g. EMFILE/ENFILE under fd pressure) must NOT
        // tear down the listener; back off briefly and keep serving.
        let sock = match listener.accept().await {
            Ok((s, _)) => s,
            Err(e) => {
                crate::ui::status(&format!("filament: accept paused ({e}), retrying..."));
                tokio::time::sleep(std::time::Duration::from_millis(200)).await;
                continue;
            }
        };
        let _ = sock.set_nodelay(true);
        // Warm path: bridge this connection straight to the daemon's link. Retried
        // per connection so it is used whenever the daemon holds a warm link.
        #[cfg(unix)]
        if warm {
            if let Some(usock) = crate::ctl::try_open(peer, rport).await {
                let guard = activity.begin();
                tokio::spawn(async move {
                    let _guard = guard; // decrements + refreshes the activity line on close
                    let _ = bridge_streams(sock, usock).await;
                });
                continue;
            }
            // Warm miss (the daemon has no live link to the peer right now): fall
            // through to a cold link instead of dropping the connection. The cold
            // manager is started once, lazily, and self-heals from there.
        }
        // Cold path (also the warm-miss fallback): ensure the managed cold link
        // exists, then serve over the current live link.
        if cold_rx.is_none() {
            crate::ui::debug(&format!(
                "filament: no warm link to {peer}, using a direct link for forwarding"
            ));
            let (tx, rx) = tokio::sync::watch::channel::<Option<Arc<Mux>>>(None);
            let (server, peer_s) = (server.to_string(), peer.to_string());
            tokio::spawn(async move { manage_cold_link(server, peer_s, relay, tx).await });
            cold_rx = Some(rx);
        }
        let rx = cold_rx.clone().unwrap();
        let guard = activity.begin();
        let peer_c = peer.to_string();
        // Serve this connection, retrying across a reconnect: a link that died in
        // the poll window is skipped (is_alive) and open_stream failures re-wait
        // for the manager's fresh link. On give-up the socket is dropped (closed),
        // but the ACCEPT LOOP ALWAYS SURVIVES -- one connection is never allowed to
        // kill the whole forward (the beta.28/29 regression class).
        tokio::spawn(async move {
            let _guard = guard; // decrements + refreshes the activity line on close
            serve_cold_connection(rx, sock, rport, peer_c).await;
        });
    }
}

/// `filament proxy`: a local SOCKS5 proxy that reaches mesh peers by name with NO
/// TUN and NO privilege (Tailscale's userspace-networking model). A SOCKS5 CONNECT
/// to `<peer>.mesh:<port>` opens an L2 stream to that peer's `localhost:<port>` over
/// filament (warm via a local daemon, else a self-healing cold link); any other
/// host is dialed directly, so the proxy is a drop-in that only diverts `.mesh`.
/// Pure userspace: no CAP_NET_ADMIN, no sudo, works in containers.
///
/// When `--http-port` is set, also runs an HTTP CONNECT proxy + PAC file endpoint
/// on that port for browser/OS proxy config (Tailscale parity).
pub async fn proxy_cmd(server: &str, bind: &str, port: u16, http_port: u16, relay: bool) -> Result<()> {
    let listener = match TcpListener::bind((bind, port)).await {
        Ok(l) => l,
        Err(e) if e.kind() == std::io::ErrorKind::AddrInUse => {
            bail!("filament: {bind}:{port} is already in use; pick another with --port");
        }
        Err(e) => {
            return Err(anyhow::Error::new(e).context(format!("filament: failed to bind {bind}:{port}")));
        }
    };
    crate::ui::say(&format!("filament: SOCKS5 proxy on {bind}:{port} (no TUN, no sudo)"));
    crate::ui::say(&format!(
        "  point apps here; {}.mesh rides the mesh, everything else connects directly",
        "<peer>"
    ));
    crate::ui::say(&format!("  e.g.  curl --socks5-hostname {bind}:{port} http://<peer>.mesh:8080/"));
    #[cfg(unix)]
    if !crate::ctl::daemon_present().await {
        crate::ui::say(&crate::ui::paint(
            crate::ui::Tone::Dim,
            "  note: no local daemon; each .mesh connection brings up its own link. `filament up` makes them instant.",
        ));
    }
    // Per-peer self-healing cold links, started lazily on first use of a peer (only
    // when the warm daemon path misses), mirroring `forward`'s cold manager.
    let cold: Arc<Mutex<HashMap<String, tokio::sync::watch::Receiver<Option<Arc<Mux>>>>>> =
        Arc::new(Mutex::new(HashMap::new()));
    // HTTP CONNECT proxy + PAC file endpoint (optional).
    if http_port > 0 {
        let http_listener = match TcpListener::bind((bind, http_port)).await {
            Ok(l) => l,
            Err(e) if e.kind() == std::io::ErrorKind::AddrInUse => {
                bail!("filament: {bind}:{http_port} is already in use; pick another with --http-port");
            }
            Err(e) => {
                return Err(anyhow::Error::new(e).context(format!("filament: failed to bind {bind}:{http_port}")));
            }
        };
        crate::ui::say(&format!("filament: HTTP CONNECT proxy on {bind}:{http_port}"));
        crate::ui::say(&format!(
            "  PAC file: http://127.0.0.1:{http_port}/proxy.pac"
        ));
        crate::ui::say(&format!(
            "  e.g.  curl -x http://127.0.0.1:{http_port} https://<peer>.mesh"
        ));
        let cold_http = cold.clone();
        let server_http = server.to_string();
        tokio::spawn(async move {
            loop {
                let sock = match http_listener.accept().await {
                    Ok((s, _)) => s,
                    Err(e) => {
                        crate::ui::status(&format!("filament: HTTP accept paused ({e}), retrying..."));
                        tokio::time::sleep(std::time::Duration::from_millis(200)).await;
                        continue;
                    }
                };
                let _ = sock.set_nodelay(true);
                let (server, cold) = (server_http.clone(), cold_http.clone());
                tokio::spawn(async move {
                    if let Err(e) = handle_http(sock, &server, port, relay, cold).await {
                        crate::ui::debug(&format!("filament: HTTP proxy connection ended: {e}"));
                    }
                });
            }
        });
    }
    loop {
        let sock = match listener.accept().await {
            Ok((s, _)) => s,
            Err(e) => {
                crate::ui::status(&format!("filament: accept paused ({e}), retrying..."));
                tokio::time::sleep(std::time::Duration::from_millis(200)).await;
                continue;
            }
        };
        let _ = sock.set_nodelay(true);
        let (server, cold) = (server.to_string(), cold.clone());
        tokio::spawn(async move {
            if let Err(e) = handle_socks(sock, &server, relay, cold).await {
                crate::ui::debug(&format!("filament: proxy connection ended: {e}"));
            }
        });
    }
}

/// Write a minimal SOCKS5 reply (`code` 0x00 = success) with a zero BND.ADDR/PORT.
async fn socks_reply(sock: &mut TcpStream, code: u8) -> std::io::Result<()> {
    sock.write_all(&[0x05, code, 0x00, 0x01, 0, 0, 0, 0, 0, 0]).await
}

/// Handle one SOCKS5 client: no-auth handshake, parse the CONNECT target, then
/// route `<peer>.mesh:<port>` over filament (warm-first, cold fallback) or dial any
/// other host directly. Errors here only affect this one connection.
async fn handle_socks(
    mut sock: TcpStream,
    server: &str,
    relay: bool,
    cold: Arc<Mutex<HashMap<String, tokio::sync::watch::Receiver<Option<Arc<Mux>>>>>>,
) -> Result<()> {
    // Greeting: VER, NMETHODS, METHODS...; we only offer no-auth (0x00).
    let mut greet = [0u8; 2];
    sock.read_exact(&mut greet).await?;
    if greet[0] != 0x05 {
        bail!("not a SOCKS5 client");
    }
    let mut methods = vec![0u8; greet[1] as usize];
    sock.read_exact(&mut methods).await?;
    sock.write_all(&[0x05, 0x00]).await?;

    // Request: VER, CMD, RSV, ATYP, ADDR, PORT.
    let mut req = [0u8; 4];
    sock.read_exact(&mut req).await?;
    if req[0] != 0x05 {
        bail!("bad SOCKS5 request");
    }
    let host = match req[3] {
        0x01 => {
            let mut a = [0u8; 4];
            sock.read_exact(&mut a).await?;
            std::net::Ipv4Addr::from(a).to_string()
        }
        0x04 => {
            let mut a = [0u8; 16];
            sock.read_exact(&mut a).await?;
            std::net::Ipv6Addr::from(a).to_string()
        }
        0x03 => {
            let mut len = [0u8; 1];
            sock.read_exact(&mut len).await?;
            let mut d = vec![0u8; len[0] as usize];
            sock.read_exact(&mut d).await?;
            String::from_utf8_lossy(&d).into_owned()
        }
        _ => {
            socks_reply(&mut sock, 0x08).await?; // address type not supported
            return Ok(());
        }
    };
    let mut pb = [0u8; 2];
    sock.read_exact(&mut pb).await?;
    let dport = u16::from_be_bytes(pb);
    if req[1] != 0x01 {
        socks_reply(&mut sock, 0x07).await?; // only CONNECT
        return Ok(());
    }

    match host.strip_suffix(".mesh") {
        Some(peer) => {
            let peer = peer.to_string();
            // Warm path: ride the local daemon's live mesh link (instant, no extra
            // presence on the peer).
            #[cfg(unix)]
            if crate::ctl::daemon_present().await {
                // PRIMARY: the L2 loopback open reaches the peer's 127.0.0.1:dport
                // over its opt-in acceptor (unchanged semantics).
                if let Some(usock) = crate::ctl::try_open(&peer, dport).await {
                    socks_reply(&mut sock, 0x00).await?;
                    return bridge_streams(sock, usock).await.map_err(Into::into);
                }
                // FALLBACK: reach a service the peer EXPOSED on its OVERLAY address
                // (which the loopback open can't), and the only path on a userspace
                // node. Tried only after the L2 open misses, so nothing that worked
                // before changes; this only adds reachability to expose'd ports.
                if let Some(usock) = crate::ctl::try_dial(&peer, dport).await {
                    socks_reply(&mut sock, 0x00).await?;
                    return bridge_streams(sock, usock).await.map_err(Into::into);
                }
            }
            // Cold fallback (no daemon, or a warm miss): a per-peer self-healing
            // link, reused across connections.
            let rx = {
                let mut map = cold.lock().await;
                if let Some(rx) = map.get(&peer) {
                    rx.clone()
                } else {
                    let (tx, rx) = tokio::sync::watch::channel::<Option<Arc<Mux>>>(None);
                    let (s, pr) = (server.to_string(), peer.clone());
                    tokio::spawn(async move { manage_cold_link(s, pr, relay, tx).await });
                    map.insert(peer.clone(), rx.clone());
                    rx
                }
            };
            socks_reply(&mut sock, 0x00).await?;
            serve_cold_connection(rx, sock, dport, peer).await;
            Ok(())
        }
        None => {
            // Not a mesh name: behave like a plain SOCKS5 proxy (dial directly), so
            // the user can set filament as their one proxy and only .mesh is diverted.
            match TcpStream::connect((host.as_str(), dport)).await {
                Ok(mut up) => {
                    let _ = up.set_nodelay(true);
                    socks_reply(&mut sock, 0x00).await?;
                    let _ = tokio::io::copy_bidirectional(&mut sock, &mut up).await;
                    Ok(())
                }
                Err(_) => {
                    socks_reply(&mut sock, 0x05).await?; // connection refused
                    Ok(())
                }
            }
        }
    }
}

/// Handle one HTTP CONNECT client or PAC file request. Reads the HTTP request,
/// routes CONNECT through the mesh, or serves the PAC file for browser config.
async fn handle_http(
    mut sock: TcpStream,
    server: &str,
    socks_port: u16,
    relay: bool,
    cold: Arc<Mutex<HashMap<String, tokio::sync::watch::Receiver<Option<Arc<Mux>>>>>>,
) -> Result<()> {
    // Read the HTTP request line + headers until empty line.
    let mut buf = Vec::new();
    let mut tmp = [0u8; 1];
    loop {
        sock.read_exact(&mut tmp).await?;
        buf.push(tmp[0]);
        // Check for \r\n\r\n (end of headers).
        if buf.len() >= 4 && &buf[buf.len()-4..] == b"\r\n\r\n" {
            break;
        }
        if buf.len() > 8192 {
            bail!("HTTP request too large");
        }
    }
    let request = String::from_utf8_lossy(&buf);
    let first_line = request.lines().next().unwrap_or("");

    // Parse: METHOD PATH HTTP/1.x
    let mut parts = first_line.split_whitespace();
    let method = parts.next().unwrap_or("");
    let path = parts.next().unwrap_or("");

    if method.eq_ignore_ascii_case("CONNECT") {
        // HTTP CONNECT proxy: CONNECT host:port HTTP/1.1
        let host_port = path;
        let (host, dport) = if let Some(colon) = host_port.rfind(':') {
            let h = &host_port[..colon];
            let p: u16 = host_port[colon+1..].parse().unwrap_or(0);
            (h.to_string(), p)
        } else {
            (host_port.to_string(), 80)
        };

        match host.strip_suffix(".mesh") {
            Some(peer) => {
                let peer = peer.to_string();
                // Warm path: ride the local daemon's live mesh link.
                #[cfg(unix)]
                if crate::ctl::daemon_present().await {
                    if let Some(usock) = crate::ctl::try_open(&peer, dport).await {
                        let _ = sock.write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n").await;
                        return bridge_streams(sock, usock).await.map_err(Into::into);
                    }
                    if let Some(usock) = crate::ctl::try_dial(&peer, dport).await {
                        let _ = sock.write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n").await;
                        return bridge_streams(sock, usock).await.map_err(Into::into);
                    }
                }
                // Cold fallback.
                let rx = {
                    let mut map = cold.lock().await;
                    if let Some(rx) = map.get(&peer) {
                        rx.clone()
                    } else {
                        let (tx, rx) = tokio::sync::watch::channel::<Option<Arc<Mux>>>(None);
                        let (s, pr) = (server.to_string(), peer.clone());
                        tokio::spawn(async move { manage_cold_link(s, pr, relay, tx).await });
                        map.insert(peer.clone(), rx.clone());
                        rx
                    }
                };
                let _ = sock.write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n").await;
                serve_cold_connection(rx, sock, dport, peer).await;
                Ok(())
            }
            None => {
                // Not a mesh name: dial directly.
                match TcpStream::connect((host.as_str(), dport)).await {
                    Ok(mut up) => {
                        let _ = up.set_nodelay(true);
                        let _ = sock.write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n").await;
                        let _ = tokio::io::copy_bidirectional(&mut sock, &mut up).await;
                        Ok(())
                    }
                    Err(_) => {
                        let _ = sock.write_all(b"HTTP/1.1 502 Bad Gateway\r\n\r\n").await;
                        Ok(())
                    }
                }
            }
        }
    } else if path == "/proxy.pac" || path == "/wpad.dat" {
        // Serve PAC file for browser/OS proxy config.
        let pac = format!(
            r#"function FindProxyForURL(url, host) {{
    if (dnsDomainIs(host, ".mesh") || shExpMatch(host, "*.mesh")) {{
        return "SOCKS5 127.0.0.1:{socks_port}; DIRECT";
    }}
    return "DIRECT";
}}
"#
        );
        let response = format!(
            "HTTP/1.1 200 OK\r\n\
             Content-Type: application/x-ns-proxy-autoconfig\r\n\
             Content-Length: {}\r\n\
             Connection: close\r\n\
             \r\n\
             {}",
            pac.len(),
            pac
        );
        let _ = sock.write_all(response.as_bytes()).await;
        Ok(())
    } else {
        // Unknown HTTP request: return 404.
        let response = "HTTP/1.1 404 Not Found\r\n\
                         Content-Length: 0\r\n\
                         Connection: close\r\n\
                         \r\n";
        let _ = sock.write_all(response.as_bytes()).await;
        Ok(())
    }
}

/// Serve one accepted forward connection over the managed cold link, tolerant of
/// a link blip: wait for a LIVE mux (skipping a stale dead one still parked in the
/// channel), open a stream, and on a transient open failure re-wait for the
/// manager's reconnected link (bounded). Never propagates errors to the accept
/// loop; on give-up it just drops `sock`.
async fn serve_cold_connection(
    mut rx: tokio::sync::watch::Receiver<Option<Arc<Mux>>>,
    sock: TcpStream,
    rport: u16,
    peer: String,
) {
    let mut tries = 0u32;
    loop {
        // Wait for a live link (a dead mux may still be parked until the manager's
        // ~1s poll republishes; is_alive() skips it so we never open on a corpse).
        let mux = loop {
            let cur = rx.borrow_and_update().clone();
            match cur {
                Some(m) if m.transport().is_alive() => break m,
                _ => {
                    if rx.changed().await.is_err() {
                        return; // manager gone; drop this socket (listener lives on)
                    }
                }
            }
        };
        match open_stream(&mux, rport).await {
            Ok((sid, rx_pipe)) => {
                serve_stream(mux, sid, sock, rx_pipe, true, None).await;
                return;
            }
            Err(_) => {
                tries += 1;
                if tries >= 3 {
                    crate::ui::debug(&format!(
                        "filament: dropping a connection to {peer} (link recovering); the forward stays up"
                    ));
                    return; // drop sock; accept loop keeps running
                }
                // The link died between the liveness check and open_stream; loop
                // back to wait for the manager to publish a fresh one.
            }
        }
    }
}

/// Own the cold forward link end to end: establish it, publish it to the accept
/// loop, watch its liveness, and reconnect on loss, narrating each transition so
/// a network blip is visible (mirrors the `up` daemon's lost/recovered UX). Never
/// returns while the watch receiver is live; a send error means the forward
/// command exited, so the manager stops.
async fn manage_cold_link(
    server: String,
    peer: String,
    relay: bool,
    tx: tokio::sync::watch::Sender<Option<Arc<Mux>>>,
) {
    let mut backoff_ms = 500u64;
    let mut had_link = false; // distinguishes first bring-up from a recovery
    loop {
        // (Re)establish. Transient states (retrying / reconnecting) update ONE
        // status line in place via ui::status; only real transitions (recovered)
        // print a permanent line via ui::say, which clears the live status line.
        let mux = match bring_up_to_known(&server, &peer, relay, "init").await {
            Ok((t, rx, guard, mut diag)) => {
                guard.forget();
                diag.up("tunnel", "datachannel-or-direct");
                let m = Mux::new(t);
                tokio::spawn(pump_initiator(rx, m.clone()));
                m
            }
            Err(e) => {
                crate::ui::status(&format!("filament: reaching {peer} failed ({e}), retrying..."));
                tokio::time::sleep(std::time::Duration::from_millis(backoff_ms)).await;
                backoff_ms = (backoff_ms * 2).min(8000);
                continue;
            }
        };
        backoff_ms = 500;
        if had_link {
            crate::ui::say(&format!("filament: link to {peer} recovered"));
        }
        had_link = true;
        if tx.send(Some(mux.clone())).is_err() {
            return; // forward command gone
        }
        // Watch liveness; a dead transport means the link dropped under us.
        loop {
            tokio::time::sleep(std::time::Duration::from_secs(1)).await;
            if tx.is_closed() {
                return;
            }
            if !mux.transport().is_alive() {
                crate::ui::status(&format!("filament: link to {peer} lost, reconnecting..."));
                let _ = tx.send(None);
                break;
            }
        }
    }
}

/// Seamless-shell bootstrap (initiator): over the already-authenticated filament
/// channel, hand the acceptor our managed pubkey and fetch its host keys, so a
/// user with ZERO ssh setup gets a no-prompt shell. The exchange is pure control
/// JSON over the transport `bring_up_to_known` returns (no mux needed).
///
/// Returns `Ok(hostkeys)` on grant (the acceptor installed our key); the caller
/// pins the host keys and spawns ssh. Returns `Err` if the acceptor DENIES (the
/// device lacks the `shell` cap) or times out, in which case the caller MUST NOT
/// fall through to a key-less ssh attempt (that would be a muddy auth failure
/// instead of a clear "zero shell" denial).
/// Result of installing our managed key on a peer (warm or cold path). `sshd` is
/// the peer's report of whether an sshd is listening on the port `filament ssh`
/// will dial: `Some(true)` reachable, `Some(false)` nothing there (so ssh would
/// fail blindly - caller bails with a clear message), `None` when the peer is an
/// older build that didn't report it (caller proceeds, status unknown).
struct BootstrapInfo {
    hostkeys: Vec<String>,
    user: Option<String>,
    sshd: Option<bool>,
}

async fn shell_bootstrap(server: &str, peer: &str, relay: bool, ssh_port: u16) -> Result<BootstrapInfo> {
    // Managed keypair lives under the filament config dir, NEVER ~/.ssh.
    let pubkey = crate::sshkeys::ensure_managed_key()?;

    // Bound the connect so an unreachable peer fails with a clear, actionable
    // message instead of looping forever (the heartbeat inside reports progress
    // meanwhile). Override with FILAMENT_SSH_CONNECT_SECS.
    let connect_secs: u64 = std::env::var("FILAMENT_SSH_CONNECT_SECS")
        .ok()
        .and_then(|s| s.parse().ok())
        .filter(|n| *n > 0)
        .unwrap_or(45);
    let (t, mut rx, guard, mut diag) = match tokio::time::timeout(
        std::time::Duration::from_secs(connect_secs),
        bring_up_to_known(server, peer, relay, "bootstrap"),
    )
    .await
    {
        Ok(inner) => inner?,
        Err(_) => {
            crate::ui::problem(
                &format!("filament ssh: can't reach '{peer}'"),
                &format!(
                    "couldn't establish a link to '{peer}' in {connect_secs}s - it may be offline or unreachable from here."
                ),
                &[
                    format!("check it's reachable: {}", crate::ui::paint(crate::ui::Tone::Brand, &format!("filament ping {peer}"))),
                    format!("diagnose the connect: {}", crate::ui::paint(crate::ui::Tone::Brand, &format!("filament doctor {peer}"))),
                ],
            );
            std::process::exit(1);
        }
    };
    // The bootstrap rides the bring-up transport directly (pure control JSON, no
    // mux), so the link being usable IS the end of this span. Record `up`; the
    // ssh data link is a SEPARATE netcat span instrumented in its own right.
    diag.up("tunnel", "datachannel-or-direct");
    t.send_control(&json!({ "type": "shell-bootstrap", "v": 1, "pubkey": pubkey, "ssh_port": ssh_port })).await?;

    // Await the verdict (bounded, a daemon without FILAMENT_L2 / without the cap
    // must not hang us forever). Capture it, then ALWAYS tear this link down
    // BEFORE returning, so the ssh data link (netcat ProxyCommand) is the only
    // boxA peer the acceptor sees, no concurrent same-device supersede churn.
    let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(20);
    let verdict: Result<BootstrapInfo> = loop {
        let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
        if remaining.is_zero() {
            break Err(anyhow!(
                "shell bootstrap timed out, is '{peer}' running `filament up` with shell access granted?"
            ));
        }
        match tokio::time::timeout(remaining, rx.recv()).await {
            Ok(Some(Ev::Control(_pid, v))) => match v["type"].as_str() {
                Some("shell-bootstrap-ack") => {
                    let hostkeys: Vec<String> = v["hostkeys"]
                        .as_array()
                        .map(|a| a.iter().filter_map(|k| k.as_str().map(String::from)).collect())
                        .unwrap_or_default();
                    // The acceptor reports the account it installed our key into,
                    // authoritative for the ssh login (see ssh_cmd).
                    let user = v["user"].as_str().map(String::from);
                    // Older acceptors omit `sshd` -> None (unknown, proceed).
                    let sshd = v["sshd"].as_bool();
                    break Ok(BootstrapInfo { hostkeys, user, sshd });
                }
                Some("shell-bootstrap-deny") => {
                    let why = v["reason"].as_str().unwrap_or("shell capability not granted");
                    break Err(anyhow!(
                        "shell refused by '{peer}': {why}. Run `filament grant <this-device> shell` on '{peer}'."
                    ));
                }
                _ => continue,
            },
            Ok(Some(_)) => continue, // other events on this link, ignore
            Ok(None) => break Err(anyhow!("channel closed before shell bootstrap completed")),
            Err(_) => continue, // timeout sliver, loop re-checks the deadline
        }
    };

    // Tear down the bootstrap link before the caller opens the ssh data link.
    drop(t);
    guard.close().await;
    verdict
}

/// Install our managed key on `peer`, WARM-first: ask the local `up` daemon to
/// run the `shell-bootstrap` over its already-established link (instant, no cold
/// establish), and fall back to a fresh `shell_bootstrap` on a miss/deny/timeout,
/// under `--relay`, or off-unix. This is what closes the last gap that left
/// `filament ssh` slow while `pty` was already warm: the bootstrap was the only
/// remaining cold establish in the ssh path.
async fn bootstrap_key(server: &str, peer: &str, relay: bool, ssh_port: u16) -> Result<BootstrapInfo> {
    #[cfg(unix)]
    if !relay {
        let pubkey = crate::sshkeys::ensure_managed_key()?;
        if let Some(v) = crate::ctl::try_bootstrap(peer, &pubkey, ssh_port).await {
            let hostkeys: Vec<String> = v["hostkeys"]
                .as_array()
                .map(|a| a.iter().filter_map(|k| k.as_str().map(String::from)).collect())
                .unwrap_or_default();
            if !hostkeys.is_empty() {
                crate::ui::trace(&format!(
                    "filament: reusing warm link to '{peer}' for ssh bootstrap (no establish)"
                ));
                return Ok(BootstrapInfo {
                    hostkeys,
                    user: v["user"].as_str().map(String::from),
                    sshd: v["sshd"].as_bool(),
                });
            }
        }
    }
    shell_bootstrap(server, peer, relay, ssh_port).await
}

/// The login account for the ssh destination: FILAMENT_SSH_USER wins, else the
/// account the ACCEPTOR installed our key into (from the bootstrap-ack, or the
/// cache), else local $USER, else root. The acceptor's report is authoritative
/// over a local $USER guess, which is usually wrong cross-machine (agboola@laptop
/// vs root@server, the "Permission denied (publickey)" mismatch).
fn resolve_login(remote_user: Option<String>) -> String {
    std::env::var("FILAMENT_SSH_USER")
        .ok()
        .or(remote_user)
        .or_else(|| std::env::var("USER").ok())
        .unwrap_or_else(|| "root".into())
}

/// Spawn the real `ssh`, pointed EXCLUSIVELY at filament-managed key material +
/// known_hosts, with a `filament netcat` ProxyCommand. Returns ssh's exit code
/// (so a cached fast-path can detect a 255 connect/auth failure and retry after a
/// fresh bootstrap). The destination is always `<login>@filament-<peer>`.
/// Run the ssh session, preferring the resilient L3 overlay. The bootstrap has
/// already installed our managed key on the peer and pinned host keys, so both
/// paths use the SAME managed identity; L3 just connects to the stable overlay
/// address directly (no ProxyCommand), so the session survives a link repair.
/// Falls back to the L2 tunnel when L3 isn't viable or its connect fails (255).
async fn run_ssh(
    server: &str,
    peer: &str,
    relay: bool,
    host: &str,
    login: &str,
    rport: u16,
    extra: &[String],
    revive: bool,
) -> Result<i32> {
    #[cfg(not(target_os = "linux"))]
    let _ = revive;
    #[cfg(target_os = "linux")]
    if std::env::var("FILAMENT_NO_L3_SSH").as_deref() != Ok("1") {
        if let Some((mesh_host, addr)) = l3_mesh_addr(peer, rport) {
            // The peer IS on the overlay. PREFER L3 (survives link repairs); only
            // fall to L2 when the overlay genuinely can't carry ssh.
            if probe_sshd(addr, std::time::Duration::from_millis(600)) {
                crate::ui::debug(&format!(
                    "ssh over the L3 overlay ({mesh_host}) - survives link repairs"
                ));
                let code = spawn_ssh_direct(login, &mesh_host, extra)?;
                if code != 255 {
                    return Ok(code);
                }
                crate::ui::say("filament: L3 ssh failed, falling back to the tunnel");
            } else if revive {
                // The route exists but the overlay path looks dead (a lapsed/zombie
                // transport). Kick the revive nudge in the BACKGROUND and fall back to
                // L2 immediately. The user must never wait the revive ceiling for an
                // interactive ssh; the next ssh will find L3 up if the revive worked.
                crate::ui::say(&format!(
                    "filament: L3 overlay to '{peer}' down, falling back to the tunnel; reviving in background"
                ));
                let peer = peer.to_string();
                tokio::spawn(async move {
                    revive_l3(&peer, rport).await;
                });
            }
            // else (revive=false, e.g. the post-255 re-bootstrap retry): don't pay the
            // revive wait twice - go straight to the L2 tunnel below.
        }
    }
    spawn_ssh(server, peer, relay, host, login, rport, extra)
}

/// ssh directly to a stable overlay host (no ProxyCommand), reusing the managed
/// key + known_hosts the L2 path uses. The overlay address is cryptographically
/// bound to the peer, so accept-new pins the host key on first use.
#[cfg(target_os = "linux")]
fn spawn_ssh_direct(login: &str, mesh_host: &str, extra: &[String]) -> Result<i32> {
    let key = crate::sshkeys::managed_key_path();
    let kh = crate::sshkeys::known_hosts_path();
    let dest_token = format!("{login}@{mesh_host}");
    let mut cmd = std::process::Command::new("ssh");
    cmd.arg("-o").arg(format!("IdentityFile={}", key.display()))
        .arg("-o").arg("IdentitiesOnly=yes")
        .arg("-o").arg(format!("UserKnownHostsFile={}", kh.display()))
        .arg("-o").arg("GlobalKnownHostsFile=/dev/null")
        .arg("-o").arg("StrictHostKeyChecking=accept-new")
        .arg("-o").arg("ConnectTimeout=10")
        .arg("-o").arg("ServerAliveInterval=15")
        .arg("-o").arg("ServerAliveCountMax=4");
    let mut split = extra.len();
    for (i, a) in extra.iter().enumerate() {
        if !a.starts_with('-') {
            split = i;
            break;
        }
    }
    for a in &extra[..split] {
        cmd.arg(a);
    }
    cmd.arg(&dest_token);
    for a in &extra[split..] {
        cmd.arg(a);
    }
    Ok(cmd.status()?.code().unwrap_or(1))
}

fn spawn_ssh(
    server: &str,
    peer: &str,
    relay: bool,
    host: &str,
    login: &str,
    rport: u16,
    extra: &[String],
) -> Result<i32> {
    let exe = std::env::current_exe()?;
    let exe = exe.to_string_lossy();
    let mut proxy = format!("{exe} --server {server}");
    if relay {
        proxy.push_str(" --relay");
    }
    proxy.push_str(&format!(" netcat {peer} {rport}"));

    let key = crate::sshkeys::managed_key_path();
    let kh = crate::sshkeys::known_hosts_path();
    let dest_token = format!("{login}@{host}");
    let mut cmd = std::process::Command::new("ssh");
    cmd.arg("-o").arg(format!("ProxyCommand={proxy}"))
        .arg("-o").arg(format!("IdentityFile={}", key.display()))
        .arg("-o").arg("IdentitiesOnly=yes")
        .arg("-o").arg(format!("UserKnownHostsFile={}", kh.display()))
        .arg("-o").arg("GlobalKnownHostsFile=/dev/null")
        .arg("-o").arg("StrictHostKeyChecking=accept-new")
        // Bound the ssh-side connect and detect a dead session, so the data link
        // (the filament netcat ProxyCommand) can't hang ssh indefinitely either.
        .arg("-o").arg("ConnectTimeout=25")
        .arg("-o").arg("ServerAliveInterval=15")
        .arg("-o").arg("ServerAliveCountMax=3");
    // Split passthrough args into ssh OPTIONS (leading flags) and the remote
    // COMMAND (from the first non-flag token on). The destination is ALWAYS our
    // managed token, inserted BETWEEN options and command, or ssh would mistake
    // the command (e.g. `hostname`) for the host.
    let mut split = extra.len();
    for (i, a) in extra.iter().enumerate() {
        if !a.starts_with('-') {
            split = i;
            break;
        }
    }
    for a in &extra[..split] {
        cmd.arg(a);
    }
    cmd.arg(&dest_token);
    for a in &extra[split..] {
        cmd.arg(a);
    }
    Ok(cmd.status()?.code().unwrap_or(1))
}

/// `filament ssh <peer> [args...]`: seamless shell over the trusted channel.
///
/// With zero pre-existing ssh setup: bootstrap our managed key + the peer's host
/// key over the authenticated filament channel, pin them, then run ssh pointed
/// EXCLUSIVELY at filament-managed material (-o IdentityFile / IdentitiesOnly /
/// UserKnownHostsFile) with a `filament netcat` ProxyCommand. No prompts, no
/// ~/.ssh, no key copying. The bootstrap is the deny-by-default gate: if the
/// peer lacks the `shell` cap we abort HERE, before invoking ssh.
/// Resolve `<peer>.mesh` (the MagicDNS /etc/hosts entry) to its overlay socket
/// address. `Some` iff the peer is on the overlay (has a route); the address is the
/// crypto-derived, STABLE overlay IP (only the transport swaps under it on a
/// repair), so it's a valid target to probe/connect across repairs. `None` means
/// the peer isn't on the mesh at all -> the caller goes straight to the L2 tunnel.
/// (Note: unlike the old `l3_ssh_target`, this does NOT probe here - the caller
/// probes and, if the route is present but dead, REVIVES rather than dumping to L2.)
#[cfg(target_os = "linux")]
fn l3_mesh_addr(peer: &str, port: u16) -> Option<(String, std::net::SocketAddr)> {
    use std::net::ToSocketAddrs;
    let name = format!("{}.mesh", crate::l3::sanitize_host(peer));
    let addr = (name.as_str(), port).to_socket_addrs().ok()?.next()?;
    Some((name, addr))
}

/// Quick reachability probe of an sshd over the overlay: a bounded TCP connect.
#[cfg(target_os = "linux")]
fn probe_sshd(addr: std::net::SocketAddr, to: std::time::Duration) -> bool {
    std::net::TcpStream::connect_timeout(&addr, to).is_ok()
}

/// Nudge the daemon to revive the overlay link to `peer`: a warm-open over the
/// control socket triggers the daemon's verify-before-accept, which drops a zombie
/// link so its re-dial / 8s self-heal rebuilds it (add_peer re-installs the SAME
/// stable overlay IP). The opened stream is discarded - the open itself is the
/// nudge. Bounded (ctl's open has no internal timeout).
#[cfg(target_os = "linux")]
async fn revive_l3(peer: &str, rport: u16) {
    let _ = tokio::time::timeout(std::time::Duration::from_secs(3), crate::ctl::try_open(peer, rport)).await;
}

/// How long to wait for the overlay to come back after a revive nudge (default 15s;
/// override with FILAMENT_L3_REVIVE_MS). This is a CEILING, not a fixed wait:
/// Info needed to connect to a peer over SSH (or sshfs/rsync). Returned by
/// `ensure_peer_bootstrap` after key installation + host key pinning.
pub(crate) struct PeerSshInfo {
    pub login: String,
    pub host: String,
    pub rport: u16,
    pub key_path: std::path::PathBuf,
    pub known_hosts_path: std::path::PathBuf,
    pub took_fast_path: bool,
}

/// Ensure our managed key is installed on the peer and host keys are pinned.
/// Returns `PeerSshInfo` with everything needed to spawn sshfs/rsync/ssh.
pub(crate) async fn ensure_peer_bootstrap(server: &str, peer: &str, relay: bool) -> Result<PeerSshInfo> {
    let peer = peer.strip_suffix(".mesh").unwrap_or(peer);
    let _host = format!("filament-{peer}");
    let rport: u16 =
        std::env::var("FILAMENT_SSH_PORT").ok().and_then(|s| s.parse().ok()).unwrap_or(22);

    ensure_peer_bootstrap_port(server, peer, relay, rport).await
}

/// Ensure our managed key is installed on the peer with a specific port.
pub(crate) async fn ensure_peer_bootstrap_port(server: &str, peer: &str, relay: bool, rport: u16) -> Result<PeerSshInfo> {
    let peer = peer.strip_suffix(".mesh").unwrap_or(peer);
    let host = format!("filament-{peer}");

    let cached = if crate::sshkeys::host_pinned(&host) {
        crate::sshkeys::bootstrap_cache_get(peer)
    } else {
        None
    };

    let (login, took_fast_path) = match cached {
        Some(cached_user) => (resolve_login(cached_user), true),
        None => {
            let info = bootstrap_key(server, peer, relay, rport).await?;
            ensure_sshd(peer, rport, info.sshd).await;
            crate::sshkeys::pin_host_keys(&host, &info.hostkeys)?;
            crate::sshkeys::bootstrap_cache_put(peer, info.user.as_deref());
            (resolve_login(info.user), false)
        }
    };

    Ok(PeerSshInfo {
        login,
        host,
        rport,
        key_path: crate::sshkeys::managed_key_path(),
        known_hosts_path: crate::sshkeys::known_hosts_path(),
        took_fast_path,
    })
}

/// Invalidate bootstrap cache and re-bootstrap a peer (for retry after exit 255).
pub(crate) async fn rebootstrap_peer(server: &str, peer: &str, relay: bool) -> Result<PeerSshInfo> {
    let peer = peer.strip_suffix(".mesh").unwrap_or(peer);
    let host = format!("filament-{peer}");
    let rport: u16 =
        std::env::var("FILAMENT_SSH_PORT").ok().and_then(|s| s.parse().ok()).unwrap_or(22);

    crate::sshkeys::bootstrap_cache_clear(peer);
    let info = shell_bootstrap(server, peer, relay, rport).await?;
    ensure_sshd(peer, rport, info.sshd).await;
    crate::sshkeys::pin_host_keys(&host, &info.hostkeys)?;
    crate::sshkeys::bootstrap_cache_put(peer, info.user.as_deref());

    Ok(PeerSshInfo {
        login: resolve_login(info.user),
        host,
        rport,
        key_path: crate::sshkeys::managed_key_path(),
        known_hosts_path: crate::sshkeys::known_hosts_path(),
        took_fast_path: false,
    })
}

/// Build ssh option args for use with sshfs/rsync (identity, known_hosts, etc).
pub(crate) fn ssh_transport_args(info: &PeerSshInfo, server: &str, peer: &str, relay: bool) -> Vec<String> {
    let mut args = vec![
        "-o".into(), format!("IdentityFile={}", info.key_path.display()),
        "-o".into(), "IdentitiesOnly=yes".into(),
        "-o".into(), format!("UserKnownHostsFile={}", info.known_hosts_path.display()),
        "-o".into(), "GlobalKnownHostsFile=/dev/null".into(),
        "-o".into(), "StrictHostKeyChecking=accept-new".into(),
        "-o".into(), "ConnectTimeout=10".into(),
        "-o".into(), "ServerAliveInterval=15".into(),
        "-o".into(), "ServerAliveCountMax=4".into(),
    ];
    let exe = std::env::current_exe().unwrap();
    let exe = exe.to_string_lossy();
    let mut proxy = format!("{exe} --server {server}");
    if relay {
        proxy.push_str(" --relay");
    }
    proxy.push_str(&format!(" netcat {peer} {}", info.rport));
    args.push("-o".into());
    args.push(format!("ProxyCommand={proxy}"));
    args
}

/// Build the L3 direct destination for sshfs/rsync (login@peer.mesh). The mesh
/// overlay (TUN) and its `.mesh` MagicDNS entries are Linux-only, so on other
/// platforms there is no L3 path: return `None` and let the caller fall back to
/// the L2 tunnel (same semantics as "peer isn't on the mesh").
#[cfg(not(target_os = "linux"))]
pub(crate) fn l3_dest(_info: &PeerSshInfo) -> Option<String> {
    None
}

/// Build the L3 direct destination for sshfs/rsync (login@peer.mesh).
#[cfg(target_os = "linux")]
pub(crate) fn l3_dest(info: &PeerSshInfo) -> Option<String> {
    let peer = info.host.strip_prefix("filament-").unwrap_or(&info.host);
    let (mesh_host, addr) = l3_mesh_addr(peer, info.rport)?;
    
    // Retry with increasing timeouts (like run_ssh does with revive+poll).
    // A single 600ms probe is too aggressive - overlay may be temporarily slow.
    for attempt in 0..3 {
        if probe_sshd(addr, std::time::Duration::from_millis(1000)) {
            return Some(format!("{}@{mesh_host}", info.login));
        }
        if attempt < 2 {
            std::thread::sleep(std::time::Duration::from_millis(500));
        }
    }
    None
}

pub async fn ssh_cmd(server: &str, peer: &str, extra: &[String], relay: bool) -> Result<()> {
    let peer = peer.strip_suffix(".mesh").unwrap_or(peer);

    let info = ensure_peer_bootstrap(server, peer, relay).await?;

    let code = run_ssh(server, peer, relay, &info.host, &info.login, info.rport, extra, true).await?;

    // A cached skip that failed at the ssh layer (connect/auth, exit 255) may mean
    // the device rotated its key/host-key or revoked the cap. Invalidate, run a
    // real bootstrap, and retry ssh ONCE.
    if code == 255 && info.took_fast_path {
        crate::ui::say(&format!("filament: re-authenticating with '{peer}'..."));
        let retry = rebootstrap_peer(server, peer, relay).await?;
        // revive=false: don't pay the L3 revive-wait twice on the same invocation.
        let code = run_ssh(server, peer, relay, &retry.host, &retry.login, retry.rport, extra, false).await?;
        ssh_failed_hint(peer, code);
        std::process::exit(code);
    }
    ssh_failed_hint(peer, code);
    std::process::exit(code);
}

/// ssh exit 255 is ssh's own connect/session failure (no sshd reachable, timed
/// out, auth) - distinct from a remote command's non-zero exit. In that case point
/// the user at the filament-native shell, which needs no sshd and survives repairs.
fn ssh_failed_hint(peer: &str, code: i32) {
    if code == 255 {
        crate::ui::say(&crate::ui::paint(
            crate::ui::Tone::Dim,
            &format!("  tip: `filament {peer}` opens a filament shell instead (no sshd needed, survives link repairs)"),
        ));
    }
}

/// Confirm an sshd is reachable on `rport` before spawning ssh, so it fails fast
/// with a clear message instead of hanging on a refused/black-holed connection.
/// A beta.20+ peer already `reported` it in the bootstrap ack; for an older peer
/// (`None`) fall back to a quick client-side probe over the warm link, which works
/// regardless of the peer's version. Only a DEFINITE "no sshd" stops us; an
/// inconclusive probe proceeds (never make ssh worse than before).
async fn ensure_sshd(peer: &str, rport: u16, reported: Option<bool>) {
    let sshd = match reported {
        Some(b) => Some(b),
        #[cfg(unix)]
        None => probe_sshd_warm(peer, rport).await,
        #[cfg(not(unix))]
        None => None,
    };
    if sshd != Some(false) {
        return;
    }
    crate::ui::problem(
        &format!("filament ssh: no sshd on '{peer}'"),
        &format!(
            "'{peer}' is reachable, but nothing is listening on localhost:{rport} for ssh. \
             (sshd may be bound to a non-localhost address like the mesh ULA — \
             `filament ssh` connects to localhost:{rport} on the peer.)",
        ),
        &[
            format!("start an sshd on '{peer}' listening on localhost (or all interfaces)"),
            format!("set {} to a different port", crate::ui::paint(crate::ui::Tone::Brand, "FILAMENT_SSH_PORT")),
            format!(
                "use {} for a shell that needs no sshd",
                crate::ui::paint(crate::ui::Tone::Brand, &format!("filament pty {peer}"))
            ),
        ],
    );
    std::process::exit(1);
}

/// Client-side "is there an sshd on `peer:rport`" probe over the daemon's WARM
/// link only (fast, never a cold establish, so it can't hang). Opens one L2
/// stream and reads: an immediate EOF means the acceptor's local dial was refused
/// (no listener); any bytes (the SSH banner) mean a listener is there. No warm
/// link or no banner in time -> `None` (unknown, caller proceeds). Works against
/// any peer version, since it relies only on the old l2-open/l2-close path.
#[cfg(unix)]
async fn probe_sshd_warm(peer: &str, rport: u16) -> Option<bool> {
    use tokio::io::AsyncReadExt;
    let mut s = crate::ctl::try_open(peer, rport).await?;
    let mut buf = [0u8; 8];
    match tokio::time::timeout(std::time::Duration::from_secs(3), s.read(&mut buf)).await {
        Ok(Ok(0)) => Some(false),  // refused: stream closed before any byte
        Ok(Ok(_)) => Some(true),   // a listener answered (sshd banner)
        Ok(Err(_)) => Some(false), // stream error: treat as unreachable
        Err(_) => None,            // no banner in time: inconclusive, don't block
    }
}

#[cfg(test)]
mod h1_tests {
    use super::*;
    use async_trait::async_trait;
    use std::sync::Mutex as StdMutex;

    /// Minimal in-memory Transport: records control messages, discards frames.
    struct MockTransport {
        controls: StdMutex<Vec<Value>>,
    }
    impl MockTransport {
        fn new() -> Arc<Self> {
            Arc::new(MockTransport { controls: StdMutex::new(Vec::new()) })
        }
    }
    #[async_trait]
    impl Transport for MockTransport {
        async fn send_control(&self, msg: &Value) -> Result<()> {
            self.controls.lock().unwrap().push(msg.clone());
            Ok(())
        }
        async fn send_frame(&self, _sid: u32, _offset: u64, _payload: &[u8]) -> Result<()> {
            Ok(())
        }
        async fn flush(&self) -> Result<()> {
            Ok(())
        }
        fn max_payload(&self) -> usize {
            1024
        }
        fn is_dead(&self) -> bool {
            false
        }
        fn as_any(&self) -> &dyn std::any::Any {
            self
        }
    }

    fn open_msg(sid: u32) -> Value {
        json!({ "type": "l2-open", "sid": sid, "host": "127.0.0.1", "rport": 9 })
    }

    /// H-1: opening + closing N PTY-style streams (register + resizer, then close)
    /// leaves BOTH the stream table and the resizer map empty on every teardown
    /// path, and the global PTY counter returns to zero.
    #[tokio::test]
    async fn pty_open_close_leaves_maps_empty() {
        let start = LIVE_PTYS.load(Ordering::SeqCst);
        let mux = Mux::new(MockTransport::new());
        let n = 5u32;

        // Path A: inbound l2-close frees stream + resizer.
        for i in 0..n {
            let sid = L2_SID_BASE | (1000 + i);
            let guard = PtyGuard::try_acquire().expect("slot free");
            let _rx = mux.register_stream(sid).await;
            let (tx, _rrx) = mpsc::unbounded_channel::<(u16, u16)>();
            mux.register_resizer(sid, tx).await;
            assert_eq!(mux.live_streams().await, 1);
            assert_eq!(mux.resizers.lock().await.len(), 1);
            // Inbound l2-close (browser closed).
            mux.on_close(sid, None).await;
            drop(guard); // session task ending frees the global slot
            assert_eq!(mux.live_streams().await, 0, "stream not freed on l2-close");
            assert_eq!(mux.resizers.lock().await.len(), 0, "resizer leaked on l2-close");
        }

        // Path B: session task exit (drop_pty) frees stream + resizer.
        for i in 0..n {
            let sid = L2_SID_BASE | (2000 + i);
            let guard = PtyGuard::try_acquire().expect("slot free");
            let _rx = mux.register_stream(sid).await;
            let (tx, _rrx) = mpsc::unbounded_channel::<(u16, u16)>();
            mux.register_resizer(sid, tx).await;
            mux.drop_pty(sid).await; // a session task own exit path
            drop(guard);
            assert_eq!(mux.live_streams().await, 0, "stream not freed on drop_pty");
            assert_eq!(mux.resizers.lock().await.len(), 0, "resizer leaked on drop_pty");
        }

        // Path C: link/mux death (shutdown_all) frees everything.
        let mut guards = Vec::new();
        for i in 0..n {
            let sid = L2_SID_BASE | (3000 + i);
            guards.push(PtyGuard::try_acquire().expect("slot free"));
            let _rx = mux.register_stream(sid).await;
            let (tx, _rrx) = mpsc::unbounded_channel::<(u16, u16)>();
            mux.register_resizer(sid, tx).await;
        }
        assert_eq!(mux.live_streams().await, n as usize);
        mux.shutdown_all().await;
        drop(guards);
        assert_eq!(mux.live_streams().await, 0, "streams leaked past shutdown_all");
        assert_eq!(mux.resizers.lock().await.len(), 0, "resizers leaked past shutdown_all");

        assert_eq!(LIVE_PTYS.load(Ordering::SeqCst), start, "global PTY count must return to baseline");
    }

    /// H-1: the per-link stream cap refuses opens beyond MAX_STREAMS_PER_LINK with
    /// an `l2-close{err:"too many streams"}`, and does NOT register the stream.
    #[tokio::test]
    async fn per_link_stream_cap_refuses_over_limit() {
        let mux = Mux::new(MockTransport::new());
        // Fill to the cap with accepted opens (they register pipes).
        for i in 0..MAX_STREAMS_PER_LINK as u32 {
            let sid = L2_SID_BASE | (i + 1);
            match mux.accept_control(&open_msg(sid), true, false).await {
                OpenVerdict::Accept { .. } => {}
                other => panic!("expected Accept under cap, got {:?}", std::mem::discriminant(&other)),
            }
        }
        assert_eq!(mux.live_streams().await, MAX_STREAMS_PER_LINK);
        // One more must be denied with the cap error, leaving the table unchanged.
        let over = L2_SID_BASE | 9999;
        match mux.accept_control(&open_msg(over), true, false).await {
            OpenVerdict::Deny { sid, err } => {
                assert_eq!(sid, over);
                assert_eq!(err, "too many streams");
            }
            other => panic!("expected Deny over cap, got {:?}", std::mem::discriminant(&other)),
        }
        assert_eq!(mux.live_streams().await, MAX_STREAMS_PER_LINK, "over-cap open must not register");
        // The denied sid is not stuck in `accepted` (can retry once room frees).
        assert!(!mux.accepted.lock().await.contains_key(&over));
    }

    /// H-1: the global PTY guard refuses acquisition once MAX_PTYS_GLOBAL slots
    /// are held, and frees them on drop.
    #[tokio::test]
    async fn global_pty_cap_is_enforced() {
        // Other tests may hold none here, but to be robust we only assert the
        // guard refuses once at-capacity relative to the current baseline.
        let mut held = Vec::new();
        while LIVE_PTYS.load(Ordering::SeqCst) < MAX_PTYS_GLOBAL {
            match PtyGuard::try_acquire() {
                Some(g) => held.push(g),
                None => break,
            }
        }
        assert_eq!(LIVE_PTYS.load(Ordering::SeqCst), MAX_PTYS_GLOBAL);
        assert!(PtyGuard::try_acquire().is_none(), "must refuse at global cap");
        let before = held.len();
        drop(held);
        assert!(LIVE_PTYS.load(Ordering::SeqCst) <= MAX_PTYS_GLOBAL - before.min(1));
    }

    // ---- #4: persistent PTY session ----------------------------------------

    /// A Transport that records every frame's payload (per sid) so a test can
    /// observe what a session actually sent / replayed.
    struct CapTransport {
        frames: StdMutex<Vec<(u32, Vec<u8>)>>,
        controls: StdMutex<Vec<Value>>,
    }
    impl CapTransport {
        fn new() -> Arc<Self> {
            Arc::new(CapTransport { frames: StdMutex::new(Vec::new()), controls: StdMutex::new(Vec::new()) })
        }
        /// All bytes ever sent to `sid`, concatenated in order.
        fn bytes_for(&self, sid: u32) -> Vec<u8> {
            self.frames
                .lock()
                .unwrap()
                .iter()
                .filter(|(s, _)| *s == sid)
                .flat_map(|(_, b)| b.clone())
                .collect()
        }
    }
    #[async_trait]
    impl Transport for CapTransport {
        async fn send_control(&self, msg: &Value) -> Result<()> {
            self.controls.lock().unwrap().push(msg.clone());
            Ok(())
        }
        async fn send_frame(&self, sid: u32, _offset: u64, payload: &[u8]) -> Result<()> {
            self.frames.lock().unwrap().push((sid, payload.to_vec()));
            Ok(())
        }
        async fn flush(&self) -> Result<()> {
            Ok(())
        }
        fn max_payload(&self) -> usize {
            1024
        }
        fn is_dead(&self) -> bool {
            false
        }
        fn as_any(&self) -> &dyn std::any::Any {
            self
        }
    }

    /// A transport whose liveness we can flip, to prove the daemon bridge tears
    /// down on transport death (not just on a clean FIN) even with an IDLE client.
    struct KillableTransport {
        alive: std::sync::atomic::AtomicBool,
    }
    impl KillableTransport {
        fn new() -> Arc<Self> {
            Arc::new(KillableTransport { alive: std::sync::atomic::AtomicBool::new(true) })
        }
        fn kill(&self) {
            self.alive.store(false, Ordering::SeqCst);
        }
    }
    #[async_trait]
    impl Transport for KillableTransport {
        async fn send_control(&self, _msg: &Value) -> Result<()> {
            Ok(())
        }
        async fn send_frame(&self, _sid: u32, _offset: u64, _payload: &[u8]) -> Result<()> {
            Ok(())
        }
        async fn flush(&self) -> Result<()> {
            Ok(())
        }
        fn max_payload(&self) -> usize {
            1024
        }
        fn is_alive(&self) -> bool {
            self.alive.load(Ordering::SeqCst)
        }
        fn is_dead(&self) -> bool {
            !self.alive.load(Ordering::SeqCst)
        }
        fn as_any(&self) -> &dyn std::any::Any {
            self
        }
    }

    /// Regression for the warm-pty deadlock: the daemon bridge (`serve_stream`) must
    /// tear down when the PEER TRANSPORT dies even while the local client is IDLE.
    /// The client->peer reader parks on the silent client socket and never notices
    /// the death; awaiting only that reader (the old code) hung the warm bridge - and
    /// the user's warm pty - until they happened to type. The liveness ticker now
    /// catches it: with an idle client and a killed transport, this returns instead
    /// of blocking forever.
    #[tokio::test]
    async fn serve_stream_tears_down_on_transport_death_with_idle_client() {
        let t = KillableTransport::new();
        let mux = Mux::new(t.clone());
        let sid = L2_SID_BASE | 7;
        let rx = mux.register(sid).await;
        // A duplex pair: one half is the bridge's "client socket", the other we keep
        // and NEVER write to, so the reader stays parked (the deadlock precondition).
        let (client, server_side) = tokio::io::duplex(1024);
        let bridge = tokio::spawn(serve_stream(mux.clone(), sid, server_side, rx, true, None));
        tokio::time::sleep(Duration::from_millis(50)).await; // let the reader park
        t.kill(); // transport dies with no clean FIN and no client input
        let r = tokio::time::timeout(Duration::from_secs(4), bridge).await;
        assert!(r.is_ok(), "serve_stream deadlocked on an idle client after transport death");
        drop(client);
    }

    /// `push_ring` keeps the buffer bounded by `cap`, evicting the OLDEST bytes,
    /// and a single oversized write keeps only its trailing `cap` bytes.
    #[test]
    fn ring_buffer_is_bounded_and_keeps_newest() {
        let mut ring = VecDeque::new();
        push_ring(&mut ring, b"hello", 8);
        assert_eq!(ring.iter().copied().collect::<Vec<u8>>(), b"hello");
        // "helloworld!!" is 12 bytes; cap 8 keeps the trailing 8: "oworld!!".
        push_ring(&mut ring, b"world!!", 8);
        assert_eq!(ring.len(), 8);
        assert_eq!(ring.iter().copied().collect::<Vec<u8>>(), b"oworld!!");
    }

    /// A single write LARGER than the cap keeps only its trailing `cap` bytes.
    #[test]
    fn ring_buffer_oversized_write_keeps_tail() {
        let mut ring = VecDeque::new();
        push_ring(&mut ring, b"0123456789", 4);
        assert_eq!(ring.iter().copied().collect::<Vec<u8>>(), b"6789");
    }

    /// End-to-end #4: a session spawned over link A, detached (link A drops),
    /// then REATTACHED over link B with the same session id REPLAYS the buffered
    /// output to link B AND the still-running shell keeps working. Uses `cat` as
    /// the "shell" (it echoes stdin), so input typed after reattach comes back on
    /// link B, proving the SAME process survived the reconnect.
    #[tokio::test]
    async fn session_survives_detach_and_reattaches_with_replay() {
        // `cat` echoes its stdin: a deterministic stand-in for a live shell whose
        // process identity we can verify survived the drop.
        if !std::path::Path::new("/bin/cat").exists() {
            return; // environment without /bin/cat: skip rather than fail
        }
        let sessions = PtySessions::new();
        let ta = CapTransport::new();
        let sid_a = L2_SID_BASE | 1;
        let guard = PtyGuard::try_acquire().expect("slot");
        let sess = spawn_pty_session(
            sessions.clone(),
            "sess-x".to_string(),
            ta.clone(),
            sid_a,
            80,
            24,
            "xterm-256color",
            vec!["/bin/cat".to_string()],
            guard,
        )
        .await
        .expect("spawn");

        // Type a line on link A; cat echoes it back to sid_a.
        sess.feed_input(b"before-drop\n".to_vec());
        // Give the PTY threads + task a moment to echo and buffer.
        tokio::time::sleep(Duration::from_millis(200)).await;
        let a_out = String::from_utf8_lossy(&ta.bytes_for(sid_a)).to_string();
        assert!(a_out.contains("before-drop"), "link A never saw the echo: {a_out:?}");

        // Link A drops: detach (the shell MUST keep running).
        sess.detach();
        tokio::time::sleep(Duration::from_millis(50)).await;
        assert!(!sess.is_dead(), "detach must NOT kill the session");

        // Reconnect: attach link B with the same session, new sid. The buffer
        // (including "before-drop") replays to sid_b.
        let tb = CapTransport::new();
        let sid_b = L2_SID_BASE | 2;
        let live = sessions.get_live("sess-x").await.expect("session still live for reattach");
        live.attach(tb.clone(), sid_b);
        tokio::time::sleep(Duration::from_millis(150)).await;
        let b_replay = String::from_utf8_lossy(&tb.bytes_for(sid_b)).to_string();
        assert!(b_replay.contains("before-drop"), "reattach did not replay buffered output: {b_replay:?}");

        // The SAME shell still works: type after reattach, see it on link B.
        live.feed_input(b"after-reconnect\n".to_vec());
        tokio::time::sleep(Duration::from_millis(200)).await;
        let b_out = String::from_utf8_lossy(&tb.bytes_for(sid_b)).to_string();
        assert!(b_out.contains("after-reconnect"), "post-reattach input did not echo: {b_out:?}");

        // Explicit end kills the shell and removes the session.
        live.end();
        tokio::time::sleep(Duration::from_millis(150)).await;
        assert!(sessions.get_live("sess-x").await.is_none(), "ended session must leave the store");
    }

    /// The `port_in_use_msg` helper must surface the conflicting port and a
    /// `filament forward <lport+1> <peer> <rport>` retry hint, so a user
    /// staring at a "port in use" error can recover in one copy-paste.
    #[test]
    fn port_in_use_msg_names_port_and_suggests_forward() {
        let msg = port_in_use_msg(8080, "laptop", 22);
        assert!(msg.contains("8080"), "message must name the conflicting port: {msg}");
        assert!(msg.contains("filament forward"), "message must suggest a filament forward retry: {msg}");
        assert!(msg.contains("8081"), "suggested port should be lport+1: {msg}");
        assert!(msg.contains("laptop"), "message should reference the peer: {msg}");
        assert!(msg.contains("22"), "message should reference the rport: {msg}");
    }

    /// The helper's `saturating_add` must not wrap when lport is u16::MAX, so
    /// the user never sees a suggested port of 0 (which would still be valid
    /// for binding but is a confusing retry hint).
    #[test]
    fn port_in_use_msg_saturates_at_u16_max() {
        let msg = port_in_use_msg(u16::MAX, "laptop", 22);
        assert!(msg.contains(&format!("{}", u16::MAX)), "must name the conflicting port: {msg}");
        // u16::MAX.saturating_add(1) == u16::MAX, NOT 0.
        assert!(!msg.contains("0 "), "saturating add must not wrap to 0: {msg}");
    }

    // ---- warm-reuse zombie self-heal (the popos pty/ssh hang) ----------------

    /// THE proof for "filament definitively works no matter what": warm-reuse over
    /// a ZOMBIE held link (alive at QUIC, black-holing new streams: NOTHING ever
    /// arrives inbound) must NOT hang. `open_stream_verified` bails within the
    /// window with an `Err`, removes the half-open stream, and sends an `l2-close`
    /// so the peer reaps its half. The caller (handle_warm_open) then drops the
    /// link and rejects, so the client falls through to a fresh establish.
    /// Crucially it verifies BEFORE the client is committed, so the fallback is
    /// instant - never the 25s ssh-ConnectTimeout stall an accepted-then-dead
    /// connection would cause.
    #[cfg(unix)]
    #[tokio::test]
    async fn warm_reuse_zombie_link_self_heals_instead_of_hanging() {
        let t = CapTransport::new();
        let mux = Mux::new(t.clone());

        let verdict =
            open_stream_verified(&mux, 22, std::time::Duration::from_millis(50)).await;

        assert!(verdict.is_err(), "a link that delivers no inbound frame must be a zombie Err");
        assert_eq!(mux.live_streams().await, 0, "zombie stream must be removed, not leaked");
        let ctrls = t.controls.lock().unwrap();
        assert!(
            ctrls.iter().any(|c| c["type"] == "l2-open"),
            "must have attempted the open"
        );
        assert!(
            ctrls.iter().any(|c| c["type"] == "l2-close"),
            "must send l2-close so the peer reaps its half of the zombie stream"
        );
    }

    /// The flip side, proving the verify costs the happy path NOTHING and never
    /// false-flags a live link: a HEALTHY link that delivers a first frame within
    /// the window returns `Ok` with that frame preserved, and `serve_verified_stream`
    /// replays it to the client byte-for-byte (no peer bytes lost to the probe).
    #[cfg(unix)]
    #[tokio::test]
    async fn warm_reuse_healthy_link_passes_and_replays_first_frame() {
        let t = CapTransport::new();
        let mux = Mux::new(t.clone());

        // Drive open_stream_verified concurrently; as soon as it registers its
        // stream, deliver the peer's first frame (sshd banner / shell prompt).
        let mux2 = mux.clone();
        let h = tokio::spawn(async move {
            open_stream_verified(&mux2, 22, std::time::Duration::from_secs(5)).await
        });
        let sid = loop {
            if let Some(&sid) = mux.streams.lock().await.keys().next() {
                break sid;
            }
            tokio::task::yield_now().await;
        };
        mux.on_frame(sid, Bytes::from_static(b"BANNER")).await;

        let (got_sid, first, rx) = h.await.expect("task panicked").expect("healthy link must be Ok");
        assert_eq!(got_sid, sid);
        assert_eq!(first, Some(Bytes::from_static(b"BANNER")), "first frame must be preserved for replay");

        // serve_verified_stream replays `first` to the client verbatim.
        let (mut client, srv) = tokio::io::duplex(1024);
        let mux3 = mux.clone();
        let s = tokio::spawn(async move { serve_verified_stream(mux3, sid, srv, first, rx).await });
        let mut buf = [0u8; 6];
        client.read_exact(&mut buf).await.expect("replayed frame must reach the client");
        assert_eq!(&buf, b"BANNER", "the verified first frame must be replayed verbatim");

        mux.on_frame(sid, Bytes::new()).await; // peer FIN closes the writer pump
        drop(client); // client EOF closes the reader pump
        s.await.expect("serve task panicked");
    }

    /// The client-speaks-first case (HTTP, most DB clients): the peer sends NO app
    /// bytes until we do, only the `l2-open-ack` confirming its local connect. Warm
    /// verify must pass on that ack - not hang until the window expires and wrongly
    /// drop a healthy link (the bug that sent every warm `forward` to a cold link) -
    /// and replay it as ZERO bytes so the client sees no spurious data before its own
    /// exchange.
    #[cfg(unix)]
    #[tokio::test]
    async fn warm_reuse_client_first_link_passes_on_open_ack() {
        let t = CapTransport::new();
        let mux = Mux::new(t.clone());

        let mux2 = mux.clone();
        let h = tokio::spawn(async move {
            open_stream_verified(&mux2, 80, std::time::Duration::from_secs(5)).await
        });
        let sid = loop {
            if let Some(&sid) = mux.streams.lock().await.keys().next() {
                break sid;
            }
            tokio::task::yield_now().await;
        };
        // Only the acceptor's connect confirmation arrives - no app data yet.
        mux.on_open_ack(sid).await;

        let (got_sid, first, rx) =
            h.await.expect("task panicked").expect("open-ack must prove the link live");
        assert_eq!(got_sid, sid);
        assert_eq!(first, Some(Bytes::new()), "the ack is an empty liveness marker");

        // Replaying the empty ack writes nothing; real app data (sent only after the
        // client would have spoken) still reaches the client intact.
        let (mut client, srv) = tokio::io::duplex(1024);
        let mux3 = mux.clone();
        let s = tokio::spawn(async move { serve_verified_stream(mux3, sid, srv, first, rx).await });
        mux.on_frame(sid, Bytes::from_static(b"HTTP/1.1 200 OK")).await;
        let mut buf = [0u8; 15];
        client
            .read_exact(&mut buf)
            .await
            .expect("real data must reach the client after the empty ack");
        assert_eq!(&buf, b"HTTP/1.1 200 OK", "the empty ack must not corrupt the stream");

        mux.on_frame(sid, Bytes::new()).await;
        drop(client);
        s.await.expect("serve task panicked");
    }
}