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
#[cfg_attr(windows, allow(unused_imports))]
pub(crate) use crate::control_mode::ControlModeUpgrade;
#[cfg(any(unix, windows))]
use crate::daemon::ShutdownHandle;
#[cfg(any(unix, windows))]
use crate::handler::{
    with_control_command_response_sink, with_control_queue_eof_cancellation,
    with_control_queue_identity, ControlClientIdentity, ControlCommandResponseSink,
    ControlQueueDrainLease, ControlQueueEofCancellation, RequestHandler,
};
#[cfg(any(unix, windows))]
use rmux_core::command_parser::{CommandArgument, ParsedCommands};
#[cfg(any(unix, windows))]
use rmux_ipc::LocalStream;
#[cfg(windows)]
use rmux_proto::CONTROL_STDIN_EOF_MARKER;
#[cfg(any(unix, windows))]
use rmux_proto::{format_exit_line, format_guard_line, ControlGuardKind};
use rmux_proto::{ControlMode, RmuxError, SessionName, MAX_INITIAL_CONTROL_COMMANDS};
#[cfg(any(unix, windows))]
use std::collections::{HashMap, HashSet, VecDeque};
#[cfg(any(unix, windows))]
use std::io;
#[cfg(any(unix, windows))]
use std::pin::Pin;
#[cfg(any(unix, windows))]
use std::sync::atomic::{AtomicBool, Ordering};
#[cfg(any(unix, windows))]
use std::sync::Arc;
#[cfg(all(test, unix))]
use std::sync::{Mutex as StdMutex, OnceLock};
#[cfg(any(unix, windows))]
use std::time::{Duration, SystemTime, UNIX_EPOCH};
#[cfg(any(unix, windows))]
use tokio::io::{AsyncReadExt, AsyncWriteExt, WriteHalf};
#[cfg(all(test, unix))]
use tokio::sync::Notify;
#[cfg(any(unix, windows))]
use tokio::sync::{mpsc, watch};
#[cfg(any(unix, windows))]
use tokio::task::JoinHandle;

#[path = "control/output_queue.rs"]
mod output_queue;
#[cfg(any(unix, windows))]
use output_queue::{ensure_control_newline, flush_output_queue, ControlOutputQueue};

#[path = "control/command_numbering.rs"]
mod command_numbering;
#[cfg(any(unix, windows))]
use command_numbering::{ControlCommandNumbering, ControlCommandOrigin};

#[path = "control/command_validation.rs"]
mod command_validation;
#[cfg(any(unix, windows))]
use command_validation::validate_control_command_arguments;

#[path = "control/subscriptions.rs"]
mod subscriptions;
#[cfg(any(unix, windows))]
use subscriptions::{
    drain_ready_pane_events, handle_pane_event, refresh_subscriptions, PaneEvent, PaneSubscription,
    PaneSubscriptionStart,
};

#[path = "control/session_attachment.rs"]
mod session_attachment;
#[cfg(any(unix, windows))]
use session_attachment::ControlSessionAttachment;

#[path = "control/eof_completion.rs"]
mod eof_completion;
#[cfg(any(unix, windows))]
use eof_completion::ControlEofCompletion;

#[cfg(any(unix, windows))]
const MAX_DEFERRED_CONTROL_NOTIFICATIONS: usize = 1024;
#[cfg(any(unix, windows))]
const MAX_DEFERRED_CONTROL_NOTIFICATION_BYTES: usize = 4 * 1024 * 1024;
#[cfg(any(unix, windows))]
const CONTROL_PANE_EVENT_CAPACITY: usize = 256;
#[cfg(any(unix, windows))]
pub(crate) const CONTROL_SERVER_EVENT_CAPACITY: usize = 256;
pub(crate) fn validate_initial_control_command_count(count: usize) -> Result<(), RmuxError> {
    if count <= MAX_INITIAL_CONTROL_COMMANDS {
        return Ok(());
    }
    Err(RmuxError::Server(format!(
        "too many initial control-mode commands: {count} (maximum {MAX_INITIAL_CONTROL_COMMANDS})"
    )))
}

#[cfg(any(unix, windows))]
fn control_commands_require_drain(commands: &ParsedCommands) -> bool {
    !commands.assignments().is_empty()
        || !commands
            .commands()
            .iter()
            .all(control_command_is_cancel_safe_wait)
}

#[cfg(any(unix, windows))]
fn control_command_is_cancel_safe_wait(command: &rmux_core::command_parser::ParsedCommand) -> bool {
    if command.name() != "wait-for" {
        return false;
    }
    match command.arguments() {
        [CommandArgument::String(_channel)] => true,
        [CommandArgument::String(flag), CommandArgument::String(_channel)] => {
            matches!(flag.as_str(), "--" | "-L")
        }
        _ => false,
    }
}
#[cfg(any(unix, windows))]
const MAX_CONTROL_LINE_BYTES: usize = 1024 * 1024;
#[cfg(any(unix, windows))]
const MAX_QUEUED_CONTROL_LINES: usize = 1024;
#[cfg(any(unix, windows))]
const MAX_QUEUED_CONTROL_BYTES: usize = 4 * 1024 * 1024;

#[cfg(any(unix, windows))]
// Keep one bounded, global post-EOF window for already accepted frames to
// publish fast replies before falling back to the detached finite drain.
const CONTROL_EOF_GRACE: Duration = Duration::from_millis(250);

#[cfg(any(unix, windows))]
type ControlEofTransition = Pin<Box<tokio::time::Sleep>>;

#[cfg(any(unix, windows))]
fn arm_control_eof_transition(transition: &mut Option<ControlEofTransition>) {
    if transition.is_none() {
        *transition = Some(Box::pin(tokio::time::sleep(CONTROL_EOF_GRACE)));
    }
}

