ghosttea-truffle 0.2.0

Truffle transport adapter for Ghosttea
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
use std::{
    collections::HashMap,
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    },
    time::{Duration, SystemTime, UNIX_EPOCH},
};

#[cfg(test)]
use std::env;

use anyhow::{Context, Result, bail};
use async_trait::async_trait;
use subtle::ConstantTimeEq;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio::sync::broadcast;
use tokio::time::MissedTickBehavior;
use truffle_core as truffle;
use truffle_core::{Node, network::tailscale::TailscaleProvider, transport::quic::QuicStream};
use uuid::Uuid;

use ghosttea::{
    RemoteActivityChanged, RemoteAttachment, RemoteControlChanged, RemoteControlClaim,
    RemoteHostSummary, RemoteReplica, RemoteResize, RemoteSelection, RemoteSessionOpen,
    RemoteTerminalRuntime, Session, SessionRegistry as Registry, SessionSummary, TerminalMesh,
    ViewAccess,
    tunnel_protocol::{
        CompactChannel, ConnectionMessage, LogicalTerminalPatch, LogicalTerminalSnapshot,
        MAX_CONTROL_MESSAGE_BYTES, MAX_STATE_MESSAGE_BYTES, PROTOCOL_MAJOR, PROTOCOL_MINOR,
        RowReplacement, SESSION_ACTIVITY_PROTOCOL_MINOR, SessionControlMessage,
        SharedSessionSummary, StateCodec, StateMessage, StreamKind, StreamPreface,
        TerminalHostAdvertisement, TunnelInput, decode_compact_message, decode_message,
        decode_preface, decode_state_message, encode_compact_message, encode_message,
        encode_preface, encode_state_message,
    },
};

pub const DEFAULT_QUIC_PORT: u16 = 9420;
pub const DEFAULT_COMPACT_PORT: u16 = 9421;
const ADVERTISEMENT_INTERVAL: Duration = Duration::from_secs(5);
const ADVERTISEMENT_TTL: Duration = Duration::from_secs(15);
const CONNECT_TIMEOUT: Duration = Duration::from_secs(20);
const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);

type HostStore = truffle::synced_store::SyncedStore<TerminalHostAdvertisement>;
type RemoteViews = Arc<tokio::sync::Mutex<HashMap<(String, String), Arc<RemoteView>>>>;
type RemoteConnections = Arc<tokio::sync::Mutex<HashMap<String, Arc<RemoteHostConnection>>>>;

#[derive(Clone)]
pub struct MeshRuntime {
    ready: Arc<tokio::sync::RwLock<Option<MeshReady>>>,
    replicas: Arc<tokio::sync::RwLock<HashMap<String, RemoteSession>>>,
    views: RemoteViews,
    connections: RemoteConnections,
    control_tx: broadcast::Sender<RemoteControlChanged>,
    activity_tx: broadcast::Sender<RemoteActivityChanged>,
}

impl Default for MeshRuntime {
    fn default() -> Self {
        let (control_tx, _) = broadcast::channel(64);
        let (activity_tx, _) = broadcast::channel(64);
        Self {
            ready: Arc::default(),
            replicas: Arc::default(),
            views: Arc::default(),
            connections: Arc::default(),
            control_tx,
            activity_tx,
        }
    }
}

#[derive(Clone)]
struct MeshReady {
    node: Arc<Node<TailscaleProvider>>,
    store: Arc<HostStore>,
    host_instance_id: String,
    capability: Option<String>,
}

#[derive(Clone)]
struct RemoteSession {
    device_id: String,
    remote_session_id: String,
    access_token: Option<String>,
    replica: Arc<RemoteReplica>,
}

struct RemoteView {
    session_control: tokio::sync::Mutex<ProtocolStream>,
    control: tokio::sync::watch::Receiver<Option<RemoteControlClaim>>,
    state_cancel: tokio::sync::watch::Sender<bool>,
    attachment_epoch: u64,
    read_write: bool,
}

struct RemoteHostConnection {
    connection: Arc<truffle::transport::quic::QuicConnection>,
    control: tokio::sync::Mutex<ProtocolStream>,
    incoming: tokio::sync::Mutex<()>,
    host_instance_id: String,
    state_codec: StateCodec,
    healthy: AtomicBool,
}

fn connection_is_reusable(
    cached_host_instance_id: &str,
    healthy: bool,
    advertised_host_instance_id: &str,
) -> bool {
    healthy && cached_host_instance_id == advertised_host_instance_id
}

fn negotiate_state_codec(offered: Option<Vec<StateCodec>>) -> StateCodec {
    offered
        .unwrap_or_default()
        .into_iter()
        .find(|codec| *codec == StateCodec::CompactJsonV1)
        .unwrap_or(StateCodec::Json)
}

impl MeshRuntime {
    pub fn new() -> Self {
        Self::default()
    }

    pub async fn hosts(&self) -> Result<Vec<RemoteHostSummary>> {
        let ready = self.ready().await?;
        let local_device_id = ready.node.local_info().device_id;
        let peers = ready.node.peers().await;
        let peer_by_device: std::collections::HashMap<_, _> = peers
            .into_iter()
            .filter_map(|peer| peer.device_id.clone().map(|device_id| (device_id, peer)))
            .collect();
        let now = now_ms();
        let mut hosts = ready
            .store
            .all()
            .await
            .into_iter()
            .filter(|(device_id, slice)| {
                device_id != &local_device_id
                    && slice.data.expires_at_ms >= now
                    && slice.data.protocol_major == PROTOCOL_MAJOR
            })
            .map(|(device_id, slice)| {
                let peer = peer_by_device.get(&device_id);
                RemoteHostSummary {
                    device_name: peer
                        .map(|peer| peer.display_name.clone())
                        .unwrap_or_else(|| device_id.clone()),
                    online: peer.is_some_and(|peer| peer.online),
                    device_id,
                    protocol_major: slice.data.protocol_major,
                    protocol_minor: slice.data.protocol_minor,
                    host_instance_id: slice.data.host_instance_id,
                    sessions: slice.data.sessions,
                }
            })
            .collect::<Vec<_>>();
        hosts.sort_by(|left, right| {
            left.device_name
                .cmp(&right.device_name)
                .then(left.device_id.cmp(&right.device_id))
        });
        Ok(hosts)
    }

    pub async fn list_sessions(&self, device_id: &str) -> Result<Vec<SharedSessionSummary>> {
        match self.list_sessions_once(device_id).await {
            Ok(sessions) => Ok(sessions),
            Err(first_error) => {
                self.invalidate_connection(device_id, None).await;
                self.list_sessions_once(device_id).await.with_context(|| {
                    format!("remote session listing failed after reconnect: {first_error:#}")
                })
            }
        }
    }

    async fn list_sessions_once(&self, device_id: &str) -> Result<Vec<SharedSessionSummary>> {
        let remote = self.remote_connection(device_id).await?;
        let mut control = remote.control.lock().await;
        let request_id = Uuid::new_v4().to_string();
        control
            .write_message(
                &ConnectionMessage::ListSessions {
                    request_id: request_id.clone(),
                },
                MAX_CONTROL_MESSAGE_BYTES,
            )
            .await?;
        let sessions = match tokio::time::timeout(
            HANDSHAKE_TIMEOUT,
            control.read_message::<ConnectionMessage>(MAX_CONTROL_MESSAGE_BYTES),
        )
        .await
        .context("timed out waiting for remote terminal sessions")??
        .context("remote host closed before listing sessions")?
        {
            ConnectionMessage::Sessions {
                request_id: response_id,
                sessions,
            } if response_id == request_id => sessions,
            ConnectionMessage::Error { message, .. } => {
                bail!("remote host rejected request: {message}")
            }
            _ => bail!("remote host returned an invalid session list"),
        };
        Ok(sessions)
    }

    pub async fn open_session(&self, request: RemoteSessionOpen) -> Result<SessionSummary> {
        let RemoteSessionOpen {
            device_id,
            remote_session_id,
            cols,
            rows,
            owner_id,
            frames,
            text_engine,
        } = request;
        let ready = self.ready().await?;
        // Advertised sessions are discovery hints and may lag registry
        // changes. Resolve the selected session against the host's live
        // registry before creating a local replica.
        let sessions = self.list_sessions(&device_id).await?;
        let remote = sessions
            .iter()
            .find(|session| session.session_id == remote_session_id && session.attachable)
            .context("remote terminal session is no longer attachable")?;
        let replica = RemoteReplica::new(
            remote.title.clone(),
            remote.cwd_label.clone(),
            cols,
            rows,
            owner_id,
            frames,
            text_engine,
        );
        replica.set_activity(remote.activity.clone());
        let summary = replica.summary();
        self.replicas.write().await.insert(
            summary.id.clone(),
            RemoteSession {
                device_id,
                remote_session_id,
                access_token: ready.capability,
                replica,
            },
        );
        Ok(summary)
    }

    pub async fn summaries(&self) -> Vec<SessionSummary> {
        self.replicas
            .read()
            .await
            .values()
            .map(|session| session.replica.summary())
            .collect()
    }

    pub async fn summary(&self, session_id: &str) -> Option<SessionSummary> {
        self.replicas
            .read()
            .await
            .get(session_id)
            .map(|session| session.replica.summary())
    }

    pub async fn attach_view(&self, session_id: &str, view_id: &str) -> Result<RemoteAttachment> {
        let device_id = self
            .replicas
            .read()
            .await
            .get(session_id)
            .map(|remote| remote.device_id.clone())
            .context("unknown remote session")?;
        match self.attach_view_once(session_id, view_id).await {
            Ok(epoch) => Ok(epoch),
            Err(first_error) => {
                self.invalidate_connection(&device_id, None).await;
                self.attach_view_once(session_id, view_id)
                    .await
                    .with_context(|| {
                        format!("remote view attach failed after reconnect: {first_error:#}")
                    })
            }
        }
    }

