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
use std::borrow::Cow;
use std::collections::VecDeque;
use std::io;
use std::sync::{atomic::Ordering, Arc};

use rmux_core::{input::mode, key_code_lookup_bits, KeyCode, LifecycleEvent, KEYC_ANY};
#[cfg(windows)]
use rmux_core::{key_string_lookup_string, KEYC_CTRL, KEYC_IMPLIED_META, KEYC_META, KEYC_SHIFT};
use rmux_proto::{AttachedKeystroke, PaneTarget, WindowTarget};
#[cfg(windows)]
use rmux_pty::WindowsConsoleKeyEvent;

use super::super::super::RequestHandler;
use super::super::decode_prompt_input_event;
use super::super::io_other;
use super::super::pane_io_encoding::{
    prepare_attached_pane_input_writes, write_attached_bytes_to_target_io,
};
use super::super::pane_prompt_input::{
    decode_utf8_char, is_extended_key_prefix, is_utf8_lead_byte, utf8_expected_len,
};
use super::bracketed_paste::{
    decode_bracketed_paste_after_append, take_incomplete_bracketed_paste_segment,
    BracketedPasteDecode,
};
use super::kitty_graphics::{decode_kitty_graphics_apc_after_append, KittyGraphicsApcDecode};
use super::palette_response::{
    decode_pane_bound_terminal_string, ModalPaletteInput, ModalPaletteInputSegment,
    PaneBoundTerminalStringDecode,
};
use super::retained::MAX_RETAINED_ATTACHED_CONTROL_INPUT;
use super::terminal_response::{
    decode_attached_terminal_control_after_append, decode_focus_event, TerminalControlEvent,
    TerminalResponseDecode,
};
use super::{
    is_enter_key, is_mouse_prefix, resolve_input_target, retain_partial_attached_control_input,
    retain_partial_attached_escape_input,
};
use crate::client_flags::ClientFlags;
use crate::handler::overlay_support::AttachedOverlayInput;
use crate::handler::{
    attach_support::{ActiveAttachIdentity, TransientMessageInput},
    prepare_lifecycle_event,
};
use crate::input_keys::{decode_extended_key, decode_mouse, ExtendedKeyDecode, MouseDecode};
use crate::key_table::{
    decode_attached_key, default_key_table_name, lookup_attached_key_table_binding,
    matches_prefix_key, session_option_key, AttachedKeyDecode,
};

#[path = "live/read_only_client_action.rs"]
mod read_only_client_action;

pub(crate) type ActiveClientEmitCache = Option<(u64, WindowTarget)>;

// Rerouting must re-evaluate attach state after hooks, mouse bindings, and prefix
// commands. Keep each reroute suffix bounded so one maximum-size local frame
// cannot turn those necessary copies into quadratic work.
const ATTACHED_LIVE_REROUTE_CHUNK_BYTES: usize = 1024;

enum AttachedLiveInputStep {
    Complete(bool),
    Reroute { bytes: Vec<u8>, forwarded: bool },
}

enum AttachedLiveChunkResult {
    Complete(bool),
    Rechunk { bytes: Vec<u8>, forwarded: bool },
}

struct AttachedLiveInputWork {
    bytes: Arc<[u8]>,
    start: usize,
    end: usize,
    windows_console_key: Option<rmux_proto::AttachedWindowsConsoleKey>,
}

struct PlainKeyDispatchSnapshot {
    prefix: Option<KeyCode>,
    prefix2: Option<KeyCode>,
    bindings: Vec<KeyCode>,
}

impl PlainKeyDispatchSnapshot {
    fn new(state: &crate::pane_terminals::HandlerState, target: &PaneTarget) -> Self {
        let table_name = default_key_table_name(state, target);
        let bindings = state
            .key_bindings
            .table(&table_name)
            .into_iter()
            .flat_map(|table| table.active().keys())
            .map(|key| key_code_lookup_bits(*key))
            .filter(|key| *key == KEYC_ANY || *key <= u64::from(char::MAX as u32))
            .collect();
        Self {
            prefix: session_option_key(
                state,
                target.session_name(),
                rmux_proto::OptionName::Prefix,
            ),
            prefix2: session_option_key(
                state,
                target.session_name(),
                rmux_proto::OptionName::Prefix2,
            ),
            bindings,
        }
    }

    fn requires_dispatch(&self, key: KeyCode) -> bool {
        let key = key_code_lookup_bits(key);
        matches_prefix_key(key, self.prefix, self.prefix2)
            || self
                .bindings
                .iter()
                .any(|binding| *binding == KEYC_ANY || *binding == key)
    }
}

impl AttachedLiveInputWork {
    fn new(
        bytes: Arc<[u8]>,
        windows_console_key: Option<rmux_proto::AttachedWindowsConsoleKey>,
    ) -> Self {
        let end = bytes.len();
        Self {
            bytes,
            start: 0,
            end,
            windows_console_key,
        }
    }

    fn len(&self) -> usize {
        self.end.saturating_sub(self.start)
    }

    fn split_at(&mut self, len: usize) -> Self {
        let split = self.start.saturating_add(len).min(self.end);
        let remaining = Self {
            bytes: Arc::clone(&self.bytes),
            start: split,
            end: self.end,
            windows_console_key: None,
        };
        self.end = split;
        remaining
    }

    fn as_bytes(&self) -> &[u8] {
        &self.bytes[self.start..self.end]
    }
}

fn take_attached_remaining_input(pending_input: &mut Vec<u8>, consumed: usize) -> Option<Vec<u8>> {
    if consumed >= pending_input.len() {
        return None;
    }
    let remaining = pending_input[consumed..].to_vec();
    pending_input.clear();
    Some(remaining)
}

impl RequestHandler {
    #[cfg(all(test, windows))]
    pub(crate) async fn handle_attached_keystroke_input(
        &self,
        attach_pid: u32,
        pending_input: &mut Vec<u8>,
        keystroke: &AttachedKeystroke,
    ) -> io::Result<bool> {
        let identity = self
            .active_attach_identity(attach_pid)
            .await
            .ok_or_else(|| io_other("attached client disappeared"))?;
        self.handle_attached_keystroke_input_for_identity(identity, pending_input, keystroke)
            .await
    }

    #[cfg(all(test, windows))]
    pub(crate) async fn handle_attached_keystroke_input_for_identity(
        &self,
        identity: ActiveAttachIdentity,
        pending_input: &mut Vec<u8>,
        keystroke: &AttachedKeystroke,
    ) -> io::Result<bool> {
        let mut active_emit_cache = None;
        self.handle_attached_live_input_inner_with_windows_console_key(
            identity,
            pending_input,
            keystroke.bytes(),
            keystroke.windows_console_key(),
            &mut active_emit_cache,
        )
        .await
    }

    pub(crate) async fn handle_attached_keystroke_input_with_active_cache_for_identity(
        &self,
        identity: ActiveAttachIdentity,
        pending_input: &mut Vec<u8>,
        keystroke: &AttachedKeystroke,
        active_emit_cache: &mut ActiveClientEmitCache,
    ) -> io::Result<bool> {
        self.handle_attached_live_input_inner_with_windows_console_key(
            identity,
            pending_input,
            keystroke.bytes(),
            keystroke.windows_console_key(),
            active_emit_cache,
        )
        .await
    }

    #[cfg(test)]
    pub(crate) async fn handle_attached_live_input(
        &self,
        attach_pid: u32,
        pending_input: &mut Vec<u8>,
        bytes: &[u8],
    ) -> io::Result<()> {
        let identity = self
            .active_attach_identity(attach_pid)
            .await
            .ok_or_else(|| io_other("attached client disappeared"))?;
        let mut active_emit_cache = None;
        self.handle_attached_live_input_inner_cached(
            identity,
            pending_input,
            bytes,
            &mut active_emit_cache,
        )
        .await
        .map(|_| ())
    }

    pub(crate) async fn handle_attached_live_input_with_active_cache_for_identity(
        &self,
        identity: ActiveAttachIdentity,
        pending_input: &mut Vec<u8>,
        bytes: &[u8],
        active_emit_cache: &mut ActiveClientEmitCache,
    ) -> io::Result<bool> {
        self.handle_attached_live_input_inner_cached(
            identity,
            pending_input,
            bytes,
            active_emit_cache,
        )
        .await
    }

    #[cfg_attr(not(test), allow(dead_code))]
    pub(crate) async fn handle_attached_live_input_inner(
        &self,
        attach_pid: u32,
        pending_input: &mut Vec<u8>,
        bytes: &[u8],
    ) -> io::Result<bool> {
        let identity = self
            .active_attach_identity(attach_pid)
            .await
            .ok_or_else(|| io_other("attached client disappeared"))?;
        let mut active_emit_cache = None;
        self.handle_attached_live_input_inner_cached(
            identity,
            pending_input,
            bytes,
            &mut active_emit_cache,
        )
        .await
    }

    pub(crate) async fn handle_attached_live_input_inner_for_identity(
        &self,
        identity: ActiveAttachIdentity,
        pending_input: &mut Vec<u8>,
        bytes: &[u8],
    ) -> io::Result<bool> {
        let mut active_emit_cache = None;
        self.handle_attached_live_input_inner_cached(
            identity,
            pending_input,
            bytes,
            &mut active_emit_cache,
        )
        .await
    }