#[cfg(any(unix, windows))]
async fn wait_for_control_eof_transition(transition: &mut Option<ControlEofTransition>) {
    match transition.as_mut() {
        Some(transition) => transition.as_mut().await,
        None => std::future::pending().await,
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) struct ControlClientFlags {
    pub(crate) pause_after_millis: Option<u64>,
    pub(crate) no_output: bool,
    pub(crate) wait_exit: bool,
}

impl ControlClientFlags {
    #[must_use]
    pub(crate) const fn uses_extended_output(self) -> bool {
        self.pause_after_millis.is_some()
    }
}

#[derive(Debug, Clone)]
pub(crate) enum ControlServerEvent {
    SessionChanged(Option<SessionName>),
    SessionChangedAt {
        session_name: SessionName,
        pane_sequences: Vec<(u32, u64)>,
    },
    Refresh,
    Notification(String),
    Exit(Option<String>),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ControlQueueCommandOrigin {
    SourceFile { depth: usize },
    IfShell,
    RunShell { depth: usize },
    QueueContinuation,
}

#[derive(Debug, Clone)]
pub(crate) enum ControlCommandResponseEvent {
    FrameStarted {
        origin: ControlQueueCommandOrigin,
    },
    Notification(String),
    FrameCompleted {
        stdout: Vec<u8>,
        error: Option<RmuxError>,
    },
}

#[derive(Debug, Clone)]
pub(crate) struct ControlCommandResult {
    pub(crate) stdout: Vec<u8>,
    pub(crate) error: Option<rmux_proto::RmuxError>,
    pub(crate) source_file_error: Option<rmux_proto::RmuxError>,
    pub(crate) execution_error: Option<rmux_proto::RmuxError>,
    pub(crate) exit_status: Option<i32>,
    pub(crate) server_shutdown_started: bool,
}

#[derive(Debug)]
#[cfg(any(unix, windows))]
pub(crate) struct ControlLifecycle {
    pub(crate) closing: Arc<AtomicBool>,
    pub(crate) shutdown_handle: ShutdownHandle,
}

#[derive(Debug)]
#[cfg(any(unix, windows))]
pub(crate) struct ControlUpgradeInput {
    buffered_bytes: Vec<u8>,
    initial_command_count: usize,
    mode: ControlMode,
}

#[cfg(any(unix, windows))]
impl ControlUpgradeInput {
    #[cfg(test)]
    pub(crate) fn new(buffered_bytes: Vec<u8>, initial_command_count: usize) -> Self {
        Self::with_mode(buffered_bytes, initial_command_count, ControlMode::Plain)
    }

    pub(crate) fn with_mode(
        buffered_bytes: Vec<u8>,
        initial_command_count: usize,
        mode: ControlMode,
    ) -> Self {
        Self {
            buffered_bytes,
            initial_command_count,
            mode,
        }
    }
}

#[cfg(any(unix, windows))]
pub(crate) async fn forward_control(
    stream: LocalStream,
    handler: Arc<RequestHandler>,
    control_identity: ControlClientIdentity,
    upgrade_input: ControlUpgradeInput,
    shutdown: watch::Receiver<()>,
    server_events: mpsc::Receiver<ControlServerEvent>,
    lifecycle: ControlLifecycle,
) -> io::Result<()> {
    with_control_queue_identity(
        control_identity,
        forward_control_inner(
            stream,
            handler,
            control_identity,
            upgrade_input,
            shutdown,
            server_events,
            lifecycle,
        ),
    )
    .await
}

#[cfg(any(unix, windows))]
async fn forward_control_inner(
    stream: LocalStream,
    handler: Arc<RequestHandler>,
    control_identity: ControlClientIdentity,
    upgrade_input: ControlUpgradeInput,
    mut shutdown: watch::Receiver<()>,
    mut server_events: mpsc::Receiver<ControlServerEvent>,
    lifecycle: ControlLifecycle,
) -> io::Result<()> {
    let requester_pid = control_identity.requester_pid();
    let control_id = control_identity.control_id();
    let ControlUpgradeInput {
        buffered_bytes: initial_socket_bytes,
        initial_command_count,
        mode,
    } = upgrade_input;
    validate_initial_control_command_count(initial_command_count)
        .map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error.to_string()))?;
    let (pane_event_tx, mut pane_event_rx) = mpsc::channel(CONTROL_PANE_EVENT_CAPACITY);
    let (mut read_half, mut write_half) = tokio::io::split(stream);
    let mut input_buffer = Vec::new();
    let mut queued_lines = VecDeque::new();
    let mut queued_input_bytes = 0_usize;
    append_control_input(
        &mut input_buffer,
        &mut queued_lines,
        &mut queued_input_bytes,
        &initial_socket_bytes,
    )?;
    let mut read_buffer = [0_u8; 8192];
    let mut shutdown_draining = shutdown.has_changed().unwrap_or(true);
    while queued_lines.len() < initial_command_count && !shutdown_draining {
        let bytes_read = tokio::select! {
            biased;
            result = shutdown.changed() => {
                let _ = result;
                shutdown_draining = true;
                continue;
            }
            result = read_half.read(&mut read_buffer) => result?,
        };
        if bytes_read == 0 {
            return Err(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                format!(
                    "control-mode stream closed after {} of {initial_command_count} initial commands",
                    queued_lines.len()
                ),
            ));
        }
        append_control_input(
            &mut input_buffer,
            &mut queued_lines,
            &mut queued_input_bytes,
            &read_buffer[..bytes_read],
        )?;
    }
    if shutdown_draining {
        input_buffer.clear();
        queued_lines.clear();
        queued_input_bytes = 0;
    }
    let mut output_queue = ControlOutputQueue::default();
    let mut subscriptions = HashMap::new();
    let mut paused_panes = HashSet::new();
    let mut deferred_server_events = DeferredServerEvents::default();
    let mut input_closed = shutdown_draining;
    let mut eof_queue_lease = None;
    let mut eof_transition = None;
    #[cfg(windows)]
    let initial_stdin_eof_marker = consume_control_eof_marker(
        &mut input_buffer,
        &mut queued_lines,
        &mut queued_input_bytes,
    );
    #[cfg(windows)]
    if initial_stdin_eof_marker {
        input_closed = true;
        acquire_control_eof_queue_lease(&mut eof_queue_lease, &handler, control_identity).await;
        arm_control_eof_transition(&mut eof_transition);
    }
    let mut attachment =
        ControlSessionAttachment::new(handler.control_session_name(requester_pid).await);
    let mut flags: ControlClientFlags = handler
        .control_client_flags(requester_pid)
        .await
        .unwrap_or_default();
    let mut current_command: Option<ActiveControlCommand> = None;
    let mut current_response_frame: Option<ActiveControlResponseFrame> = None;
    let mut current_response_notifications: Option<mpsc::Receiver<ControlCommandResponseEvent>> =
        None;
    let mut initial_command_completion_pending = false;
    let mut eof_completion = ControlEofCompletion::default();
    #[cfg(windows)]
    if initial_stdin_eof_marker {
        eof_completion.observe_stdin_eof_marker(attachment.is_attached(), !queued_lines.is_empty());
    }
    let mut command_numbering = if initial_command_count == 0 {
        let initial_timestamp = unix_epoch_seconds();
        output_queue.enqueue_line(
            format_guard_line(ControlGuardKind::Begin, initial_timestamp, 1, 0).into_bytes(),
            false,
        );
        output_queue.enqueue_line(
            format_guard_line(ControlGuardKind::End, initial_timestamp, 1, 0).into_bytes(),
            false,
        );
        ControlCommandNumbering::after_initial_ack()
    } else {
        ControlCommandNumbering::with_initial_commands(initial_command_count)
    };

    refresh_subscriptions(
        &handler,
        control_identity,
        attachment.session_name(),
        &mut subscriptions,
        pane_event_tx.clone(),
        PaneSubscriptionStart::Now,
    )
    .await;
    while let Ok(event) = server_events.try_recv() {
        let mut event_context = ServerEventContext {
            handler: &handler,
            control_identity,
            requester_pid,
            session_name: attachment.session_name_mut(),
            subscriptions: &mut subscriptions,
            pane_event_tx: pane_event_tx.clone(),
            pane_event_rx: &mut pane_event_rx,
            output_queue: &mut output_queue,
            write_half: &mut write_half,
            paused_panes: &mut paused_panes,
            flags: &mut flags,
            deferred: &mut deferred_server_events,
        };
        if handle_server_event(event, &mut event_context, false).await? {
            return Ok(());
        }
    }

    loop {
        if !shutdown_draining && shutdown.has_changed().unwrap_or(true) {
            shutdown_draining = true;
            input_closed = true;
            input_buffer.clear();
            queued_lines.clear();
            queued_input_bytes = 0;
            eof_transition = None;
            if let Some(command) = current_command.as_ref() {
                command.eof_cancellation.cancel_for_eof();
            }
        }
        if current_command.is_none() {
            let reconcile_ready_control_events = initial_command_completion_pending
                || (input_closed && !control_control_waits_for_attached_session(mode, &attachment));
            let mut event_context = ServerEventContext {
                handler: &handler,
                control_identity,
                requester_pid,
                session_name: attachment.session_name_mut(),
                subscriptions: &mut subscriptions,
                pane_event_tx: pane_event_tx.clone(),
                pane_event_rx: &mut pane_event_rx,
                output_queue: &mut output_queue,
                write_half: &mut write_half,
                paused_panes: &mut paused_panes,
                flags: &mut flags,
                deferred: &mut deferred_server_events,
            };
            if flush_deferred_server_events(&mut event_context).await? {
                return Ok(());
            }
            if reconcile_ready_control_events {
                // A successful attach publishes its session-change event before
                // the command task returns. When completion and both futures are
                // ready, the biased select below deliberately observes command
                // completion first. Reconcile the bounded snapshot of events
                // already published before deciding whether the completed CLI
                // batch is unattached or treating an EOF-bound client as
                // terminal. New arrivals are left to the select, so a continuous
                // producer cannot starve either terminal decision.
                let ready_server_event_count = server_events.len();
                for _ in 0..ready_server_event_count {
                    let Ok(event) = server_events.try_recv() else {
                        break;
                    };
                    if handle_server_event(event, &mut event_context, false).await? {
                        return Ok(());
                    }
                }
            }
        }
        eof_completion.observe_attachment(
            attachment.is_attached(),
            current_command.is_some() || !queued_lines.is_empty(),
        );
        if output_queue.is_transport_closed()
            && input_closed
            && current_command.is_none()
            && queued_lines.is_empty()
        {
            // A terminal write failure makes an already-closed input queue
            // reclaimable, including persistent attached `-CC`. It does not
            // itself prove read EOF: complete frames may still be buffered in
            // the pipe, so open input must keep draining until the read side
            // independently closes.
            return Ok(());
        }
        if shutdown_draining && current_command.is_none() {
            output_queue.enqueue_line(
                format_exit_line(Some("server shutting down")).into_bytes(),
                false,
            );
            flush_output_queue(&mut output_queue, &mut write_half, flags, &mut paused_panes)
                .await?;
            return Ok(());
        }
        if lifecycle.closing.load(Ordering::SeqCst) && current_command.is_none() {
            output_queue.enqueue_line(format_exit_line(None).into_bytes(), false);
            flush_output_queue(&mut output_queue, &mut write_half, flags, &mut paused_panes)
                .await?;
            return Ok(());
        }
        if initial_command_completion_pending && current_command.is_none() {
            initial_command_completion_pending = false;
            if !attachment.is_attached() {
                output_queue.enqueue_line(format_exit_line(None).into_bytes(), false);
                flush_output_queue(&mut output_queue, &mut write_half, flags, &mut paused_panes)
                    .await?;
                write_half.shutdown().await?;
                return Ok(());
            }
        }
        if !shutdown_draining
            && input_closed
            && current_command.is_none()
            && queued_lines.is_empty()
            && !control_control_waits_for_attached_session(mode, &attachment)
        {
            // Any incomplete line remaining in input_buffer after EOF is
            // discarded, matching tmux's `evbuffer_readln` semantics. EOF
            // itself is promoted to a bare `%exit\n` so the control-mode
            // transcript is terminated by a guard-tuple-free exit line,
            // matching tmux's `server_client_control_mode` close path.
            output_queue.enqueue_line(format_exit_line(None).into_bytes(), false);
            flush_output_queue(&mut output_queue, &mut write_half, flags, &mut paused_panes)
                .await?;
            return Ok(());
        }

        while !shutdown_draining && current_command.is_none() {
            let Some(next_line) = queued_lines.front() else {
                break;
            };
            #[cfg(windows)]
            if next_line == CONTROL_STDIN_EOF_MARKER {
                queued_lines
                    .pop_front()
                    .expect("peeked control EOF marker remains queued");
                input_closed = true;
                acquire_control_eof_queue_lease(&mut eof_queue_lease, &handler, control_identity)
                    .await;
                arm_control_eof_transition(&mut eof_transition);
                input_buffer.clear();
                queued_lines.clear();
                queued_input_bytes = 0;
                eof_completion.observe_stdin_eof_marker(attachment.is_attached(), false);
                break;
            }
            if next_line.is_empty() {
                queued_lines
                    .pop_front()
                    .expect("peeked empty control line remains queued");
                output_queue.enqueue_line(format_exit_line(None).into_bytes(), false);
                flush_output_queue(&mut output_queue, &mut write_half, flags, &mut paused_panes)
                    .await?;
                return Ok(());
            }
            let parsed_commands = handler
                .parse_control_commands(next_line)
                .await
                .and_then(validate_control_command_arguments);
            let requires_drain = parsed_commands
                .as_ref()
                .is_ok_and(control_commands_require_drain);
            let Some(normal_request_guard) = handler.try_begin_normal_request(requires_drain)
            else {
                shutdown_draining = true;
                input_closed = true;
                input_buffer.clear();
                queued_lines.clear();
                queued_input_bytes = 0;
                eof_transition = None;
                break;
            };
            let line = queued_lines
                .pop_front()
                .expect("admitted control command remains queued");
            queued_input_bytes = queued_input_bytes.saturating_sub(line.len());

            let timestamp = unix_epoch_seconds();
            let command_frame = command_numbering.next_frame();
            output_queue.enqueue_line(
                format_guard_line(
                    ControlGuardKind::Begin,
                    timestamp,
                    command_frame.number,
                    command_frame.guard_flag,
                )
                .into_bytes(),
                false,
            );
            flush_output_queue(&mut output_queue, &mut write_half, flags, &mut paused_panes)
                .await?;

            match parsed_commands {
                Ok(commands) => {
                    eof_completion.command_started(&commands);
                    let handler = Arc::clone(&handler);
                    let eof_cancellation = ControlQueueEofCancellation::new(control_identity);
                    if input_closed {
                        eof_cancellation.cancel_for_eof();
                    }
                    let task_eof_cancellation = eof_cancellation.clone();
                    let (response_tx, response_rx) = mpsc::channel(CONTROL_SERVER_EVENT_CAPACITY);
                    let response_sink = ControlCommandResponseSink::new(
                        control_identity,
                        response_tx,
                        Arc::clone(&lifecycle.closing),
                    );
                    current_response_notifications = Some(response_rx);
                    current_response_frame = Some(ActiveControlResponseFrame::owner());
                    current_command = Some(ActiveControlCommand {
                        timestamp,
                        command_number: command_frame.number,
                        guard_flag: command_frame.guard_flag,
                        origin: command_frame.origin,
                        eof_cancellation,
                        task: Some(tokio::spawn(async move {
                            let _normal_request_guard = normal_request_guard;
                            with_control_command_response_sink(
                                response_sink,
                                with_control_queue_eof_cancellation(
                                    task_eof_cancellation,
                                    handler.execute_control_commands_identity(
                                        requester_pid,
                                        control_id,
                                        commands,
                                    ),
                                ),
                            )
                            .await
                        })),
                    });
                    if input_closed {
                        arm_control_eof_transition(&mut eof_transition);
                    }
                }
                Err(error) => {
                    drop(normal_request_guard);
                    output_queue.enqueue_stdout(format!("parse error: {error}").into_bytes());
                    if drain_ready_pane_events(
                        &mut pane_event_rx,
                        &mut output_queue,
                        &mut paused_panes,
                        flags,
                    )? {
                        flush_output_queue(
                            &mut output_queue,
                            &mut write_half,
                            flags,
                            &mut paused_panes,
                        )
                        .await?;
                        return Ok(());
                    }
                    output_queue.enqueue_line(
                        format_guard_line(
                            ControlGuardKind::Error,
                            timestamp,
                            command_frame.number,
                            command_frame.guard_flag,
                        )
                        .into_bytes(),
                        false,
                    );
                    flush_output_queue(
                        &mut output_queue,
                        &mut write_half,
                        flags,
                        &mut paused_panes,
                    )
                    .await?;
                    if command_frame.origin.completes_initial_batch() {
                        initial_command_completion_pending = true;
                        break;
                    }
                }
            }
        }
        if initial_command_completion_pending && current_command.is_none() {
            continue;
        }
        if shutdown_draining && current_command.is_none() {
            continue;
        }
        if !shutdown_draining
            && input_closed
            && current_command.is_none()
            && queued_lines.is_empty()
            && !control_control_waits_for_attached_session(mode, &attachment)
        {
            output_queue.enqueue_line(format_exit_line(None).into_bytes(), false);
            flush_output_queue(&mut output_queue, &mut write_half, flags, &mut paused_panes)
                .await?;
            return Ok(());
        }

        tokio::select! {
            biased;

            result = shutdown.changed(), if !shutdown_draining => {
                let _ = result;
                shutdown_draining = true;
                input_closed = true;
                input_buffer.clear();
                queued_lines.clear();
                queued_input_bytes = 0;
                eof_transition = None;
                if let Some(command) = current_command.as_ref() {
                    command.eof_cancellation.cancel_for_eof();
                }
            }
            result = read_half.read(&mut read_buffer), if !input_closed && !shutdown_draining => {
                let bytes_read = result?;
                if bytes_read == 0 {
                    input_closed = true;
                    acquire_control_eof_queue_lease(
                        &mut eof_queue_lease,
                        &handler,
                        control_identity,
                    )
                    .await;
                    if let Some(command) = current_command.as_ref() {
                        command.eof_cancellation.cancel_for_eof();
                    }
                    #[cfg(windows)]
                    eof_completion.observe_transport_eof(
                        attachment.is_attached(),
                        current_command.is_some() || !queued_lines.is_empty(),
                    );
                    arm_control_eof_transition(&mut eof_transition);
                } else {
                    append_control_input(
                        &mut input_buffer,
                        &mut queued_lines,
                        &mut queued_input_bytes,
                        &read_buffer[..bytes_read],
                    )?;
                    #[cfg(windows)]
                    if consume_control_eof_marker(
                        &mut input_buffer,
                        &mut queued_lines,
                        &mut queued_input_bytes,
                    ) {
                        input_closed = true;
                        acquire_control_eof_queue_lease(
                            &mut eof_queue_lease,
                            &handler,
                            control_identity,
                        )
                        .await;
                        if let Some(command) = current_command.as_ref() {
                            command.eof_cancellation.cancel_for_eof();
                        }
                        eof_completion.observe_stdin_eof_marker(
                            attachment.is_attached(),
                            current_command.is_some() || !queued_lines.is_empty(),
                        );
                        arm_control_eof_transition(&mut eof_transition);
                    }
                }
            }
            Some(event) = async {
                match current_response_notifications.as_mut() {
                    Some(notifications) => notifications.recv().await,
                    None => std::future::pending().await,
                }
            }, if current_command.is_some() => {
                let mut event_context = ServerEventContext {
                    handler: &handler,
                    control_identity,
                    requester_pid,
                    session_name: attachment.session_name_mut(),
                    subscriptions: &mut subscriptions,
                    pane_event_tx: pane_event_tx.clone(),
                    pane_event_rx: &mut pane_event_rx,
                    output_queue: &mut output_queue,
                    write_half: &mut write_half,
                    paused_panes: &mut paused_panes,
                    flags: &mut flags,
                    deferred: &mut deferred_server_events,
                };
                let command = current_command
                    .as_mut()
                    .expect("response events belong to an active command");
                let response_frame = current_response_frame
                    .as_mut()
                    .expect("active commands own response frame state");
                if handle_control_command_response_event(
                    event,
                    &mut command_numbering,
                    command,
                    response_frame,
                    &mut event_context,
                )
                .await?
                {
                    return Ok(());
                }
            }
            result = async {
                match current_command.as_mut() {
                    Some(command) => match command.task.as_mut() {
                        Some(task) => Some(task.await),
                        None => std::future::pending().await,
                    },
                    None => std::future::pending().await,
                }
            } => {
                let Some(task_result) = result else {
                    continue;
                };
                let result = task_result
                    .map_err(|error| io::Error::other(format!("control command task failed: {error}")))?;
                let mut response_notifications = current_response_notifications
                    .take()
                    .expect("active control command owns a response channel");
                // The typed response sender is dropped before the task joins.
                // Drain its finite FIFO without waiting so the last child
                // boundary is applied before command completion.
                while let Ok(event) = response_notifications.try_recv() {
                    let mut event_context = ServerEventContext {
                        handler: &handler,
                        control_identity,
                        requester_pid,
                        session_name: attachment.session_name_mut(),
                        subscriptions: &mut subscriptions,
                        pane_event_tx: pane_event_tx.clone(),
                        pane_event_rx: &mut pane_event_rx,
                        output_queue: &mut output_queue,
                        write_half: &mut write_half,
                        paused_panes: &mut paused_panes,
                        flags: &mut flags,
                        deferred: &mut deferred_server_events,
                    };
                    let command = current_command
                        .as_mut()
                        .expect("drained responses belong to an active command");
                    let response_frame = current_response_frame
                        .as_mut()
                        .expect("active commands own response frame state");
                    if handle_control_command_response_event(
                        event,
                        &mut command_numbering,
                        command,
                        response_frame,
                        &mut event_context,
                    )
                    .await?
                    {
                        return Ok(());
                    }
                }
                let Some(command) = current_command.take() else {
                    continue;
                };
                eof_completion.command_finished();
                let response_frame = current_response_frame
                    .take()
                    .expect("completed commands own response frame state");
                let server_shutdown_started = result.server_shutdown_started;
                if response_frame.open {
                    if !result.stdout.is_empty() {
                        output_queue.enqueue_stdout(result.stdout);
                    }
                    if drain_ready_pane_events(
                        &mut pane_event_rx,
                        &mut output_queue,
                        &mut paused_panes,
                        flags,
                    )? {
                        flush_output_queue(
                            &mut output_queue,
                            &mut write_half,
                            flags,
                            &mut paused_panes,
                        )
                        .await?;
                        return Ok(());
                    }
                    enqueue_control_frame_terminal(&mut output_queue, &command, result.error);
                }
                flush_output_queue(&mut output_queue, &mut write_half, flags, &mut paused_panes).await?;
                if command.origin.completes_initial_batch() {
                    initial_command_completion_pending = true;
                }
                let shutdown_requested =
                    server_shutdown_started || handler.request_shutdown_if_pending();
                if shutdown_requested {
                    // The listener publishes its shutdown watch on a later
                    // scheduler turn. Stop this exact queue synchronously so a
                    // buffered frame cannot start after kill-server.
                    shutdown_draining = true;
                    input_closed = true;
                    input_buffer.clear();
                    queued_lines.clear();
                    queued_input_bytes = 0;
                    eof_transition = None;
                    lifecycle.shutdown_handle.request_shutdown();
                } else if input_closed {
                    arm_control_eof_transition(&mut eof_transition);
                }
            }
            _ = wait_for_control_eof_transition(&mut eof_transition),
                if !shutdown_draining
                    && input_closed
                    && current_command.is_some()
                    && !mode.is_control_control()
                    && eof_completion.allows_detached_drain_transition() =>
            {
                // The transport can close as soon as the active guard has
                // been terminated, but every complete frame accepted before
                // EOF still belongs to this exact control registration. Keep
                // its queue lease until those finite frames have drained.
                let deferred_exit_reason = deferred_server_events.exit_reason.take();
                let lease = match eof_queue_lease {
                    Some(lease) => lease,
                    None => handler.begin_control_queue_drain(control_identity).await,
                };
                // Exit is terminal even when its event was consumed while the
                // active command was still running. A missing exact
                // registration or an already-closing lifecycle is terminal
                // too: the Exit producer may have detached and removed this
                // control client even when its event channel was full.
                // Acquire the lease when possible so a same-PID replacement
                // still waits for the active frame, but never turn its absence
                // into a product error after the transport has reached EOF.
                let stop_after_active = deferred_exit_reason.is_some()
                    || lease == ControlQueueDrainLease::Unavailable
                    || lifecycle.closing.load(Ordering::SeqCst);
                let closed = close_active_control_command_on_eof(
                    &mut current_command,
                    &mut current_response_frame,
                    &mut output_queue,
                    &mut write_half,
                    flags,
                    &mut paused_panes,
                    deferred_exit_reason
                        .as_ref()
                        .and_then(Option::as_deref),
                )
                .await;
                #[cfg(windows)]
                {
                    // Tokio's named-pipe `AsyncWrite::shutdown` only flushes;
                    // it does not half-close the duplex handle. Release both
                    // split halves after the terminal `%exit` is flushed so
                    // Windows clients can use transport EOF as the unambiguous
                    // completion signal while the finite queue drains below.
                    drop(read_half);
                    drop(write_half);
                }
                let mut drain_context = EofDrainContext {
                    server_events: &mut server_events,
                    events_open: true,
                    handler: &handler,
                    control_identity,
                    shutdown: &mut shutdown,
                    shutdown_handle: &lifecycle.shutdown_handle,
                };
                let drain_result = drain_control_queue_after_eof(
                    closed.task,
                    &mut queued_lines,
                    &mut queued_input_bytes,
                    stop_after_active,
                    &mut drain_context,
                )
                .await;
                drain_result?;
                return closed.transport_result;
            }
            Some(event) = server_events.recv() => {
                let mut event_context = ServerEventContext {
                    handler: &handler,
                    control_identity,
                    requester_pid,
                    session_name: attachment.session_name_mut(),
                    subscriptions: &mut subscriptions,
                    pane_event_tx: pane_event_tx.clone(),
                    pane_event_rx: &mut pane_event_rx,
                    output_queue: &mut output_queue,
                    write_half: &mut write_half,
                    paused_panes: &mut paused_panes,
                    flags: &mut flags,
                    deferred: &mut deferred_server_events,
                };
                if handle_server_event(event, &mut event_context, current_command.is_some()).await?
                {
                    return Ok(());
                }
            }
            Some(event) = pane_event_rx.recv() => {
                let lagged =
                    handle_pane_event(event, &mut output_queue, &mut paused_panes, flags)?;
                flush_output_queue(&mut output_queue, &mut write_half, flags, &mut paused_panes).await?;
                if lagged {
                    return Ok(());
                }
            }
        }
    }
}