    async fn attach_view_once(&self, session_id: &str, view_id: &str) -> Result<RemoteAttachment> {
        let key = (session_id.to_owned(), view_id.to_owned());
        if let Some(view) = self.views.lock().await.get(&key) {
            return Ok(RemoteAttachment {
                attachment_epoch: view.attachment_epoch,
                read_write: view.read_write,
            });
        }
        let remote = self
            .replicas
            .read()
            .await
            .get(session_id)
            .cloned()
            .context("unknown remote session")?;
        let summary = remote.replica.summary();
        let host = self.remote_connection(&remote.device_id).await?;
        // A connection carries multiple view streams, but their LiveState
        // streams arrive on one connection-wide accept queue. Serialize the
        // attach handshake so concurrent panes cannot consume each other's
        // state stream.
        let _incoming = host.incoming.lock().await;
        let connection = Arc::clone(&host.connection);
        let mut session_control = ProtocolStream::new(connection.open_stream().await?);
        session_control
            .write_preface(&StreamPreface {
                stream_kind: StreamKind::SessionControl,
                session_id: Some(remote.remote_session_id.clone()),
                view_id: Some(view_id.to_owned()),
            })
            .await?;
        let request_id = Uuid::new_v4().to_string();
        session_control
            .write_message(
                &SessionControlMessage::AttachView {
                    request_id: request_id.clone(),
                    session_id: remote.remote_session_id.clone(),
                    view_id: view_id.to_owned(),
                    access_token: remote.access_token,
                    cols: summary.cols,
                    rows: summary.rows,
                },
                MAX_CONTROL_MESSAGE_BYTES,
            )
            .await?;
        let attach_response = tokio::time::timeout(
            HANDSHAKE_TIMEOUT,
            session_control.read_message::<SessionControlMessage>(MAX_CONTROL_MESSAGE_BYTES),
        )
        .await
        .context("timed out attaching remote terminal view")?
        .context("read remote terminal attach response")?
        .context("remote terminal closed before attaching view")?;
        let (attachment_epoch, read_write) = match attach_response {
            SessionControlMessage::ViewAttached {
                request_id: response_id,
                attachment_epoch,
                read_write,
                ..
            } if response_id == request_id => (attachment_epoch, read_write),
            _ => bail!("remote terminal returned an invalid attach response"),
        };
        let state_stream = tokio::time::timeout(HANDSHAKE_TIMEOUT, connection.accept_stream())
            .await
            .context("timed out waiting for remote terminal state")??
            .context("remote terminal closed before opening state stream")?;
        let mut state = ProtocolStream::new(state_stream);
        let preface = tokio::time::timeout(HANDSHAKE_TIMEOUT, state.read_preface())
            .await
            .context("timed out reading remote state preface")?
            .context("read remote terminal state preface")?;
        if preface.stream_kind != StreamKind::LiveState
            || preface.session_id.as_deref() != Some(remote.remote_session_id.as_str())
            || preface.view_id.as_deref() != Some(view_id)
        {
            bail!("remote terminal returned a misrouted state stream");
        }
        let (control_sender, control) = tokio::sync::watch::channel(None);
        let (state_cancel, mut state_cancelled) = tokio::sync::watch::channel(false);
        let view = Arc::new(RemoteView {
            session_control: tokio::sync::Mutex::new(session_control),
            control,
            state_cancel,
            attachment_epoch,
            read_write,
        });
        let local_view_key = key.clone();
        self.views.lock().await.insert(key, Arc::clone(&view));
        let replica = Arc::clone(&remote.replica);
        let local_session_id = session_id.to_owned();
        let remote_device_id = remote.device_id.clone();
        let remote_view = Arc::clone(&view);
        let remote_host = Arc::clone(&host);
        let views = Arc::clone(&self.views);
        let connections = Arc::clone(&self.connections);
        let remote_control_tx = self.control_tx.clone();
        let remote_activity_tx = self.activity_tx.clone();
        tokio::spawn(async move {
            let mut connection_failed = true;
            loop {
                let message = tokio::select! {
                    changed = state_cancelled.changed() => {
                        if changed.is_err() || *state_cancelled.borrow() {
                            connection_failed = false;
                            break;
                        }
                        continue;
                    }
                    message = state.read_state_message(remote_host.state_codec) => message,
                };
                match message {
                    Ok(Some(StateMessage::Snapshot(snapshot))) => {
                        if let Err(error) = replica.publish(snapshot) {
                            eprintln!("[terminal-mesh] failed to render remote state: {error:#}");
                            break;
                        }
                    }
                    Ok(Some(StateMessage::Patch(patch))) => {
                        if let Err(error) = replica.publish_patch(patch) {
                            eprintln!(
                                "[terminal-mesh] failed to apply remote state patch: {error:#}"
                            );
                            break;
                        }
                    }
                    Ok(Some(StateMessage::ControlChanged {
                        controller_view_id,
                        control_epoch,
                        cols,
                        rows,
                        layout_epoch,
                    })) => {
                        let claim = RemoteControlClaim {
                            controller_view_id: controller_view_id.clone(),
                            control_epoch,
                            cols,
                            rows,
                            layout_epoch,
                        };
                        control_sender.send_replace(Some(claim));
                        let _ = remote_control_tx.send(RemoteControlChanged {
                            session_id: local_session_id.clone(),
                            controller_view_id,
                            control_epoch,
                            cols,
                            rows,
                            layout_epoch,
                        });
                    }
                    Ok(Some(StateMessage::ActivityChanged { activity })) => {
                        replica.set_activity(activity.clone());
                        let _ = remote_activity_tx.send(RemoteActivityChanged {
                            session_id: local_session_id.clone(),
                            activity,
                        });
                    }
                    Ok(None) => break,
                    Err(error) => {
                        eprintln!("[terminal-mesh] remote state stream closed: {error:#}");
                        break;
                    }
                }
            }
            let mut current_views = views.lock().await;
            if current_views
                .get(&local_view_key)
                .is_some_and(|current| Arc::ptr_eq(current, &remote_view))
            {
                current_views.remove(&local_view_key);
            }
            drop(current_views);

            if connection_failed {
                remote_host.healthy.store(false, Ordering::Release);
                remote_host.connection.close();
                let mut current_connections = connections.lock().await;
                if current_connections
                    .get(&remote_device_id)
                    .is_some_and(|current| Arc::ptr_eq(current, &remote_host))
                {
                    current_connections.remove(&remote_device_id);
                }
            }
        });
        remote.replica.set_read_write(read_write);
        Ok(RemoteAttachment {
            attachment_epoch,
            read_write,
        })
    }

    pub async fn send_input(
        &self,
        session_id: &str,
        view_id: &str,
        attachment_epoch: u64,
        input_sequence: u64,
        operation: TunnelInput,
    ) -> Result<()> {
        let view = self
            .remote_view(session_id, view_id, attachment_epoch)
            .await?;
        if !view.read_write {
            bail!("remote terminal view is read-only");
        }
        view.session_control
            .lock()
            .await
            .write_message(
                &SessionControlMessage::Input {
                    view_id: view_id.to_owned(),
                    attachment_epoch,
                    input_sequence,
                    operation,
                },
                MAX_CONTROL_MESSAGE_BYTES,
            )
            .await
    }

    pub async fn claim_control(
        &self,
        session_id: &str,
        view_id: &str,
        attachment_epoch: u64,
        cols: u16,
        rows: u16,
    ) -> Result<RemoteControlClaim> {
        let view = self
            .remote_view(session_id, view_id, attachment_epoch)
            .await?;
        if !view.read_write {
            bail!("remote terminal view is read-only");
        }
        let mut state = view.control.clone();
        let previous_epoch = state
            .borrow()
            .as_ref()
            .map_or(0, |current| current.control_epoch);
        view.session_control
            .lock()
            .await
            .write_message(
                &SessionControlMessage::FocusAndResize {
                    view_id: view_id.to_owned(),
                    attachment_epoch,
                    cols,
                    rows,
                    client_sequence: 0,
                },
                MAX_CONTROL_MESSAGE_BYTES,
            )
            .await?;
        tokio::time::timeout(HANDSHAKE_TIMEOUT, async {
            loop {
                state
                    .changed()
                    .await
                    .context("remote terminal control stream closed")?;
                let current = state.borrow_and_update().clone();
                if let Some(current) = current
                    && current.controller_view_id == view_id
                    && current.control_epoch > previous_epoch
                {
                    return Ok(current);
                }
            }
        })
        .await
        .context("timed out claiming remote terminal control")?
    }

    pub async fn resize(
        &self,
        session_id: &str,
        view_id: &str,
        request: RemoteResize,
    ) -> Result<()> {
        let RemoteResize {
            attachment_epoch,
            control_epoch,
            resize_sequence,
            cols,
            rows,
        } = request;
        let view = self
            .remote_view(session_id, view_id, attachment_epoch)
            .await?;
        if !view.read_write {
            bail!("remote terminal view is read-only");
        }
        view.session_control
            .lock()
            .await
            .write_message(
                &SessionControlMessage::Resize {
                    view_id: view_id.to_owned(),
                    attachment_epoch,
                    control_epoch,
                    resize_sequence,
                    cols,
                    rows,
                },
                MAX_CONTROL_MESSAGE_BYTES,
            )
            .await
    }

    pub async fn selection_text(
        &self,
        session_id: &str,
        view_id: &str,
        request: RemoteSelection,
    ) -> Result<String> {
        let view = self
            .remote_view(session_id, view_id, request.attachment_epoch)
            .await?;
        let request_id = Uuid::new_v4().to_string();
        let mut control = view.session_control.lock().await;
        control
            .write_message(
                &SessionControlMessage::SelectionText {
                    request_id: request_id.clone(),
                    view_id: view_id.to_owned(),
                    attachment_epoch: request.attachment_epoch,
                    start_column: request.start_column,
                    start_row: request.start_row,
                    end_column: request.end_column,
                    end_row: request.end_row,
                    select_all: request.select_all,
                },
                MAX_CONTROL_MESSAGE_BYTES,
            )
            .await?;
        match control
            .read_message::<SessionControlMessage>(MAX_CONTROL_MESSAGE_BYTES)
            .await?
            .context("remote terminal closed before returning selection text")?
        {
            SessionControlMessage::SelectionTextResult {
                request_id: response_id,
                text,
            } if response_id == request_id => Ok(text),
            _ => bail!("remote terminal returned an invalid selection response"),
        }
    }

    pub async fn refresh(&self, session_id: &str) -> Result<()> {
        let replica = self
            .replicas
            .read()
            .await
            .get(session_id)
            .map(|session| Arc::clone(&session.replica))
            .context("unknown remote session")?;
        replica.refresh()
    }

    pub async fn detach_view(&self, session_id: &str, view_id: &str, attachment_epoch: u64) {
        let key = (session_id.to_owned(), view_id.to_owned());
        let Some(view) = self.views.lock().await.remove(&key) else {
            return;
        };
        if view.attachment_epoch == attachment_epoch {
            let _ = view
                .session_control
                .lock()
                .await
                .write_message(
                    &SessionControlMessage::Detach {
                        view_id: view_id.to_owned(),
                        attachment_epoch,
                    },
                    MAX_CONTROL_MESSAGE_BYTES,
                )
                .await;
        }
        view.state_cancel.send_replace(true);
    }

    pub async fn close_session(&self, session_id: &str) -> bool {
        let removed = self.replicas.write().await.remove(session_id).is_some();
        let views = self
            .views
            .lock()
            .await
            .iter()
            .filter(|((candidate, _), _)| candidate == session_id)
            .map(|((_, view_id), view)| (view_id.clone(), view.attachment_epoch))
            .collect::<Vec<_>>();
        for (view_id, epoch) in views {
            self.detach_view(session_id, &view_id, epoch).await;
        }
        removed
    }