    /// Flushes retained input that starts with the ambiguous `ESC ]` or
    /// `ESC _` bytes once the escape deadline fires. Reaching the deadline
    /// resolves the ambiguity between a fragmented consumed terminal
    /// response (OSC 4/10/11/12/52), a kitty graphics APC (`ESC _G`), and
    /// keyboard input in favor of the keyboard: dispatch M-] / M-_ through
    /// the normal key path (key tables, copy mode, per-pane key encoding)
    /// and reroute any accumulated body bytes as ordinary input. Writing the
    /// raw bytes to the pane instead would start an unterminated OSC/APC
    /// inside the pane's own parser and swallow subsequent input there.
    pub(super) async fn flush_attached_consumed_osc_prefix(
        &self,
        identity: ActiveAttachIdentity,
        pending_input: &mut Vec<u8>,
    ) -> io::Result<bool> {
        let bytes = std::mem::take(pending_input);
        let backspace = self.attached_backspace_byte().await;
        let AttachedKeyDecode::Matched { size, key } = decode_live_attached_key(&bytes, backspace)
        else {
            // `ESC ]` always decodes as M-]; keep the raw forward as a
            // defensive fallback rather than dropping the input.
            self.write_attached_bytes_for_identity(identity, &bytes)
                .await?;
            return Ok(true);
        };
        let handled = self.handle_attached_live_key(identity, key).await?;
        let mut forwarded = !handled;
        if let Some(remaining) = bytes.get(size..).filter(|rest| !rest.is_empty()) {
            forwarded |= self
                .handle_attached_live_input_inner_for_identity(identity, pending_input, remaining)
                .await?;
        }
        Ok(forwarded)
    }

    async fn handle_attached_live_input_inner_cached(
        &self,
        identity: ActiveAttachIdentity,
        pending_input: &mut Vec<u8>,
        bytes: &[u8],
        active_emit_cache: &mut ActiveClientEmitCache,
    ) -> io::Result<bool> {
        self.handle_attached_live_input_inner_with_windows_console_key(
            identity,
            pending_input,
            bytes,
            None,
            active_emit_cache,
        )
        .await
    }

    async fn handle_attached_live_input_inner_with_windows_console_key(
        &self,
        identity: ActiveAttachIdentity,
        pending_input: &mut Vec<u8>,
        bytes: &[u8],
        windows_console_key: Option<rmux_proto::AttachedWindowsConsoleKey>,
        active_emit_cache: &mut ActiveClientEmitCache,
    ) -> io::Result<bool> {
        if !bytes.is_empty() {
            self.record_attached_input_activity(identity).await?;
        }
        if bytes.len() <= ATTACHED_LIVE_REROUTE_CHUNK_BYTES {
            return match self
                .handle_attached_live_input_chunk(
                    identity,
                    pending_input,
                    bytes,
                    windows_console_key,
                    active_emit_cache,
                )
                .await?
            {
                AttachedLiveChunkResult::Complete(forwarded) => Ok(forwarded),
                AttachedLiveChunkResult::Rechunk { bytes, forwarded } => {
                    self.handle_attached_live_input_work_queue(
                        identity,
                        pending_input,
                        AttachedLiveInputWork::new(Arc::from(bytes), None),
                        forwarded,
                        active_emit_cache,
                    )
                    .await
                }
            };
        }

        // Preserve one-shot fast-path semantics for a large printable line,
        // including submitted-line tracking. Inputs that contain a prefix or
        // terminal control fall back to bounded reroute chunks below.
        if windows_console_key.is_none() {
            if let Some(forwarded) = self
                .try_forward_plain_attached_bytes_fast(
                    identity,
                    pending_input,
                    bytes,
                    active_emit_cache,
                )
                .await?
            {
                return Ok(forwarded);
            }
        }

        self.handle_attached_live_input_work_queue(
            identity,
            pending_input,
            AttachedLiveInputWork::new(Arc::from(bytes), windows_console_key),
            false,
            active_emit_cache,
        )
        .await
    }

    /// Commits the recency of one accepted attached-client interaction.
    ///
    /// This is the single admission boundary for live client input, reached
    /// before the server decides whether the bytes become a prefix, a key
    /// binding, prompt or overlay editing, a copy/clock/mode-tree key,
    /// display-panes selection, a bracketed paste, a clipboard or terminal
    /// response, or a pane write. Committing here is what makes locally
    /// consumed interaction count as session use, matching tmux, which updates
    /// session activity immediately after admitting a key and before any
    /// dispatch decision. Committing after pane I/O instead would silently
    /// drop every key the server handles itself.
    ///
    /// Both counters are advanced under the same two guards, so client order
    /// and session order share one policy and one linearization point:
    /// concurrent clients are ordered by which one acquires these locks first,
    /// not by which pane write finishes first. One logical input advances the
    /// session once here regardless of how many panes it later reaches, so
    /// `synchronize-panes` cannot inflate recency.
    ///
    /// Rejected input never reaches the commit: empty frames are filtered by
    /// the caller, a vanished or closing attach fails, and a client that
    /// cannot write or is read-only returns without advancing anything. That
    /// read-only exclusion is a deliberate RMUX divergence — tmux does count
    /// read-only keys — and is the existing client-activity policy this
    /// boundary reuses rather than a new rule.
    async fn record_attached_input_activity(
        &self,
        identity: ActiveAttachIdentity,
    ) -> io::Result<()> {
        // Handler lock order is state before active_attach.
        let mut state = self.state.lock().await;
        let mut active_attach = self.active_attach.lock().await;
        let active = active_attach
            .by_pid
            .get(&identity.attach_pid())
            .filter(|active| {
                identity.matches_active(active)
                    && !active.closing.load(std::sync::atomic::Ordering::SeqCst)
            })
            .ok_or_else(|| io_other("attached client disappeared"))?;
        if active.can_write && !active.flags.contains(ClientFlags::READONLY) {
            // The attach owns its current session, which a switch may have
            // changed since `identity` was captured. Requiring the session id
            // to still match keeps a same-name session recreated underneath
            // this client from inheriting the older session's interaction.
            if let Some(session) = state
                .sessions
                .session_mut(&active.session_name)
                .filter(|session| session.id() == active.session_id)
            {
                session.touch_activity();
            }
            let sequence = self.next_client_activity_sequence();
            let _ = active_attach.record_client_activity(identity.attach_pid(), sequence);
        }
        Ok(())
    }

    async fn handle_attached_live_input_work_queue(
        &self,
        identity: ActiveAttachIdentity,
        pending_input: &mut Vec<u8>,
        initial_work: AttachedLiveInputWork,
        mut forwarded: bool,
        active_emit_cache: &mut ActiveClientEmitCache,
    ) -> io::Result<bool> {
        let mut work_queue = VecDeque::from([initial_work]);
        while let Some(mut work) = work_queue.pop_front() {
            if work.len() > ATTACHED_LIVE_REROUTE_CHUNK_BYTES
                && self
                    .attached_live_input_can_use_reroute_chunks(identity)
                    .await?
            {
                let remaining = work.split_at(ATTACHED_LIVE_REROUTE_CHUNK_BYTES);
                work_queue.push_front(remaining);
            }

            let windows_console_key = work.windows_console_key.take();
            match self
                .handle_attached_live_input_chunk(
                    identity,
                    pending_input,
                    work.as_bytes(),
                    windows_console_key,
                    active_emit_cache,
                )
                .await?
            {
                AttachedLiveChunkResult::Complete(step_forwarded) => {
                    forwarded |= step_forwarded;
                }
                AttachedLiveChunkResult::Rechunk {
                    bytes,
                    forwarded: step_forwarded,
                } => {
                    forwarded |= step_forwarded;
                    work_queue.push_front(AttachedLiveInputWork::new(Arc::from(bytes), None));
                }
            }
        }
        Ok(forwarded)
    }

    async fn handle_attached_live_input_chunk(
        &self,
        identity: ActiveAttachIdentity,
        pending_input: &mut Vec<u8>,
        bytes: &[u8],
        mut windows_console_key: Option<rmux_proto::AttachedWindowsConsoleKey>,
        active_emit_cache: &mut ActiveClientEmitCache,
    ) -> io::Result<AttachedLiveChunkResult> {
        let mut bytes = Cow::Borrowed(bytes);
        let mut forwarded = false;

        loop {
            match self
                .handle_attached_live_input_step(
                    identity,
                    pending_input,
                    bytes.as_ref(),
                    windows_console_key.take(),
                    active_emit_cache,
                )
                .await?
            {
                AttachedLiveInputStep::Complete(step_forwarded) => {
                    return Ok(AttachedLiveChunkResult::Complete(
                        forwarded | step_forwarded,
                    ));
                }
                AttachedLiveInputStep::Reroute {
                    bytes: remaining,
                    forwarded: step_forwarded,
                } => {
                    forwarded |= step_forwarded;
                    if remaining.len() > ATTACHED_LIVE_REROUTE_CHUNK_BYTES
                        && self
                            .attached_live_input_can_use_reroute_chunks(identity)
                            .await?
                    {
                        return Ok(AttachedLiveChunkResult::Rechunk {
                            bytes: remaining,
                            forwarded,
                        });
                    }
                    bytes = Cow::Owned(remaining);
                }
            }
        }
    }

