rmux-server 0.10.0

Tokio daemon and request dispatcher for the RMUX terminal multiplexer.
Documentation
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
#[cfg(any(unix, windows))]
use rmux_core::TerminalPassthrough;
#[cfg(any(unix, windows))]
use rmux_proto::{AttachFrameDecoder, AttachMessage};
#[cfg(any(unix, windows))]
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize};
#[cfg(any(unix, windows))]
use std::sync::Arc;
#[cfg(any(unix, windows))]
use std::{collections::VecDeque, io, sync::atomic::Ordering};
#[cfg(any(unix, windows))]
use tokio::sync::mpsc;
#[cfg(any(unix, windows))]
use tokio::sync::watch;
#[cfg(any(unix, windows))]
use tokio::time::{Duration, Instant};

pub(crate) const READ_BUFFER_SIZE: usize = 64 * 1024;
#[cfg(any(unix, windows))]
const ATTACH_INTERACTIVE_OUTPUT_WINDOW: Duration = Duration::from_millis(250);
#[cfg(any(unix, windows))]
// Bound each opportunistic socket drain so sustained attach input cannot keep
// this task away from render, control, shutdown, or escape-flush futures.
const MAX_IMMEDIATE_ATTACH_READS: usize = 8;
#[cfg(windows)]
const ATTACH_EXIT_OUTPUT_DRAIN_TIMEOUT: Duration = Duration::from_millis(500);
#[cfg(any(unix, windows))]
const ATTACH_INPUT_STACK_PAYLOAD: usize = 1024;
#[cfg(all(unix, test))]
const MAX_PREDICTED_LOCAL_ECHO_BYTES: usize = 16;
#[cfg(unix)]
const PREDICTED_LOCAL_ECHO_TIMEOUT: Duration = Duration::from_millis(250);

#[cfg(test)]
#[derive(Debug, Default)]
struct LiveAttachInputApplyPause {
    reached: tokio::sync::Notify,
    release: tokio::sync::Notify,
}

#[cfg(test)]
static LIVE_ATTACH_INPUT_APPLY_PAUSE: std::sync::Mutex<
    Option<(
        crate::handler::attach_support::ActiveAttachIdentity,
        Arc<LiveAttachInputApplyPause>,
    )>,
> = std::sync::Mutex::new(None);

#[cfg(test)]
static LIVE_ATTACH_INPUT_VALIDATION_PAUSE: std::sync::Mutex<
    Vec<(
        crate::handler::attach_support::ActiveAttachIdentity,
        Arc<LiveAttachInputApplyPause>,
    )>,
> = std::sync::Mutex::new(Vec::new());

#[cfg(test)]
fn install_live_attach_input_apply_pause(
    identity: crate::handler::attach_support::ActiveAttachIdentity,
) -> Arc<LiveAttachInputApplyPause> {
    let pause = Arc::new(LiveAttachInputApplyPause::default());
    *LIVE_ATTACH_INPUT_APPLY_PAUSE
        .lock()
        .expect("live attach input pause lock") = Some((identity, Arc::clone(&pause)));
    pause
}

#[cfg(test)]
fn install_live_attach_input_validation_pause(
    identity: crate::handler::attach_support::ActiveAttachIdentity,
) -> Arc<LiveAttachInputApplyPause> {
    let pause = Arc::new(LiveAttachInputApplyPause::default());
    LIVE_ATTACH_INPUT_VALIDATION_PAUSE
        .lock()
        .expect("live attach input validation pause lock")
        .push((identity, Arc::clone(&pause)));
    pause
}

#[cfg(test)]
async fn pause_before_live_attach_input_validation(
    identity: crate::handler::attach_support::ActiveAttachIdentity,
) {
    let pause = {
        let mut installed = LIVE_ATTACH_INPUT_VALIDATION_PAUSE
            .lock()
            .expect("live attach input validation pause lock");
        installed
            .iter()
            .position(|(expected, _)| *expected == identity)
            .map(|position| installed.remove(position).1)
    };
    let Some(pause) = pause else {
        return;
    };
    pause.reached.notify_one();
    pause.release.notified().await;
}

#[cfg(test)]
async fn pause_after_live_attach_input_validation(
    identity: crate::handler::attach_support::ActiveAttachIdentity,
) {
    let pause = {
        let mut installed = LIVE_ATTACH_INPUT_APPLY_PAUSE
            .lock()
            .expect("live attach input pause lock");
        installed
            .as_ref()
            .is_some_and(|(expected, _)| *expected == identity)
            .then(|| {
                installed
                    .take()
                    .expect("matching pause remains installed")
                    .1
            })
    };
    let Some(pause) = pause else {
        return;
    };
    pause.reached.notify_one();
    pause.release.notified().await;
}
mod attach_control;
mod attach_output_batch;
mod attach_transport;
mod control;
mod deferred_passthrough;
mod exit_log;
mod live_render;
mod passthrough;
mod pending_escape;
mod persistent_overlay;
mod reader;
mod refresh_scheduler;
mod types;
mod wire;

#[cfg(any(unix, windows))]
use crate::renderer::{PaneRenderDelta, PaneRenderDeltaFrame};
#[cfg(test)]
pub(crate) use attach_control::release_attach_control_backlog;
#[cfg_attr(windows, allow(unused_imports))]
pub(crate) use attach_control::{AttachControl, AttachControlSender};
#[cfg(any(unix, windows))]
use attach_output_batch::{
    collect_attach_output_batch, collect_attach_output_batch_metadata, AttachOutputBatch,
};
#[cfg(all(any(unix, windows), feature = "web"))]
pub(crate) use attach_transport::in_process_attach_pair;
use attach_transport::{AttachTransport, TryAttachRead};
#[cfg(any(unix, windows))]
use control::{
    apply_pending_attach_controls, coalesce_render_switches, preserves_live_output,
    recv_attach_control, redraw_after_persistent_overlay_state_advance, should_emit_overlay,
    switch_attach_target, take_pending_live_passthroughs, try_recv_attach_control,
    PendingAttachAction, PendingAttachExit, PendingAttachInputState,
};
#[cfg(any(unix, windows))]
use deferred_passthrough::{
    clear_deferred_passthroughs_if_target_changed, defer_passthroughs, flush_deferred_passthroughs,
    take_passthrough_frame_with_live_passthroughs,
};
#[cfg(any(unix, windows))]
use exit_log::{record_attach_error, record_attach_exit, AttachExitReason};
pub(crate) use live_render::LivePaneRender;
#[cfg(any(unix, windows))]
use pending_escape::PendingEscapeFlush;
#[cfg(test)]
pub(crate) use persistent_overlay::replay_client_visible_payloads;
#[cfg(any(unix, windows))]
use persistent_overlay::{
    accept_persistent_overlay_state, advance_persistent_overlay_state, clear_then_base_frame,
    defer_persistent_clear, discard_stale_persistent_overlays, is_stale_persistent_switch,
    persistent_overlay_replacement_pending, prime_persistent_overlay_barriers,
    replacement_persistent_overlay_frame, switch_requires_screen_clear,
    take_pending_persistent_overlay_for_state, update_persistent_overlay_cache,
};
#[cfg(windows)]
pub(crate) use reader::spawn_pane_exit_watcher;
pub(crate) use reader::spawn_pane_output_reader;
#[cfg(windows)]
pub(crate) use reader::PaneOutputEofState;
#[cfg(unix)]
pub(crate) use reader::PaneOutputReaderTask;
#[cfg(test)]
pub(crate) use reader::{publish_pane_bytes_capturing_alerts, publish_pane_bytes_for_test};
#[cfg(any(unix, windows))]
use refresh_scheduler::{
    wait_for_refresh_deadline, AttachRefreshScheduler, AttachStatusRefreshScheduler,
};
#[cfg(test)]
pub(crate) use types::pane_output_channel_with_limits;
#[cfg(any(unix, windows))]
pub(crate) use types::LiveAttachInputContext;
#[cfg_attr(windows, allow(unused_imports))]
pub(crate) use types::{
    pane_output_channel, AttachSessionUpgrade, AttachTarget, HandleOutcome, OverlayFrame,
    PaneAlertCallback, PaneAlertEvent, PaneBoundary, PaneExitCallback, PaneExitEvent,
    PaneInvalidationReason, PaneObservationItem, PaneOutputReceiver, PaneOutputSender,
};
#[cfg(any(unix, windows))]
use wire::{
    emit_attach_bytes, emit_attach_frame, emit_attach_message, emit_attach_stop,
    emit_coalescible_render_frame, emit_detached_attach_stop, emit_exited_attach_stop,
    emit_render_frame, invalid_attach_message, open_attach_target, read_socket_bytes,
    recv_pane_output_optional, try_read_socket_bytes,
};

#[cfg(any(unix, windows))]
struct AttachControlBacklogCleanup(Arc<AtomicUsize>);

#[cfg(any(unix, windows))]
impl Drop for AttachControlBacklogCleanup {
    fn drop(&mut self) {
        // The receiver and all deferred controls are dropped before this
        // guard, so no retained queue allocation remains to be accounted.
        self.0.store(0, Ordering::Release);
    }
}