    async fn remote_view(
        &self,
        session_id: &str,
        view_id: &str,
        attachment_epoch: u64,
    ) -> Result<Arc<RemoteView>> {
        let view = self
            .views
            .lock()
            .await
            .get(&(session_id.to_owned(), view_id.to_owned()))
            .cloned()
            .context("remote view is not attached")?;
        if view.attachment_epoch != attachment_epoch {
            bail!("stale remote view attachment");
        }
        Ok(view)
    }

    async fn remote_connection(&self, device_id: &str) -> Result<Arc<RemoteHostConnection>> {
        let mut connections = self.connections.lock().await;
        let ready = self.ready().await?;
        let advertisement = validated_advertisement(&ready, device_id).await?;
        if let Some(connection) = connections.get(device_id) {
            if connection_is_reusable(
                &connection.host_instance_id,
                connection.healthy.load(Ordering::Acquire),
                &advertisement.host_instance_id,
            ) {
                return Ok(Arc::clone(connection));
            }
            connection.connection.close();
            connections.remove(device_id);
        }
        let connection = Arc::new(
            tokio::time::timeout(
                CONNECT_TIMEOUT,
                ready.node.connect_quic(device_id, advertisement.quic_port),
            )
            .await
            .context("timed out connecting to remote terminal host")?
            .context("connect to remote terminal host")?,
        );
        let mut control = ProtocolStream::new(connection.open_stream().await?);
        control
            .write_preface(&StreamPreface {
                stream_kind: StreamKind::ConnectionControl,
                session_id: None,
                view_id: None,
            })
            .await?;
        let nonce = Uuid::new_v4().to_string();
        control
            .write_message(
                &ConnectionMessage::ClientHello {
                    protocol_major: PROTOCOL_MAJOR,
                    protocol_minor: PROTOCOL_MINOR,
                    host_instance_id: ready.host_instance_id,
                    local_device_id: ready.node.local_info().device_id,
                    nonce: nonce.clone(),
                    state_codecs: Some(vec![StateCodec::CompactJsonV1]),
                },
                MAX_CONTROL_MESSAGE_BYTES,
            )
            .await?;
        let state_codec = match tokio::time::timeout(
            HANDSHAKE_TIMEOUT,
            control.read_message::<ConnectionMessage>(MAX_CONTROL_MESSAGE_BYTES),
        )
        .await
        .context("timed out waiting for remote terminal handshake")??
        .context("remote host closed during handshake")?
        {
            ConnectionMessage::ServerHello {
                protocol_major,
                protocol_minor,
                host_instance_id,
                nonce: echoed_nonce,
                state_codec,
            } if protocol_major == PROTOCOL_MAJOR
                && protocol_minor > 0
                && echoed_nonce == nonce
                && host_instance_id == advertisement.host_instance_id
                && state_codec.is_none_or(|codec| codec == StateCodec::CompactJsonV1) =>
            {
                state_codec.unwrap_or(StateCodec::Json)
            }
            _ => bail!("remote host returned an invalid server hello"),
        };
        let remote = Arc::new(RemoteHostConnection {
            connection,
            control: tokio::sync::Mutex::new(control),
            incoming: tokio::sync::Mutex::new(()),
            host_instance_id: advertisement.host_instance_id,
            state_codec,
            healthy: AtomicBool::new(true),
        });
        connections.insert(device_id.to_owned(), Arc::clone(&remote));
        Ok(remote)
    }

    async fn invalidate_connection(
        &self,
        device_id: &str,
        expected: Option<&Arc<RemoteHostConnection>>,
    ) {
        let mut connections = self.connections.lock().await;
        let should_remove = connections
            .get(device_id)
            .is_some_and(|current| expected.is_none_or(|expected| Arc::ptr_eq(current, expected)));
        if should_remove && let Some(connection) = connections.remove(device_id) {
            connection.healthy.store(false, Ordering::Release);
            connection.connection.close();
        }
    }

    async fn ready(&self) -> Result<MeshReady> {
        self.ready
            .read()
            .await
            .clone()
            .context("Truffle terminal networking is disabled or still starting")
    }
}

async fn validated_advertisement(
    ready: &MeshReady,
    device_id: &str,
) -> Result<TerminalHostAdvertisement> {
    let advertisement = ready
        .store
        .get(device_id)
        .await
        .context("terminal host is not advertised")?
        .data;
    if advertisement.expires_at_ms < now_ms() {
        bail!("terminal host advertisement has expired");
    }
    if advertisement.protocol_major != PROTOCOL_MAJOR {
        bail!("remote terminal protocol major is incompatible");
    }
    if advertisement.protocol_minor == 0 {
        bail!("remote terminal protocol minor is invalid");
    }
    Ok(advertisement)
}

#[derive(Clone, Debug)]
/// Terminal-specific routing and authorization layered on a shared Truffle
/// node. Application identity, node state, and sidecar configuration belong to
/// the embedding host instead.
pub struct TruffleTerminalConfig {
    pub service_name: String,
    pub quic_port: u16,
    pub compact_port: u16,
    pub capability: Option<String>,
    pub allow_tailnet_write: bool,
}

impl Default for TruffleTerminalConfig {
    fn default() -> Self {
        Self {
            service_name: "terminal.v1".to_owned(),
            quic_port: DEFAULT_QUIC_PORT,
            compact_port: DEFAULT_COMPACT_PORT,
            capability: None,
            allow_tailnet_write: false,
        }
    }
}

impl TruffleTerminalConfig {
    fn validate(&self) -> Result<()> {
        if self.service_name.trim().is_empty() {
            bail!("Truffle terminal service name must not be empty");
        }
        if self.quic_port == 0 {
            bail!("Truffle terminal QUIC port must be nonzero");
        }
        if self.compact_port == 0 {
            bail!("Truffle terminal compact-stream port must be nonzero");
        }
        if self.compact_port == self.quic_port {
            bail!("Truffle terminal QUIC and compact-stream ports must differ");
        }
        Ok(())
    }

    fn access_for(&self, supplied: Option<&str>) -> ViewAccess {
        if self.allow_tailnet_write {
            return ViewAccess::ReadWrite;
        }
        let Some(expected) = self.capability.as_deref() else {
            return ViewAccess::ReadOnly;
        };
        let Some(supplied) = supplied else {
            return ViewAccess::ReadOnly;
        };
        if expected.len() == supplied.len()
            && bool::from(expected.as_bytes().ct_eq(supplied.as_bytes()))
        {
            ViewAccess::ReadWrite
        } else {
            ViewAccess::ReadOnly
        }
    }

    fn advertises_write(&self) -> bool {
        self.allow_tailnet_write || self.capability.is_some()
    }
}

/// A terminal transport adapter that borrows a host-owned Truffle node by
/// `Arc`. Its discovery store and QUIC listener are scoped to this terminal
/// service, while the node and sidecar remain shared with the host.
pub struct TruffleTerminalMesh {
    node: Arc<Node<TailscaleProvider>>,
    config: TruffleTerminalConfig,
    runtime: MeshRuntime,
}

impl TruffleTerminalMesh {
    pub fn new(node: Arc<Node<TailscaleProvider>>, config: TruffleTerminalConfig) -> Result<Self> {
        config.validate()?;
        Ok(Self {
            node,
            config,
            runtime: MeshRuntime::new(),
        })
    }

    pub fn runtime(&self) -> MeshRuntime {
        self.runtime.clone()
    }

    pub async fn serve(self, registry: Registry) -> Result<()> {
        let Self {
            node,
            config,
            runtime,
        } = self;
        let host_instance_id = Uuid::new_v4().to_string();
        let listener = Arc::new(
            node.listen_quic(config.quic_port)
                .await
                .context("listen for terminal QUIC connections")?,
        );
        let compact_listener = node
            .listen_tcp(config.compact_port)
            .await
            .context("listen for Apple terminal compact-stream connections")?;
        let store_id = format!("{}.hosts", config.service_name);
        let store_namespace = format!("ss:{store_id}");
        // Profiles keep a stable Truffle device ID, so persist the local store
        // version with it. Otherwise a restarted terminald begins again at
        // version 1 and a still-running peer rejects its advertisements as older
        // than the previous process's slice.
        let store = node.synced_store_with_backend::<TerminalHostAdvertisement>(
            &store_id,
            Arc::new(truffle::FileBackend::new(
                node.state_dir().join("synced-store"),
            )),
        );
        *runtime.ready.write().await = Some(MeshReady {
            node: Arc::clone(&node),
            store: Arc::clone(&store),
            host_instance_id: host_instance_id.clone(),
            capability: config.capability.clone(),
        });
        eprintln!(
            "[terminal-mesh] ready as {} on QUIC port {} and compact-stream port {}",
            node.local_info().device_name,
            listener.port(),
            compact_listener.port
        );

        let advertise = advertise_loop(
            Arc::clone(&node),
            Arc::clone(&store),
            registry.clone(),
            config.clone(),
            host_instance_id.clone(),
            store_namespace,
        );
        let accept = accept_loop(
            Arc::clone(&node),
            Arc::clone(&listener),
            registry.clone(),
            config.clone(),
            host_instance_id.clone(),
        );
        let compact_accept = compact_accept_loop(
            Arc::clone(&node),
            compact_listener,
            registry,
            config.clone(),
            host_instance_id,
        );
        let result = tokio::select! {
            result = advertise => result,
            result = accept => result,
            result = compact_accept => result,
        };
        if let Err(error) = node.unlisten_tcp(config.compact_port).await {
            eprintln!("[terminal-mesh] compact-stream listener cleanup failed: {error}");
        }
        runtime.connections.lock().await.clear();
        *runtime.ready.write().await = None;
        result
    }
}

async fn advertise_loop(
    node: Arc<Node<TailscaleProvider>>,
    store: Arc<HostStore>,
    registry: Registry,
    config: TruffleTerminalConfig,
    host_instance_id: String,
    store_namespace: String,
) -> Result<()> {
    let mut interval = tokio::time::interval(ADVERTISEMENT_INTERVAL);
    interval.set_missed_tick_behavior(MissedTickBehavior::Skip);
    loop {
        interval.tick().await;
        let now = now_ms();
        let sessions = registry
            .read()
            .unwrap()
            .values()
            .map(|session| {
                let summary = session.summary();
                SharedSessionSummary {
                    session_id: summary.id,
                    title: summary.title.unwrap_or_else(|| summary.executable.clone()),
                    cwd_label: summary.cwd,
                    running: !summary.exited,
                    attachable: true,
                    read_write: config.advertises_write(),
                    created_at_ms: session.created_at_ms(),
                    activity: summary.activity,
                }
            })
            .collect();
        store
            .set(TerminalHostAdvertisement {
                protocol_major: PROTOCOL_MAJOR,
                protocol_minor: PROTOCOL_MINOR,
                quic_port: config.quic_port,
                host_instance_id: host_instance_id.clone(),
                published_at_ms: now,
                expires_at_ms: now.saturating_add(ADVERTISEMENT_TTL.as_millis() as u64),
                sessions,
            })
            .await;

        // SyncedStore subscribes after Node startup. With durable Truffle
        // profiles, peer discovery can therefore finish before the store's
        // peer-event receiver exists, causing it to miss the one-time Joined
        // event that normally performs the initial full sync. A broadcast
        // alone cannot recover because it only targets message channels that
        // are already connected. Targeted requests both establish that
        // channel lazily and ask every known same-app peer for its latest
        // slice, making discovery converge after either side restarts.
        request_advertisements_from_online_peers(&node, &store_namespace).await;
    }
}