    async fn handle_attached_live_input_step(
        &self,
        identity: ActiveAttachIdentity,
        pending_input: &mut Vec<u8>,
        bytes: &[u8],
        windows_console_key: Option<rmux_proto::AttachedWindowsConsoleKey>,
        active_emit_cache: &mut ActiveClientEmitCache,
    ) -> io::Result<AttachedLiveInputStep> {
        #[cfg(not(windows))]
        let _ = windows_console_key;
        #[cfg(windows)]
        let windows_console_key = windows_console_key
            .filter(|_| pending_input.is_empty() && !bytes.is_empty())
            .map(windows_console_key_event);
        let initial_transient_prefix = self
            .take_transient_terminal_prefix_for_identity(identity)
            .await;
        let mut has_transient_terminal_prefix = !initial_transient_prefix.is_empty();
        pending_input.extend(initial_transient_prefix);
        let mut forwarded_to_pane = false;
        #[cfg(windows)]
        let try_plain_fast_path = windows_console_key.is_none();
        #[cfg(not(windows))]
        let try_plain_fast_path = true;
        if try_plain_fast_path {
            if let Some(forwarded) = self
                .try_forward_plain_attached_bytes_fast(
                    identity,
                    pending_input,
                    bytes,
                    active_emit_cache,
                )
                .await?
            {
                return Ok(AttachedLiveInputStep::Complete(forwarded));
            }
        }
        if self
            .attached_client_input_is_read_only_for_identity(identity)
            .await?
        {
            if has_transient_terminal_prefix {
                pending_input.clear();
            }
            let backspace = self.attached_backspace_byte().await;
            #[cfg(windows)]
            let windows_key_override = windows_console_key.and_then(|key_event| {
                let AttachedKeyDecode::Matched { size, key } =
                    decode_live_attached_key(bytes, backspace)
                else {
                    return None;
                };
                (size == bytes.len()).then(|| windows_console_binding_key(key, key_event))
            });
            #[cfg(not(windows))]
            let windows_key_override = None;
            self.handle_read_only_client_action_input(
                identity,
                pending_input,
                bytes,
                backspace,
                windows_key_override,
            )
            .await?;
            return Ok(AttachedLiveInputStep::Complete(false));
        }
        self.clear_attached_focus_alerts(identity).await;
        match self
            .handle_ignored_transient_message_input_for_identity(identity, pending_input, bytes)
            .await
        {
            TransientMessageInput::Inactive => {}
            TransientMessageInput::Consumed => {
                return Ok(AttachedLiveInputStep::Complete(false));
            }
            TransientMessageInput::TerminalControls(controls) => {
                return Ok(AttachedLiveInputStep::Complete(
                    self.handle_transient_terminal_controls(identity, controls)
                        .await?,
                ));
            }
            TransientMessageInput::Dismissed(_) => {
                debug_assert!(
                    false,
                    "ignore-only transient input cannot dismiss a message"
                );
                return Ok(AttachedLiveInputStep::Complete(false));
            }
        }
        if self
            .attached_modal_surface_active_for_identity(identity)
            .await
        {
            if let Some(input) = self.split_attached_modal_palette_input(pending_input, bytes) {
                pending_input.clear();
                return self
                    .handle_attached_modal_palette_input(identity, pending_input, input)
                    .await;
            }
        }
        let pending_was_empty = pending_input.is_empty();
        match self
            .handle_transient_message_input_for_identity(identity, pending_input, bytes)
            .await
        {
            // The timer may expire between the first residual-prefix drain
            // and this identity-guarded mutation. Pull the prefix once more
            // before ordinary decoding so a split terminal response remains
            // contiguous across the expiry boundary.
            TransientMessageInput::Inactive => {
                let residual = self
                    .take_transient_terminal_prefix_for_identity(identity)
                    .await;
                has_transient_terminal_prefix |= !residual.is_empty();
                pending_input.extend(residual);
            }
            TransientMessageInput::Consumed => {
                return Ok(AttachedLiveInputStep::Complete(false));
            }
            TransientMessageInput::TerminalControls(controls) => {
                return Ok(AttachedLiveInputStep::Complete(
                    self.handle_transient_terminal_controls(identity, controls)
                        .await?,
                ));
            }
            TransientMessageInput::Dismissed(rerouted)
                if pending_was_empty && rerouted.as_slice() == bytes =>
            {
                // Continue in this same step. Besides avoiding a second
                // parse, this preserves the native Windows KEY_EVENT that
                // belongs to these exact bytes.
                debug_assert!(pending_input.is_empty());
            }
            TransientMessageInput::Dismissed(bytes) => {
                return Ok(AttachedLiveInputStep::Reroute {
                    bytes,
                    forwarded: false,
                });
            }
        }
        if !has_transient_terminal_prefix {
            if let Some(step) = self
                .handle_attached_modal_input_step(identity, pending_input, bytes)
                .await?
            {
                return Ok(step);
            }
        }
        let (target, target_session_id) = self
            .attached_input_target_identity(identity)
            .await
            .map_err(io_other)?;
        self.emit_attached_client_active_if_changed(identity, &target, active_emit_cache)
            .await;
        if self
            .target_is_in_clock_mode(&target)
            .await
            .map_err(io_other)?
        {
            let new_input_at = pending_input.len();
            pending_input.extend_from_slice(bytes);
            match decode_bracketed_paste_after_append(pending_input, new_input_at) {
                BracketedPasteDecode::Matched { .. } => {
                    #[cfg(test)]
                    self.pause_before_live_clock_mode_exit_for_test(identity)
                        .await;
                    let _ = self
                        .exit_clock_mode_for_attached_identity(&target, identity, target_session_id)
                        .await
                        .map_err(io_other)?;
                    return Ok(AttachedLiveInputStep::Reroute {
                        bytes: std::mem::take(pending_input),
                        forwarded: false,
                    });
                }
                BracketedPasteDecode::Partial => {
                    if pending_input.len() > MAX_RETAINED_ATTACHED_CONTROL_INPUT {
                        #[cfg(test)]
                        self.pause_before_live_clock_mode_exit_for_test(identity)
                            .await;
                        let _ = self
                            .exit_clock_mode_for_attached_identity(
                                &target,
                                identity,
                                target_session_id,
                            )
                            .await
                            .map_err(io_other)?;
                        return Ok(AttachedLiveInputStep::Reroute {
                            bytes: std::mem::take(pending_input),
                            forwarded: false,
                        });
                    }
                    retain_partial_attached_control_input(
                        "clock mode bracketed paste",
                        pending_input,
                    )?;
                    return Ok(AttachedLiveInputStep::Complete(false));
                }
                BracketedPasteDecode::NotPaste => {}
            }
            if is_mouse_prefix(pending_input) {
                let last_mouse = self.attached_last_mouse_event_for_identity(identity).await;
                let consumed = match decode_mouse(pending_input, last_mouse) {
                    MouseDecode::Matched { size, .. } | MouseDecode::Discard { size } => size,
                    MouseDecode::Partial | MouseDecode::Overlong => {
                        retain_partial_attached_escape_input(
                            "clock mode mouse input",
                            pending_input,
                        )?;
                        return Ok(AttachedLiveInputStep::Complete(false));
                    }
                    MouseDecode::Invalid => 0,
                };
                if consumed > 0 {
                    pending_input.drain(..consumed);
                    #[cfg(test)]
                    self.pause_before_live_clock_mode_exit_for_test(identity)
                        .await;
                    let _ = self
                        .exit_clock_mode_for_attached_identity(&target, identity, target_session_id)
                        .await
                        .map_err(io_other)?;
                    let remaining =
                        (!pending_input.is_empty()).then(|| std::mem::take(pending_input));
                    return Ok(attached_mode_input_step(remaining));
                }
            }
            let backspace = self.attached_backspace_byte().await;
            let consumed = match decode_attached_key(pending_input, backspace) {
                AttachedKeyDecode::Matched { size, .. } => size,
                AttachedKeyDecode::Partial => {
                    retain_partial_attached_escape_input("clock mode input", pending_input)?;
                    return Ok(AttachedLiveInputStep::Complete(false));
                }
                AttachedKeyDecode::Invalid => {
                    let Some((_, consumed)) = decode_prompt_input_event(pending_input) else {
                        retain_partial_attached_escape_input("clock mode input", pending_input)?;
                        return Ok(AttachedLiveInputStep::Complete(false));
                    };
                    consumed
                }
            };
            pending_input.drain(..consumed);
            #[cfg(test)]
            self.pause_before_live_clock_mode_exit_for_test(identity)
                .await;
            let _ = self
                .exit_clock_mode_for_attached_identity(&target, identity, target_session_id)
                .await
                .map_err(io_other)?;
            let remaining = (!pending_input.is_empty()).then(|| std::mem::take(pending_input));
            return Ok(attached_mode_input_step(remaining));
        }
        let target_in_copy_mode = self
            .target_is_in_copy_mode(&target)
            .await
            .map_err(io_other)?;
        let target_mode = self.target_pane_mode(&target).await.map_err(io_other)?;
        let target_focus_events = target_mode & mode::MODE_FOCUSON != 0;
        let backspace = self.attached_backspace_byte().await;

        #[cfg(windows)]
        if pending_input.is_empty() && bytes == b"\x04" {
            if let Some(key) = windows_key_code_named("C-d") {
                let handled = self
                    .handle_attached_live_key_inner(
                        identity,
                        key,
                        super::AttachedPaneForward::WindowsConsoleKey {
                            key: WindowsConsoleKeyEvent::ctrl_d(),
                            bytes,
                        },
                    )
                    .await?;
                return Ok(AttachedLiveInputStep::Complete(!handled));
            }
        }

        #[cfg(windows)]
        if let Some(key_event) = windows_console_key.filter(|_| pending_input.is_empty()) {
            if let AttachedKeyDecode::Matched { size, key } = decode_attached_key(bytes, backspace)
            {
                if size == bytes.len() {
                    if let Some(key) = windows_console_binding_override_key(key, key_event) {
                        let handled = self
                            .handle_attached_live_key_inner(
                                identity,
                                key,
                                super::AttachedPaneForward::WindowsConsoleKey {
                                    key: key_event,
                                    bytes,
                                },
                            )
                            .await?;
                        return Ok(AttachedLiveInputStep::Complete(!handled));
                    }
                }
            }
        }

        if pending_input.is_empty()
            && !self.attached_key_table_active(identity).await
            && self
                .dispatch_immediate_prefix_detach(identity, &target, bytes, backspace)
                .await?
        {
            return Ok(AttachedLiveInputStep::Complete(false));
        }

        let new_input_at = pending_input.len();
        pending_input.extend_from_slice(bytes);
        let mut raw_start = 0;
        let mut offset = 0;
        let mut plain_key_dispatch = None;

        while offset < pending_input.len() {
            let slice = &pending_input[offset..];
            let slice_new_input_at = new_input_at.saturating_sub(offset);
            match decode_bracketed_paste_after_append(slice, slice_new_input_at) {
                BracketedPasteDecode::Matched {
                    size,
                    body_start,
                    body_end,
                } => {
                    if target_in_copy_mode {
                        offset += size;
                        raw_start = offset;
                        continue;
                    }
                    if raw_start < offset {
                        self.write_attached_bytes_for_identity(
                            identity,
                            &pending_input[raw_start..offset],
                        )
                        .await?;
                    }
                    self.write_attached_bracketed_paste_for_identity(
                        identity,
                        &pending_input[offset + body_start..offset + body_end],
                    )
                    .await?;
                    forwarded_to_pane = true;
                    offset += size;
                    raw_start = offset;
                    continue;
                }
                BracketedPasteDecode::Partial => {
                    if raw_start < offset {
                        self.write_attached_bytes_for_identity(
                            identity,
                            &pending_input[raw_start..offset],
                        )
                        .await?;
                        forwarded_to_pane = true;
                    }
                    pending_input.drain(..offset);
                    if let Some(segment) = take_incomplete_bracketed_paste_segment(
                        pending_input,
                        MAX_RETAINED_ATTACHED_CONTROL_INPUT,
                    ) {
                        if !target_in_copy_mode {
                            self.write_attached_bracketed_paste_for_identity(identity, &segment)
                                .await?;
                            forwarded_to_pane = true;
                        }
                    }
                    retain_partial_attached_control_input("live bracketed paste", pending_input)?;
                    return Ok(AttachedLiveInputStep::Complete(forwarded_to_pane));
                }
                BracketedPasteDecode::NotPaste => {}
            }
            match decode_kitty_graphics_apc_after_append(slice, slice_new_input_at) {
                KittyGraphicsApcDecode::Matched { size } => {
                    if raw_start < offset {
                        self.write_attached_bytes_for_identity(
                            identity,
                            &pending_input[raw_start..offset],
                        )
                        .await?;
                    }
                    self.write_attached_target_bytes_for_identity(
                        identity,
                        &pending_input[offset..offset + size],
                    )
                    .await?;
                    forwarded_to_pane = true;
                    offset += size;
                    raw_start = offset;
                    continue;
                }
                KittyGraphicsApcDecode::Partial => {
                    if raw_start < offset {
                        self.write_attached_bytes_for_identity(
                            identity,
                            &pending_input[raw_start..offset],
                        )
                        .await?;
                        forwarded_to_pane = true;
                    }
                    pending_input.drain(..offset);
                    retain_partial_attached_control_input(
                        "live kitty graphics APC",
                        pending_input,
                    )?;
                    return Ok(AttachedLiveInputStep::Complete(forwarded_to_pane));
                }
                KittyGraphicsApcDecode::NotKittyGraphics => {}
            }
            if let Some(event) = decode_focus_event(slice) {
                if raw_start < offset {
                    self.write_attached_bytes_for_identity(
                        identity,
                        &pending_input[raw_start..offset],
                    )
                    .await?;
                    forwarded_to_pane = true;
                }
                if target_focus_events {
                    self.write_attached_target_bytes_for_identity(
                        identity,
                        &pending_input[offset..offset + 3],
                    )
                    .await?;
                    forwarded_to_pane = true;
                }
                self.handle_attached_terminal_control_event(identity, &target, event)
                    .await;
                offset += 3;
                raw_start = offset;
                if let Some(remaining) = take_attached_remaining_input(pending_input, raw_start) {
                    return Ok(AttachedLiveInputStep::Reroute {
                        bytes: remaining,
                        forwarded: forwarded_to_pane,
                    });
                }
                continue;
            }
            match decode_attached_terminal_control_after_append(
                slice,
                target_focus_events,
                slice_new_input_at,
            ) {
                TerminalResponseDecode::Matched { size, event } => {
                    if raw_start < offset {
                        self.write_attached_bytes_for_identity(
                            identity,
                            &pending_input[raw_start..offset],
                        )
                        .await?;
                        forwarded_to_pane = true;
                    }
                    if let Some(event) = event {
                        self.handle_attached_terminal_control_event(identity, &target, event)
                            .await;
                    }
                    offset += size;
                    raw_start = offset;
                    if event.is_some() {
                        if let Some(remaining) =
                            take_attached_remaining_input(pending_input, raw_start)
                        {
                            return Ok(AttachedLiveInputStep::Reroute {
                                bytes: remaining,
                                forwarded: forwarded_to_pane,
                            });
                        }
                    }
                    continue;
                }
                TerminalResponseDecode::PaneBound { size } => {
                    if raw_start < offset {
                        self.write_attached_bytes_for_identity(
                            identity,
                            &pending_input[raw_start..offset],
                        )
                        .await?;
                    }
                    self.write_attached_target_bytes_for_identity(
                        identity,
                        &pending_input[offset..offset + size],
                    )
                    .await?;
                    forwarded_to_pane = true;
                    offset += size;
                    raw_start = offset;
                    continue;
                }
                TerminalResponseDecode::PaletteResponse { size, index } => {
                    if raw_start < offset {
                        self.write_attached_bytes_for_identity(
                            identity,
                            &pending_input[raw_start..offset],
                        )
                        .await?;
                        forwarded_to_pane = true;
                    }
                    forwarded_to_pane |= self
                        .write_attached_palette_response_for_identity(
                            identity,
                            index,
                            &pending_input[offset..offset + size],
                        )
                        .await?;
                    offset += size;
                    raw_start = offset;
                    continue;
                }
                TerminalResponseDecode::ClipboardResponse {
                    size,
                    selection,
                    content,
                } => {
                    if raw_start < offset {
                        self.write_attached_bytes_for_identity(
                            identity,
                            &pending_input[raw_start..offset],
                        )
                        .await?;
                        forwarded_to_pane = true;
                    }
                    forwarded_to_pane |= self
                        .handle_attached_clipboard_response(identity, selection, content)
                        .await?;
                    offset += size;
                    raw_start = offset;
                    continue;
                }
                TerminalResponseDecode::Partial => {
                    if raw_start < offset {
                        self.write_attached_bytes_for_identity(
                            identity,
                            &pending_input[raw_start..offset],
                        )
                        .await?;
                        forwarded_to_pane = true;
                    }
                    pending_input.drain(..offset);
                    retain_partial_attached_control_input("live terminal response", pending_input)?;
                    return Ok(AttachedLiveInputStep::Complete(forwarded_to_pane));
                }
                TerminalResponseDecode::NotResponse => {}
            }
            match decode_pane_bound_terminal_string(slice) {
                PaneBoundTerminalStringDecode::Matched { size } => {
                    if raw_start < offset {
                        self.write_attached_bytes_for_identity(
                            identity,
                            &pending_input[raw_start..offset],
                        )
                        .await?;
                    }
                    self.write_attached_target_bytes_for_identity(
                        identity,
                        &pending_input[offset..offset + size],
                    )
                    .await?;
                    forwarded_to_pane = true;
                    offset += size;
                    raw_start = offset;
                    continue;
                }
                PaneBoundTerminalStringDecode::Partial => {
                    if raw_start < offset {
                        self.write_attached_bytes_for_identity(
                            identity,
                            &pending_input[raw_start..offset],
                        )
                        .await?;
                        forwarded_to_pane = true;
                    }
                    pending_input.drain(..offset);
                    retain_partial_attached_control_input(
                        "live pane-bound terminal string",
                        pending_input,
                    )?;
                    return Ok(AttachedLiveInputStep::Complete(forwarded_to_pane));
                }
                PaneBoundTerminalStringDecode::NotString => {}
            }
            if is_mouse_prefix(slice) {
                if raw_start < offset {
                    self.write_attached_bytes_for_identity(
                        identity,
                        &pending_input[raw_start..offset],
                    )
                    .await?;
                    forwarded_to_pane = true;
                }
                let last_mouse = self.attached_last_mouse_event_for_identity(identity).await;
                match decode_mouse(slice, last_mouse) {
                    MouseDecode::Matched { size, event } => {
                        self.handle_attached_live_mouse(identity, event).await?;
                        offset += size;
                        raw_start = offset;
                        if let Some(remaining) =
                            take_attached_remaining_input(pending_input, raw_start)
                        {
                            return Ok(AttachedLiveInputStep::Reroute {
                                bytes: remaining,
                                forwarded: forwarded_to_pane,
                            });
                        }
                    }
                    MouseDecode::Discard { size } => {
                        offset += size;
                        raw_start = offset;
                    }
                    MouseDecode::Partial | MouseDecode::Overlong => {
                        pending_input.drain(..offset);
                        retain_partial_attached_escape_input("live mouse", pending_input)?;
                        return Ok(AttachedLiveInputStep::Complete(forwarded_to_pane));
                    }
                    MouseDecode::Invalid => {
                        raw_start = offset;
                        offset += 1;
                    }
                }
                continue;
            }
            if is_extended_key_prefix(slice) {
                if raw_start < offset {
                    self.write_attached_bytes_for_identity(
                        identity,
                        &pending_input[raw_start..offset],
                    )
                    .await?;
                    forwarded_to_pane = true;
                }
                match decode_extended_key(slice, backspace) {
                    ExtendedKeyDecode::Matched { size, key } => {
                        if raw_start < offset && is_enter_key(key) {
                            self.record_attached_submitted_text(
                                identity,
                                &pending_input[raw_start..offset],
                            )
                            .await?;
                        }
                        #[cfg(windows)]
                        let handled = if let Some(key_event) = windows_console_key
                            .filter(|_| {
                                raw_start == offset
                                    && offset == 0
                                    && size == pending_input.len()
                                    && size == bytes.len()
                            })
                            .or_else(|| windows_synthetic_console_key_for_decoded_key(key))
                        {
                            let key = windows_console_binding_key(key, key_event);
                            self.handle_attached_live_key_inner(
                                identity,
                                key,
                                super::AttachedPaneForward::WindowsConsoleKey {
                                    key: key_event,
                                    bytes: &pending_input[offset..offset + size],
                                },
                            )
                            .await?
                        } else {
                            self.handle_attached_live_key(identity, key).await?
                        };
                        #[cfg(not(windows))]
                        let handled = self.handle_attached_live_key(identity, key).await?;
                        if !handled {
                            forwarded_to_pane = true;
                        }
                        offset += size;
                        raw_start = offset;
                        if handled {
                            if let Some(remaining) =
                                take_attached_remaining_input(pending_input, raw_start)
                            {
                                return Ok(AttachedLiveInputStep::Reroute {
                                    bytes: remaining,
                                    forwarded: forwarded_to_pane,
                                });
                            }
                        }
                        if self.prompt_active_for_identity(identity).await {
                            break;
                        }
                        continue;
                    }
                    ExtendedKeyDecode::Partial => {
                        pending_input.drain(..offset);
                        retain_partial_attached_escape_input("live extended key", pending_input)?;
                        return Ok(AttachedLiveInputStep::Complete(forwarded_to_pane));
                    }
                    ExtendedKeyDecode::Invalid => {
                        raw_start = offset;
                    }
                }
            }
            let key_table_active = self.attached_key_table_active(identity).await;
            if !key_table_active && !target_in_copy_mode {
                let first = slice[0];
                if !first.is_ascii_control() {
                    let (key, size) = if first.is_ascii() {
                        (KeyCode::from(first), 1)
                    } else if let Some((character, size)) = decode_utf8_char(slice) {
                        (KeyCode::from(character), size)
                    } else {
                        if is_utf8_lead_byte(first) && slice.len() < utf8_expected_len(first) {
                            if raw_start < offset {
                                self.write_attached_bytes_for_identity(
                                    identity,
                                    &pending_input[raw_start..offset],
                                )
                                .await?;
                                forwarded_to_pane = true;
                            }
                            pending_input.drain(..offset);
                            retain_partial_attached_escape_input("live utf-8", pending_input)?;
                            return Ok(AttachedLiveInputStep::Complete(forwarded_to_pane));
                        }
                        offset += 1;
                        continue;
                    };
                    if plain_key_dispatch.is_none() {
                        let state = self.state.lock().await;
                        plain_key_dispatch = Some(PlainKeyDispatchSnapshot::new(&state, &target));
                    }
                    if !plain_key_dispatch
                        .as_ref()
                        .expect("plain key dispatch snapshot must be initialized")
                        .requires_dispatch(key)
                    {
                        offset += size;
                        continue;
                    }
                }
            }
            match decode_live_attached_key(slice, backspace) {
                AttachedKeyDecode::Matched { size, key } => {
                    if raw_start < offset && is_enter_key(key) {
                        self.record_attached_submitted_text(
                            identity,
                            &pending_input[raw_start..offset],
                        )
                        .await?;
                    }
                    if raw_start < offset {
                        self.write_attached_bytes_for_identity(
                            identity,
                            &pending_input[raw_start..offset],
                        )
                        .await?;
                        forwarded_to_pane = true;
                    }
                    #[cfg(windows)]
                    let handled = if let Some(key_event) = windows_console_key
                        .filter(|_| {
                            raw_start == offset
                                && offset == 0
                                && size == pending_input.len()
                                && size == bytes.len()
                        })
                        .or_else(|| windows_synthetic_console_key_for_decoded_key(key))
                    {
                        let key = windows_console_binding_key(key, key_event);
                        self.handle_attached_live_key_inner(
                            identity,
                            key,
                            super::AttachedPaneForward::WindowsConsoleKey {
                                key: key_event,
                                bytes: &pending_input[offset..offset + size],
                            },
                        )
                        .await?
                    } else {
                        self.handle_attached_live_key(identity, key).await?
                    };
                    #[cfg(not(windows))]
                    let handled = self.handle_attached_live_key(identity, key).await?;
                    if !handled {
                        forwarded_to_pane = true;
                    }
                    offset += size;
                    raw_start = offset;
                    if handled {
                        if let Some(remaining) =
                            take_attached_remaining_input(pending_input, raw_start)
                        {
                            return Ok(AttachedLiveInputStep::Reroute {
                                bytes: remaining,
                                forwarded: forwarded_to_pane,
                            });
                        }
                    }
                    if self.prompt_active_for_identity(identity).await {
                        break;
                    }
                    continue;
                }
                AttachedKeyDecode::Partial => {
                    if raw_start < offset {
                        self.write_attached_bytes_for_identity(
                            identity,
                            &pending_input[raw_start..offset],
                        )
                        .await?;
                        forwarded_to_pane = true;
                    }
                    pending_input.drain(..offset);
                    retain_partial_attached_escape_input("live attached key", pending_input)?;
                    return Ok(AttachedLiveInputStep::Complete(forwarded_to_pane));
                }
                AttachedKeyDecode::Invalid => {}
            }
            offset += 1;
        }

        if self.prompt_active_for_identity(identity).await && raw_start < pending_input.len() {
            let remaining = pending_input[raw_start..].to_vec();
            pending_input.clear();
            return Ok(AttachedLiveInputStep::Reroute {
                bytes: remaining,
                forwarded: forwarded_to_pane,
            });
        }

        if raw_start < pending_input.len() {
            self.write_attached_bytes_for_identity(identity, &pending_input[raw_start..])
                .await?;
            forwarded_to_pane = true;
        }
        pending_input.clear();
        Ok(AttachedLiveInputStep::Complete(forwarded_to_pane))
    }