#[allow(clippy::too_many_arguments)]
#[cfg(any(unix, windows))]
pub(crate) async fn forward_attach(
    stream: impl Into<AttachTransport>,
    target: AttachTarget,
    initial_socket_bytes: Vec<u8>,
    mut shutdown: watch::Receiver<()>,
    control_rx: mpsc::UnboundedReceiver<AttachControl>,
    control_backlog: Arc<AtomicUsize>,
    closing: Arc<AtomicBool>,
    persistent_overlay_epoch: Arc<AtomicU64>,
    live_input: LiveAttachInputContext,
    render_stream: bool,
) -> io::Result<()> {
    // Declare the guard before receiver/deferred-control locals so it runs
    // after their destructors on every normal, error, or cancellation exit.
    let _control_backlog_cleanup = AttachControlBacklogCleanup(Arc::clone(&control_backlog));
    let stream = stream.into();
    let mut decoder = AttachFrameDecoder::new();
    let mut pending_input = Vec::new();
    let mut active_emit_cache = None;
    let mut attach_controls = Some(control_rx);
    let mut deferred_controls = VecDeque::new();
    let mut pending_escape_flush = PendingEscapeFlush::default();
    let mut current_target = open_attach_target(target, render_stream)?;
    let mut render_generation = 0_u64;
    let mut overlay_generation = 0_u64;
    let mut persistent_overlay = None::<Vec<u8>>;
    let mut persistent_overlay_visible = false;
    let mut persistent_overlay_state_id = current_target.persistent_overlay_state_id;
    let mut pane_refresh = AttachRefreshScheduler::default();
    let mut pane_refresh_requires_full = false;
    let mut close_pane_output_after_refresh = false;
    let mut deferred_passthroughs = Vec::new();
    let mut last_client_input_at = None::<Instant>;
    let mut status_refresh = AttachStatusRefreshScheduler::new(
        live_input
            .handler
            .attached_status_interval(&current_target.session_name)
            .await,
    );
    let mut locked = false;
    let mut pending_shutdown_requested = false;
    let mut shutdown_draining = false;
    let mut shutdown_pending_output_batch = None;
    decoder.push_bytes(&initial_socket_bytes);
    emit_attach_bytes(
        &stream,
        &current_target.outer_terminal.attach_start_sequence(),
    )
    .await?;
    if let Some(sequence) = current_target
        .outer_terminal
        .render_cursor_style_transition(None, current_target.cursor_style)
    {
        emit_attach_bytes(&stream, sequence.as_bytes()).await?;
    }
    emit_coalescible_render_frame(
        &stream,
        &current_target.outer_terminal,
        &current_target.render_frame,
        current_target.render_stream,
    )
    .await?;

    let result = async {
        loop {
            if shutdown_draining || attach_shutdown_observable(&shutdown) {
                if closing.load(Ordering::SeqCst) {
                    if let Some(control) = take_pending_terminal_attach_control(
                        &mut deferred_controls,
                        attach_controls.as_mut(),
                        &control_backlog,
                    ) {
                        // Terminal controls only finish the already-committed pane-output and
                        // transport sequence. They never enter RequestHandler mutation paths, so
                        // honoring one here preserves the finite exit banner without admitting a
                        // post-shutdown attach mutation.
                        let reason = finish_terminal_attach_control(
                            control,
                            &stream,
                            &mut current_target,
                            &mut deferred_passthroughs,
                            shutdown_pending_output_batch.take(),
                        )
                        .await?;
                        log_attach_exit(&live_input, &current_target, reason);
                        return Ok(());
                    }
                }
                let reason = if pending_shutdown_requested {
                    AttachExitReason::PendingServerShutdown
                } else {
                    AttachExitReason::ServerShutdown
                };
                log_attach_exit(&live_input, &current_target, reason);
                let _ = emit_attach_stop(&stream, &current_target).await;
                return Ok(());
            }
            // Socket reads and attach-control refreshes can both remain
            // continuously ready. Service an expired input ambiguity before
            // either queue so its deadline is a real upper bound rather than
            // merely another selectable wakeup.
            let Some(pending_escape_batch) =
                begin_attach_mutation_batch(&live_input, &shutdown)
            else {
                shutdown_draining = true;
                continue;
            };
            flush_due_pending_escape_input(
                &mut pending_escape_flush,
                &live_input,
                &mut pending_input,
                locked,
            )
            .await?;
            drop(pending_escape_batch);
            if attach_shutdown_observable(&shutdown) {
                continue;
            }
            let Some(control_batch) = begin_attach_mutation_batch(&live_input, &shutdown) else {
                shutdown_draining = true;
                continue;
            };
            synchronize_persistent_overlay_epoch(
                &persistent_overlay_epoch,
                &stream,
                &current_target,
                attach_controls.as_mut(),
                &mut deferred_controls,
                &control_backlog,
                &mut persistent_overlay,
                &mut persistent_overlay_visible,
                &mut persistent_overlay_state_id,
            )
            .await?;
            match apply_pending_attach_controls(
                &mut deferred_controls,
                attach_controls.as_mut(),
                &control_backlog,
                &mut current_target,
                &stream,
                &mut render_generation,
                &mut overlay_generation,
                &mut persistent_overlay,
                &mut persistent_overlay_visible,
                &mut persistent_overlay_state_id,
                &mut locked,
                Some(PendingAttachInputState::new(
                    &mut pending_input,
                    &mut pending_escape_flush,
                )),
            )
            .await?
            {
                PendingAttachAction::Exit(PendingAttachExit { reason, .. }) => {
                    finish_pending_attach_exit(
                        reason,
                        &stream,
                        &mut current_target,
                        &mut deferred_passthroughs,
                    )
                    .await?;
                    log_attach_exit(&live_input, &current_target, reason);
                    return Ok(());
                }
                PendingAttachAction::Continue { target_changed } => {
                    reschedule_status_refresh_if_target_changed(
                        target_changed,
                        &mut status_refresh,
                        &live_input,
                        &current_target,
                    )
                    .await;
                    clear_close_pane_output_after_refresh_if_target_changed(
                        target_changed,
                        &mut close_pane_output_after_refresh,
                    );
                    clear_deferred_passthroughs_if_target_changed(
                        target_changed,
                        &mut deferred_passthroughs,
                    );
                    flush_deferred_passthroughs(
                        &stream,
                        &current_target,
                        &mut deferred_passthroughs,
                        persistent_overlay_visible,
                        persistent_overlay.is_some(),
                    )
                    .await?;
                    continue;
                }
                PendingAttachAction::InteractiveInput => {
                    mark_attach_interactive_input(&mut pane_refresh, &mut last_client_input_at);
                    absorb_transient_terminal_prefix(
                        &live_input,
                        &mut pending_input,
                        &mut pending_escape_flush,
                    )
                    .await;
                    pane_refresh.schedule_now();
                    continue;
                }
                PendingAttachAction::Refresh { target_changed } => {
                    reschedule_status_refresh_if_target_changed(
                        target_changed,
                        &mut status_refresh,
                        &live_input,
                        &current_target,
                    )
                    .await;
                    clear_close_pane_output_after_refresh_if_target_changed(
                        target_changed,
                        &mut close_pane_output_after_refresh,
                    );
                    clear_deferred_passthroughs_if_target_changed(
                        target_changed,
                        &mut deferred_passthroughs,
                    );
                    schedule_attach_render_refresh(
                        &mut pane_refresh,
                        &mut pane_refresh_requires_full,
                        &live_input,
                    )
                    .await;
                    continue;
                }
                PendingAttachAction::Write => {}
            }
            drop(control_batch);
            if attach_shutdown_observable(&shutdown) {
                continue;
            }
            // A pending repaint must not stop input from reaching the pane.
            // The repaint is rendered from the current transcript when its
            // deadline fires, so fresh input can safely pull the deadline in.
            for _ in 0..MAX_IMMEDIATE_ATTACH_READS {
                match try_read_socket_bytes(&stream, &mut decoder)? {
                    TryAttachRead::Read => {}
                    TryAttachRead::Closed => {
                        log_attach_exit(
                            &live_input,
                            &current_target,
                            AttachExitReason::AttachStreamClosed,
                        );
                        let _ = emit_attach_stop(&stream, &current_target).await;
                        return Ok(());
                    }
                    TryAttachRead::WouldBlock => break,
                }
            }
            if attach_shutdown_observable(&shutdown) {
                continue;
            }
            let Some(socket_batch) = begin_attach_mutation_batch(&live_input, &shutdown) else {
                shutdown_draining = true;
                continue;
            };
            process_attach_socket_messages(
                &mut decoder,
                &stream,
                &live_input,
                &closing,
                &mut current_target,
                &mut pending_input,
                &mut active_emit_cache,
                &mut locked,
                &mut pane_refresh,
                &mut pending_escape_flush,
                &mut last_client_input_at,
            )
            .await?;
            drop(socket_batch);
            if attach_shutdown_observable(&shutdown) {
                continue;
            }
            let Some(control_batch) = begin_attach_mutation_batch(&live_input, &shutdown) else {
                shutdown_draining = true;
                continue;
            };
            prime_persistent_overlay_barriers(
                &mut persistent_overlay_state_id,
                attach_controls.as_mut(),
                &mut deferred_controls,
                &control_backlog,
            );
            match apply_pending_attach_controls(
                &mut deferred_controls,
                attach_controls.as_mut(),
                &control_backlog,
                &mut current_target,
                &stream,
                &mut render_generation,
                &mut overlay_generation,
                &mut persistent_overlay,
                &mut persistent_overlay_visible,
                &mut persistent_overlay_state_id,
                &mut locked,
                Some(PendingAttachInputState::new(
                    &mut pending_input,
                    &mut pending_escape_flush,
                )),
            )
            .await?
            {
                PendingAttachAction::Exit(PendingAttachExit { reason, .. }) => {
                    finish_pending_attach_exit(
                        reason,
                        &stream,
                        &mut current_target,
                        &mut deferred_passthroughs,
                    )
                    .await?;
                    log_attach_exit(&live_input, &current_target, reason);
                    return Ok(());
                }
                PendingAttachAction::Continue { target_changed } => {
                    reschedule_status_refresh_if_target_changed(
                        target_changed,
                        &mut status_refresh,
                        &live_input,
                        &current_target,
                    )
                    .await;
                    clear_close_pane_output_after_refresh_if_target_changed(
                        target_changed,
                        &mut close_pane_output_after_refresh,
                    );
                    clear_deferred_passthroughs_if_target_changed(
                        target_changed,
                        &mut deferred_passthroughs,
                    );
                    flush_deferred_passthroughs(
                        &stream,
                        &current_target,
                        &mut deferred_passthroughs,
                        persistent_overlay_visible,
                        persistent_overlay.is_some(),
                    )
                    .await?;
                    continue;
                }
                PendingAttachAction::InteractiveInput => {
                    mark_attach_interactive_input(&mut pane_refresh, &mut last_client_input_at);
                    absorb_transient_terminal_prefix(
                        &live_input,
                        &mut pending_input,
                        &mut pending_escape_flush,
                    )
                    .await;
                    pane_refresh.schedule_now();
                    continue;
                }
                PendingAttachAction::Refresh { target_changed } => {
                    reschedule_status_refresh_if_target_changed(
                        target_changed,
                        &mut status_refresh,
                        &live_input,
                        &current_target,
                    )
                    .await;
                    clear_close_pane_output_after_refresh_if_target_changed(
                        target_changed,
                        &mut close_pane_output_after_refresh,
                    );
                    clear_deferred_passthroughs_if_target_changed(
                        target_changed,
                        &mut deferred_passthroughs,
                    );
                    schedule_attach_render_refresh(
                        &mut pane_refresh,
                        &mut pane_refresh_requires_full,
                        &live_input,
                    )
                    .await;
                    continue;
                }
                PendingAttachAction::Write => {}
            }
            drop(control_batch);
            pending_shutdown_requested |= live_input.handler.request_shutdown_if_pending();

            tokio::select! {
                biased;
                result = shutdown.changed() => {
                    let _ = result;
                    shutdown_draining = true;
                    continue;
                }
                result = read_socket_bytes(&stream, &mut decoder) => {
                    if !result? {
                        log_attach_exit(
                            &live_input,
                            &current_target,
                            AttachExitReason::AttachStreamClosed,
                        );
                        let _ = emit_attach_stop(&stream, &current_target).await;
                        return Ok(());
                    }
                    if attach_shutdown_observable(&shutdown) {
                        continue;
                    }
                    let Some(socket_batch) = begin_attach_mutation_batch(&live_input, &shutdown) else {
                        shutdown_draining = true;
                        continue;
                    };
                    process_attach_socket_messages(
                        &mut decoder,
                        &stream,
                        &live_input,
                        &closing,
                        &mut current_target,
                        &mut pending_input,
                        &mut active_emit_cache,
                        &mut locked,
                        &mut pane_refresh,
                        &mut pending_escape_flush,
                        &mut last_client_input_at,
                    )
                    .await?;
                    drop(socket_batch);
                }
                _ = wait_for_refresh_deadline(pane_refresh.deadline()) => {
                    if attach_shutdown_observable(&shutdown) {
                        continue;
                    }
                    let Some(_control_batch) = begin_attach_mutation_batch(&live_input, &shutdown) else {
                        shutdown_draining = true;
                        continue;
                    };
                    pane_refresh.clear();
                    match apply_pending_attach_controls(
                        &mut deferred_controls,
                        attach_controls.as_mut(),
                &control_backlog,
                        &mut current_target,
                        &stream,
                        &mut render_generation,
                        &mut overlay_generation,
                        &mut persistent_overlay,
                        &mut persistent_overlay_visible,
                        &mut persistent_overlay_state_id,
                        &mut locked,
                        Some(PendingAttachInputState::new(
                            &mut pending_input,
                            &mut pending_escape_flush,
                        )),
                    )
                    .await?
                    {
                        PendingAttachAction::Exit(PendingAttachExit { reason, .. }) => {
                            finish_pending_attach_exit(
                                reason,
                                &stream,
                                &mut current_target,
                                &mut deferred_passthroughs,
                            )
                            .await?;
                            log_attach_exit(&live_input, &current_target, reason);
                            return Ok(());
                        }
                        PendingAttachAction::Continue { target_changed } => {
                            reschedule_status_refresh_if_target_changed(
                                target_changed,
                                &mut status_refresh,
                                &live_input,
                                &current_target,
                            )
                            .await;
                            clear_close_pane_output_after_refresh_if_target_changed(
                                target_changed,
                                &mut close_pane_output_after_refresh,
                            );
                            clear_deferred_passthroughs_if_target_changed(
                                target_changed,
                                &mut deferred_passthroughs,
                            );
                            flush_deferred_passthroughs(
                                &stream,
                                &current_target,
                                &mut deferred_passthroughs,
                                persistent_overlay_visible,
                                persistent_overlay.is_some(),
                            )
                            .await?;
                            continue;
                        }
                        PendingAttachAction::InteractiveInput => {
                            mark_attach_interactive_input(
                                &mut pane_refresh,
                                &mut last_client_input_at,
                            );
                            absorb_transient_terminal_prefix(
                                &live_input,
                                &mut pending_input,
                                &mut pending_escape_flush,
                            )
                            .await;
                            pane_refresh.schedule_now();
                            continue;
                        }
                        PendingAttachAction::Refresh { target_changed } => {
                            reschedule_status_refresh_if_target_changed(
                                target_changed,
                                &mut status_refresh,
                                &live_input,
                                &current_target,
                            )
                            .await;
                            clear_close_pane_output_after_refresh_if_target_changed(
                                target_changed,
                                &mut close_pane_output_after_refresh,
                            );
                            clear_deferred_passthroughs_if_target_changed(
                                target_changed,
                                &mut deferred_passthroughs,
                            );
                            schedule_attach_render_refresh(
                                &mut pane_refresh,
                                &mut pane_refresh_requires_full,
                                &live_input,
                            )
                            .await;
                            continue;
                        }
                        PendingAttachAction::Write => {
                            if locked {
                                continue;
                            }
                            if closing.load(Ordering::SeqCst) {
                                log_attach_exit(
                                    &live_input,
                                    &current_target,
                                    AttachExitReason::AttachClosingFlag,
                                );
                                let _ = emit_attach_stop(&stream, &current_target).await;
                                return Ok(());
                            }
                            let force_full_refresh = pane_refresh_requires_full
                                || persistent_overlay_visible
                                || persistent_overlay.is_some()
                                || current_target.live_pane.is_none();
                            pane_refresh_requires_full = false;
                            if force_full_refresh {
                                refresh_current_attach_client(&live_input).await;
                            } else {
                                let pending_output =
                                    collect_pending_attach_output_batch_metadata(&mut current_target);
                                let mut drained_sustained_output = false;
                                let mut live_passthroughs = Vec::new();
                                if let Some(batch) = pending_output {
                                    match batch {
                                        AttachOutputBatch::Closed => {
                                            current_target.pane_output = None;
                                        }
                                        AttachOutputBatch::Gap => {
                                            pane_refresh_requires_full = true;
                                            pane_refresh.schedule_now();
                                            continue;
                                        }
                                        AttachOutputBatch::Events {
                                            bytes: _,
                                            passthroughs,
                                            close_after_render,
                                            sustained,
                                            ..
                                        } => {
                                            drained_sustained_output = sustained;
                                            live_passthroughs = passthroughs;
                                            if close_after_render {
                                                close_pane_output_after_refresh = true;
                                            }
                                        }
                                    }
                                }
                                let passthrough_frame = take_passthrough_frame_with_live_passthroughs(
                                    &current_target,
                                    &mut deferred_passthroughs,
                                    live_passthroughs,
                                );
                                let replaceable_render = current_target.render_stream
                                    && !drained_sustained_output
                                    && !pane_refresh.is_sustained();
                                match current_target
                                    .live_pane
                                    .as_mut()
                                    .map(|pane| {
                                        pane.render_frame_from_transcript(replaceable_render)
                                    }) {
                                    Some(PaneRenderDelta::Incremental(delta)) => {
                                        emit_live_render_frame(
                                            &stream,
                                            &mut current_target,
                                            &delta,
                                            replaceable_render,
                                        )
                                        .await?;
                                        emit_attach_bytes(&stream, &passthrough_frame).await?;
                                    }
                                    Some(PaneRenderDelta::RequiresFullRefresh) | None => {
                                        refresh_current_attach_client(&live_input).await;
                                        emit_attach_bytes(&stream, &passthrough_frame).await?;
                                    }
                                }
                                let _ = pane_refresh.note_output_batch(drained_sustained_output);
                            }
                            if close_pane_output_after_refresh {
                                current_target.pane_output = None;
                                close_pane_output_after_refresh = false;
                            }
                        }
                    }
                }
                _ = wait_for_refresh_deadline(status_refresh.deadline()) => {
                    if attach_shutdown_observable(&shutdown) {
                        continue;
                    }
                    let Some(_control_batch) = begin_attach_mutation_batch(&live_input, &shutdown) else {
                        shutdown_draining = true;
                        continue;
                    };
                    match apply_pending_attach_controls(
                        &mut deferred_controls,
                        attach_controls.as_mut(),
                &control_backlog,
                        &mut current_target,
                        &stream,
                        &mut render_generation,
                        &mut overlay_generation,
                        &mut persistent_overlay,
                        &mut persistent_overlay_visible,
                        &mut persistent_overlay_state_id,
                        &mut locked,
                        Some(PendingAttachInputState::new(
                            &mut pending_input,
                            &mut pending_escape_flush,
                        )),
                    )
                    .await?
                    {
                        PendingAttachAction::Exit(PendingAttachExit { reason, .. }) => {
                            finish_pending_attach_exit(
                                reason,
                                &stream,
                                &mut current_target,
                                &mut deferred_passthroughs,
                            )
                            .await?;
                            log_attach_exit(&live_input, &current_target, reason);
                            return Ok(());
                        }
                        PendingAttachAction::Continue { target_changed } => {
                            reschedule_status_refresh_for_target(
                                &mut status_refresh,
                                &live_input,
                                &current_target,
                            )
                            .await;
                            clear_close_pane_output_after_refresh_if_target_changed(
                                target_changed,
                                &mut close_pane_output_after_refresh,
                            );
                            clear_deferred_passthroughs_if_target_changed(
                                target_changed,
                                &mut deferred_passthroughs,
                            );
                            flush_deferred_passthroughs(
                                &stream,
                                &current_target,
                                &mut deferred_passthroughs,
                                persistent_overlay_visible,
                                persistent_overlay.is_some(),
                            )
                            .await?;
                            continue;
                        }
                        PendingAttachAction::InteractiveInput => {
                            mark_attach_interactive_input(
                                &mut pane_refresh,
                                &mut last_client_input_at,
                            );
                            absorb_transient_terminal_prefix(
                                &live_input,
                                &mut pending_input,
                                &mut pending_escape_flush,
                            )
                            .await;
                            pane_refresh.schedule_now();
                            continue;
                        }
                        PendingAttachAction::Refresh { target_changed } => {
                            reschedule_status_refresh_if_target_changed(
                                target_changed,
                                &mut status_refresh,
                                &live_input,
                                &current_target,
                            )
                            .await;
                            clear_close_pane_output_after_refresh_if_target_changed(
                                target_changed,
                                &mut close_pane_output_after_refresh,
                            );
                            clear_deferred_passthroughs_if_target_changed(
                                target_changed,
                                &mut deferred_passthroughs,
                            );
                            schedule_attach_render_refresh(
                                &mut pane_refresh,
                                &mut pane_refresh_requires_full,
                                &live_input,
                            )
                            .await;
                            continue;
                        }
                        PendingAttachAction::Write => {}
                    }
                    if closing.load(Ordering::SeqCst) {
                        log_attach_exit(
                            &live_input,
                            &current_target,
                            AttachExitReason::AttachClosingFlag,
                        );
                        let _ = emit_attach_stop(&stream, &current_target).await;
                        return Ok(());
                    }
                    let session_name = current_target.session_name.clone();
                    if locked {
                        reschedule_status_refresh_for_session(
                            &mut status_refresh,
                            &live_input,
                            &session_name,
                        )
                        .await;
                        continue;
                    }
                    let _ = live_input
                        .handler
                        .refresh_attached_client_status(live_input.attach_pid(), &session_name)
                        .await;
                    reschedule_status_refresh_for_session(
                        &mut status_refresh,
                        &live_input,
                        &session_name,
                    )
                        .await;
                }
                _ = wait_for_refresh_deadline(pending_escape_flush.deadline()) => {
                    if attach_shutdown_observable(&shutdown) {
                        continue;
                    }
                    let Some(_pending_escape_batch) = begin_attach_mutation_batch(&live_input, &shutdown) else {
                        shutdown_draining = true;
                        continue;
                    };
                    flush_due_pending_escape_input(
                        &mut pending_escape_flush,
                        &live_input,
                        &mut pending_input,
                        locked,
                    )
                    .await?;
                }
                control = recv_attach_control(&mut deferred_controls, attach_controls.as_mut(), &control_backlog) => {
                    if attach_shutdown_observable(&shutdown) {
                        if let Some(control) = control {
                            deferred_controls.push_front(control);
                        }
                        continue;
                    }
                    let Some(_control_batch) = begin_attach_mutation_batch(&live_input, &shutdown) else {
                        if let Some(control) = control {
                            deferred_controls.push_front(control);
                        }
                        shutdown_draining = true;
                        continue;
                    };
                    // Dismissal publishes its persistent-overlay epoch before
                    // the fresh base frame is ready. This select arm may have
                    // already received a stale tree control while that epoch
                    // advanced, so fence it again immediately before dispatch.
                    synchronize_persistent_overlay_epoch(
                        &persistent_overlay_epoch,
                        &stream,
                        &current_target,
                        attach_controls.as_mut(),
                        &mut deferred_controls,
                        &control_backlog,
                        &mut persistent_overlay,
                        &mut persistent_overlay_visible,
                        &mut persistent_overlay_state_id,
                    )
                    .await?;
                    match control {
                        Some(AttachControl::Detach) => {
                            log_attach_exit(
                                &live_input,
                                &current_target,
                                AttachExitReason::AttachControlDetach,
                            );
                            let _ = emit_detached_attach_stop(&stream, &current_target).await;
                            return Ok(());
                        }
                        Some(AttachControl::Exited) => {
                            finish_pending_attach_exit(
                                AttachExitReason::AttachControlExited,
                                &stream,
                                &mut current_target,
                                &mut deferred_passthroughs,
                            )
                            .await?;
                            log_attach_exit(
                                &live_input,
                                &current_target,
                                AttachExitReason::AttachControlExited,
                            );
                            return Ok(());
                        }
                        Some(AttachControl::DetachKill) => {
                            log_attach_exit(
                                &live_input,
                                &current_target,
                                AttachExitReason::AttachControlDetachKill,
                            );
                            emit_attach_stop(&stream, &current_target).await?;
                            emit_attach_message(&stream, &AttachMessage::DetachKill).await?;
                            return Ok(());
                        }
                        Some(AttachControl::DetachExecShellCommand(command)) => {
                            log_attach_exit(
                                &live_input,
                                &current_target,
                                AttachExitReason::AttachControlDetachExec,
                            );
                            emit_attach_stop(&stream, &current_target).await?;
                            emit_attach_message(
                                &stream,
                                &AttachMessage::DetachExecShellCommand(command),
                            )
                            .await?;
                            return Ok(());
                        }
                        Some(AttachControl::Refresh) => {
                            schedule_attach_render_refresh(
                                &mut pane_refresh,
                                &mut pane_refresh_requires_full,
                                &live_input,
                            )
                            .await;
                        }
                        Some(AttachControl::InteractiveInput) => {
                            mark_attach_interactive_input(
                                &mut pane_refresh,
                                &mut last_client_input_at,
                            );
                            absorb_transient_terminal_prefix(
                                &live_input,
                                &mut pending_input,
                                &mut pending_escape_flush,
                            )
                            .await;
                            pane_refresh.schedule_now();
                        }
                        Some(AttachControl::Switch(next_target)) => {
                            let (next_target, switch_count) = coalesce_render_switches(
                                next_target,
                                &mut deferred_controls,
                                attach_controls.as_mut(),
                                &control_backlog,
                            );
                            let drop_live_output =
                                !preserves_live_output(&current_target, &next_target);
                            let pending_passthroughs = if drop_live_output {
                                Vec::new()
                            } else {
                                take_pending_live_passthroughs(
                                    &mut current_target,
                                    next_target.pane_output_start_sequence,
                                )
                            };
                            if is_stale_persistent_switch(
                                persistent_overlay_state_id,
                                next_target.as_ref(),
                            ) {
                                render_generation = render_generation.saturating_add(switch_count);
                                continue;
                            }
                            close_pane_output_after_refresh = false;
                            render_generation = render_generation.saturating_add(switch_count);
                            PendingAttachInputState::new(
                                &mut pending_input,
                                &mut pending_escape_flush,
                            )
                            .clear_if_pane_source_changed(
                                &current_target,
                                next_target.as_ref(),
                            );
                            clear_deferred_passthroughs_if_target_changed(
                                drop_live_output,
                                &mut deferred_passthroughs,
                            );
                            let pending_overlay = take_pending_persistent_overlay_for_state(
                                attach_controls.as_mut(),
                                &mut deferred_controls,
                                next_target.persistent_overlay_state_id,
                                render_generation,
                                overlay_generation,
                                &control_backlog,
                            );
                            let replacement_frame = pending_overlay
                                .as_ref()
                                .map(|overlay| overlay.frame.clone())
                                .or_else(|| {
                                    replacement_persistent_overlay_frame(
                                        &persistent_overlay,
                                        persistent_overlay_visible,
                                        next_target.as_ref(),
                                    )
                                });
                            let clear_screen = switch_requires_screen_clear(
                                persistent_overlay_visible,
                                persistent_overlay.is_some(),
                                persistent_overlay_state_id,
                                current_target.persistent_overlay_state_id,
                                next_target.persistent_overlay_state_id,
                            );
                            if replacement_frame.is_none() {
                                persistent_overlay.take();
                                persistent_overlay_visible = false;
                            }
                            if let Some(overlay) = pending_overlay.as_ref() {
                                overlay_generation = overlay.overlay_generation;
                            }
                            switch_attach_target(
                                &stream,
                                &mut current_target,
                                *next_target,
                                clear_screen,
                                replacement_frame.as_deref(),
                            )
                            .await?;
                            if !pending_passthroughs.is_empty() {
                                let passthrough_frame = take_passthrough_frame_with_live_passthroughs(
                                    &current_target,
                                    &mut deferred_passthroughs,
                                    pending_passthroughs,
                                );
                                emit_attach_bytes(&stream, &passthrough_frame).await?;
                            }
                            status_refresh.reschedule(
                                live_input
                                    .handler
                                    .attached_status_interval(&current_target.session_name)
                                    .await,
                            );
                            if let Some(overlay) = pending_overlay {
                                update_persistent_overlay_cache(
                                    &mut persistent_overlay,
                                    &mut persistent_overlay_visible,
                                    &overlay,
                                );
                            }
                            persistent_overlay_state_id = current_target.persistent_overlay_state_id;
                            if let Some(barrier_state_id) = persistent_overlay_state_id {
                                discard_stale_persistent_overlays(
                                    attach_controls.as_mut(),
                                    &mut deferred_controls,
                                    barrier_state_id,
                                    &control_backlog,
                                );
                            }
                        }
                        Some(AttachControl::AdvancePersistentOverlayState(state_id)) => {
                            let previous_overlay_state_id = persistent_overlay_state_id;
                            advance_persistent_overlay_state(
                                &mut persistent_overlay_state_id,
                                attach_controls.as_mut(),
                                &mut deferred_controls,
                                state_id,
                                &control_backlog,
                            );
                            redraw_after_persistent_overlay_state_advance(
                                &stream,
                                &current_target,
                                &mut persistent_overlay,
                                &mut persistent_overlay_visible,
                                previous_overlay_state_id,
                                persistent_overlay_state_id,
                                persistent_overlay_replacement_pending(
                                    &deferred_controls,
                                    persistent_overlay_state_id,
                                ),
                            )
                            .await?;
                        }
                        Some(AttachControl::Overlay(overlay)) => {
                            if !accept_persistent_overlay_state(
                                &mut persistent_overlay_state_id,
                                &overlay,
                            ) {
                                continue;
                            }
                            let persistent_clear = overlay.persistent && overlay.frame.is_empty();
                            if persistent_clear
                                || should_emit_overlay(
                                    render_generation,
                                    &mut overlay_generation,
                                    &overlay,
                                )
                            {
                                update_persistent_overlay_cache(
                                    &mut persistent_overlay,
                                    &mut persistent_overlay_visible,
                                    &overlay,
                                );
                                if defer_persistent_clear(
                                    persistent_clear,
                                    &deferred_controls,
                                    persistent_overlay_state_id,
                                ) {
                                    continue;
                                }
                                let clear_frame =
                                    persistent_clear.then(|| clear_then_base_frame(&current_target));
                                emit_render_frame(
                                    &stream,
                                    &current_target.outer_terminal,
                                    clear_frame.as_deref().unwrap_or(&overlay.frame),
                                )
                                .await?;
                                flush_deferred_passthroughs(
                                    &stream,
                                    &current_target,
                                    &mut deferred_passthroughs,
                                    persistent_overlay_visible,
                                    persistent_overlay.is_some(),
                                )
                                .await?;
                            }
                        }
                        Some(AttachControl::Write(bytes)) => {
                            emit_attach_bytes(&stream, &bytes).await?;
                        }
                        Some(AttachControl::ClipboardWrite { bytes, reservation }) => {
                            emit_attach_bytes(&stream, &bytes).await?;
                            drop(reservation);
                        }
                        Some(AttachControl::LockShellCommand(command)) => {
                            PendingAttachInputState::new(
                                &mut pending_input,
                                &mut pending_escape_flush,
                            )
                            .clear();
                            locked = true;
                            emit_attach_stop(&stream, &current_target).await?;
                            emit_attach_message(&stream, &AttachMessage::LockShellCommand(command))
                                .await?;
                        }
                        Some(AttachControl::Suspend) => {
                            PendingAttachInputState::new(
                                &mut pending_input,
                                &mut pending_escape_flush,
                            )
                            .clear();
                            locked = true;
                            emit_attach_stop(&stream, &current_target).await?;
                            emit_attach_message(&stream, &AttachMessage::Suspend).await?;
                        }
                        None => attach_controls = None,
                    }
                }
                result = recv_pane_output_optional(current_target.pane_output.as_mut()), if !pane_refresh.is_pending() => {
                    let Some(item) = result? else {
                        current_target.pane_output = None;
                        continue;
                    };
                    let Some(_output_batch) = begin_attach_mutation_batch(&live_input, &shutdown) else {
                        shutdown_pending_output_batch = Some(collect_attach_output_batch(
                            item,
                            current_target.pane_output.as_mut(),
                        ));
                        shutdown_draining = true;
                        continue;
                    };
                    #[cfg(unix)]
                    if let rmux_core::events::OutputCursorItem::Event(event) = &item {
                        if event.passthroughs().is_empty() {
                            match consume_predicted_echo(&mut current_target, event.bytes()) {
                                PredictedEcho::Consumed => continue,
                                PredictedEcho::Mismatch => {
                                    pane_refresh_requires_full = true;
                                    pane_refresh.schedule_immediate();
                                }
                                PredictedEcho::NoPrediction => {}
                            }
                        }
                    }
                    let item = if deferred_controls.is_empty()
                        && control_backlog.load(Ordering::Acquire) == 0
                        && !locked
                        && !closing.load(Ordering::SeqCst)
                        && !persistent_overlay_visible
                        && persistent_overlay.is_none()
                        && should_treat_attach_output_as_interactive(last_client_input_at)
                    {
                        match item {
                            rmux_core::events::OutputCursorItem::Event(event)
                                if !event.is_empty()
                                    && event.byte_len() <= 512
                                    && event.passthroughs().is_empty()
                                    && pane_refresh.can_bypass_small_plain_output()
                                    && current_target.live_pane.as_ref().is_some_and(|pane| {
                                        pane.can_forward_plain_bytes(event.bytes())
                                    }) =>
                            {
                                let snapshot_synced = current_target
                                    .live_pane
                                    .as_mut()
                                    .is_some_and(|pane| pane.apply_forwarded_plain_bytes(event.bytes()));
                                if snapshot_synced {
                                    emit_attach_bytes(&stream, event.bytes()).await?;
                                    let _ = pane_refresh.note_output_batch(false);
                                    continue;
                                }
                                rmux_core::events::OutputCursorItem::Event(event)
                            }
                            other => other,
                        }
                    } else {
                        item
                    };
                    let pending_output_batch =
                        match collect_attach_output_batch(item, current_target.pane_output.as_mut()) {
                        AttachOutputBatch::Closed => {
                            current_target.pane_output = None;
                            continue;
                        }
                        AttachOutputBatch::Gap => {
                            if current_target.live_pane.is_none()
                                || persistent_overlay_visible
                                || persistent_overlay.is_some()
                            {
                                pane_refresh_requires_full = true;
                            }
                            pane_refresh.schedule_sustained();
                            continue;
                        }
                        batch @ AttachOutputBatch::Events { .. } => batch,
                        };
                    match apply_pending_attach_controls(
                        &mut deferred_controls,
                        attach_controls.as_mut(),
                &control_backlog,
                        &mut current_target,
                        &stream,
                        &mut render_generation,
                        &mut overlay_generation,
                        &mut persistent_overlay,
                        &mut persistent_overlay_visible,
                        &mut persistent_overlay_state_id,
                        &mut locked,
                        Some(PendingAttachInputState::new(
                            &mut pending_input,
                            &mut pending_escape_flush,
                        )),
                    )
                    .await?
                    {
                        PendingAttachAction::Exit(PendingAttachExit {
                            reason,
                            drop_pending_output,
                            snapshot_covered_output_before_sequence,
                        }) => {
                            // The receiver cursor already owns this batch. Hand it to the
                            // terminal exit drain unless an earlier control deliberately
                            // invalidated output from the old attach target.
                            finish_pending_attach_exit_with_batch(
                                reason,
                                &stream,
                                &mut current_target,
                                &mut deferred_passthroughs,
                                pending_attach_exit_output_batch(
                                    drop_pending_output,
                                    snapshot_covered_output_before_sequence,
                                    pending_output_batch,
                                ),
                            )
                            .await?;
                            log_attach_exit(&live_input, &current_target, reason);
                            return Ok(());
                        }
                        PendingAttachAction::Continue { target_changed } => {
                            reschedule_status_refresh_if_target_changed(
                                target_changed,
                                &mut status_refresh,
                                &live_input,
                                &current_target,
                            )
                            .await;
                            clear_close_pane_output_after_refresh_if_target_changed(
                                target_changed,
                                &mut close_pane_output_after_refresh,
                            );
                            clear_deferred_passthroughs_if_target_changed(
                                target_changed,
                                &mut deferred_passthroughs,
                            );
                            continue;
                        }
                        PendingAttachAction::InteractiveInput => {
                            mark_attach_interactive_input(
                                &mut pane_refresh,
                                &mut last_client_input_at,
                            );
                            absorb_transient_terminal_prefix(
                                &live_input,
                                &mut pending_input,
                                &mut pending_escape_flush,
                            )
                            .await;
                            pane_refresh.schedule_now();
                            continue;
                        }
                        PendingAttachAction::Refresh { target_changed } => {
                            let AttachOutputBatch::Events {
                                passthroughs,
                                close_after_render,
                                ..
                            } = pending_output_batch
                            else {
                                unreachable!("closed and gap batches return before control dispatch")
                            };
                            reschedule_status_refresh_if_target_changed(
                                target_changed,
                                &mut status_refresh,
                                &live_input,
                                &current_target,
                            )
                            .await;
                            clear_close_pane_output_after_refresh_if_target_changed(
                                target_changed,
                                &mut close_pane_output_after_refresh,
                            );
                            clear_deferred_passthroughs_if_target_changed(
                                target_changed,
                                &mut deferred_passthroughs,
                            );
                            defer_passthroughs(&mut deferred_passthroughs, passthroughs);
                            schedule_attach_render_refresh(
                                &mut pane_refresh,
                                &mut pane_refresh_requires_full,
                                &live_input,
                            )
                            .await;
                            if close_after_render {
                                current_target.pane_output = None;
                            }
                            continue;
                        }
                        PendingAttachAction::Write => {
                            let AttachOutputBatch::Events {
                                bytes: raw_output_bytes,
                                passthroughs,
                                close_after_render,
                                sustained: sustained_output,
                                ..
                            } = pending_output_batch
                            else {
                                unreachable!("closed and gap batches return before control dispatch")
                            };
                            if locked {
                                if close_after_render {
                                    current_target.pane_output = None;
                                }
                                continue;
                            }
                            if closing.load(Ordering::SeqCst) {
                                log_attach_exit(
                                    &live_input,
                                    &current_target,
                                    AttachExitReason::AttachClosingFlag,
                                );
                                let _ = emit_attach_stop(&stream, &current_target).await;
                                return Ok(());
                            }
                            if persistent_overlay_visible || persistent_overlay.is_some() {
                                defer_passthroughs(&mut deferred_passthroughs, passthroughs);
                                pane_refresh_requires_full = true;
                                pane_refresh.schedule_now();
                                if close_after_render {
                                    current_target.pane_output = None;
                                }
                                continue;
                            }
                            if passthroughs.is_empty() && current_target.live_pane.is_some() {
                                let interactive_output =
                                    should_treat_attach_output_as_interactive(last_client_input_at);
                                let small_plain_output = raw_output_bytes.len() <= 512;
                                let output_can_bypass_render = small_plain_output
                                    && pane_refresh.can_bypass_small_plain_output();
                                if !sustained_output
                                    && output_can_bypass_render
                                    && try_forward_plain_output(
                                        &stream,
                                        &mut current_target,
                                        &raw_output_bytes,
                                    )
                                    .await?
                                {
                                    let _ = pane_refresh.note_output_batch(sustained_output);
                                    if close_after_render {
                                        current_target.pane_output = None;
                                    }
                                    continue;
                                }
                                if interactive_output {
                                    pane_refresh.note_interactive_output();
                                    match current_target
                                        .live_pane
                                        .as_mut()
                                        .map(|pane| pane.render_interactive_frame_from_transcript())
                                    {
                                        Some(PaneRenderDelta::Incremental(delta)) => {
                                            emit_live_render_frame(
                                                &stream,
                                                &mut current_target,
                                                &delta,
                                                false,
                                            )
                                            .await?;
                                            if close_after_render {
                                                current_target.pane_output = None;
                                            }
                                            continue;
                                        }
                                        Some(PaneRenderDelta::RequiresFullRefresh) | None => {
                                            pane_refresh_requires_full = true;
                                            pane_refresh.schedule_immediate();
                                        }
                                    }
                                } else if pane_refresh.note_output_batch(sustained_output) {
                                    pane_refresh.schedule_sustained();
                                } else {
                                    pane_refresh.schedule_now();
                                }
                                if close_after_render {
                                    close_pane_output_after_refresh = true;
                                }
                                continue;
                            }
                            let passthrough_frame = take_passthrough_frame_with_live_passthroughs(
                                &current_target,
                                &mut deferred_passthroughs,
                                passthroughs,
                            );
                            let replaceable_render = current_target.render_stream;
                            match current_target
                                .live_pane
                                .as_mut()
                                .map(|pane| pane.render_frame_from_transcript(replaceable_render))
                            {
                                Some(PaneRenderDelta::Incremental(delta)) => {
                                    emit_live_render_frame(
                                        &stream,
                                        &mut current_target,
                                        &delta,
                                        replaceable_render,
                                    )
                                    .await?;
                                    emit_attach_bytes(&stream, &passthrough_frame).await?;
                                }
                                Some(PaneRenderDelta::RequiresFullRefresh) | None => {
                                    pane_refresh_requires_full = true;
                                    pane_refresh.schedule_now();
                                    emit_attach_bytes(&stream, &passthrough_frame).await?;
                                }
                            }
                            if close_after_render {
                                current_target.pane_output = None;
                            }
                        }
                    }
                }
            }
        }
    }
    .await;

    if let Err(error) = &result {
        record_attach_error(live_input.attach_pid(), &current_target.session_name, error);
        let _ = emit_attach_stop(&stream, &current_target).await;
    }

    result
}