#[cfg(any(unix, windows))]
fn control_control_waits_for_attached_session(
    mode: ControlMode,
    attachment: &ControlSessionAttachment,
) -> bool {
    mode.is_control_control() && attachment.is_attached()
}

#[cfg(any(unix, windows))]
async fn acquire_control_eof_queue_lease(
    eof_queue_lease: &mut Option<ControlQueueDrainLease>,
    handler: &RequestHandler,
    control_identity: ControlClientIdentity,
) {
    if eof_queue_lease.is_some() {
        return;
    }
    *eof_queue_lease = Some(handler.begin_control_queue_drain(control_identity).await);
    #[cfg(all(test, unix))]
    pause_after_control_eof_queue_lease(handler, control_identity).await;
}

#[cfg(all(test, unix))]
struct ControlEofQueueLeasePause {
    handler: Arc<RequestHandler>,
    identity: ControlClientIdentity,
    reached: Notify,
    release: Notify,
}

#[cfg(all(test, unix))]
impl ControlEofQueueLeasePause {
    fn matches(&self, handler: &RequestHandler, identity: ControlClientIdentity) -> bool {
        std::ptr::eq(self.handler.as_ref(), handler) && self.identity == identity
    }
}

#[cfg(all(test, unix))]
struct ControlEofQueueLeasePauseGuard {
    pause: Arc<ControlEofQueueLeasePause>,
}