async fn request_advertisements_from_online_peers(
    node: &Node<TailscaleProvider>,
    store_namespace: &str,
) {
    let local_device_id = node.local_info().device_id;
    let request = truffle::SyncMessage::Request {};
    let Ok(payload) = serde_json::to_value(&request) else {
        return;
    };
    for peer in node.peers().await {
        let Some(device_id) = peer.device_id else {
            continue;
        };
        if !peer.online || device_id == local_device_id {
            continue;
        }
        if let Err(cause) = node
            .send_typed(&device_id, store_namespace, "request", &payload)
            .await
        {
            eprintln!(
                "[terminal-mesh] could not request advertisement from {}: {cause}",
                peer.display_name
            );
        }
    }
}

async fn compact_accept_loop(
    node: Arc<Node<TailscaleProvider>>,
    mut listener: truffle::transport::RawListener,
    registry: Registry,
    config: TruffleTerminalConfig,
    host_instance_id: String,
) -> Result<()> {
    while let Some(incoming) = listener.accept().await {
        let node = Arc::clone(&node);
        let registry = registry.clone();
        let config = config.clone();
        let host_instance_id = host_instance_id.clone();
        tokio::spawn(async move {
            if let Err(error) =
                handle_compact_connection(node, incoming, registry, config, host_instance_id).await
            {
                eprintln!("[terminal-mesh] rejected compact-stream connection: {error:#}");
            }
        });
    }
    Ok(())
}

async fn handle_compact_connection(
    node: Arc<Node<TailscaleProvider>>,
    incoming: truffle::transport::RawIncoming,
    registry: Registry,
    config: TruffleTerminalConfig,
    host_instance_id: String,
) -> Result<()> {
    let authenticated_node_id = incoming
        .remote_identity
        .as_ref()
        .and_then(|identity| identity.node_id.as_deref())
        .context("compact-stream source lacks a Tailscale WhoIs stable node ID")?;
    let peer = node
        .peers()
        .await
        .into_iter()
        .find(|peer| peer.tailscale_id == authenticated_node_id)
        .context("compact-stream source is not a current Truffle peer")?;
    let client_id = format!("truffle:{}", peer.peer_ref);
    handle_compact_protocol(
        incoming.stream,
        registry,
        config,
        host_instance_id,
        peer.device_id,
        client_id,
    )
    .await
}

async fn handle_compact_protocol<S>(
    stream: S,
    registry: Registry,
    config: TruffleTerminalConfig,
    host_instance_id: String,
    expected_device_id: Option<String>,
    client_id: String,
) -> Result<()>
where
    S: AsyncRead + AsyncWrite + Unpin + Send,
{
    let mut control = CompactProtocolStream::new(stream);
    let preface = tokio::time::timeout(HANDSHAKE_TIMEOUT, control.read_preface())
        .await
        .context("timed out reading compact-stream preface")??;
    let hello = tokio::time::timeout(
        HANDSHAKE_TIMEOUT,
        control.read_message::<ConnectionMessage>(MAX_CONTROL_MESSAGE_BYTES),
    )
    .await
    .context("timed out reading compact-stream client hello")??
    .context("compact stream closed before client hello")?;
    let (client_nonce, state_codec, protocol_minor) = match hello {
        ConnectionMessage::ClientHello {
            protocol_major,
            protocol_minor,
            local_device_id,
            nonce,
            state_codecs,
            ..
        } if protocol_major == PROTOCOL_MAJOR
            && protocol_minor > 0
            && !local_device_id.trim().is_empty()
            && expected_device_id
                .as_deref()
                .is_none_or(|expected| expected == local_device_id) =>
        {
            (
                nonce,
                negotiate_state_codec(state_codecs),
                protocol_minor.min(PROTOCOL_MINOR),
            )
        }
        ConnectionMessage::ClientHello { .. } => {
            bail!("compact-stream client hello identity or protocol mismatch")
        }
        _ => bail!("expected compact-stream client hello"),
    };
    control
        .write_message(
            &ConnectionMessage::ServerHello {
                protocol_major: PROTOCOL_MAJOR,
                protocol_minor: PROTOCOL_MINOR,
                host_instance_id,
                nonce: client_nonce,
                state_codec: (state_codec != StateCodec::Json).then_some(state_codec),
            },
            MAX_CONTROL_MESSAGE_BYTES,
        )
        .await?;

    match preface.stream_kind {
        StreamKind::ConnectionControl => {
            while let Some(message) = control
                .read_message::<ConnectionMessage>(MAX_CONTROL_MESSAGE_BYTES)
                .await?
            {
                match message {
                    ConnectionMessage::ListSessions { request_id } => {
                        control
                            .write_message(
                                &ConnectionMessage::Sessions {
                                    request_id,
                                    sessions: shared_sessions(&registry, &config),
                                },
                                MAX_CONTROL_MESSAGE_BYTES,
                            )
                            .await?;
                    }
                    _ => {
                        control
                            .write_message(
                                &ConnectionMessage::Error {
                                    request_id: None,
                                    code: "unexpected-message".into(),
                                    message:
                                        "message is not valid on the connection control stream"
                                            .into(),
                                },
                                MAX_CONTROL_MESSAGE_BYTES,
                            )
                            .await?;
                    }
                }
            }
        }
        StreamKind::SessionControl => {
            handle_compact_session_protocol(
                &mut control,
                preface,
                registry,
                config,
                client_id,
                state_codec,
                protocol_minor,
            )
            .await?;
        }
        _ => bail!("compact stream kind is not client-openable"),
    }
    Ok(())
}

async fn handle_compact_session_protocol<S>(
    control: &mut CompactProtocolStream<S>,
    preface: StreamPreface,
    registry: Registry,
    config: TruffleTerminalConfig,
    client_id: String,
    state_codec: StateCodec,
    protocol_minor: u16,
) -> Result<()>
where
    S: AsyncRead + AsyncWrite + Unpin + Send,
{
    let session_id = preface
        .session_id
        .context("compact session stream lacks session id")?;
    let attach = tokio::time::timeout(
        HANDSHAKE_TIMEOUT,
        control.read_compact_message::<SessionControlMessage>(
            CompactChannel::Control,
            MAX_CONTROL_MESSAGE_BYTES,
        ),
    )
    .await
    .context("timed out reading compact session attach")??
    .context("compact session stream closed before attach")?;
    let (request_id, view_id, access_token) = match attach {
        SessionControlMessage::AttachView {
            request_id,
            session_id: requested_session,
            view_id,
            access_token,
            ..
        } if requested_session == session_id => (request_id, view_id, access_token),
        _ => bail!("expected matching compact attach-view message"),
    };
    let session = registry
        .read()
        .unwrap()
        .get(&session_id)
        .cloned()
        .context("unknown shared terminal session")?;
    let access = config.access_for(access_token.as_deref());
    // Attaching already performs and publishes a full refresh; render the
    // state once before acknowledging the new compact view.
    let attachment_epoch = session
        .attach_view_with_access(&view_id, &client_id, access)
        .context("attach compact terminal view")?;
    let (_, canonical_cols, canonical_rows, layout_epoch) = session.control_state();
    control
        .write_compact_message(
            CompactChannel::Control,
            &SessionControlMessage::ViewAttached {
                request_id,
                session_epoch: session.session_epoch(),
                layout_epoch,
                attachment_epoch,
                cols: canonical_cols,
                rows: canonical_rows,
                read_write: access == ViewAccess::ReadWrite,
            },
            MAX_CONTROL_MESSAGE_BYTES,
        )
        .await
        .context("write compact view-attached response")?;

    let result = async {
        let mut controls = session.subscribe_control();
        let mut activities = session.subscribe_activity();
        let mut snapshots = session.subscribe_logical();
        let mut previous = session.logical_snapshot();
        let mut patch_sequence = 0_u64;
        if let Some(snapshot) = previous.as_ref() {
            control
                .write_compact_state_message(
                    &StateMessage::Snapshot(snapshot.clone()),
                    state_codec,
                )
                .await?;
        }
        let (controller, cols, rows, layout_epoch) = session.control_state();
        if let Some(controller) = controller {
            control
                .write_compact_state_message(
                    &StateMessage::ControlChanged {
                        controller_view_id: controller.view_id,
                        control_epoch: controller.control_epoch,
                        cols,
                        rows,
                        layout_epoch,
                    },
                    state_codec,
                )
                .await?;
        }
        if protocol_minor >= SESSION_ACTIVITY_PROTOCOL_MINOR {
            control
                .write_compact_state_message(
                    &StateMessage::ActivityChanged {
                        activity: session.summary().activity,
                    },
                    state_codec,
                )
                .await?;
        }

        loop {
            tokio::select! {
                incoming = control.read_compact_message::<SessionControlMessage>(
                    CompactChannel::Control,
                    MAX_CONTROL_MESSAGE_BYTES,
                ) => {
                    let Some(message) = incoming? else { break };
                    match message {
                        SessionControlMessage::FocusAndResize {
                            view_id: incoming_view,
                            attachment_epoch: epoch,
                            cols,
                            rows,
                            ..
                        } if incoming_view == view_id && epoch == attachment_epoch => {
                            session.claim_control(&view_id, &client_id, cols, rows)?;
                        }
                        SessionControlMessage::Resize {
                            view_id: incoming_view,
                            attachment_epoch: epoch,
                            control_epoch,
                            resize_sequence,
                            cols,
                            rows,
                        } if incoming_view == view_id && epoch == attachment_epoch => {
                            if session.resize_view(
                                &view_id,
                                &client_id,
                                control_epoch,
                                resize_sequence,
                                cols,
                                rows,
                            ).is_err() {
                                session.announce_control();
                            }
                        }
                        SessionControlMessage::Input {
                            view_id: incoming_view,
                            attachment_epoch: epoch,
                            input_sequence,
                            operation,
                        } if incoming_view == view_id && epoch == attachment_epoch => match operation {
                            TunnelInput::Text(text) => session.send_text(
                                &view_id, &client_id, attachment_epoch, input_sequence, text,
                            )?,
                            TunnelInput::Paste(text) => session.paste(
                                &view_id, &client_id, attachment_epoch, input_sequence, text,
                            )?,
                            TunnelInput::Key(input) => session.key(
                                &view_id, &client_id, attachment_epoch, input_sequence, input,
                            )?,
                            TunnelInput::Mouse(input) => session.mouse(
                                &view_id, &client_id, attachment_epoch, input_sequence, input,
                            )?,
                            TunnelInput::Scroll(rows) => session.scroll(
                                &view_id,
                                &client_id,
                                attachment_epoch,
                                input_sequence,
                                isize::try_from(rows.clamp(-10_000, 10_000))?,
                            )?,
                            TunnelInput::ScrollTo(row) => session.scroll_to(
                                &view_id,
                                &client_id,
                                attachment_epoch,
                                input_sequence,
                                usize::try_from(row)?,
                            )?,
                            TunnelInput::Focus(focused) => session.focus(
                                &view_id, &client_id, attachment_epoch, input_sequence, focused,
                            )?,
                            TunnelInput::Interrupt => session.interrupt(
                                &view_id, &client_id, attachment_epoch, input_sequence,
                            )?,
                        },
                        SessionControlMessage::RequestSnapshot => {
                            let snapshot = session
                                .logical_snapshot()
                                .context("shared terminal has no logical snapshot")?;
                            previous = Some(snapshot.clone());
                            patch_sequence = 0;
                            control.write_compact_state_message(
                                &StateMessage::Snapshot(snapshot),
                                state_codec,
                            ).await?;
                        }
                        SessionControlMessage::StateAck { .. } => {}
                        SessionControlMessage::SelectionText {
                            request_id,
                            view_id: incoming_view,
                            attachment_epoch: epoch,
                            start_column,
                            start_row,
                            end_column,
                            end_row,
                            select_all,
                        } if incoming_view == view_id && epoch == attachment_epoch => {
                            let text = session.selection_text(
                                start_column,
                                start_row,
                                end_column,
                                end_row,
                                select_all,
                            )?;
                            control.write_compact_message(
                                CompactChannel::Control,
                                &SessionControlMessage::SelectionTextResult { request_id, text },
                                MAX_CONTROL_MESSAGE_BYTES,
                            ).await?;
                        }
                        SessionControlMessage::Detach {
                            view_id: incoming_view,
                            attachment_epoch: epoch,
                        } if incoming_view == view_id && epoch == attachment_epoch => break,
                        _ => bail!("invalid, stale, or misrouted compact session message"),
                    }
                }
                snapshot = snapshots.recv() => {
                    let message = match snapshot {
                        Ok(snapshot) => {
                            let next_sequence = patch_sequence.saturating_add(1);
                            let message = previous
                                .as_ref()
                                .and_then(|previous| logical_patch(previous, &snapshot, next_sequence))
                                .map(StateMessage::Patch)
                                .unwrap_or_else(|| StateMessage::Snapshot(snapshot.clone()));
                            if matches!(message, StateMessage::Patch(_)) {
                                patch_sequence = next_sequence;
                            } else {
                                patch_sequence = 0;
                            }
                            previous = Some(snapshot);
                            message
                        }
                        Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
                            let snapshot = session
                                .logical_snapshot()
                                .context("shared terminal has no logical snapshot after lag")?;
                            previous = Some(snapshot.clone());
                            patch_sequence = 0;
                            StateMessage::Snapshot(snapshot)
                        }
                        Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
                    };
                    control.write_compact_state_message(
                        &message,
                        state_codec,
                    ).await?;
                }
                changed = controls.recv() => {
                    let changed = match changed {
                        Ok(changed) => changed,
                        Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
                            session.announce_control();
                            continue;
                        }
                        Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
                    };
                    control.write_compact_state_message(
                        &StateMessage::ControlChanged {
                            controller_view_id: changed.controller.view_id,
                            control_epoch: changed.controller.control_epoch,
                            cols: changed.cols,
                            rows: changed.rows,
                            layout_epoch: changed.layout_epoch,
                        },
                        state_codec,
                    ).await?;
                }
                changed = activities.recv(), if protocol_minor >= SESSION_ACTIVITY_PROTOCOL_MINOR => {
                    let activity = match changed {
                        Ok(activity) => activity,
                        Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
                            session.announce_activity();
                            continue;
                        }
                        Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
                    };
                    control.write_compact_state_message(
                        &StateMessage::ActivityChanged { activity },
                        state_codec,
                    ).await?;
                }
            }
        }
        Ok(())
    }
    .await;
    session.detach_view(&view_id, &client_id);
    result
}