#[allow(clippy::too_many_arguments)]
#[cfg(any(unix, windows))]
async fn synchronize_persistent_overlay_epoch(
    persistent_overlay_epoch: &AtomicU64,
    stream: &AttachTransport,
    current_target: &types::OpenAttachTarget,
    attach_controls: Option<&mut mpsc::UnboundedReceiver<AttachControl>>,
    deferred_controls: &mut VecDeque<AttachControl>,
    control_backlog: &AtomicUsize,
    persistent_overlay: &mut Option<Vec<u8>>,
    persistent_overlay_visible: &mut bool,
    persistent_overlay_state_id: &mut Option<u64>,
) -> io::Result<()> {
    let overlay_barrier = persistent_overlay_epoch.load(Ordering::SeqCst);
    let previous_overlay_state_id = *persistent_overlay_state_id;
    advance_persistent_overlay_state(
        persistent_overlay_state_id,
        attach_controls,
        deferred_controls,
        overlay_barrier,
        control_backlog,
    );
    redraw_after_persistent_overlay_state_advance(
        stream,
        current_target,
        persistent_overlay,
        persistent_overlay_visible,
        previous_overlay_state_id,
        *persistent_overlay_state_id,
        persistent_overlay_replacement_pending(deferred_controls, *persistent_overlay_state_id),
    )
    .await
}