#[cfg(all(test, unix))]
impl std::ops::Deref for ControlEofQueueLeasePauseGuard {
    type Target = ControlEofQueueLeasePause;

    fn deref(&self) -> &Self::Target {
        &self.pause
    }
}

#[cfg(all(test, unix))]
impl Drop for ControlEofQueueLeasePauseGuard {
    fn drop(&mut self) {
        let Some(pauses) = CONTROL_EOF_QUEUE_LEASE_PAUSES.get() else {
            return;
        };
        let mut installed = pauses.lock().expect("control EOF queue lease pause");
        if let Some(index) = installed
            .iter()
            .position(|pause| Arc::ptr_eq(pause, &self.pause))
        {
            installed.swap_remove(index);
        }
    }
}

#[cfg(all(test, unix))]
static CONTROL_EOF_QUEUE_LEASE_PAUSES: OnceLock<StdMutex<Vec<Arc<ControlEofQueueLeasePause>>>> =
    OnceLock::new();

#[cfg(all(test, unix))]
fn install_control_eof_queue_lease_pause(
    handler: &Arc<RequestHandler>,
    identity: ControlClientIdentity,
) -> ControlEofQueueLeasePauseGuard {
    let pause = Arc::new(ControlEofQueueLeasePause {
        handler: Arc::clone(handler),
        identity,
        reached: Notify::new(),
        release: Notify::new(),
    });
    let mut installed = CONTROL_EOF_QUEUE_LEASE_PAUSES
        .get_or_init(|| StdMutex::new(Vec::new()))
        .lock()
        .expect("control EOF queue lease pause");
    let duplicate = installed
        .iter()
        .any(|installed| installed.matches(handler, identity));
    if !duplicate {
        installed.push(Arc::clone(&pause));
    }
    drop(installed);
    assert!(
        !duplicate,
        "only one control EOF queue lease pause may be installed per handler and identity"
    );
    ControlEofQueueLeasePauseGuard { pause }
}