async fn accept_loop(
    node: Arc<Node<TailscaleProvider>>,
    listener: Arc<truffle::transport::quic::QuicListener>,
    registry: Registry,
    config: TruffleTerminalConfig,
    host_instance_id: String,
) -> Result<()> {
    while let Some(connection) = listener.accept().await {
        let node = Arc::clone(&node);
        let registry = registry.clone();
        let config = config.clone();
        let host_instance_id = host_instance_id.clone();
        tokio::spawn(async move {
            if let Err(error) = handle_connection(
                node,
                Arc::new(connection),
                registry,
                config,
                host_instance_id,
            )
            .await
            {
                eprintln!("[terminal-mesh] rejected connection: {error:#}");
            }
        });
    }
    Ok(())
}

async fn handle_connection(
    node: Arc<Node<TailscaleProvider>>,
    connection: Arc<truffle::transport::quic::QuicConnection>,
    registry: Registry,
    config: TruffleTerminalConfig,
    host_instance_id: String,
) -> Result<()> {
    let remote_ip = connection.remote_address().ip();
    let peer = node
        .peers()
        .await
        .into_iter()
        .find(|peer| peer.ip == remote_ip)
        .context("QUIC source is not a current Truffle peer")?;
    let expected_device_id = peer
        .device_id
        .clone()
        .context("peer identity has not completed its eager hello")?;
    let client_id = format!("truffle:{}", peer.peer_ref);

    let stream = tokio::time::timeout(HANDSHAKE_TIMEOUT, connection.accept_stream())
        .await
        .context("timed out accepting connection control stream")?
        .context("accept connection control stream")?
        .context("connection closed before control handshake")?;
    let mut control = ProtocolStream::new(stream);
    let preface = tokio::time::timeout(HANDSHAKE_TIMEOUT, control.read_preface())
        .await
        .context("timed out reading connection control preface")??;
    if preface.stream_kind != StreamKind::ConnectionControl {
        bail!("first stream is not connection-control");
    }
    let hello = tokio::time::timeout(
        HANDSHAKE_TIMEOUT,
        control.read_message::<ConnectionMessage>(MAX_CONTROL_MESSAGE_BYTES),
    )
    .await
    .context("timed out reading client hello")??
    .context("connection closed before client hello")?;
    let (client_nonce, state_codec, protocol_minor) = match hello {
        ConnectionMessage::ClientHello {
            protocol_major,
            protocol_minor,
            local_device_id,
            nonce,
            state_codecs,
            ..
        } if protocol_major == PROTOCOL_MAJOR
            && protocol_minor > 0
            && local_device_id == expected_device_id =>
        {
            let state_codec = negotiate_state_codec(state_codecs);
            (nonce, state_codec, protocol_minor.min(PROTOCOL_MINOR))
        }
        ConnectionMessage::ClientHello { .. } => {
            bail!("client hello identity or protocol mismatch")
        }
        _ => bail!("expected client hello"),
    };
    control
        .write_message(
            &ConnectionMessage::ServerHello {
                protocol_major: PROTOCOL_MAJOR,
                protocol_minor: PROTOCOL_MINOR,
                host_instance_id,
                nonce: client_nonce,
                state_codec: (state_codec != StateCodec::Json).then_some(state_codec),
            },
            MAX_CONTROL_MESSAGE_BYTES,
        )
        .await?;

    let streams_connection = Arc::clone(&connection);
    let streams_registry = registry.clone();
    let streams_config = config.clone();
    let streams_client_id = client_id.clone();
    let streams_state_codec = state_codec;
    let streams = tokio::spawn(async move {
        while let Some(stream) = streams_connection.accept_stream().await? {
            let registry = streams_registry.clone();
            let config = streams_config.clone();
            let client_id = streams_client_id.clone();
            let state_codec = streams_state_codec;
            let protocol_minor = protocol_minor;
            let connection = Arc::clone(&streams_connection);
            tokio::spawn(async move {
                if let Err(error) = handle_application_stream(
                    connection,
                    stream,
                    registry,
                    config,
                    client_id,
                    state_codec,
                    protocol_minor,
                )
                .await
                {
                    eprintln!("[terminal-mesh] stream closed: {error:#}");
                }
            });
        }
        Ok::<(), anyhow::Error>(())
    });

    while let Some(message) = control
        .read_message::<ConnectionMessage>(MAX_CONTROL_MESSAGE_BYTES)
        .await?
    {
        match message {
            ConnectionMessage::ListSessions { request_id } => {
                let sessions = shared_sessions(&registry, &config);
                control
                    .write_message(
                        &ConnectionMessage::Sessions {
                            request_id,
                            sessions,
                        },
                        MAX_CONTROL_MESSAGE_BYTES,
                    )
                    .await?;
            }
            _ => {
                control
                    .write_message(
                        &ConnectionMessage::Error {
                            request_id: None,
                            code: "unexpected-message".into(),
                            message: "message is not valid on the connection control stream".into(),
                        },
                        MAX_CONTROL_MESSAGE_BYTES,
                    )
                    .await?;
            }
        }
    }
    streams.abort();
    connection.close();
    Ok(())
}

async fn handle_application_stream(
    connection: Arc<truffle::transport::quic::QuicConnection>,
    stream: QuicStream,
    registry: Registry,
    config: TruffleTerminalConfig,
    client_id: String,
    state_codec: StateCodec,
    protocol_minor: u16,
) -> Result<()> {
    let mut control = ProtocolStream::new(stream);
    let preface = control.read_preface().await?;
    if preface.stream_kind != StreamKind::SessionControl {
        bail!("peer-opened stream kind is not supported");
    }
    let session_id = preface
        .session_id
        .context("session control stream lacks session id")?;
    let attach = tokio::time::timeout(
        HANDSHAKE_TIMEOUT,
        control.read_message::<SessionControlMessage>(MAX_CONTROL_MESSAGE_BYTES),
    )
    .await
    .context("timed out reading session attach")??
    .context("session stream closed before attach")?;
    let (request_id, view_id, access_token, _cols, _rows) = match attach {
        SessionControlMessage::AttachView {
            request_id,
            session_id: requested_session,
            view_id,
            access_token,
            cols,
            rows,
        } if requested_session == session_id => (request_id, view_id, access_token, cols, rows),
        _ => bail!("expected matching attach-view message"),
    };
    let session = registry
        .read()
        .unwrap()
        .get(&session_id)
        .cloned()
        .context("unknown shared terminal session")?;
    let access = config.access_for(access_token.as_deref());
    let attachment_epoch = session.attach_view_with_access(&view_id, &client_id, access)?;
    session.refresh()?;
    let (_, canonical_cols, canonical_rows, layout_epoch) = session.control_state();
    control
        .write_message(
            &SessionControlMessage::ViewAttached {
                request_id,
                session_epoch: session.session_epoch(),
                layout_epoch,
                attachment_epoch,
                cols: canonical_cols,
                rows: canonical_rows,
                read_write: access == ViewAccess::ReadWrite,
            },
            MAX_CONTROL_MESSAGE_BYTES,
        )
        .await?;
    let (state_cancel, state_cancelled) = tokio::sync::watch::channel(false);
    spawn_state_stream(
        Arc::clone(&connection),
        Arc::clone(&session),
        &view_id,
        state_cancelled.clone(),
        state_codec,
        protocol_minor,
    )
    .await?;

    let result = session_control_loop(
        &mut control,
        Arc::clone(&connection),
        Arc::clone(&session),
        &client_id,
        &view_id,
        attachment_epoch,
        StateStreamContext {
            cancelled: state_cancelled,
            codec: state_codec,
            protocol_minor,
        },
    )
    .await;
    state_cancel.send_replace(true);
    session.detach_view(&view_id, &client_id);
    result
}