#[cfg(any(unix, windows))]
fn attach_shutdown_observable(shutdown: &watch::Receiver<()>) -> bool {
    shutdown.has_changed().unwrap_or(true)
}

#[cfg(any(unix, windows))]
/// Linearize one attach mutation batch against shutdown.
///
/// Callers keep the returned Drain guard through the batch's last handler mutation and any
/// lifecycle publication it awaits. Transport reads may happen before this point, but decoded
/// input or attach controls must not be applied until admission succeeds.
fn begin_attach_mutation_batch(
    live_input: &LiveAttachInputContext,
    shutdown: &watch::Receiver<()>,
) -> Option<crate::handler::NormalRequestGuard> {
    if attach_shutdown_observable(shutdown) {
        return None;
    }
    let guard = live_input.handler.try_begin_normal_request(true)?;
    if attach_shutdown_observable(shutdown) {
        // The listener closes normal admission before publishing transport shutdown. If the
        // watch raced the optimistic admission, reject the batch before its first mutation.
        return None;
    }
    Some(guard)
}

#[cfg(any(unix, windows))]
fn take_pending_terminal_attach_control(
    deferred_controls: &mut VecDeque<AttachControl>,
    mut attach_controls: Option<&mut mpsc::UnboundedReceiver<AttachControl>>,
    control_backlog: &AtomicUsize,
) -> Option<AttachControl> {
    loop {
        let control = match deferred_controls.pop_front() {
            Some(control) => control,
            None => {
                let control_rx = attach_controls.as_mut()?;
                match try_recv_attach_control(control_rx, control_backlog) {
                    Ok(control) => control,
                    Err(
                        mpsc::error::TryRecvError::Empty | mpsc::error::TryRecvError::Disconnected,
                    ) => return None,
                }
            }
        };
        if control.is_terminal() {
            return Some(control);
        }
        // Shutdown has already been observed. Dropping a queued refresh, switch, overlay,
        // write, lock, or suspend releases its memory reservation without starting the
        // attach-control batch that could otherwise mutate the live forwarder state.
    }
}