#[cfg(all(test, unix))]
async fn pause_after_control_eof_queue_lease(
    handler: &RequestHandler,
    identity: ControlClientIdentity,
) {
    let pause = {
        let mut installed = CONTROL_EOF_QUEUE_LEASE_PAUSES
            .get_or_init(|| StdMutex::new(Vec::new()))
            .lock()
            .expect("control EOF queue lease pause");
        installed
            .iter()
            .position(|pause| pause.matches(handler, identity))
            .map(|index| installed.swap_remove(index))
    };
    if let Some(pause) = pause {
        pause.reached.notify_one();
        pause.release.notified().await;
    }
}

#[cfg(any(unix, windows))]
struct ClosedControlCommand {
    task: Option<JoinHandle<ControlCommandResult>>,
    transport_result: io::Result<()>,
}

#[cfg(any(unix, windows))]
async fn close_active_control_command_on_eof(
    current_command: &mut Option<ActiveControlCommand>,
    current_response_frame: &mut Option<ActiveControlResponseFrame>,
    output_queue: &mut ControlOutputQueue,
    write_half: &mut WriteHalf<LocalStream>,
    flags: ControlClientFlags,
    paused_panes: &mut HashSet<u32>,
    exit_reason: Option<&str>,
) -> ClosedControlCommand {
    let Some(mut command) = current_command.take() else {
        *current_response_frame = None;
        return ClosedControlCommand {
            task: None,
            transport_result: Ok(()),
        };
    };
    let response_frame = current_response_frame
        .take()
        .expect("active commands own response frame state");
    if response_frame.open {
        output_queue.enqueue_line(
            format_guard_line(
                ControlGuardKind::End,
                command.timestamp,
                command.command_number,
                command.guard_flag,
            )
            .into_bytes(),
            false,
        );
    }
    output_queue.enqueue_line(format_exit_line(exit_reason).into_bytes(), false);
    command.eof_cancellation.cancel_for_eof();
    let task = command.task.take();
    drop(command);
    let transport_result = async {
        flush_output_queue(output_queue, write_half, flags, paused_panes).await?;
        write_half.shutdown().await
    }
    .await;
    ClosedControlCommand {
        task,
        transport_result,
    }
}