    async fn handle_attached_modal_input_step(
        &self,
        identity: ActiveAttachIdentity,
        pending_input: &mut Vec<u8>,
        bytes: &[u8],
    ) -> io::Result<Option<AttachedLiveInputStep>> {
        match self
            .handle_transient_message_input_for_identity(identity, pending_input, bytes)
            .await
        {
            TransientMessageInput::Inactive => {
                let residual = self
                    .take_transient_terminal_prefix_for_identity(identity)
                    .await;
                if !residual.is_empty() {
                    pending_input.extend(residual);
                    return Ok(None);
                }
            }
            TransientMessageInput::Consumed => {
                return Ok(Some(AttachedLiveInputStep::Complete(false)));
            }
            TransientMessageInput::TerminalControls(controls) => {
                return Ok(Some(AttachedLiveInputStep::Complete(
                    self.handle_transient_terminal_controls(identity, controls)
                        .await?,
                )));
            }
            TransientMessageInput::Dismissed(bytes) => {
                return Ok(Some(AttachedLiveInputStep::Reroute {
                    bytes,
                    forwarded: false,
                }));
            }
        }
        if self.prompt_active_for_identity(identity).await {
            let remaining = self
                .handle_attached_prompt_input(identity, pending_input, bytes)
                .await?;
            return Ok(Some(attached_mode_input_step(remaining)));
        }
        if self.mode_tree_active_for_identity(identity).await {
            let remaining = self
                .handle_attached_mode_tree_input(identity, pending_input, bytes)
                .await?;
            return Ok(Some(attached_mode_input_step(remaining)));
        }
        if self.overlay_active_for_identity(identity).await {
            return match self
                .handle_attached_overlay_input_for_identity(identity, pending_input, bytes)
                .await?
            {
                AttachedOverlayInput::Consumed => Ok(Some(AttachedLiveInputStep::Complete(false))),
                AttachedOverlayInput::Reroute(bytes) => Ok(Some(AttachedLiveInputStep::Reroute {
                    bytes,
                    forwarded: false,
                })),
            };
        }
        if self.display_panes_active_for_identity(identity).await {
            let remaining = self
                .handle_attached_display_panes_input_for_identity(identity, pending_input, bytes)
                .await?;
            return Ok(Some(attached_mode_input_step(remaining)));
        }
        Ok(None)
    }