#[cfg(any(unix, windows))]
async fn finish_terminal_attach_control(
    control: AttachControl,
    stream: &AttachTransport,
    current_target: &mut types::OpenAttachTarget,
    deferred_passthroughs: &mut Vec<TerminalPassthrough>,
    pending_output_batch: Option<AttachOutputBatch>,
) -> io::Result<AttachExitReason> {
    match control {
        AttachControl::Detach => {
            emit_detached_attach_stop(stream, current_target).await?;
            Ok(AttachExitReason::AttachControlDetach)
        }
        AttachControl::Exited => {
            finish_pending_attach_exit_with_batch(
                AttachExitReason::AttachControlExited,
                stream,
                current_target,
                deferred_passthroughs,
                pending_output_batch,
            )
            .await?;
            Ok(AttachExitReason::AttachControlExited)
        }
        AttachControl::DetachKill => {
            emit_attach_stop(stream, current_target).await?;
            emit_attach_message(stream, &AttachMessage::DetachKill).await?;
            Ok(AttachExitReason::AttachControlDetachKill)
        }
        AttachControl::DetachExecShellCommand(command) => {
            emit_attach_stop(stream, current_target).await?;
            emit_attach_message(stream, &AttachMessage::DetachExecShellCommand(command)).await?;
            Ok(AttachExitReason::AttachControlDetachExec)
        }
        AttachControl::InteractiveInput
        | AttachControl::Refresh
        | AttachControl::Switch(_)
        | AttachControl::AdvancePersistentOverlayState(_)
        | AttachControl::Overlay(_)
        | AttachControl::Write(_)
        | AttachControl::ClipboardWrite { .. }
        | AttachControl::LockShellCommand(_)
        | AttachControl::Suspend => {
            unreachable!("only terminal attach controls reach shutdown finalization")
        }
    }
}