#[cfg(any(unix, windows))]
struct EofDrainContext<'a> {
    server_events: &'a mut mpsc::Receiver<ControlServerEvent>,
    events_open: bool,
    handler: &'a Arc<RequestHandler>,
    control_identity: ControlClientIdentity,
    shutdown: &'a mut watch::Receiver<()>,
    shutdown_handle: &'a ShutdownHandle,
}

#[cfg(any(unix, windows))]
async fn drain_control_queue_after_eof(
    active_task: Option<JoinHandle<ControlCommandResult>>,
    queued_lines: &mut VecDeque<String>,
    queued_input_bytes: &mut usize,
    stop_after_active: bool,
    context: &mut EofDrainContext<'_>,
) -> io::Result<()> {
    let active_requested_stop = match active_task {
        Some(task) => drain_control_command_after_eof(task, context).await?,
        None => context.shutdown.has_changed().unwrap_or(true),
    };
    let mut stop = stop_after_active || active_requested_stop;

    while !stop {
        if context.shutdown.has_changed().unwrap_or(true) {
            break;
        }
        let Some(line) = queued_lines.pop_front() else {
            break;
        };
        *queued_input_bytes = queued_input_bytes.saturating_sub(line.len());
        #[cfg(windows)]
        if line == CONTROL_STDIN_EOF_MARKER {
            break;
        }
        if line.is_empty() {
            break;
        }

        let commands = match context
            .handler
            .parse_control_commands(&line)
            .await
            .and_then(validate_control_command_arguments)
        {
            Ok(commands) => commands,
            // The transport has already received its terminal %exit, so a
            // queued parse error has nowhere to be reported. It behaves like
            // the live queue: this frame fails without suppressing later
            // complete frames.
            Err(_) => continue,
        };
        let Some(normal_request_guard) = context
            .handler
            .try_begin_normal_request(control_commands_require_drain(&commands))
        else {
            break;
        };
        let handler_for_command = Arc::clone(context.handler);
        let control_identity = context.control_identity;
        let eof_cancellation = ControlQueueEofCancellation::new(control_identity);
        eof_cancellation.cancel_for_eof();
        let task = tokio::spawn(async move {
            let _normal_request_guard = normal_request_guard;
            with_control_queue_eof_cancellation(
                eof_cancellation,
                handler_for_command.execute_control_commands_identity(
                    control_identity.requester_pid(),
                    control_identity.control_id(),
                    commands,
                ),
            )
            .await
        });
        stop = drain_control_command_after_eof(task, context).await?;
    }

    queued_lines.clear();
    *queued_input_bytes = 0;
    Ok(())
}

#[cfg(any(unix, windows))]
async fn drain_control_command_after_eof(
    mut task: JoinHandle<ControlCommandResult>,
    context: &mut EofDrainContext<'_>,
) -> io::Result<bool> {
    let mut exit_received = false;
    let result = loop {
        tokio::select! {
            biased;

            result = &mut task => break result,
            event = context.server_events.recv(), if context.events_open => {
                match event {
                    Some(ControlServerEvent::Exit(_)) => exit_received = true,
                    Some(_) => {}
                    None => context.events_open = false,
                }
            }
        }
    };
    let result = result
        .map_err(|error| io::Error::other(format!("control command task failed: {error}")))?;
    // The command result and its terminal Exit event can become ready in the
    // same scheduler turn. Explicitly drain events emitted before task
    // completion so a later queued frame cannot run after client exit.
    while context.events_open {
        match context.server_events.try_recv() {
            Ok(ControlServerEvent::Exit(_)) => exit_received = true,
            Ok(_) => {}
            Err(mpsc::error::TryRecvError::Empty) => break,
            Err(mpsc::error::TryRecvError::Disconnected) => {
                context.events_open = false;
            }
        }
    }
    if context.shutdown.has_changed().unwrap_or(true) {
        return Ok(true);
    }
    let shutdown_requested =
        result.server_shutdown_started || context.handler.request_shutdown_if_pending();
    if shutdown_requested {
        context.shutdown_handle.request_shutdown();
    }
    // A terminal action in the command can mark the client closing while the
    // event channel is full. In that case no Exit reaches this receiver, so
    // revalidate after the task joins rather than relying on the closing
    // snapshot taken before the active frame.
    let registration_closed = !context
        .handler
        .control_queue_identity_is_open(context.control_identity)
        .await;
    Ok(exit_received || shutdown_requested || registration_closed)
}

#[cfg(any(unix, windows))]
async fn handle_server_event(
    event: ControlServerEvent,
    context: &mut ServerEventContext<'_>,
    command_active: bool,
) -> io::Result<bool> {
    match event {
        ControlServerEvent::SessionChanged(next_session) => {
            if command_active {
                context.deferred.defer_session_change(next_session, None);
                return Ok(false);
            }
            *context.session_name = next_session;
            refresh_subscriptions(
                context.handler,
                context.control_identity,
                context.session_name.as_ref(),
                context.subscriptions,
                context.pane_event_tx.clone(),
                PaneSubscriptionStart::Oldest,
            )
            .await;
        }
        ControlServerEvent::SessionChangedAt {
            session_name: next_session,
            pane_sequences,
        } => {
            if command_active {
                context
                    .deferred
                    .defer_session_change(Some(next_session), Some(pane_sequences));
                return Ok(false);
            }
            *context.session_name = Some(next_session);
            refresh_subscriptions(
                context.handler,
                context.control_identity,
                context.session_name.as_ref(),
                context.subscriptions,
                context.pane_event_tx.clone(),
                PaneSubscriptionStart::Sequences(&pane_sequences),
            )
            .await;
        }
        ControlServerEvent::Refresh => {
            refresh_subscriptions(
                context.handler,
                context.control_identity,
                context.session_name.as_ref(),
                context.subscriptions,
                context.pane_event_tx.clone(),
                PaneSubscriptionStart::Oldest,
            )
            .await;
        }
        ControlServerEvent::Notification(line) => {
            if command_active || context.deferred.exit_reason.is_some() {
                context.deferred.defer_notification(line);
                return Ok(false);
            }
            if write_control_notification(line, context).await? {
                return Ok(true);
            }
        }
        ControlServerEvent::Exit(reason) => {
            if command_active || !context.deferred.notifications.is_empty() {
                context.deferred.exit_reason = Some(reason);
                return Ok(false);
            }
            context
                .output_queue
                .enqueue_line(format_exit_line(reason.as_deref()).into_bytes(), false);
            flush_output_queue(
                context.output_queue,
                context.write_half,
                *context.flags,
                context.paused_panes,
            )
            .await?;
            return Ok(true);
        }
    }

    *context.flags = context
        .handler
        .control_client_flags(context.requester_pid)
        .await
        .unwrap_or(*context.flags);
    Ok(false)
}

#[cfg(any(unix, windows))]
async fn write_control_notification(
    line: String,
    context: &mut ServerEventContext<'_>,
) -> io::Result<bool> {
    if drain_ready_pane_events(
        context.pane_event_rx,
        context.output_queue,
        context.paused_panes,
        *context.flags,
    )? {
        flush_output_queue(
            context.output_queue,
            context.write_half,
            *context.flags,
            context.paused_panes,
        )
        .await?;
        return Ok(true);
    }
    context
        .output_queue
        .enqueue_line(ensure_control_newline(line.into_bytes()), false);
    flush_output_queue(
        context.output_queue,
        context.write_half,
        *context.flags,
        context.paused_panes,
    )
    .await?;
    Ok(false)
}