    pub(super) async fn handle_transient_terminal_controls(
        &self,
        identity: ActiveAttachIdentity,
        controls: Vec<Vec<u8>>,
    ) -> io::Result<bool> {
        let mut forwarded = false;
        for bytes in controls {
            // Hooks emitted by one report may switch the client, pane, or
            // terminal mode. Match the ordinary live path by re-resolving
            // before every subsequent report in the same input chunk.
            let (target, _) = self
                .attached_input_target_identity(identity)
                .await
                .map_err(io_other)?;
            let forward_focus =
                self.target_pane_mode(&target).await.map_err(io_other)? & mode::MODE_FOCUSON != 0;
            let decoded = decode_focus_event(&bytes).map_or_else(
                || decode_attached_terminal_control_after_append(&bytes, false, 0),
                |event| TerminalResponseDecode::Matched {
                    size: bytes.len(),
                    event: Some(event),
                },
            );
            match decoded {
                TerminalResponseDecode::PaneBound { .. } => {
                    // Without a pane-originated outer-terminal query token,
                    // `CSI ... R` is ambiguous with xterm modified F-keys
                    // (for example Shift-F3 is `CSI 1;2 R`). Under `-N` it
                    // must remain ignored like every other key press.
                }
                TerminalResponseDecode::PaletteResponse { index, .. } => {
                    forwarded |= self
                        .write_attached_palette_response_for_identity(identity, index, &bytes)
                        .await?;
                }
                TerminalResponseDecode::ClipboardResponse {
                    selection, content, ..
                } => {
                    forwarded |= self
                        .handle_attached_clipboard_response(identity, selection, content)
                        .await?;
                }
                TerminalResponseDecode::Matched {
                    event: Some(event), ..
                } => {
                    if forward_focus
                        && matches!(
                            event,
                            TerminalControlEvent::FocusIn | TerminalControlEvent::FocusOut
                        )
                    {
                        self.write_attached_target_bytes_for_identity(identity, &bytes)
                            .await?;
                        forwarded = true;
                    }
                    self.handle_attached_terminal_control_event(identity, &target, event)
                        .await;
                }
                TerminalResponseDecode::Matched { event: None, .. } => {}
                TerminalResponseDecode::NotResponse | TerminalResponseDecode::Partial => {
                    debug_assert!(false, "transient input emitted an unexpected control");
                }
            }
        }
        Ok(forwarded)
    }