struct StateStreamContext {
    cancelled: tokio::sync::watch::Receiver<bool>,
    codec: StateCodec,
    protocol_minor: u16,
}

async fn session_control_loop(
    control: &mut ProtocolStream,
    connection: Arc<truffle::transport::quic::QuicConnection>,
    session: Arc<Session>,
    client_id: &str,
    attached_view_id: &str,
    attachment_epoch: u64,
    state_stream: StateStreamContext,
) -> Result<()> {
    while let Some(message) = control
        .read_message::<SessionControlMessage>(MAX_CONTROL_MESSAGE_BYTES)
        .await?
    {
        match message {
            SessionControlMessage::FocusAndResize {
                view_id,
                attachment_epoch: epoch,
                cols,
                rows,
                ..
            } if view_id == attached_view_id && epoch == attachment_epoch => {
                session.claim_control(&view_id, client_id, cols, rows)?;
            }
            SessionControlMessage::Resize {
                view_id,
                attachment_epoch: epoch,
                control_epoch,
                resize_sequence,
                cols,
                rows,
            } if view_id == attached_view_id && epoch == attachment_epoch => {
                if session
                    .resize_view(
                        &view_id,
                        client_id,
                        control_epoch,
                        resize_sequence,
                        cols,
                        rows,
                    )
                    .is_err()
                {
                    session.announce_control();
                }
            }
            SessionControlMessage::Input {
                view_id,
                attachment_epoch: epoch,
                input_sequence,
                operation,
            } if view_id == attached_view_id && epoch == attachment_epoch => match operation {
                TunnelInput::Text(text) => session.send_text(
                    &view_id,
                    client_id,
                    attachment_epoch,
                    input_sequence,
                    text,
                )?,
                TunnelInput::Paste(text) => {
                    session.paste(&view_id, client_id, attachment_epoch, input_sequence, text)?
                }
                TunnelInput::Key(input) => {
                    session.key(&view_id, client_id, attachment_epoch, input_sequence, input)?
                }
                TunnelInput::Mouse(input) => {
                    session.mouse(&view_id, client_id, attachment_epoch, input_sequence, input)?
                }
                TunnelInput::Scroll(rows) => session.scroll(
                    &view_id,
                    client_id,
                    attachment_epoch,
                    input_sequence,
                    isize::try_from(rows.clamp(-10_000, 10_000))?,
                )?,
                TunnelInput::ScrollTo(row) => session.scroll_to(
                    &view_id,
                    client_id,
                    attachment_epoch,
                    input_sequence,
                    usize::try_from(row)?,
                )?,
                TunnelInput::Focus(focused) => session.focus(
                    &view_id,
                    client_id,
                    attachment_epoch,
                    input_sequence,
                    focused,
                )?,
                TunnelInput::Interrupt => {
                    session.interrupt(&view_id, client_id, attachment_epoch, input_sequence)?
                }
            },
            SessionControlMessage::RequestSnapshot => {
                spawn_state_stream(
                    Arc::clone(&connection),
                    Arc::clone(&session),
                    attached_view_id,
                    state_stream.cancelled.clone(),
                    state_stream.codec,
                    state_stream.protocol_minor,
                )
                .await?;
            }
            SessionControlMessage::StateAck { .. } => {}
            SessionControlMessage::SelectionText {
                request_id,
                view_id,
                attachment_epoch: epoch,
                start_column,
                start_row,
                end_column,
                end_row,
                select_all,
            } if view_id == attached_view_id && epoch == attachment_epoch => {
                let text = session.selection_text(
                    start_column,
                    start_row,
                    end_column,
                    end_row,
                    select_all,
                )?;
                control
                    .write_message(
                        &SessionControlMessage::SelectionTextResult { request_id, text },
                        MAX_CONTROL_MESSAGE_BYTES,
                    )
                    .await?;
            }
            SessionControlMessage::Detach {
                view_id,
                attachment_epoch: epoch,
            } if view_id == attached_view_id && epoch == attachment_epoch => break,
            _ => bail!("invalid, stale, or misrouted session control message"),
        }
    }
    Ok(())
}

async fn spawn_state_stream(
    connection: Arc<truffle::transport::quic::QuicConnection>,
    session: Arc<Session>,
    view_id: &str,
    mut cancelled: tokio::sync::watch::Receiver<bool>,
    state_codec: StateCodec,
    protocol_minor: u16,
) -> Result<()> {
    let stream = connection.open_stream().await?;
    let mut state = ProtocolStream::new(stream);
    state
        .write_preface(&StreamPreface {
            stream_kind: StreamKind::LiveState,
            session_id: Some(session.id()),
            view_id: Some(view_id.to_owned()),
        })
        .await?;
    let mut controls = session.subscribe_control();
    let mut activities = session.subscribe_activity();
    let mut snapshots = session.subscribe_logical();
    let mut previous = session.logical_snapshot();
    if let Some(snapshot) = previous.as_ref() {
        state
            .write_state_message(&StateMessage::Snapshot(snapshot.clone()), state_codec)
            .await?;
    }
    let (controller, cols, rows, layout_epoch) = session.control_state();
    if let Some(controller) = controller {
        state
            .write_state_message(
                &StateMessage::ControlChanged {
                    controller_view_id: controller.view_id,
                    control_epoch: controller.control_epoch,
                    cols,
                    rows,
                    layout_epoch,
                },
                state_codec,
            )
            .await?;
    }
    if protocol_minor >= SESSION_ACTIVITY_PROTOCOL_MINOR {
        state
            .write_state_message(
                &StateMessage::ActivityChanged {
                    activity: session.summary().activity,
                },
                state_codec,
            )
            .await?;
    }
    tokio::spawn(async move {
        let mut patch_sequence = 0_u64;
        loop {
            let message = tokio::select! {
                changed = cancelled.changed() => {
                    if changed.is_err() || *cancelled.borrow() {
                        break;
                    }
                    continue;
                },
                snapshot = snapshots.recv() => match snapshot {
                    Ok(snapshot) => {
                        let next_sequence = patch_sequence.saturating_add(1);
                        let message = previous
                            .as_ref()
                            .and_then(|previous| logical_patch(previous, &snapshot, next_sequence))
                            .map(StateMessage::Patch)
                            .unwrap_or_else(|| StateMessage::Snapshot(snapshot.clone()));
                        if matches!(message, StateMessage::Patch(_)) {
                            patch_sequence = next_sequence;
                        } else {
                            patch_sequence = 0;
                        }
                        previous = Some(snapshot);
                        Some(message)
                    }
                    Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
                    Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
                },
                changed = controls.recv() => match changed {
                    Ok(changed) => Some(StateMessage::ControlChanged {
                        controller_view_id: changed.controller.view_id,
                        control_epoch: changed.controller.control_epoch,
                        cols: changed.cols,
                        rows: changed.rows,
                        layout_epoch: changed.layout_epoch,
                    }),
                    Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
                    Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
                },
                changed = activities.recv(), if protocol_minor >= SESSION_ACTIVITY_PROTOCOL_MINOR => match changed {
                    Ok(activity) => Some(StateMessage::ActivityChanged { activity }),
                    Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
                        session.announce_activity();
                        continue;
                    }
                    Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
                },
            };
            if let Some(message) = message
                && state
                    .write_state_message(&message, state_codec)
                    .await
                    .is_err()
            {
                break;
            }
        }
    });
    Ok(())
}

fn logical_patch(
    previous: &LogicalTerminalSnapshot,
    current: &LogicalTerminalSnapshot,
    patch_sequence: u64,
) -> Option<LogicalTerminalPatch> {
    if previous.session_epoch != current.session_epoch
        || previous.layout_epoch != current.layout_epoch
        || previous.cols != current.cols
        || previous.rows.len() != current.rows.len()
        || previous.title != current.title
        || previous.cwd != current.cwd
        || current.terminal_revision <= previous.terminal_revision
    {
        return None;
    }
    let row_replacements = previous
        .rows
        .iter()
        .zip(&current.rows)
        .enumerate()
        .filter_map(|(index, (old, new))| {
            if old == new {
                return None;
            }
            Some(RowReplacement {
                row_index: u16::try_from(index).ok()?,
                row_revision: current.terminal_revision,
                row: new.clone(),
            })
        })
        .collect::<Vec<_>>();
    Some(LogicalTerminalPatch {
        session_epoch: current.session_epoch,
        layout_epoch: current.layout_epoch,
        patch_sequence,
        terminal_revision: current.terminal_revision,
        row_replacements,
        cursor: (previous.cursor != current.cursor).then_some(current.cursor),
        mouse_tracking: (previous.mouse_tracking != current.mouse_tracking)
            .then_some(current.mouse_tracking),
        scrollbar: (previous.scrollbar != current.scrollbar).then_some(current.scrollbar),
    })
}

fn shared_sessions(
    registry: &Registry,
    config: &TruffleTerminalConfig,
) -> Vec<SharedSessionSummary> {
    registry
        .read()
        .unwrap()
        .values()
        .map(|session| {
            let summary = session.summary();
            SharedSessionSummary {
                session_id: summary.id,
                title: summary.title.unwrap_or_else(|| summary.executable.clone()),
                cwd_label: summary.cwd,
                running: !summary.exited,
                attachable: true,
                read_write: config.advertises_write(),
                created_at_ms: session.created_at_ms(),
                activity: summary.activity,
            }
        })
        .collect()
}

fn now_ms() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis() as u64
}

#[derive(Default)]
struct ReadBuffer {
    bytes: Vec<u8>,
    start: usize,
}

impl ReadBuffer {
    fn available(&self) -> usize {
        self.bytes.len() - self.start
    }

    fn unread(&self, length: usize) -> &[u8] {
        &self.bytes[self.start..self.start + length]
    }

    fn consume(&mut self, length: usize) {
        self.start += length;
        if self.start == self.bytes.len() {
            self.bytes.clear();
            self.start = 0;
        }
    }

    fn compact(&mut self) {
        if self.start == 0 {
            return;
        }
        self.bytes.copy_within(self.start.., 0);
        self.bytes.truncate(self.available());
        self.start = 0;
    }

    fn append(&mut self, chunk: Vec<u8>) {
        if self.available() == 0 {
            self.bytes = chunk;
            self.start = 0;
            return;
        }
        self.compact();
        self.bytes.extend_from_slice(&chunk);
    }
}