#[cfg(any(unix, windows))]
async fn handle_control_command_response_event(
    event: ControlCommandResponseEvent,
    numbering: &mut ControlCommandNumbering,
    command: &mut ActiveControlCommand,
    response_frame: &mut ActiveControlResponseFrame,
    context: &mut ServerEventContext<'_>,
) -> io::Result<bool> {
    match event {
        ControlCommandResponseEvent::Notification(line) => {
            if !response_frame.open {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    "control response notification has no open owner guard",
                ));
            }
            write_control_notification(line, context).await
        }
        ControlCommandResponseEvent::FrameStarted { origin } => {
            if response_frame.open {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!(
                        "synchronous {origin:?} child started before its owner guard completed"
                    ),
                ));
            }
            command.timestamp = unix_epoch_seconds();
            command.command_number = numbering.next_synchronous_child_number();
            response_frame.open = true;
            response_frame.origin = Some(origin);
            context.output_queue.enqueue_line(
                format_guard_line(
                    ControlGuardKind::Begin,
                    command.timestamp,
                    command.command_number,
                    command.guard_flag,
                )
                .into_bytes(),
                false,
            );
            flush_output_queue(
                context.output_queue,
                context.write_half,
                *context.flags,
                context.paused_panes,
            )
            .await?;
            Ok(false)
        }
        ControlCommandResponseEvent::FrameCompleted { stdout, error } => {
            if !response_frame.open {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    "control response completed without an open owner guard",
                ));
            }
            if !stdout.is_empty() {
                context.output_queue.enqueue_stdout(stdout);
            }
            if drain_ready_pane_events(
                context.pane_event_rx,
                context.output_queue,
                context.paused_panes,
                *context.flags,
            )? {
                flush_output_queue(
                    context.output_queue,
                    context.write_half,
                    *context.flags,
                    context.paused_panes,
                )
                .await?;
                return Ok(true);
            }
            enqueue_control_frame_terminal(context.output_queue, command, error);
            response_frame.open = false;
            let _completed_origin = response_frame.origin.take();
            flush_output_queue(
                context.output_queue,
                context.write_half,
                *context.flags,
                context.paused_panes,
            )
            .await?;
            Ok(false)
        }
    }
}

#[cfg(any(unix, windows))]
fn enqueue_control_frame_terminal(
    output_queue: &mut ControlOutputQueue,
    command: &ActiveControlCommand,
    error: Option<RmuxError>,
) {
    let terminal = match error {
        Some(error) => {
            output_queue.enqueue_stdout(error.to_string().into_bytes());
            ControlGuardKind::Error
        }
        None => ControlGuardKind::End,
    };
    output_queue.enqueue_line(
        format_guard_line(
            terminal,
            command.timestamp,
            command.command_number,
            command.guard_flag,
        )
        .into_bytes(),
        false,
    );
}

#[cfg(any(unix, windows))]
async fn flush_deferred_server_events(context: &mut ServerEventContext<'_>) -> io::Result<bool> {
    while let Some(line) = context.deferred.pop_notification() {
        if handle_server_event(ControlServerEvent::Notification(line), context, false).await? {
            return Ok(true);
        }
    }

    if let Some(DeferredSessionChange {
        session_name,
        pane_sequences,
    }) = context.deferred.session_change.take()
    {
        let event = match (session_name, pane_sequences) {
            (Some(session_name), Some(pane_sequences)) => ControlServerEvent::SessionChangedAt {
                session_name,
                pane_sequences,
            },
            (next_session, None) => ControlServerEvent::SessionChanged(next_session),
            (None, Some(_)) => unreachable!("pane cursors require a control session"),
        };
        if handle_server_event(event, context, false).await? {
            return Ok(true);
        }
    }

    if let Some(reason) = context.deferred.exit_reason.take() {
        return handle_server_event(ControlServerEvent::Exit(reason), context, false).await;
    }

    Ok(false)
}

#[cfg(any(unix, windows))]
struct ServerEventContext<'a> {
    handler: &'a RequestHandler,
    control_identity: ControlClientIdentity,
    requester_pid: u32,
    session_name: &'a mut Option<SessionName>,
    subscriptions: &'a mut HashMap<u32, PaneSubscription>,
    pane_event_tx: mpsc::Sender<PaneEvent>,
    pane_event_rx: &'a mut mpsc::Receiver<PaneEvent>,
    output_queue: &'a mut ControlOutputQueue,
    write_half: &'a mut WriteHalf<LocalStream>,
    paused_panes: &'a mut HashSet<u32>,
    flags: &'a mut ControlClientFlags,
    deferred: &'a mut DeferredServerEvents,
}

#[derive(Debug, Default)]
#[cfg(any(unix, windows))]
struct DeferredServerEvents {
    notifications: VecDeque<String>,
    notification_bytes: usize,
    session_change: Option<DeferredSessionChange>,
    exit_reason: Option<Option<String>>,
}

#[derive(Debug)]
#[cfg(any(unix, windows))]
struct DeferredSessionChange {
    session_name: Option<SessionName>,
    pane_sequences: Option<Vec<(u32, u64)>>,
}

#[cfg(any(unix, windows))]
impl DeferredServerEvents {
    fn defer_notification(&mut self, line: String) {
        if self.exit_reason.is_some() {
            return;
        }
        let next_bytes = self.notification_bytes.saturating_add(line.len());
        if self.notifications.len() >= MAX_DEFERRED_CONTROL_NOTIFICATIONS
            || next_bytes > MAX_DEFERRED_CONTROL_NOTIFICATION_BYTES
        {
            self.notifications.clear();
            self.notification_bytes = 0;
            self.exit_reason = Some(Some("control notification queue exceeded".to_owned()));
            return;
        }
        self.notification_bytes = next_bytes;
        self.notifications.push_back(line);
    }

    fn pop_notification(&mut self) -> Option<String> {
        let line = self.notifications.pop_front()?;
        self.notification_bytes = self.notification_bytes.saturating_sub(line.len());
        Some(line)
    }

    fn defer_session_change(
        &mut self,
        next_session: Option<SessionName>,
        pane_sequences: Option<Vec<(u32, u64)>>,
    ) {
        if self.exit_reason.is_some() {
            return;
        }
        self.session_change = Some(DeferredSessionChange {
            session_name: next_session,
            pane_sequences,
        });
    }
}

#[derive(Debug)]
#[cfg(any(unix, windows))]
struct ActiveControlResponseFrame {
    open: bool,
    origin: Option<ControlQueueCommandOrigin>,
}

#[cfg(any(unix, windows))]
impl ActiveControlResponseFrame {
    const fn owner() -> Self {
        Self {
            open: true,
            origin: None,
        }
    }
}

#[derive(Debug)]
#[cfg(any(unix, windows))]
struct ActiveControlCommand {
    timestamp: i64,
    command_number: u64,
    guard_flag: u8,
    origin: ControlCommandOrigin,
    eof_cancellation: ControlQueueEofCancellation,
    task: Option<JoinHandle<ControlCommandResult>>,
}

#[cfg(any(unix, windows))]
impl Drop for ActiveControlCommand {
    fn drop(&mut self) {
        if let Some(task) = self.task.as_ref() {
            if !task.is_finished() {
                task.abort();
            }
        }
    }
}