#[cfg(any(unix, windows))]
fn log_attach_exit(
    live_input: &LiveAttachInputContext,
    current_target: &types::OpenAttachTarget,
    reason: AttachExitReason,
) {
    record_attach_exit(
        live_input.attach_pid(),
        &current_target.session_name,
        reason,
    );
}

#[cfg(any(unix, windows))]
async fn finish_pending_attach_exit(
    reason: AttachExitReason,
    stream: &AttachTransport,
    current_target: &mut types::OpenAttachTarget,
    deferred_passthroughs: &mut Vec<TerminalPassthrough>,
) -> io::Result<()> {
    finish_pending_attach_exit_with_batch(
        reason,
        stream,
        current_target,
        deferred_passthroughs,
        None,
    )
    .await
}

#[cfg(any(unix, windows))]
fn pending_attach_exit_output_batch(
    drop_pending_output: bool,
    snapshot_covered_output_before_sequence: Option<u64>,
    batch: AttachOutputBatch,
) -> Option<AttachOutputBatch> {
    if drop_pending_output {
        return None;
    }
    Some(match snapshot_covered_output_before_sequence {
        Some(before_sequence) => batch.covered_by_render_snapshot(before_sequence),
        None => batch,
    })
}

#[cfg(any(unix, windows))]
async fn finish_pending_attach_exit_with_batch(
    reason: AttachExitReason,
    stream: &AttachTransport,
    current_target: &mut types::OpenAttachTarget,
    deferred_passthroughs: &mut Vec<TerminalPassthrough>,
    pending_batch: Option<AttachOutputBatch>,
) -> io::Result<()> {
    if reason != AttachExitReason::AttachControlExited {
        return Ok(());
    }

    let mut output_bytes = Vec::new();
    let mut passthroughs = Vec::new();
    let mut saw_gap = false;
    let output_closed = pending_batch.is_some_and(|batch| {
        collect_final_attach_output_batch(batch, &mut output_bytes, &mut passthroughs, &mut saw_gap)
    });
    let pane_output = if output_closed {
        None
    } else {
        current_target.pane_output.take()
    };
    if let Some(mut pane_output) = pane_output {
        #[cfg(not(windows))]
        while let Some(item) = pane_output.try_recv() {
            if collect_final_attach_output_item(
                item,
                &mut pane_output,
                &mut output_bytes,
                &mut passthroughs,
                &mut saw_gap,
            ) {
                break;
            }
        }
        #[cfg(windows)]
        {
            let deadline = Instant::now() + ATTACH_EXIT_OUTPUT_DRAIN_TIMEOUT;
            loop {
                let item = match pane_output.try_recv() {
                    Some(item) => item,
                    None => match tokio::time::timeout_at(deadline, pane_output.recv()).await {
                        Ok(item) => item,
                        Err(_) => break,
                    },
                };
                if collect_final_attach_output_item(
                    item,
                    &mut pane_output,
                    &mut output_bytes,
                    &mut passthroughs,
                    &mut saw_gap,
                ) {
                    break;
                }
            }
        }
    }

    let output_forwarded = !output_bytes.is_empty()
        && try_forward_plain_output(stream, current_target, &output_bytes).await?;
    let require_final_render = saw_gap || (!output_bytes.is_empty() && !output_forwarded);
    if require_final_render {
        match current_target
            .live_pane
            .as_mut()
            .map(|pane| pane.render_frame_from_transcript(true))
        {
            Some(PaneRenderDelta::Incremental(frame)) => {
                emit_live_render_frame(stream, current_target, &frame, false).await?;
            }
            Some(PaneRenderDelta::RequiresFullRefresh) | None => {
                emit_attach_bytes(stream, &output_bytes).await?;
            }
        }
    }

    let passthrough_frame = take_passthrough_frame_with_live_passthroughs(
        current_target,
        deferred_passthroughs,
        passthroughs,
    );
    emit_attach_bytes(stream, &passthrough_frame).await?;
    emit_exited_attach_stop(stream, current_target).await
}

#[cfg(any(unix, windows))]
fn collect_final_attach_output_item(
    item: rmux_core::events::OutputCursorItem,
    pane_output: &mut types::PaneOutputReceiver,
    output_bytes: &mut Vec<u8>,
    passthroughs: &mut Vec<TerminalPassthrough>,
    saw_gap: &mut bool,
) -> bool {
    let batch = collect_attach_output_batch(item, Some(pane_output));
    collect_final_attach_output_batch(batch, output_bytes, passthroughs, saw_gap)
}