struct CompactProtocolStream<S> {
    stream: S,
    buffered: ReadBuffer,
}

impl<S> CompactProtocolStream<S>
where
    S: AsyncRead + AsyncWrite + Unpin,
{
    fn new(stream: S) -> Self {
        Self {
            stream,
            buffered: ReadBuffer::default(),
        }
    }

    #[cfg(test)]
    async fn write_preface(&mut self, preface: &StreamPreface) -> Result<()> {
        self.stream.write_all(&encode_preface(preface)?).await?;
        Ok(())
    }

    async fn read_preface(&mut self) -> Result<StreamPreface> {
        if !self.fill(16).await? {
            bail!("EOF before compact-stream preface");
        }
        let metadata_len =
            u32::from_be_bytes(self.buffered.unread(16)[12..16].try_into().unwrap()) as usize;
        if metadata_len > ghosttea::tunnel_protocol::MAX_PREFACE_METADATA_BYTES {
            bail!("compact-stream preface metadata exceeds limit");
        }
        let total = 16 + metadata_len;
        if !self.fill(total).await? {
            bail!("EOF in compact-stream preface metadata");
        }
        let preface = decode_preface(self.buffered.unread(total))?.0;
        self.buffered.consume(total);
        Ok(preface)
    }

    async fn write_message<T: serde::Serialize>(
        &mut self,
        message: &T,
        limit: usize,
    ) -> Result<()> {
        self.stream
            .write_all(&encode_message(message, limit)?)
            .await?;
        Ok(())
    }

    async fn read_message<T: serde::de::DeserializeOwned>(
        &mut self,
        limit: usize,
    ) -> Result<Option<T>> {
        if !self.fill(4).await? {
            return Ok(None);
        }
        let payload_len =
            u32::from_be_bytes(self.buffered.unread(4)[..4].try_into().unwrap()) as usize;
        if payload_len > limit {
            bail!("compact-stream terminal protocol message exceeds limit");
        }
        let total = 4 + payload_len;
        if !self.fill(total).await? {
            bail!("EOF in compact-stream terminal protocol message");
        }
        let message = decode_message(self.buffered.unread(total), limit)?.0;
        self.buffered.consume(total);
        Ok(Some(message))
    }

    async fn write_compact_message<T: serde::Serialize>(
        &mut self,
        channel: CompactChannel,
        message: &T,
        limit: usize,
    ) -> Result<()> {
        self.stream
            .write_all(&encode_compact_message(channel, message, limit)?)
            .await?;
        Ok(())
    }

    async fn write_compact_state_message(
        &mut self,
        message: &StateMessage,
        codec: StateCodec,
    ) -> Result<()> {
        let encoded = encode_state_message(message, codec, MAX_STATE_MESSAGE_BYTES)?;
        let payload = &encoded[4..];
        let framed_len = payload
            .len()
            .checked_add(1)
            .context("compact state message length overflow")?;
        let mut framed = Vec::with_capacity(4 + framed_len);
        framed.extend_from_slice(&u32::try_from(framed_len)?.to_be_bytes());
        framed.push(CompactChannel::State.as_byte());
        framed.extend_from_slice(payload);
        self.stream.write_all(&framed).await?;
        Ok(())
    }

    async fn read_compact_message<T: serde::de::DeserializeOwned>(
        &mut self,
        expected_channel: CompactChannel,
        limit: usize,
    ) -> Result<Option<T>> {
        if !self.fill(4).await? {
            return Ok(None);
        }
        let framed_len =
            u32::from_be_bytes(self.buffered.unread(4)[..4].try_into().unwrap()) as usize;
        if framed_len == 0 || framed_len - 1 > limit {
            bail!("compact terminal message exceeds limit");
        }
        let total = 4 + framed_len;
        if !self.fill(total).await? {
            bail!("EOF in compact terminal protocol message");
        }
        let message =
            decode_compact_message(self.buffered.unread(total), expected_channel, limit)?.0;
        self.buffered.consume(total);
        Ok(Some(message))
    }

    async fn fill(&mut self, length: usize) -> Result<bool> {
        while self.buffered.available() < length {
            self.buffered.compact();
            self.buffered.bytes.reserve(64 * 1024);
            let read = self.stream.read_buf(&mut self.buffered.bytes).await?;
            if read == 0 {
                if self.buffered.available() == 0 {
                    return Ok(false);
                }
                bail!("truncated compact terminal stream");
            }
        }
        Ok(true)
    }
}

struct ProtocolStream {
    stream: QuicStream,
    buffered: ReadBuffer,
}

impl ProtocolStream {
    fn new(stream: QuicStream) -> Self {
        Self {
            stream,
            buffered: ReadBuffer::default(),
        }
    }

    async fn write_preface(&mut self, preface: &StreamPreface) -> Result<()> {
        self.stream.write(&encode_preface(preface)?).await?;
        Ok(())
    }

    async fn read_preface(&mut self) -> Result<StreamPreface> {
        if !self.fill(16).await? {
            bail!("EOF before stream preface");
        }
        let metadata_len =
            u32::from_be_bytes(self.buffered.unread(16)[12..16].try_into().unwrap()) as usize;
        if metadata_len > ghosttea::tunnel_protocol::MAX_PREFACE_METADATA_BYTES {
            bail!("stream preface metadata exceeds limit");
        }
        let total = 16 + metadata_len;
        if !self.fill(total).await? {
            bail!("EOF in stream preface metadata");
        }
        let preface = decode_preface(self.buffered.unread(total))?.0;
        self.buffered.consume(total);
        Ok(preface)
    }

    async fn write_message<T: serde::Serialize>(
        &mut self,
        message: &T,
        limit: usize,
    ) -> Result<()> {
        self.stream.write(&encode_message(message, limit)?).await?;
        Ok(())
    }

    async fn write_state_message(
        &mut self,
        message: &StateMessage,
        codec: StateCodec,
    ) -> Result<()> {
        self.stream
            .write(&encode_state_message(
                message,
                codec,
                MAX_STATE_MESSAGE_BYTES,
            )?)
            .await?;
        Ok(())
    }

    async fn read_message<T: serde::de::DeserializeOwned>(
        &mut self,
        limit: usize,
    ) -> Result<Option<T>> {
        if !self.fill(4).await? {
            return Ok(None);
        }
        let payload_len =
            u32::from_be_bytes(self.buffered.unread(4)[..4].try_into().unwrap()) as usize;
        if payload_len > limit {
            bail!("terminal protocol message exceeds limit");
        }
        let total = 4 + payload_len;
        if !self.fill(total).await? {
            bail!("EOF in terminal protocol message");
        }
        let message = decode_message(self.buffered.unread(total), limit)?.0;
        self.buffered.consume(total);
        Ok(Some(message))
    }

    async fn read_state_message(&mut self, codec: StateCodec) -> Result<Option<StateMessage>> {
        if !self.fill(4).await? {
            return Ok(None);
        }
        let payload_len =
            u32::from_be_bytes(self.buffered.unread(4)[..4].try_into().unwrap()) as usize;
        if payload_len > MAX_STATE_MESSAGE_BYTES {
            bail!("terminal protocol state message exceeds limit");
        }
        let total = 4 + payload_len;
        if !self.fill(total).await? {
            bail!("EOF in terminal protocol state message");
        }
        let message =
            decode_state_message(self.buffered.unread(total), codec, MAX_STATE_MESSAGE_BYTES)?.0;
        self.buffered.consume(total);
        Ok(Some(message))
    }

    async fn fill(&mut self, length: usize) -> Result<bool> {
        while self.buffered.available() < length {
            match self.stream.read(64 * 1024).await? {
                Some(chunk) => self.buffered.append(chunk),
                None if self.buffered.available() == 0 => return Ok(false),
                None => bail!("truncated QUIC stream"),
            }
        }
        Ok(true)
    }
}

#[async_trait]
impl RemoteTerminalRuntime for MeshRuntime {
    fn subscribe_control(&self) -> broadcast::Receiver<RemoteControlChanged> {
        self.control_tx.subscribe()
    }

    fn subscribe_activity(&self) -> broadcast::Receiver<RemoteActivityChanged> {
        self.activity_tx.subscribe()
    }

    async fn hosts(&self) -> Result<Vec<RemoteHostSummary>> {
        MeshRuntime::hosts(self).await
    }

    async fn list_sessions(&self, device_id: &str) -> Result<Vec<SharedSessionSummary>> {
        MeshRuntime::list_sessions(self, device_id).await
    }

    async fn open_session(&self, request: RemoteSessionOpen) -> Result<SessionSummary> {
        MeshRuntime::open_session(self, request).await
    }

    async fn summaries(&self) -> Vec<SessionSummary> {
        MeshRuntime::summaries(self).await
    }

    async fn summary(&self, session_id: &str) -> Option<SessionSummary> {
        MeshRuntime::summary(self, session_id).await
    }

    async fn attach_view(&self, session_id: &str, view_id: &str) -> Result<RemoteAttachment> {
        MeshRuntime::attach_view(self, session_id, view_id).await
    }

    async fn send_input(
        &self,
        session_id: &str,
        view_id: &str,
        attachment_epoch: u64,
        input_sequence: u64,
        operation: TunnelInput,
    ) -> Result<()> {
        MeshRuntime::send_input(
            self,
            session_id,
            view_id,
            attachment_epoch,
            input_sequence,
            operation,
        )
        .await
    }

    async fn claim_control(
        &self,
        session_id: &str,
        view_id: &str,
        attachment_epoch: u64,
        cols: u16,
        rows: u16,
    ) -> Result<RemoteControlClaim> {
        MeshRuntime::claim_control(self, session_id, view_id, attachment_epoch, cols, rows).await
    }

    async fn resize(&self, session_id: &str, view_id: &str, request: RemoteResize) -> Result<()> {
        MeshRuntime::resize(self, session_id, view_id, request).await
    }

    async fn selection_text(
        &self,
        session_id: &str,
        view_id: &str,
        request: RemoteSelection,
    ) -> Result<String> {
        MeshRuntime::selection_text(self, session_id, view_id, request).await
    }

    async fn refresh(&self, session_id: &str) -> Result<()> {
        MeshRuntime::refresh(self, session_id).await
    }

    async fn detach_view(&self, session_id: &str, view_id: &str, attachment_epoch: u64) {
        MeshRuntime::detach_view(self, session_id, view_id, attachment_epoch).await;
    }

    async fn close_session(&self, session_id: &str) -> bool {
        MeshRuntime::close_session(self, session_id).await
    }
}

#[async_trait]
impl TerminalMesh for TruffleTerminalMesh {
    fn runtime(&self) -> Arc<dyn RemoteTerminalRuntime> {
        Arc::new(self.runtime())
    }