#[cfg(any(unix, windows))]
fn extract_complete_control_lines(buffer: &mut Vec<u8>) -> Vec<String> {
    let mut lines = Vec::new();

    while let Some(position) = buffer.iter().position(|byte| *byte == b'\n') {
        let mut line = buffer.drain(..=position).collect::<Vec<_>>();
        if matches!(line.last(), Some(b'\n')) {
            let _ = line.pop();
        }
        if matches!(line.last(), Some(b'\r')) {
            let _ = line.pop();
        }
        lines.push(String::from_utf8_lossy(&line).into_owned());
    }

    lines
}

#[cfg(any(unix, windows))]
fn append_control_input(
    input_buffer: &mut Vec<u8>,
    queued_lines: &mut VecDeque<String>,
    queued_input_bytes: &mut usize,
    bytes: &[u8],
) -> io::Result<()> {
    input_buffer.extend_from_slice(bytes);
    let lines = extract_complete_control_lines(input_buffer);
    if input_buffer.len() > MAX_CONTROL_LINE_BYTES {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            format!("control input line exceeds {MAX_CONTROL_LINE_BYTES} bytes without a newline"),
        ));
    }
    for line in lines {
        if line.len() > MAX_CONTROL_LINE_BYTES {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!("control input line exceeds {MAX_CONTROL_LINE_BYTES} bytes"),
            ));
        }
        let next_line_count = queued_lines.len().saturating_add(1);
        let next_byte_count = queued_input_bytes.saturating_add(line.len());
        if next_line_count > MAX_QUEUED_CONTROL_LINES || next_byte_count > MAX_QUEUED_CONTROL_BYTES
        {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!(
                    "control input queue exceeds {MAX_QUEUED_CONTROL_LINES} lines or {MAX_QUEUED_CONTROL_BYTES} bytes"
                ),
            ));
        }
        *queued_input_bytes = next_byte_count;
        queued_lines.push_back(line);
    }
    Ok(())
}

#[cfg(windows)]
fn consume_control_eof_marker(
    input_buffer: &mut Vec<u8>,
    queued_lines: &mut VecDeque<String>,
    queued_input_bytes: &mut usize,
) -> bool {
    let Some(marker_index) = queued_lines.iter().position(|line| {
        line == CONTROL_STDIN_EOF_MARKER || line.ends_with(CONTROL_STDIN_EOF_MARKER)
    }) else {
        return false;
    };

    // The Windows client writes this private terminal marker immediately
    // before closing its named-pipe writer. Observe it even while a blocking
    // command is active; waiting for the normal command-dequeue path would
    // deadlock because wait-for cancellation itself depends on input_closed.
    queued_lines.truncate(marker_index);
    *queued_input_bytes = queued_lines.iter().map(String::len).sum();
    input_buffer.clear();
    true
}

#[cfg(any(unix, windows))]
fn unix_epoch_seconds() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs() as i64
}

#[cfg(all(test, any(unix, windows)))]
mod deferred_tests {
    use super::{
        DeferredServerEvents, MAX_DEFERRED_CONTROL_NOTIFICATIONS,
        MAX_DEFERRED_CONTROL_NOTIFICATION_BYTES,
    };

    #[test]
    fn deferred_control_notifications_are_bounded() {
        let mut deferred = DeferredServerEvents::default();

        for index in 0..MAX_DEFERRED_CONTROL_NOTIFICATIONS {
            deferred.defer_notification(format!("%message {index}"));
        }

        assert_eq!(
            deferred.notifications.len(),
            MAX_DEFERRED_CONTROL_NOTIFICATIONS
        );
        assert!(deferred.exit_reason.is_none());

        deferred.defer_notification("%message overflow".to_owned());

        assert!(deferred.notifications.is_empty());
        assert_eq!(
            deferred.exit_reason,
            Some(Some("control notification queue exceeded".to_owned()))
        );

        deferred.defer_notification("%message after-overflow".to_owned());
        assert!(deferred.notifications.is_empty());
    }

    #[test]
    fn deferred_control_notification_bytes_are_bounded_and_accounted_on_pop() {
        let mut deferred = DeferredServerEvents::default();
        let first = "x".repeat(MAX_DEFERRED_CONTROL_NOTIFICATION_BYTES / 2);
        let second = "y".repeat(MAX_DEFERRED_CONTROL_NOTIFICATION_BYTES / 2);
        deferred.defer_notification(first.clone());
        deferred.defer_notification(second);
        assert_eq!(
            deferred.notification_bytes,
            MAX_DEFERRED_CONTROL_NOTIFICATION_BYTES
        );

        assert_eq!(deferred.pop_notification(), Some(first));
        assert_eq!(
            deferred.notification_bytes,
            MAX_DEFERRED_CONTROL_NOTIFICATION_BYTES / 2
        );

        deferred.defer_notification("z".repeat(MAX_DEFERRED_CONTROL_NOTIFICATION_BYTES / 2 + 1));
        assert!(deferred.notifications.is_empty());
        assert_eq!(deferred.notification_bytes, 0);
        assert!(deferred.exit_reason.is_some());
    }
}

#[cfg(all(test, windows))]
mod windows_eof_marker_tests {
    use std::collections::VecDeque;

    use super::{
        append_control_input, arm_control_eof_transition, consume_control_eof_marker,
        wait_for_control_eof_transition, CONTROL_EOF_GRACE,
    };
    use rmux_proto::CONTROL_STDIN_EOF_MARKER;

    #[test]
    fn windows_eof_marker_discards_an_incomplete_command_prefix() {
        let mut input_buffer = Vec::new();
        let mut queued_lines = VecDeque::new();
        let mut queued_bytes = 0;
        let input = format!("display-message -p must-not-run{CONTROL_STDIN_EOF_MARKER}\n");
        append_control_input(
            &mut input_buffer,
            &mut queued_lines,
            &mut queued_bytes,
            input.as_bytes(),
        )
        .expect("private EOF marker input parses");

        assert!(consume_control_eof_marker(
            &mut input_buffer,
            &mut queued_lines,
            &mut queued_bytes,
        ));
        assert!(queued_lines.is_empty());
        assert_eq!(queued_bytes, 0);
        assert!(input_buffer.is_empty());
    }

    #[tokio::test]
    async fn windows_eof_marker_uses_the_global_persistent_deadline() {
        let mut input_buffer = Vec::new();
        let mut queued_lines = VecDeque::new();
        let mut queued_bytes = 0;
        append_control_input(
            &mut input_buffer,
            &mut queued_lines,
            &mut queued_bytes,
            format!("wait-for marker{CONTROL_STDIN_EOF_MARKER}\n").as_bytes(),
        )
        .expect("private EOF marker input parses");
        assert!(consume_control_eof_marker(
            &mut input_buffer,
            &mut queued_lines,
            &mut queued_bytes,
        ));

        let mut transition = None;
        arm_control_eof_transition(&mut transition);
        let initial_deadline = transition
            .as_ref()
            .expect("marker deadline is armed")
            .deadline();
        arm_control_eof_transition(&mut transition);
        assert_eq!(
            transition
                .as_ref()
                .expect("marker deadline stays armed")
                .deadline(),
            initial_deadline,
            "another post-marker frame must not extend the global budget"
        );
        assert!(
            tokio::time::timeout(
                std::time::Duration::from_millis(50),
                wait_for_control_eof_transition(&mut transition),
            )
            .await
            .is_err(),
            "the marker deadline leaves a bounded grace for fast output"
        );
        assert!(
            tokio::time::timeout(
                CONTROL_EOF_GRACE + std::time::Duration::from_millis(100),
                wait_for_control_eof_transition(&mut transition),
            )
            .await
            .is_ok(),
            "the marker deadline still expires within its global budget"
        );
    }
}

#[cfg(all(test, unix))]
#[path = "control/tests.rs"]
mod tests;