    async fn handle_attached_modal_palette_input(
        &self,
        identity: ActiveAttachIdentity,
        pending_input: &mut Vec<u8>,
        input: ModalPaletteInput,
    ) -> io::Result<AttachedLiveInputStep> {
        let ModalPaletteInput { segments, retained } = input;
        let mut segments = VecDeque::from(segments);
        let mut modal_pending = Vec::new();
        let mut forwarded = false;

        while let Some(segment) = segments.pop_front() {
            let bytes = match segment {
                ModalPaletteInputSegment::Input(bytes) => bytes,
                ModalPaletteInputSegment::PaneBound(bytes) => {
                    self.write_attached_target_bytes_for_identity(identity, &bytes)
                        .await?;
                    forwarded = true;
                    continue;
                }
                ModalPaletteInputSegment::Response { index, bytes } => {
                    if !self
                        .attached_modal_surface_active_for_identity(identity)
                        .await
                    {
                        let mut rerouted = modal_pending;
                        rerouted.extend_from_slice(&bytes);
                        append_modal_palette_remainder(&mut rerouted, segments, &retained);
                        return Ok(AttachedLiveInputStep::Reroute {
                            bytes: rerouted,
                            forwarded,
                        });
                    }
                    if self
                        .write_attached_palette_response_for_identity(identity, index, &bytes)
                        .await?
                    {
                        forwarded = true;
                    }
                    // A syntactically valid OSC 4 response is terminal
                    // protocol input, never a modal keystroke. Matching
                    // responses reach the pane above; unsolicited, mismatched,
                    // or duplicate responses are discarded just as they are
                    // on the ordinary live-input path. Feeding a duplicate
                    // through a prompt or mode-tree would let its leading ESC
                    // close the surface after another attached client had
                    // already consumed the shared query slot.
                    continue;
                }
                ModalPaletteInputSegment::ClipboardResponse {
                    selection, content, ..
                } => {
                    forwarded |= self
                        .handle_attached_clipboard_response(identity, selection, content)
                        .await?;
                    continue;
                }
            };

            let Some(step) = self
                .handle_attached_modal_input_step(identity, &mut modal_pending, &bytes)
                .await?
            else {
                let mut rerouted = modal_pending;
                rerouted.extend_from_slice(&bytes);
                append_modal_palette_remainder(&mut rerouted, segments, &retained);
                return Ok(AttachedLiveInputStep::Reroute {
                    bytes: rerouted,
                    forwarded,
                });
            };
            match step {
                AttachedLiveInputStep::Complete(step_forwarded) => {
                    forwarded |= step_forwarded;
                }
                AttachedLiveInputStep::Reroute {
                    bytes,
                    forwarded: step_forwarded,
                } => {
                    let mut rerouted = modal_pending;
                    rerouted.extend_from_slice(&bytes);
                    append_modal_palette_remainder(&mut rerouted, segments, &retained);
                    return Ok(AttachedLiveInputStep::Reroute {
                        bytes: rerouted,
                        forwarded: forwarded | step_forwarded,
                    });
                }
            }
        }

        modal_pending.extend_from_slice(&retained);
        if modal_pending.is_empty() {
            return Ok(AttachedLiveInputStep::Complete(forwarded));
        }
        if self
            .attached_modal_surface_active_for_identity(identity)
            .await
        {
            *pending_input = modal_pending;
            retain_partial_attached_control_input("modal palette response", pending_input)?;
            Ok(AttachedLiveInputStep::Complete(forwarded))
        } else {
            Ok(AttachedLiveInputStep::Reroute {
                bytes: modal_pending,
                forwarded,
            })
        }
    }

    async fn try_forward_plain_attached_bytes_fast(
        &self,
        identity: ActiveAttachIdentity,
        pending_input: &[u8],
        bytes: &[u8],
        active_emit_cache: &mut ActiveClientEmitCache,
    ) -> io::Result<Option<bool>> {
        if !pending_input.is_empty() || !is_plain_attached_fast_path_input(bytes) {
            return Ok(None);
        }

        let Some((session_name, session_id)) = self.fast_path_attached_session(identity).await?
        else {
            return Ok(None);
        };
        let prepared = self
            .with_live_input_session_state(identity, &session_name, session_id, |state| {
                let target =
                    resolve_input_target(state, None, Some(&session_name)).map_err(io_other)?;
                let transcript = state.transcript_handle(&target).map_err(io_other)?;
                {
                    let transcript = transcript
                        .lock()
                        .expect("pane transcript mutex must not be poisoned");
                    if transcript.copy_mode_state().is_some()
                        || transcript.clock_mode_generation().is_some()
                        || transcript.mode() & mode::MODE_MOUSE_ALL != 0
                    {
                        return Ok(None);
                    }
                }
                if plain_input_requires_key_dispatch(bytes, &target, state) {
                    return Ok(None);
                }
                if let Some(submitted) = submitted_text_before_enter(bytes) {
                    state
                        .record_attached_submitted_text(&target, submitted)
                        .map_err(io_other)?;
                }
                let clear_alerts_changed =
                    state
                        .sessions
                        .session_mut(&session_name)
                        .is_some_and(|session| {
                            session.clear_all_winlink_alert_flags(target.window_index())
                        });
                let writes =
                    prepare_attached_pane_input_writes(state, &target, bytes).map_err(io_other)?;
                Ok(Some((target, writes, clear_alerts_changed)))
            })
            .await?
            .flatten();
        let Some((target, writes, clear_alerts_changed)) = prepared else {
            return Ok(None);
        };

        self.emit_attached_client_active_if_changed(identity, &target, active_emit_cache)
            .await;
        for write in writes {
            write_attached_bytes_to_target_io(write, bytes.to_vec())
                .await
                .map_err(io_other)?;
        }
        if clear_alerts_changed {
            let handler = self.clone();
            let refresh_session_name = session_name.clone();
            tokio::spawn(async move {
                handler
                    .refresh_attached_session_for_session_identity(
                        &refresh_session_name,
                        session_id,
                    )
                    .await;
            });
        }
        Ok(Some(true))
    }