    async fn serve(self: Box<Self>, registry: Registry) -> Result<()> {
        TruffleTerminalMesh::serve(*self, registry).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn logical_snapshot(revision: u64, text: &str) -> LogicalTerminalSnapshot {
        LogicalTerminalSnapshot {
            session_epoch: 1,
            layout_epoch: 2,
            terminal_revision: revision,
            cols: 80,
            rows: vec![ghosttea::tunnel_protocol::LogicalRow {
                text: text.into(),
                cells: vec![],
            }],
            cursor: ghosttea::tunnel_protocol::LogicalCursor::default(),
            mouse_tracking: false,
            scrollbar: ghosttea::tunnel_protocol::LogicalScrollbar::default(),
            title: Some("terminal".into()),
            cwd: Some("/tmp".into()),
        }
    }

    #[test]
    fn terminal_access_policy_requires_an_explicit_write_grant() {
        let config = TruffleTerminalConfig {
            service_name: "terminal.test".into(),
            quic_port: DEFAULT_QUIC_PORT,
            compact_port: DEFAULT_COMPACT_PORT,
            capability: Some("secret".into()),
            allow_tailnet_write: false,
        };
        assert_eq!(config.access_for(None), ViewAccess::ReadOnly);
        assert_eq!(config.access_for(Some("wrong")), ViewAccess::ReadOnly);
        assert_eq!(config.access_for(Some("secret")), ViewAccess::ReadWrite);
    }

    #[test]
    fn terminal_service_scope_and_port_are_validated() {
        let node_free = TruffleTerminalConfig {
            service_name: " ".into(),
            ..TruffleTerminalConfig::default()
        };
        assert!(node_free.validate().is_err());
        let zero_port = TruffleTerminalConfig {
            quic_port: 0,
            ..TruffleTerminalConfig::default()
        };
        assert!(zero_port.validate().is_err());
        let same_ports = TruffleTerminalConfig {
            compact_port: DEFAULT_QUIC_PORT,
            ..TruffleTerminalConfig::default()
        };
        assert!(same_ports.validate().is_err());
    }

    #[test]
    fn compact_state_codec_is_used_only_when_the_peer_offers_it() {
        assert_eq!(negotiate_state_codec(None), StateCodec::Json);
        assert_eq!(
            negotiate_state_codec(Some(vec![StateCodec::Json])),
            StateCodec::Json
        );
        assert_eq!(
            negotiate_state_codec(Some(vec![StateCodec::Json, StateCodec::CompactJsonV1])),
            StateCodec::CompactJsonV1
        );
    }

    #[tokio::test]
    async fn compact_stream_frames_negotiated_state_payloads() {
        let (server_io, mut client_io) = tokio::io::duplex(4096);
        let mut server = CompactProtocolStream::new(server_io);
        server
            .write_compact_state_message(
                &StateMessage::ControlChanged {
                    controller_view_id: "view".into(),
                    control_epoch: 9,
                    cols: 120,
                    rows: 40,
                    layout_epoch: 3,
                },
                StateCodec::CompactJsonV1,
            )
            .await
            .unwrap();

        let mut header = [0_u8; 4];
        client_io.read_exact(&mut header).await.unwrap();
        let framed_len = u32::from_be_bytes(header) as usize;
        let mut framed = vec![0_u8; framed_len];
        client_io.read_exact(&mut framed).await.unwrap();
        assert_eq!(framed[0], CompactChannel::State.as_byte());
        assert_eq!(
            serde_json::from_slice::<serde_json::Value>(&framed[1..]).unwrap(),
            serde_json::json!({"c": ["view", 9, 120, 40, 3]})
        );
    }

    #[tokio::test]
    async fn compact_stream_handshake_and_session_listing_match_apple_client() {
        let (server_io, client_io) = tokio::io::duplex(64 * 1024);
        let registry = Registry::default();
        let server = tokio::spawn(handle_compact_protocol(
            server_io,
            registry,
            TruffleTerminalConfig::default(),
            "desktop-instance".into(),
            Some("ios-device".into()),
            "truffle:peer:1".into(),
        ));
        let mut client = CompactProtocolStream::new(client_io);
        client
            .write_preface(&StreamPreface {
                stream_kind: StreamKind::ConnectionControl,
                session_id: None,
                view_id: None,
            })
            .await
            .unwrap();
        client
            .write_message(
                &ConnectionMessage::ClientHello {
                    protocol_major: PROTOCOL_MAJOR,
                    protocol_minor: PROTOCOL_MINOR,
                    host_instance_id: String::new(),
                    local_device_id: "ios-device".into(),
                    nonce: "fixed-nonce".into(),
                    state_codecs: Some(vec![StateCodec::CompactJsonV1]),
                },
                MAX_CONTROL_MESSAGE_BYTES,
            )
            .await
            .unwrap();
        let hello = client
            .read_message::<ConnectionMessage>(MAX_CONTROL_MESSAGE_BYTES)
            .await
            .unwrap()
            .unwrap();
        assert!(matches!(
            hello,
            ConnectionMessage::ServerHello {
                protocol_major: PROTOCOL_MAJOR,
                protocol_minor: PROTOCOL_MINOR,
                ref host_instance_id,
                ref nonce,
                state_codec: Some(StateCodec::CompactJsonV1),
            } if host_instance_id == "desktop-instance" && nonce == "fixed-nonce"
        ));

        client
            .write_message(
                &ConnectionMessage::ListSessions {
                    request_id: "request-1".into(),
                },
                MAX_CONTROL_MESSAGE_BYTES,
            )
            .await
            .unwrap();
        let sessions = client
            .read_message::<ConnectionMessage>(MAX_CONTROL_MESSAGE_BYTES)
            .await
            .unwrap()
            .unwrap();
        assert!(matches!(
            sessions,
            ConnectionMessage::Sessions {
                ref request_id,
                ref sessions,
            } if request_id == "request-1" && sessions.is_empty()
        ));
        drop(client);
        server.await.unwrap().unwrap();
    }

    #[tokio::test]
    async fn compact_stream_rejects_a_claim_that_conflicts_with_confirmed_peer_identity() {
        let (server_io, client_io) = tokio::io::duplex(64 * 1024);
        let server = tokio::spawn(handle_compact_protocol(
            server_io,
            Registry::default(),
            TruffleTerminalConfig::default(),
            "desktop-instance".into(),
            Some("expected-device".into()),
            "truffle:peer:1".into(),
        ));
        let mut client = CompactProtocolStream::new(client_io);
        client
            .write_preface(&StreamPreface {
                stream_kind: StreamKind::ConnectionControl,
                session_id: None,
                view_id: None,
            })
            .await
            .unwrap();
        client
            .write_message(
                &ConnectionMessage::ClientHello {
                    protocol_major: PROTOCOL_MAJOR,
                    protocol_minor: PROTOCOL_MINOR,
                    host_instance_id: String::new(),
                    local_device_id: "claimed-device".into(),
                    nonce: "fixed-nonce".into(),
                    state_codecs: None,
                },
                MAX_CONTROL_MESSAGE_BYTES,
            )
            .await
            .unwrap();
        drop(client);
        assert!(server.await.unwrap().is_err());
    }

    #[test]
    fn connection_cache_requires_health_and_the_current_host_generation() {
        assert!(connection_is_reusable("host-a", true, "host-a"));
        assert!(!connection_is_reusable("host-a", false, "host-a"));
        assert!(!connection_is_reusable("host-a", true, "host-b"));
    }

    #[test]
    fn logical_state_uses_patches_only_with_a_compatible_baseline() {
        let previous = logical_snapshot(4, "before");
        let current = logical_snapshot(5, "after");
        let patch = logical_patch(&previous, &current, 1).unwrap();
        assert_eq!(patch.patch_sequence, 1);
        assert_eq!(patch.row_replacements.len(), 1);
        assert_eq!(patch.row_replacements[0].row.text, "after");

        let mut resized = current;
        resized.layout_epoch += 1;
        assert!(logical_patch(&previous, &resized, 1).is_none());
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    #[ignore = "requires TRUFFLE_TEST_AUTHKEY and a reachable Tailscale control plane"]
    async fn latest_truffle_quic_round_trip() -> Result<()> {
        let _ = dotenvy::dotenv();
        let auth_key = env::var("TRUFFLE_TEST_AUTHKEY")
            .context("TRUFFLE_TEST_AUTHKEY is required for this ignored test")?;
        let sidecar_path = env::var("TRUFFLE_SIDECAR_PATH")
            .context("TRUFFLE_SIDECAR_PATH is required for this ignored test")?;
        let a_state = tempfile::tempdir()?;
        let b_state = tempfile::tempdir()?;
        let suffix = &Uuid::new_v4().simple().to_string()[..8];
        let build_a = Node::<TailscaleProvider>::builder()
            .app_id("ghosttea-test")?
            .device_name(format!("terminal-a-{suffix}"))
            .state_dir(a_state.path().to_string_lossy().as_ref())
            .sidecar_path(&sidecar_path)
            .auth_key(&auth_key)
            .ephemeral(true)
            .build();
        let build_b = Node::<TailscaleProvider>::builder()
            .app_id("ghosttea-test")?
            .device_name(format!("terminal-b-{suffix}"))
            .state_dir(b_state.path().to_string_lossy().as_ref())
            .sidecar_path(&sidecar_path)
            .auth_key(&auth_key)
            .ephemeral(true)
            .build();
        let (node_a, node_b) = tokio::time::timeout(Duration::from_secs(60), async {
            tokio::try_join!(build_a, build_b)
        })
        .await
        .context("timed out starting the two Truffle 0.7.2 nodes")??;
        let node_a = Arc::new(node_a);
        let node_b = Arc::new(node_b);
        let b_id = node_b.local_info().device_id;
        tokio::time::timeout(Duration::from_secs(35), node_a.peer(&b_id, Some(30_000)))
            .await
            .context("timed out discovering the second Truffle node")??
            .context("node B did not appear in node A's peer registry")?;

        let listener = node_b.listen_quic(19_420).await?;
        let accept = listener.accept();
        let connect = node_a.connect_quic(&b_id, 19_420);
        let (accepted, client) = tokio::time::timeout(Duration::from_secs(30), async {
            tokio::join!(accept, connect)
        })
        .await
        .context("timed out establishing the Truffle QUIC connection")?;
        let server = accepted.context("QUIC listener closed")?;
        let client = client?;
        let mut client_stream = client.open_stream().await?;
        client_stream.write(b"truffle-0.7.1").await?;
        client_stream.finish();
        let mut server_stream =
            tokio::time::timeout(Duration::from_secs(10), server.accept_stream())
                .await
                .context("timed out accepting the Truffle QUIC stream")??
                .context("client stream was not accepted")?;
        assert_eq!(
            server_stream.read(64).await?.as_deref(),
            Some(b"truffle-0.7.1".as_slice())
        );
        client.close();
        server.close();
        listener.close();
        tokio::time::timeout(Duration::from_secs(10), node_a.stop())
            .await
            .context("timed out stopping Truffle node A")?;
        tokio::time::timeout(Duration::from_secs(10), node_b.stop())
            .await
            .context("timed out stopping Truffle node B")?;
        Ok(())
    }
}