#[cfg(any(unix, windows))]
fn collect_final_attach_output_batch(
    batch: AttachOutputBatch,
    output_bytes: &mut Vec<u8>,
    passthroughs: &mut Vec<TerminalPassthrough>,
    saw_gap: &mut bool,
) -> bool {
    match batch {
        AttachOutputBatch::Closed => true,
        AttachOutputBatch::Gap => {
            *saw_gap = true;
            false
        }
        AttachOutputBatch::Events {
            bytes,
            passthroughs: batch_passthroughs,
            close_after_render,
            sustained: _,
            ..
        } => {
            output_bytes.extend_from_slice(&bytes);
            passthroughs.extend(batch_passthroughs);
            close_after_render
        }
    }
}

#[cfg(any(unix, windows))]
fn clear_close_pane_output_after_refresh_if_target_changed(
    target_changed: bool,
    close_pane_output_after_refresh: &mut bool,
) {
    if target_changed {
        *close_pane_output_after_refresh = false;
    }
}

#[cfg(any(unix, windows))]
async fn reschedule_status_refresh_if_target_changed(
    target_changed: bool,
    status_refresh: &mut AttachStatusRefreshScheduler,
    live_input: &LiveAttachInputContext,
    current_target: &types::OpenAttachTarget,
) {
    if target_changed {
        reschedule_status_refresh_for_target(status_refresh, live_input, current_target).await;
    }
}

#[cfg(any(unix, windows))]
async fn emit_live_render_frame(
    stream: &AttachTransport,
    current_target: &mut types::OpenAttachTarget,
    frame: &PaneRenderDeltaFrame,
    replaceable: bool,
) -> io::Result<()> {
    if let Some(cursor_style) = frame.cursor_style() {
        if let Some(sequence) = current_target
            .outer_terminal
            .render_cursor_style_transition(Some(current_target.cursor_style), cursor_style)
        {
            emit_attach_bytes(stream, sequence.as_bytes()).await?;
        }
        current_target.cursor_style = cursor_style;
    }
    if replaceable {
        emit_coalescible_render_frame(
            stream,
            &current_target.outer_terminal,
            frame.frame(),
            current_target.render_stream,
        )
        .await
    } else {
        emit_render_frame(stream, &current_target.outer_terminal, frame.frame()).await
    }
}

#[cfg(any(unix, windows))]
async fn try_forward_plain_output(
    stream: &AttachTransport,
    current_target: &mut types::OpenAttachTarget,
    bytes: &[u8],
) -> io::Result<bool> {
    if bytes.is_empty() {
        return Ok(false);
    }

    if current_target
        .live_pane
        .as_ref()
        .is_some_and(|pane| pane.can_forward_plain_bytes(bytes))
    {
        let snapshot_synced = current_target
            .live_pane
            .as_mut()
            .is_some_and(|pane| pane.apply_forwarded_plain_bytes(bytes));
        if !snapshot_synced {
            return Ok(false);
        }

        emit_attach_bytes(stream, bytes).await?;
        return Ok(true);
    }

    if let Some(frame) = current_target
        .live_pane
        .as_mut()
        .and_then(|pane| pane.positioned_plain_output_frame(bytes))
    {
        emit_attach_bytes(stream, &frame).await?;
        return Ok(true);
    }

    Ok(false)
}

#[cfg(any(unix, windows))]
async fn schedule_attach_render_refresh(
    pane_refresh: &mut AttachRefreshScheduler,
    pane_refresh_requires_full: &mut bool,
    live_input: &LiveAttachInputContext,
) {
    live_input
        .handler
        .clear_attached_render_refresh_pending(live_input.attach_pid())
        .await;
    *pane_refresh_requires_full = true;
    pane_refresh.note_interactive_output();
    pane_refresh.schedule_now();
}

#[cfg(any(unix, windows))]
fn collect_pending_attach_output_batch_metadata(
    current_target: &mut types::OpenAttachTarget,
) -> Option<AttachOutputBatch> {
    let pane_output = current_target.pane_output.as_mut()?;
    let first = pane_output.try_recv()?;
    Some(collect_attach_output_batch_metadata(
        first,
        Some(pane_output),
    ))
}

#[cfg(any(unix, windows))]
async fn refresh_current_attach_client(live_input: &LiveAttachInputContext) {
    if let Ok(session_name) = live_input
        .handler
        .attached_session_name(live_input.attach_pid())
        .await
    {
        live_input
            .handler
            .refresh_attached_client(live_input.attach_pid(), &session_name)
            .await;
    }
}

#[cfg(any(unix, windows))]
async fn reschedule_status_refresh_for_target(
    status_refresh: &mut AttachStatusRefreshScheduler,
    live_input: &LiveAttachInputContext,
    current_target: &types::OpenAttachTarget,
) {
    reschedule_status_refresh_for_session(status_refresh, live_input, &current_target.session_name)
        .await;
}

#[cfg(any(unix, windows))]
async fn reschedule_status_refresh_for_session(
    status_refresh: &mut AttachStatusRefreshScheduler,
    live_input: &LiveAttachInputContext,
    session_name: &rmux_proto::SessionName,
) {
    status_refresh.reschedule(
        live_input
            .handler
            .attached_status_interval(session_name)
            .await,
    );
}

#[cfg(any(unix, windows))]
async fn sync_pending_escape_flush(
    pending_escape_flush: &mut PendingEscapeFlush,
    live_input: &LiveAttachInputContext,
    pending_input: &[u8],
) {
    if pending_input.is_empty() {
        pending_escape_flush.clear();
        return;
    }
    let escape_time = live_input.handler.attached_escape_time().await;
    sync_pending_escape_flush_with_escape_time(pending_escape_flush, pending_input, escape_time);
}

#[cfg(any(unix, windows))]
async fn absorb_transient_terminal_prefix(
    live_input: &LiveAttachInputContext,
    pending_input: &mut Vec<u8>,
    pending_escape_flush: &mut PendingEscapeFlush,
) {
    let prefix = live_input
        .handler
        .take_transient_terminal_prefix_for_identity(live_input.identity)
        .await;
    if prefix.is_empty() {
        return;
    }
    pending_input.extend(prefix);
    sync_pending_escape_flush(pending_escape_flush, live_input, pending_input).await;
}

#[cfg(any(unix, windows))]
async fn flush_due_pending_escape_input(
    pending_escape_flush: &mut PendingEscapeFlush,
    live_input: &LiveAttachInputContext,
    pending_input: &mut Vec<u8>,
    locked: bool,
) -> io::Result<()> {
    if !pending_escape_deadline_due(pending_escape_flush) {
        return Ok(());
    }

    #[cfg(test)]
    let skip_identity_validation = !live_input.validate_identity;
    #[cfg(not(test))]
    let skip_identity_validation = false;
    if !skip_identity_validation
        && !live_input
            .handler
            .current_live_attach_input(live_input.identity)
            .await
    {
        pending_escape_flush.clear();
        pending_input.clear();
        return Err(io::Error::other(
            "stale attach forwarder retained pending input",
        ));
    }

    pending_escape_flush.clear();
    if locked {
        pending_input.clear();
        return Ok(());
    }

    live_input
        .handler
        .flush_attached_pending_escape_input_for_identity(live_input.identity, pending_input)
        .await?;
    // Rerouting flushed remainder bytes can retain a fresh ambiguous prefix
    // (for example, a second ESC ] inside the body). Re-arm it immediately
    // rather than waiting for another client read.
    sync_pending_escape_flush(pending_escape_flush, live_input, pending_input).await;
    Ok(())
}

#[cfg(any(unix, windows))]
fn pending_escape_deadline_due(pending_escape_flush: &PendingEscapeFlush) -> bool {
    pending_escape_flush
        .deadline()
        .is_some_and(|deadline| deadline <= Instant::now())
}

#[cfg(any(unix, windows))]
fn sync_pending_escape_flush_with_escape_time(
    pending_escape_flush: &mut PendingEscapeFlush,
    pending_input: &[u8],
    escape_time: Duration,
) {
    // `PendingEscapeFlush` owns the retained-input grammar. Keeping the
    // classifier out of this wrapper prevents the decoder/timer split-brain
    // that previously dropped APC and numeric CSI deadlines here.
    pending_escape_flush.sync(pending_input, escape_time);
}

#[cfg(any(unix, windows))]
#[allow(clippy::too_many_arguments)]
async fn process_attach_socket_messages(
    decoder: &mut AttachFrameDecoder,
    stream: &AttachTransport,
    live_input: &LiveAttachInputContext,
    closing: &AtomicBool,
    current_target: &mut types::OpenAttachTarget,
    pending_input: &mut Vec<u8>,
    active_emit_cache: &mut Option<(u64, rmux_proto::WindowTarget)>,
    locked: &mut bool,
    pane_refresh: &mut AttachRefreshScheduler,
    pending_escape_flush: &mut PendingEscapeFlush,
    last_client_input_at: &mut Option<Instant>,
) -> io::Result<()> {
    let forwarded_to_pane = match process_socket_messages(
        decoder,
        stream,
        live_input,
        Some(current_target),
        PendingAttachInputState::new(pending_input, pending_escape_flush),
        active_emit_cache,
        locked,
    )
    .await
    {
        Ok(forwarded_to_pane) => forwarded_to_pane,
        Err(_) if closing.load(Ordering::SeqCst) => {
            // A terminal attach control is queued before `closing` is
            // published. Input may already be between the queue poll and its
            // identity check when close removes the registration. Discard that
            // now-stale input and let the next loop iteration consume the
            // terminal control, which owns the finite output drain.
            PendingAttachInputState::new(pending_input, pending_escape_flush).clear();
            return Ok(());
        }
        Err(error) => return Err(error),
    };
    if forwarded_to_pane {
        mark_attach_interactive_input(pane_refresh, last_client_input_at);
        if pane_refresh.is_pending() {
            pane_refresh.schedule_immediate();
        }
    }
    sync_pending_escape_flush(pending_escape_flush, live_input, pending_input).await;
    Ok(())
}

#[cfg(any(unix, windows))]
fn mark_attach_interactive_input(
    pane_refresh: &mut AttachRefreshScheduler,
    last_client_input_at: &mut Option<Instant>,
) {
    *last_client_input_at = Some(Instant::now());
    pane_refresh.note_interactive_output();
}

#[cfg(any(unix, windows))]
enum DeferredAttachInputOutput {
    Frame(AttachMessage),
    Unlock {
        start_sequence: Vec<u8>,
        outer_terminal: Box<crate::outer_terminal::OuterTerminal>,
        render_frame: Vec<u8>,
    },
}