    async fn fast_path_attached_session(
        &self,
        identity: ActiveAttachIdentity,
    ) -> io::Result<Option<(rmux_proto::SessionName, rmux_proto::SessionId)>> {
        let active_attach = self.active_attach.lock().await;
        let active = active_attach
            .by_pid
            .get(&identity.attach_pid())
            .filter(|active| {
                identity.matches_active(active)
                    && !active.closing.load(std::sync::atomic::Ordering::SeqCst)
            })
            .ok_or_else(|| {
                io_other(rmux_proto::RmuxError::Server(
                    "attached client disappeared".to_owned(),
                ))
            })?;
        if !active.can_write || active.flags.contains(ClientFlags::READONLY) {
            return Ok(None);
        }
        if active.prompt.is_some()
            || active.mode_tree.is_some()
            || active.overlay.is_some()
            || active.display_panes.is_some()
            || active.transient_message.is_some()
            || active.key_table_name.is_some()
        {
            return Ok(None);
        }
        Ok(Some((active.session_name.clone(), active.session_id)))
    }

    async fn attached_live_input_can_use_reroute_chunks(
        &self,
        identity: ActiveAttachIdentity,
    ) -> io::Result<bool> {
        let active_attach = self.active_attach.lock().await;
        let active = active_attach
            .by_pid
            .get(&identity.attach_pid())
            .filter(|active| {
                identity.matches_active(active)
                    && !active.closing.load(std::sync::atomic::Ordering::SeqCst)
            })
            .ok_or_else(|| {
                io_other(rmux_proto::RmuxError::Server(
                    "attached client disappeared".to_owned(),
                ))
            })?;
        Ok(active.can_write
            && !active.flags.contains(ClientFlags::READONLY)
            && active.prompt.is_none()
            && active.mode_tree.is_none()
            && active.overlay.is_none()
            && active.display_panes.is_none()
            && active.transient_message.is_none())
    }

    async fn attached_modal_surface_active_for_identity(
        &self,
        identity: ActiveAttachIdentity,
    ) -> bool {
        let active_attach = self.active_attach.lock().await;
        let Some(active) = active_attach
            .by_pid
            .get(&identity.attach_pid())
            .filter(|active| {
                identity.matches_active(active)
                    && !active.closing.load(std::sync::atomic::Ordering::SeqCst)
            })
        else {
            return false;
        };
        active.prompt.is_some()
            || active.mode_tree.is_some()
            || active.overlay.is_some()
            || active.display_panes.is_some()
            || active.transient_message.is_some()
    }

    async fn attached_key_table_active(&self, identity: ActiveAttachIdentity) -> bool {
        let active_attach = self.active_attach.lock().await;
        active_attach
            .by_pid
            .get(&identity.attach_pid())
            .is_some_and(|active| {
                identity.matches_active(active)
                    && !active.closing.load(std::sync::atomic::Ordering::SeqCst)
                    && active.key_table_name.is_some()
            })
    }

    async fn emit_attached_client_active_if_changed(
        &self,
        identity: ActiveAttachIdentity,
        target: &PaneTarget,
        active_emit_cache: &mut ActiveClientEmitCache,
    ) {
        let attach_pid = identity.attach_pid();
        let window_target =
            WindowTarget::with_window(target.session_name().clone(), target.window_index());
        let epoch = self.active_attach_epoch.load(Ordering::Acquire);
        if active_emit_cache
            .as_ref()
            .is_some_and(|(cached_epoch, cached)| {
                *cached_epoch == epoch && cached == &window_target
            })
        {
            return;
        }

        let (should_emit, cache_epoch, client_name) = {
            let mut active_attach = self.active_attach.lock().await;
            let Some(client_name) = active_attach
                .by_pid
                .get(&attach_pid)
                .filter(|active| {
                    identity.matches_active(active)
                        && !active.closing.load(std::sync::atomic::Ordering::SeqCst)
                })
                .map(|active| active.client_name.clone())
            else {
                return;
            };
            let changed = active_attach.record_active_client_for_window(attach_pid, target);
            let cache_epoch = if changed {
                self.active_attach_epoch
                    .fetch_add(1, Ordering::AcqRel)
                    .saturating_add(1)
            } else {
                self.active_attach_epoch.load(Ordering::Acquire)
            };
            (changed, cache_epoch, client_name)
        };
        *active_emit_cache = Some((cache_epoch, window_target));
        if should_emit {
            self.emit(LifecycleEvent::ClientActive {
                session_name: target.session_name().clone(),
                client_name: Some(client_name),
            })
            .await;
        }
    }

    async fn handle_attached_terminal_control_event(
        &self,
        identity: ActiveAttachIdentity,
        target: &PaneTarget,
        event: TerminalControlEvent,
    ) {
        let Ok((session_name, session_id, client_name)) = self
            .attached_session_identity_and_client_name_for_identity(identity)
            .await
        else {
            return;
        };
        if target.session_name() != &session_name {
            return;
        }
        let session_name = target.session_name().clone();
        let client_name = Some(client_name);
        let events = match event {
            TerminalControlEvent::FocusIn => {
                vec![
                    LifecycleEvent::ClientFocusIn {
                        session_name,
                        client_name,
                    },
                    LifecycleEvent::PaneFocusIn {
                        target: target.clone(),
                    },
                ]
            }
            TerminalControlEvent::FocusOut => {
                vec![
                    LifecycleEvent::PaneFocusOut {
                        target: target.clone(),
                    },
                    LifecycleEvent::ClientFocusOut {
                        session_name,
                        client_name,
                    },
                ]
            }
            TerminalControlEvent::ClientLightTheme => {
                vec![LifecycleEvent::ClientLightTheme {
                    session_name,
                    client_name,
                }]
            }
            TerminalControlEvent::ClientDarkTheme => {
                vec![LifecycleEvent::ClientDarkTheme {
                    session_name,
                    client_name,
                }]
            }
        };
        let prepared = {
            let mut state = self.state.lock().await;
            if super::ensure_target_session_identity(&state, target, session_id).is_err() {
                return;
            }
            events
                .iter()
                .map(|event| prepare_lifecycle_event(&mut state, event))
                .collect::<Vec<_>>()
        };
        for event in prepared {
            self.emit_prepared_and_wait(event).await;
        }
    }

    async fn clear_attached_focus_alerts(&self, identity: ActiveAttachIdentity) {
        let focused_window = {
            let session_name = {
                let active_attach = self.active_attach.lock().await;
                active_attach
                    .by_pid
                    .get(&identity.attach_pid())
                    .filter(|active| {
                        identity.matches_active(active)
                            && !active.closing.load(std::sync::atomic::Ordering::SeqCst)
                    })
                    .map(|active| active.session_name.clone())
            };
            match session_name {
                Some(session_name) => {
                    let window_index = {
                        let state = self.state.lock().await;
                        state
                            .sessions
                            .session(&session_name)
                            .map(rmux_core::Session::active_window_index)
                    };
                    window_index.map(|window_index| (session_name, window_index))
                }
                None => None,
            }
        };
        if let Some((session_name, window_index)) = focused_window {
            let _ = self
                .clear_session_alerts_on_focus(&session_name, window_index)
                .await;
        }
    }

    #[cfg(test)]
    pub(crate) async fn handle_attached_live_input_for_test(
        &self,
        attach_pid: u32,
        bytes: &[u8],
    ) -> io::Result<()> {
        let mut pending_input = Vec::new();
        self.handle_attached_live_input(attach_pid, &mut pending_input, bytes)
            .await
    }
}

fn attached_mode_input_step(remaining: Option<Vec<u8>>) -> AttachedLiveInputStep {
    match remaining {
        Some(bytes) => AttachedLiveInputStep::Reroute {
            bytes,
            forwarded: false,
        },
        None => AttachedLiveInputStep::Complete(false),
    }
}

fn append_modal_palette_remainder(
    bytes: &mut Vec<u8>,
    mut segments: VecDeque<ModalPaletteInputSegment>,
    retained: &[u8],
) {
    while let Some(segment) = segments.pop_front() {
        bytes.extend_from_slice(&segment.into_bytes());
    }
    bytes.extend_from_slice(retained);
}

fn is_plain_attached_fast_path_input(bytes: &[u8]) -> bool {
    !bytes.is_empty()
        && bytes
            .iter()
            .all(|byte| matches!(*byte, b'\r' | b'\n' | b' '..=b'~'))
}