#[cfg(any(unix, windows))]
async fn process_socket_messages(
    decoder: &mut AttachFrameDecoder,
    stream: &AttachTransport,
    live_input: &LiveAttachInputContext,
    mut current_target: Option<&mut types::OpenAttachTarget>,
    mut pending_input: PendingAttachInputState<'_>,
    active_emit_cache: &mut Option<(u64, rmux_proto::WindowTarget)>,
    locked: &mut bool,
) -> io::Result<bool> {
    // The transport read and frame accumulation have already completed. Each
    // mutation below carries the immutable registration identity and validates
    // it at its own atomic snapshot point; no guard spans PTY or command awaits.
    #[cfg(test)]
    pause_before_live_attach_input_validation(live_input.identity).await;
    #[cfg(test)]
    let skip_identity_validation = !live_input.validate_identity;
    #[cfg(not(test))]
    let skip_identity_validation = false;
    if !skip_identity_validation
        && !live_input
            .handler
            .current_live_attach_input(live_input.identity)
            .await
    {
        let (pending_input, pending_escape_flush) = pending_input.parts_mut();
        pending_input.clear();
        pending_escape_flush.clear();
        return Err(io::Error::other("stale attach forwarder input"));
    }
    #[cfg(test)]
    pause_after_live_attach_input_validation(live_input.identity).await;
    let (pending_input, pending_escape_flush) = pending_input.parts_mut();
    let mut forwarded_to_pane = false;
    let mut deferred_outputs = Vec::new();
    let mut data_scratch = [0_u8; ATTACH_INPUT_STACK_PAYLOAD];
    'messages: loop {
        loop {
            if pending_escape_deadline_due(pending_escape_flush) {
                break 'messages;
            }
            let Some(bytes) = decoder
                .next_data_payload_into(&mut data_scratch)
                .map_err(invalid_attach_message)?
            else {
                break;
            };
            let retained_before = pending_input.len();
            forwarded_to_pane |= process_attach_data_payload(
                live_input,
                stream,
                current_target.as_deref_mut(),
                pending_input,
                active_emit_cache,
                locked,
                bytes,
            )
            .await?;
            pending_escape_flush.observe_input_dispatch(
                retained_before,
                bytes.len(),
                pending_input,
            );
        }

        if pending_escape_deadline_due(pending_escape_flush) {
            break;
        }
        let Some(message) = decoder.next_message().map_err(invalid_attach_message)? else {
            break;
        };
        match message {
            AttachMessage::Data(bytes) => {
                let retained_before = pending_input.len();
                forwarded_to_pane |= process_attach_data_payload(
                    live_input,
                    stream,
                    current_target.as_deref_mut(),
                    pending_input,
                    active_emit_cache,
                    locked,
                    &bytes,
                )
                .await?;
                pending_escape_flush.observe_input_dispatch(
                    retained_before,
                    bytes.len(),
                    pending_input,
                );
            }
            AttachMessage::Keystroke(keystroke) => {
                let retained_before = pending_input.len();
                let appended = keystroke.bytes().len();
                let keystroke_forwarded_to_pane = if *locked {
                    pending_input.clear();
                    false
                } else {
                    live_input
                        .handler
                        .handle_attached_keystroke_input_with_active_cache_for_identity(
                            live_input.identity,
                            pending_input,
                            &keystroke,
                            active_emit_cache,
                        )
                        .await?
                };
                pending_escape_flush.observe_input_dispatch(
                    retained_before,
                    appended,
                    pending_input,
                );
                forwarded_to_pane |= keystroke_forwarded_to_pane;
                let response = live_input
                    .handler
                    .handle_attached_keystroke_for_identity(
                        live_input.identity,
                        &keystroke,
                        !keystroke_forwarded_to_pane,
                    )
                    .await
                    .map_err(io::Error::other)?;
                deferred_outputs.push(DeferredAttachInputOutput::Frame(
                    AttachMessage::KeyDispatched(response),
                ));
            }
            AttachMessage::Resize(size) => {
                live_input
                    .handler
                    .handle_attached_resize_for_identity(live_input.identity, size)
                    .await
                    .map_err(io::Error::other)?;
            }
            AttachMessage::ResizeGeometry(geometry) => {
                live_input
                    .handler
                    .handle_attached_resize_geometry_for_identity(live_input.identity, geometry)
                    .await
                    .map_err(io::Error::other)?;
            }
            AttachMessage::Render(_)
            | AttachMessage::Lock(_)
            | AttachMessage::LockShellCommand(_) => {
                return Err(io::Error::other(
                    "received unexpected server-to-client message from attach client",
                ));
            }
            AttachMessage::Suspend
            | AttachMessage::DetachKill
            | AttachMessage::DetachExec(_)
            | AttachMessage::DetachExecShellCommand(_) => {
                return Err(io::Error::other(
                    "received unexpected control action from attach client",
                ));
            }
            AttachMessage::Unlock => {
                if !live_input
                    .handler
                    .handle_attached_unlock_for_identity(live_input.identity)
                    .await
                {
                    pending_input.clear();
                    pending_escape_flush.clear();
                    return Err(io::Error::other("stale attach forwarder unlock"));
                }
                *locked = false;
                if let Some(current_target) = current_target.as_deref() {
                    deferred_outputs.push(DeferredAttachInputOutput::Unlock {
                        start_sequence: current_target.outer_terminal.attach_start_sequence(),
                        outer_terminal: Box::new(current_target.outer_terminal.clone()),
                        render_frame: current_target.render_frame.clone(),
                    });
                }
                let session_name = live_input
                    .handler
                    .attached_session_name_for_identity(live_input.identity)
                    .await
                    .map_err(io::Error::other)?;
                live_input
                    .handler
                    .refresh_attached_client_for_identity(
                        live_input.attach_pid(),
                        live_input.identity.attach_id(),
                        &session_name,
                        "attach unlock",
                    )
                    .await
                    .map_err(io::Error::other)?;
                // Resuming terminal ownership is an inter-frame barrier. A
                // following binding may block indefinitely, so flush the
                // start sequence and render before decoding another frame.
                break 'messages;
            }
            AttachMessage::KeyDispatched(_) => {
                return Err(io::Error::other(
                    "received unexpected key dispatch acknowledgement from attach client",
                ));
            }
        }
    }

    // Client writes can block behind transport backpressure. They are emitted
    // only after all identity-checked state mutations are complete.
    for output in deferred_outputs {
        match output {
            DeferredAttachInputOutput::Frame(message) => {
                emit_attach_frame(stream, &message).await?;
            }
            DeferredAttachInputOutput::Unlock {
                start_sequence,
                outer_terminal,
                render_frame,
            } => {
                emit_attach_bytes(stream, &start_sequence).await?;
                emit_render_frame(stream, &outer_terminal, &render_frame).await?;
            }
        }
    }

    Ok(forwarded_to_pane)
}

#[cfg(any(unix, windows))]
async fn process_attach_data_payload(
    live_input: &LiveAttachInputContext,
    stream: &AttachTransport,
    current_target: Option<&mut types::OpenAttachTarget>,
    pending_input: &mut Vec<u8>,
    active_emit_cache: &mut Option<(u64, rmux_proto::WindowTarget)>,
    locked: &mut bool,
    bytes: &[u8],
) -> io::Result<bool> {
    if *locked {
        pending_input.clear();
        return Ok(false);
    }
    let _ = (stream, current_target);
    live_input
        .handler
        .handle_attached_live_input_with_active_cache_for_identity(
            live_input.identity,
            pending_input,
            bytes,
            active_emit_cache,
        )
        .await
}

#[cfg(all(test, unix))]
fn is_predictable_local_echo(bytes: &[u8]) -> bool {
    predictable_local_echo_prefix_len(bytes) == bytes.len()
}

#[cfg(all(unix, test))]
fn predictable_local_echo_prefix_len(bytes: &[u8]) -> usize {
    let printable_prefix = bytes
        .iter()
        .take(MAX_PREDICTED_LOCAL_ECHO_BYTES)
        .take_while(|byte| matches!(**byte, b' '..=b'~'))
        .count();
    if printable_prefix == 0 {
        return 0;
    }
    if printable_prefix == bytes.len() {
        return printable_prefix;
    }
    if matches!(bytes.get(printable_prefix), Some(b'\r' | b'\n')) {
        return printable_prefix;
    }
    0
}

#[cfg(unix)]
fn consume_predicted_echo(
    current_target: &mut types::OpenAttachTarget,
    bytes: &[u8],
) -> PredictedEcho {
    expire_stale_predicted_echo(current_target);
    if current_target.predicted_echo.is_empty() || bytes.is_empty() {
        return PredictedEcho::NoPrediction;
    }
    if current_target.predicted_echo.len() < bytes.len() {
        clear_predicted_echo(current_target);
        return PredictedEcho::Mismatch;
    }
    if !current_target
        .predicted_echo
        .iter()
        .take(bytes.len())
        .copied()
        .eq(bytes.iter().copied())
    {
        clear_predicted_echo(current_target);
        return PredictedEcho::Mismatch;
    }

    current_target.predicted_echo.drain(..bytes.len());
    if current_target.predicted_echo.is_empty() {
        current_target.predicted_echo_started_at = None;
    }
    if let Some(pane) = current_target.live_pane.as_mut() {
        let _ = pane.apply_forwarded_plain_bytes(bytes);
    }
    PredictedEcho::Consumed
}

#[cfg(unix)]
fn expire_stale_predicted_echo(current_target: &mut types::OpenAttachTarget) {
    if current_target
        .predicted_echo_started_at
        .is_some_and(|started_at| {
            Instant::now().saturating_duration_since(started_at) >= PREDICTED_LOCAL_ECHO_TIMEOUT
        })
    {
        clear_predicted_echo(current_target);
    }
}

#[cfg(unix)]
fn clear_predicted_echo(current_target: &mut types::OpenAttachTarget) {
    current_target.predicted_echo.clear();
    current_target.predicted_echo_started_at = None;
}

#[cfg(unix)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PredictedEcho {
    NoPrediction,
    Consumed,
    Mismatch,
}

#[cfg(any(unix, windows))]
fn should_treat_attach_output_as_interactive(last_client_input_at: Option<Instant>) -> bool {
    last_client_input_at.is_some_and(|input_at| {
        Instant::now().saturating_duration_since(input_at) <= ATTACH_INTERACTIVE_OUTPUT_WINDOW
    })
}

#[cfg(all(test, unix))]
mod tests;