fn decode_live_attached_key(input: &[u8], backspace: Option<u8>) -> AttachedKeyDecode {
    match decode_attached_key(input, backspace) {
        AttachedKeyDecode::Invalid => {
            let Some(&first) = input.first() else {
                return AttachedKeyDecode::Partial;
            };
            let (utf8, consumed_prefix, modifiers) = if first == b'\x1b' {
                let Some(&second) = input.get(1) else {
                    return AttachedKeyDecode::Partial;
                };
                if second.is_ascii() {
                    return AttachedKeyDecode::Invalid;
                }
                (
                    &input[1..],
                    1,
                    rmux_core::KEYC_META | rmux_core::KEYC_IMPLIED_META,
                )
            } else {
                (input, 0, 0)
            };
            let Some(&utf8_first) = utf8.first() else {
                return AttachedKeyDecode::Partial;
            };
            if let Some((character, size)) = decode_utf8_char(utf8) {
                return AttachedKeyDecode::Matched {
                    size: consumed_prefix + size,
                    key: character as rmux_core::KeyCode | modifiers,
                };
            }
            if is_utf8_lead_byte(utf8_first) && utf8.len() < utf8_expected_len(utf8_first) {
                AttachedKeyDecode::Partial
            } else {
                AttachedKeyDecode::Invalid
            }
        }
        decoded => decoded,
    }
}

fn plain_input_requires_key_dispatch(
    bytes: &[u8],
    target: &PaneTarget,
    state: &crate::pane_terminals::HandlerState,
) -> bool {
    let prefix = session_option_key(state, target.session_name(), rmux_proto::OptionName::Prefix);
    let prefix2 = session_option_key(
        state,
        target.session_name(),
        rmux_proto::OptionName::Prefix2,
    );
    let table_name = default_key_table_name(state, target);
    let mut checked_bytes = [false; 256];

    bytes.iter().copied().any(|byte| {
        let byte_index = usize::from(byte);
        if checked_bytes[byte_index] {
            return false;
        }
        checked_bytes[byte_index] = true;

        let encoded = [byte];
        let AttachedKeyDecode::Matched { key, .. } = decode_live_attached_key(&encoded, None)
        else {
            return true;
        };
        matches_prefix_key(key, prefix, prefix2)
            || lookup_attached_key_table_binding(state, &table_name, key_code_lookup_bits(key))
                .is_some()
    })
}

fn submitted_text_before_enter(bytes: &[u8]) -> Option<&[u8]> {
    let enter = bytes
        .iter()
        .position(|byte| matches!(*byte, b'\r' | b'\n'))?;
    (enter > 0).then_some(&bytes[..enter])
}

#[cfg(test)]
mod live_key_decode_tests {
    use rmux_core::{key_code_lookup_bits, key_string_lookup_string, KEYC_IMPLIED_META, KEYC_META};

    use super::{decode_live_attached_key, AttachedKeyDecode};

    #[test]
    fn meta_unicode_decodes_as_one_key_with_implied_meta() {
        let AttachedKeyDecode::Matched { size, key } =
            decode_live_attached_key(b"\x1b\xc3\xa9", None)
        else {
            panic!("Meta-é should decode as one attached key");
        };
        assert_eq!(size, 3);
        assert_eq!(
            key_code_lookup_bits(key),
            key_code_lookup_bits(key_string_lookup_string("M-é").expect("Meta-é parses"))
        );
        assert_ne!(key & KEYC_META, 0);
        assert_ne!(key & KEYC_IMPLIED_META, 0);
    }

    #[test]
    fn meta_unicode_waits_for_every_utf8_byte() {
        for partial in [
            b"\x1b\xc3".as_slice(),
            b"\x1b\xe6".as_slice(),
            b"\x1b\xe6\x97".as_slice(),
            b"\x1b\xf0".as_slice(),
            b"\x1b\xf0\x9f".as_slice(),
            b"\x1b\xf0\x9f\x92".as_slice(),
        ] {
            assert_eq!(
                decode_live_attached_key(partial, None),
                AttachedKeyDecode::Partial,
                "{partial:?} must stay pending until its declared UTF-8 length"
            );
        }
        assert!(matches!(
            decode_live_attached_key(b"\x1b\xc3\xa9", None),
            AttachedKeyDecode::Matched { size: 3, .. }
        ));
        assert!(matches!(
            decode_live_attached_key(b"\x1b\xe6\x97\xa5", None),
            AttachedKeyDecode::Matched { size: 4, .. }
        ));
        assert!(matches!(
            decode_live_attached_key(b"\x1b\xf0\x9f\x92\xa1", None),
            AttachedKeyDecode::Matched { size: 5, .. }
        ));
    }
}

#[cfg(windows)]
fn windows_console_key_event(key: rmux_proto::AttachedWindowsConsoleKey) -> WindowsConsoleKeyEvent {
    WindowsConsoleKeyEvent::new(
        key.virtual_key_code(),
        key.virtual_scan_code(),
        key.unicode_char(),
        key.control_key_state(),
        key.repeat_count(),
    )
}

#[cfg(windows)]
fn windows_console_binding_key(
    decoded: rmux_core::KeyCode,
    key: WindowsConsoleKeyEvent,
) -> rmux_core::KeyCode {
    windows_console_binding_override_key(decoded, key).unwrap_or(decoded)
}

#[cfg(windows)]
fn windows_synthetic_console_key_for_decoded_key(
    decoded: rmux_core::KeyCode,
) -> Option<WindowsConsoleKeyEvent> {
    key_matches_name(decoded, "C-d").then(WindowsConsoleKeyEvent::ctrl_d)
}

#[cfg(windows)]
fn windows_console_binding_override_key(
    decoded: rmux_core::KeyCode,
    key: WindowsConsoleKeyEvent,
) -> Option<rmux_core::KeyCode> {
    const RIGHT_ALT_PRESSED: u32 = 0x0001;
    const LEFT_ALT_PRESSED: u32 = 0x0002;
    const LEFT_CTRL_PRESSED: u32 = 0x0008;
    const RIGHT_CTRL_PRESSED: u32 = 0x0004;
    const CTRL_PRESSED: u32 = LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED;

    let control_key_state = key.control_key_state();
    if decoded & KEYC_CTRL != 0 || control_key_state & CTRL_PRESSED == 0 {
        return None;
    }

    if control_key_state & RIGHT_ALT_PRESSED != 0 {
        return None;
    }
    if control_key_state & LEFT_ALT_PRESSED != 0 && control_key_state & RIGHT_CTRL_PRESSED == 0 {
        return None;
    }

    let character = char::from_u32(u32::from(key.unicode_char()))?;
    if !character.is_ascii() || character.is_ascii_control() {
        return None;
    }

    let preserved_modifiers = decoded & (KEYC_META | KEYC_IMPLIED_META | KEYC_SHIFT);
    Some(character.to_ascii_lowercase() as rmux_core::KeyCode | KEYC_CTRL | preserved_modifiers)
}

#[cfg(windows)]
fn key_matches_name(key: rmux_core::KeyCode, name: &str) -> bool {
    windows_key_code_named(name).is_some_and(|expected| expected == key)
}

#[cfg(windows)]
fn windows_key_code_named(name: &str) -> Option<rmux_core::KeyCode> {
    key_string_lookup_string(name).map(key_code_lookup_bits)
}

#[cfg(all(test, windows))]
mod windows_console_binding_tests {
    use rmux_core::{KEYC_CTRL, KEYC_IMPLIED_META, KEYC_META, KEYC_SHIFT};
    use rmux_pty::WindowsConsoleKeyEvent;

    use super::windows_console_binding_override_key;

    const RIGHT_ALT_PRESSED: u32 = 0x0001;
    const LEFT_ALT_PRESSED: u32 = 0x0002;
    const RIGHT_CTRL_PRESSED: u32 = 0x0004;
    const LEFT_CTRL_PRESSED: u32 = 0x0008;

    fn key(unicode_char: char, control_key_state: u32) -> WindowsConsoleKeyEvent {
        WindowsConsoleKeyEvent::new(0, 0, unicode_char as u16, control_key_state, 1)
    }

    #[test]
    fn alt_gr_is_not_promoted_to_control_binding() {
        assert_eq!(
            windows_console_binding_override_key(
                b'[' as u64,
                key('[', RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED),
            ),
            None
        );
    }

    #[test]
    fn plain_left_control_promotes_printable_character() {
        assert_eq!(
            windows_console_binding_override_key(b';' as u64, key(';', LEFT_CTRL_PRESSED)),
            Some(b';' as u64 | KEYC_CTRL)
        );
    }

    #[test]
    fn meta_and_shift_modifiers_survive_control_promotion() {
        let decoded = b';' as u64 | KEYC_META | KEYC_IMPLIED_META | KEYC_SHIFT;

        assert_eq!(
            windows_console_binding_override_key(decoded, key(';', LEFT_CTRL_PRESSED)),
            Some(b';' as u64 | KEYC_CTRL | KEYC_META | KEYC_IMPLIED_META | KEYC_SHIFT)
        );
    }

    #[test]
    fn left_alt_without_right_ctrl_is_not_alt_gr_or_control_override() {
        assert_eq!(
            windows_console_binding_override_key(b'q' as u64, key('q', LEFT_ALT_PRESSED)),
            None
        );
    }

    #[test]
    fn right_control_still_promotes_printable_character() {
        assert_eq!(
            windows_console_binding_override_key(b'a' as u64, key('A', RIGHT_CTRL_PRESSED)),
            Some(b'a' as u64 | KEYC_CTRL)
        );
    }
}