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
use super::*;

use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use std::time::Duration;

use rmux_core::command_parser::CommandParser;
use rmux_proto::{
    ControlMode, DetachClientRequest, KillSessionRequest, NewSessionRequest, NewWindowRequest,
    OptionName, Request, Response, ScopeSelector, SessionName, SetOptionMode, SetOptionRequest,
    SwitchClientRequest, TerminalSize, WindowTarget,
};
use tokio::sync::mpsc;

use crate::control::{ControlModeUpgrade, ControlServerEvent, CONTROL_SERVER_EVENT_CAPACITY};

const INITIAL_SIZE: TerminalSize = TerminalSize { cols: 80, rows: 24 };
const TARGET_SIZE: TerminalSize = TerminalSize { cols: 60, rows: 15 };
const CONTROL_SIZE: TerminalSize = TerminalSize {
    cols: 100,
    rows: 40,
};
const SOURCE_ATTACHED_SIZE: TerminalSize = TerminalSize { cols: 70, rows: 20 };
const TARGET_ATTACHED_SIZE: TerminalSize = TerminalSize { cols: 90, rows: 30 };
const CONTROL_NOTIFICATION_TIMEOUT: Duration = Duration::from_secs(5);
const CONTROL_NOTIFICATION_SETTLE: Duration = Duration::from_millis(250);
const CONTROL_NOTIFICATION_POLL: Duration = Duration::from_millis(25);

const fn attached_content_size(terminal_size: TerminalSize) -> TerminalSize {
    TerminalSize {
        cols: terminal_size.cols,
        rows: terminal_size.rows.saturating_sub(1),
    }
}

#[tokio::test]
async fn refresh_client_control_size_echoes_each_window_once_like_tmux37() {
    // Frozen tmux 3.7b oracle, measured 2026-07-26 with two windows and one
    // command per flush:
    //
    //   policy  declaration sequence                  layouts per command
    //   latest  100x40, 100x40, 101x41, 101x41        @0, @1
    //   manual  100x40, 100x40, 101x41, 101x41        @0, @1
    //
    // Under manual, both windows remain 80x24 throughout. Every observer sees
    // one layout per window in window order, with no duplicate for the window
    // whose geometry was really applied under latest.
    for (policy_index, policy) in ["latest", "manual"].into_iter().enumerate() {
        let handler = RequestHandler::new();
        let session = session_name(&format!("control-refresh-echo-{policy}"));
        create_session(&handler, session.clone(), INITIAL_SIZE).await;
        let created = handler
            .handle(Request::NewWindow(Box::new(NewWindowRequest {
                target: session.clone(),
                name: Some("second".to_owned()),
                detached: true,
                start_directory: None,
                environment: None,
                command: None,
                process_command: None,
                target_window_index: Some(1),
                insert_at_target: false,
            })))
            .await;
        assert!(matches!(created, Response::NewWindow(_)), "{created:?}");
        for window_index in [0, 1] {
            set_window_size_policy_for_window(&handler, &session, window_index, policy).await;
        }

        let control_pid = 92_180 + policy_index as u32 * 2;
        let observer_pid = control_pid + 1;
        let (_control_id, mut control_events) =
            register_control_client_with_id(&handler, control_pid, &session).await;
        let (_observer_id, mut observer_events) =
            register_control_client_with_id(&handler, observer_pid, &session).await;
        let _ = settle_control_notifications(&mut control_events).await;
        let _ = settle_control_notifications(&mut observer_events).await;
        let expected_window_ids = window_ids(&handler, &session).await;

        for declared_size in [
            CONTROL_SIZE,
            CONTROL_SIZE,
            TerminalSize {
                cols: 101,
                rows: 41,
            },
            TerminalSize {
                cols: 101,
                rows: 41,
            },
        ] {
            let response = handler
                .handle(Request::RefreshClient(Box::new(
                    refresh_client_size_request(control_pid, declared_size),
                )))
                .await;
            assert!(
                matches!(response, Response::RefreshClient(_)),
                "{response:?}"
            );

            for (label, events) in [
                ("issuing client", &mut control_events),
                ("observing client", &mut observer_events),
            ] {
                let lines = settle_control_notifications(events).await;
                let actual_window_ids = lines
                    .iter()
                    .filter_map(|line| layout_change_window_id(line))
                    .collect::<Vec<_>>();
                assert_eq!(
                    actual_window_ids, expected_window_ids,
                    "{policy} {declared_size:?}: {label} must receive exactly one layout per window \
                     in oracle order; got {lines:?}"
                );
            }
            if policy == "manual" {
                assert_eq!(
                    session_window_sizes(&handler, &session).await,
                    vec![INITIAL_SIZE, INITIAL_SIZE],
                    "manual must record the client size without applying it"
                );
            }
        }
    }
}

#[tokio::test]
async fn refresh_client_control_size_respects_window_size_policy_like_tmux37() {
    // Frozen tmux 3.7b oracle, 2026-07-25: with a 70x20 attached client,
    // refreshing a control client to 100x40 selects the control geometry for
    // latest/largest, the attached geometry for smallest, and no size for
    // manual. The oracle's visible window rows are one less for the ordinary
    // client because its status line consumes a row.
    for (index, (policy, expected_size)) in [
        ("latest", CONTROL_SIZE),
        ("largest", CONTROL_SIZE),
        ("smallest", attached_content_size(SOURCE_ATTACHED_SIZE)),
        ("manual", INITIAL_SIZE),
    ]
    .into_iter()
    .enumerate()
    {
        let handler = RequestHandler::new();
        let session = session_name(&format!("control-refresh-{policy}"));
        create_session(&handler, session.clone(), INITIAL_SIZE).await;
        set_window_size_policy(&handler, &session, policy).await;
        let (_attach_id, _attach_events) = register_attached_client(
            &handler,
            92_200 + index as u32,
            &session,
            SOURCE_ATTACHED_SIZE,
        )
        .await;
        let requester_pid = std::process::id();
        let (_control_id, _events) =
            register_control_client_with_id(&handler, requester_pid, &session).await;

        let response = handler
            .handle(Request::RefreshClient(Box::new(
                refresh_client_size_request(requester_pid, CONTROL_SIZE),
            )))
            .await;

        assert!(
            matches!(response, Response::RefreshClient(_)),
            "{response:?}"
        );
        assert_eq!(
            control_client_size(&handler, requester_pid).await,
            CONTROL_SIZE
        );
        assert_eq!(
            session_size(&handler, &session).await,
            expected_size,
            "{policy}"
        );
    }
}

#[tokio::test]
async fn older_control_resize_keeps_the_latest_client_order_like_tmux37() {
    // Frozen tmux 3.7b oracle, 2026-07-25: `latest` is client arrival
    // order. Resizing an older control client updates its reported geometry
    // without making it the newest window-size candidate.
    let handler = RequestHandler::new();
    let session = session_name("control-latest-resize-order");
    create_session(&handler, session.clone(), INITIAL_SIZE).await;
    set_window_size_policy(&handler, &session, "latest").await;
    let older_pid = 92_280;
    let latest_pid = older_pid + 1;
    let (_older_id, _older_events) =
        register_control_client_with_id(&handler, older_pid, &session).await;
    let older_size = TerminalSize {
        cols: 100,
        rows: 40,
    };
    let response = handler
        .handle(Request::RefreshClient(Box::new(
            refresh_client_size_request(older_pid, older_size),
        )))
        .await;
    assert!(
        matches!(response, Response::RefreshClient(_)),
        "{response:?}"
    );

    let (_latest_id, _latest_events) =
        register_control_client_with_id(&handler, latest_pid, &session).await;
    let latest_size = TerminalSize { cols: 60, rows: 20 };
    let response = handler
        .handle(Request::RefreshClient(Box::new(
            refresh_client_size_request(latest_pid, latest_size),
        )))
        .await;
    assert!(
        matches!(response, Response::RefreshClient(_)),
        "{response:?}"
    );
    assert_eq!(session_size(&handler, &session).await, latest_size);

    let resized_older = TerminalSize {
        cols: 101,
        rows: 41,
    };
    let response = handler
        .handle(Request::RefreshClient(Box::new(
            refresh_client_size_request(older_pid, resized_older),
        )))
        .await;
    assert!(
        matches!(response, Response::RefreshClient(_)),
        "{response:?}"
    );
    assert_eq!(
        control_client_size(&handler, older_pid).await,
        resized_older,
        "the older control still records its new geometry"
    );
    assert_eq!(
        session_size(&handler, &session).await,
        latest_size,
        "resizing an older control must not steal latest-client ordering"
    );
}

#[tokio::test]
async fn switch_control_client_reapplies_reported_size_like_tmux37() {
    // Frozen tmux 3.7b oracle, 2026-07-25: after refresh-client -C 100x40,
    // switch-client chooses that geometry for latest/largest, the resident
    // 90x30 attached geometry for smallest, and no resize for manual.
    let handler = RequestHandler::new();
    let source = session_name("control-switch-source");
    create_session(&handler, source.clone(), INITIAL_SIZE).await;
    let requester_pid = std::process::id();
    let (_control_id, _events) =
        register_control_client_with_id(&handler, requester_pid, &source).await;
    let refreshed = handler
        .handle(Request::RefreshClient(Box::new(
            refresh_client_size_request(requester_pid, CONTROL_SIZE),
        )))
        .await;
    assert!(
        matches!(refreshed, Response::RefreshClient(_)),
        "{refreshed:?}"
    );

    for (index, (policy, expected_size)) in [
        ("latest", CONTROL_SIZE),
        ("largest", CONTROL_SIZE),
        ("smallest", attached_content_size(TARGET_ATTACHED_SIZE)),
        ("manual", TARGET_SIZE),
    ]
    .into_iter()
    .enumerate()
    {
        let target = session_name(&format!("control-switch-{policy}"));
        create_session(&handler, target.clone(), TARGET_SIZE).await;
        set_window_size_policy(&handler, &target, policy).await;
        let (_attach_id, _attach_events) = register_attached_client(
            &handler,
            92_300 + index as u32,
            &target,
            TARGET_ATTACHED_SIZE,
        )
        .await;

        let response = handler
            .handle(Request::SwitchClient(SwitchClientRequest {
                target: target.clone(),
            }))
            .await;

        assert!(
            matches!(response, Response::SwitchClient(_)),
            "{response:?}"
        );
        assert_eq!(
            session_size(&handler, &target).await,
            expected_size,
            "{policy}"
        );
    }
}

#[tokio::test]
async fn new_session_attach_existing_reconciles_control_geometry_like_tmux37() {
    let handler = RequestHandler::new();
    let source = session_name("control-new-session-attach-source");
    let target = session_name("control-new-session-attach-target");
    create_session(&handler, source.clone(), INITIAL_SIZE).await;
    create_session(&handler, target.clone(), TARGET_SIZE).await;
    set_window_size_policy(&handler, &source, "largest").await;
    set_window_size_policy(&handler, &target, "largest").await;

    let switching_pid = 92_350;
    let surviving_pid = switching_pid + 1;
    let (switching_id, mut switching_events) =
        register_control_client_with_id(&handler, switching_pid, &source).await;
    let (_surviving_id, mut surviving_events) =
        register_control_client_with_id(&handler, surviving_pid, &source).await;
    for (pid, size) in [
        (switching_pid, CONTROL_SIZE),
        (surviving_pid, SOURCE_ATTACHED_SIZE),
    ] {
        let response = handler
            .handle(Request::RefreshClient(Box::new(
                refresh_client_size_request(pid, size),
            )))
            .await;
        assert!(
            matches!(response, Response::RefreshClient(_)),
            "{response:?}"
        );
    }
    assert_eq!(session_size(&handler, &source).await, CONTROL_SIZE);
    let source_layout_prefix = format!(
        "%layout-change @{} ",
        active_window_id(&handler, &source).await
    );
    settle_control_notifications(&mut switching_events).await;
    settle_control_notifications(&mut surviving_events).await;

    let commands = CommandParser::new()
        .parse(&format!("new-session -A -s {target}"))
        .expect("new-session -A parses");
    let result = handler
        .execute_control_commands_identity(switching_pid, switching_id, commands)
        .await;

    assert!(result.error.is_none(), "{:?}", result.error);
    assert_eq!(
        session_size(&handler, &source).await,
        SOURCE_ATTACHED_SIZE,
        "the source must fall back to its surviving control client"
    );
    assert_eq!(
        session_size(&handler, &target).await,
        CONTROL_SIZE,
        "the destination must adopt the arriving control client's size"
    );
    let lines =
        collect_control_notifications_through(&mut surviving_events, &source_layout_prefix).await;
    let changed = lines
        .iter()
        .position(|line| line.starts_with("%client-session-changed "))
        .expect("the surviving client is told that the other client moved");
    let resized = lines
        .iter()
        .position(|line| line.starts_with(&source_layout_prefix))
        .expect("the surviving client is told that the source resized");
    assert!(
        changed < resized,
        "tmux 3.7b reports the client move before its source resize: {lines:?}"
    );
}

#[tokio::test]
async fn control_clients_share_largest_and_smallest_size_candidates_like_tmux37() {
    for (index, (policy, first_size, second_size, expected_size)) in [
        ("largest", CONTROL_SIZE, TARGET_SIZE, CONTROL_SIZE),
        ("smallest", TARGET_SIZE, CONTROL_SIZE, TARGET_SIZE),
    ]
    .into_iter()
    .enumerate()
    {
        let handler = RequestHandler::new();
        let session = session_name(&format!("control-multi-{policy}"));
        create_session(&handler, session.clone(), INITIAL_SIZE).await;
        set_window_size_policy(&handler, &session, policy).await;
        let first_pid = 92_400 + index as u32 * 2;
        let second_pid = first_pid + 1;
        let (_first_id, _first_events) =
            register_control_client_with_id(&handler, first_pid, &session).await;
        let (_second_id, _second_events) =
            register_control_client_with_id(&handler, second_pid, &session).await;

        for (pid, size) in [(first_pid, first_size), (second_pid, second_size)] {
            let response = handler
                .handle(Request::RefreshClient(Box::new(
                    refresh_client_size_request(pid, size),
                )))
                .await;
            assert!(
                matches!(response, Response::RefreshClient(_)),
                "{response:?}"
            );
        }

        assert_eq!(
            session_size(&handler, &session).await,
            expected_size,
            "{policy}"
        );
    }
}

#[tokio::test]
async fn undeclared_control_client_never_shrinks_an_attached_session_like_tmux37() {
    // tmux 3.7b oracle, measured 2026-07-25 with a live 200x50 PTY client on a
    // 200x50 session, then `tmux -C attach -t main` and no `refresh-client -C`:
    //
    //   window-size   before   after
    //   latest        200x49   200x49
    //   largest       200x49   200x49
    //   smallest      200x49   200x49
    //   manual        200x50   200x50
    //
    // `ignore_client_size()` skips a CLIENT_CONTROL client that has no
    // CLIENT_SIZECHANGED, so the 80x24 placeholder a control client starts with
    // is not a size candidate. rmux used to hand it to the policy and crushed
    // the session to the placeholder under latest and smallest.
    // Probe: .rmux-audit/control-attach-8023/probe_ctl_attach_shrink.py
    for (index, policy) in ["latest", "largest", "smallest", "manual"]
        .into_iter()
        .enumerate()
    {
        let handler = RequestHandler::new();
        let session = session_name(&format!("control-undeclared-attached-{policy}"));
        create_session(&handler, session.clone(), INITIAL_SIZE).await;
        set_window_size_policy(&handler, &session, policy).await;
        let attach_pid = 92_700 + index as u32 * 2;
        let control_pid = attach_pid + 1;
        let (_attach_id, _attach_events) =
            register_attached_client(&handler, attach_pid, &session, CONTROL_SIZE).await;
        handler
            .reconcile_attached_session_size_and_emit(&session)
            .await
            .expect("the ordinary client owns the session geometry");
        let expected_size = if policy == "manual" {
            INITIAL_SIZE
        } else {
            attached_content_size(CONTROL_SIZE)
        };
        assert_eq!(
            session_size(&handler, &session).await,
            expected_size,
            "{policy} before the control client arrives"
        );

        let (_control_id, _control_events) =
            register_control_client_with_id(&handler, control_pid, &session).await;
        handler
            .reconcile_attached_session_size_and_emit(&session)
            .await
            .expect("a control arrival reconciles the session geometry");

        assert_eq!(
            session_size(&handler, &session).await,
            expected_size,
            "{policy}: a control client that never ran refresh-client -C must not resize"
        );
    }
}

#[tokio::test]
async fn undeclared_control_client_alone_never_resizes_the_session_like_tmux37() {
    // tmux 3.7b oracle, measured 2026-07-25: a 200x50 session with no other
    // client at all keeps 200x50 under every `window-size` value when a control
    // client attaches without declaring a size. With no ordinary client to
    // outvote it the placeholder also won `largest`, so this cell is the one
    // that pins the rule for every automatic policy.
    // Probe: .rmux-audit/control-attach-8023/probe_ctl_only_client.py
    for (index, policy) in ["latest", "largest", "smallest", "manual"]
        .into_iter()
        .enumerate()
    {
        let handler = RequestHandler::new();
        let session = session_name(&format!("control-undeclared-alone-{policy}"));
        create_session(&handler, session.clone(), CONTROL_SIZE).await;
        set_window_size_policy(&handler, &session, policy).await;
        let control_pid = 92_720 + index as u32;
        let (_control_id, _control_events) =
            register_control_client_with_id(&handler, control_pid, &session).await;
        handler
            .reconcile_attached_session_size_and_emit(&session)
            .await
            .expect("a control arrival reconciles the session geometry");

        assert_eq!(
            session_size(&handler, &session).await,
            CONTROL_SIZE,
            "{policy}: the session keeps its own geometry, the control client owns none"
        );
    }
}

#[tokio::test]
async fn undeclared_control_client_switch_never_resizes_the_target_like_tmux37() {
    // The same rule on the switch-client path, which feeds the reporting
    // client's own size straight into the policy instead of going through the
    // candidate list. tmux 3.7b, 2026-07-25: a control client that never ran
    // `refresh-client -C` leaves the destination session's geometry alone.
    for (index, policy) in ["latest", "largest", "smallest", "manual"]
        .into_iter()
        .enumerate()
    {
        let handler = RequestHandler::new();
        let source = session_name(&format!("control-undeclared-switch-source-{policy}"));
        create_session(&handler, source.clone(), INITIAL_SIZE).await;
        let (_control_id, _control_events) =
            register_control_client_with_id(&handler, std::process::id(), &source).await;

        let target = session_name(&format!("control-undeclared-switch-target-{policy}"));
        create_session(&handler, target.clone(), INITIAL_SIZE).await;
        set_window_size_policy(&handler, &target, policy).await;
        let (_attach_id, _attach_events) =
            register_attached_client(&handler, 92_740 + index as u32, &target, CONTROL_SIZE).await;
        handler
            .reconcile_attached_session_size_and_emit(&target)
            .await
            .expect("the ordinary client owns the destination geometry");
        let expected_size = if policy == "manual" {
            INITIAL_SIZE
        } else {
            attached_content_size(CONTROL_SIZE)
        };

        let response = handler
            .handle(Request::SwitchClient(SwitchClientRequest {
                target: target.clone(),
            }))
            .await;
        assert!(
            matches!(response, Response::SwitchClient(_)),
            "{response:?}"
        );

        assert_eq!(
            session_size(&handler, &target).await,
            expected_size,
            "{policy}: switching an undeclared control client must not resize the target"
        );
    }
}

#[tokio::test]
async fn switching_control_client_reconciles_the_source_session_geometry() {
    let handler = RequestHandler::new();
    let source = session_name("control-switch-reconcile-source");
    let target = session_name("control-switch-reconcile-target");
    create_session(&handler, source.clone(), INITIAL_SIZE).await;
    create_session(&handler, target.clone(), TARGET_SIZE).await;
    set_window_size_policy(&handler, &source, "largest").await;
    set_window_size_policy(&handler, &target, "largest").await;

    let switching_pid = std::process::id();
    let surviving_pid = switching_pid.saturating_add(1);
    let switching_size = TerminalSize {
        cols: 101,
        rows: 41,
    };
    let surviving_size = TerminalSize { cols: 60, rows: 20 };
    let (_switching_id, _switching_events) =
        register_control_client_with_id(&handler, switching_pid, &source).await;
    let (_surviving_id, _surviving_events) =
        register_control_client_with_id(&handler, surviving_pid, &source).await;

    for (pid, size) in [
        (switching_pid, switching_size),
        (surviving_pid, surviving_size),
    ] {
        let response = handler
            .handle(Request::RefreshClient(Box::new(
                refresh_client_size_request(pid, size),
            )))
            .await;
        assert!(
            matches!(response, Response::RefreshClient(_)),
            "{response:?}"
        );
    }
    assert_eq!(session_size(&handler, &source).await, switching_size);

    let response = handler
        .handle(Request::SwitchClient(SwitchClientRequest {
            target: target.clone(),
        }))
        .await;

    assert!(
        matches!(response, Response::SwitchClient(_)),
        "{response:?}"
    );
    assert_eq!(session_size(&handler, &source).await, surviving_size);
    assert_eq!(session_size(&handler, &target).await, switching_size);
}

#[tokio::test]
async fn switching_control_client_notifies_the_source_session_layout_change_like_tmux37() {
    // Frozen tmux 3.7b oracle, measured 2026-07-25 with two control clients on
    // `source` (101x41 and 60x20, window-size largest). After the 101x41 client
    // runs `switch-client -t target`, the surviving 60x20 control client of the
    // source session receives, in this order:
    //     %client-session-changed client-71338 $1 target
    //     %layout-change @0 a1dd,60x20,0,0,0 a1dd,60x20,0,0,0 *
    // and the switched client receives `%session-changed $1 target` before its
    // own `%layout-change @1 aefe,101x41,0,0,1 ...`. The switched client, now
    // scoped to `target`, is never told about the source window.
    let handler = RequestHandler::new();
    let source = session_name("control-switch-notify-source");
    let target = session_name("control-switch-notify-target");
    create_session(&handler, source.clone(), INITIAL_SIZE).await;
    create_session(&handler, target.clone(), TARGET_SIZE).await;
    set_window_size_policy(&handler, &source, "largest").await;
    set_window_size_policy(&handler, &target, "largest").await;

    let switching_pid = std::process::id();
    let surviving_pid = switching_pid.saturating_add(1);
    let switching_size = TerminalSize {
        cols: 101,
        rows: 41,
    };
    let surviving_size = TerminalSize { cols: 60, rows: 20 };
    let (_switching_id, mut switching_events) =
        register_control_client_with_id(&handler, switching_pid, &source).await;
    let (_surviving_id, mut surviving_events) =
        register_control_client_with_id(&handler, surviving_pid, &source).await;

    for (pid, size) in [
        (switching_pid, switching_size),
        (surviving_pid, surviving_size),
    ] {
        let response = handler
            .handle(Request::RefreshClient(Box::new(
                refresh_client_size_request(pid, size),
            )))
            .await;
        assert!(
            matches!(response, Response::RefreshClient(_)),
            "{response:?}"
        );
    }
    assert_eq!(session_size(&handler, &source).await, switching_size);
    let source_window_id = active_window_id(&handler, &source).await;
    let source_layout_prefix = format!("%layout-change @{source_window_id} ");
    // The setup resizes publish asynchronously; wait for the streams to go
    // quiet so nothing from them is mistaken for a post-switch notification.
    settle_control_notifications(&mut switching_events).await;
    settle_control_notifications(&mut surviving_events).await;

    let response = handler
        .handle(Request::SwitchClient(SwitchClientRequest {
            target: target.clone(),
        }))
        .await;

    assert!(
        matches!(response, Response::SwitchClient(_)),
        "{response:?}"
    );
    assert_eq!(session_size(&handler, &source).await, surviving_size);

    let surviving_lines =
        collect_control_notifications_through(&mut surviving_events, &source_layout_prefix).await;
    let layout_index = surviving_lines
        .iter()
        .position(|line| line.starts_with(&source_layout_prefix))
        .expect("the surviving control client must be told the source window shrank");
    assert_eq!(
        layout_change_geometry(&surviving_lines[layout_index]).as_deref(),
        Some("60x20"),
        "{:?}",
        surviving_lines[layout_index]
    );
    let session_changed_index = surviving_lines
        .iter()
        .position(|line| line.starts_with("%client-session-changed "))
        .expect("the surviving control client must be told the other client moved away");
    assert!(
        session_changed_index < layout_index,
        "tmux 3.7b reports the client move before the layout it causes: {surviving_lines:?}"
    );

    let target_window_id = active_window_id(&handler, &target).await;
    let target_layout_prefix = format!("%layout-change @{target_window_id} ");
    let switching_lines =
        collect_control_notifications_through(&mut switching_events, &target_layout_prefix).await;
    assert!(
        !switching_lines
            .iter()
            .any(|line| line.starts_with(&source_layout_prefix)),
        "the switched client left the source session and must not be told about its window: \
         {switching_lines:?}"
    );
    let target_layout_index = switching_lines
        .iter()
        .position(|line| line.starts_with(&target_layout_prefix))
        .expect("the switched client must be told its new window's layout");
    let own_session_changed_index = switching_lines
        .iter()
        .position(|line| line.starts_with("%session-changed "))
        .expect("the switched client must be told it changed session");
    assert!(
        own_session_changed_index < target_layout_index,
        "tmux 3.7b reports %session-changed before the switched client's own layout: \
         {switching_lines:?}"
    );
}

#[tokio::test]
async fn switching_attached_client_notifies_the_source_session_layout_change_like_tmux37() {
    // Frozen tmux 3.7b oracle, measured 2026-07-25 on a source session holding
    // a 101x41 PTY-attached client and a 60x20 control client, `window-size
    // largest`. After the PTY client runs `switch-client -t target` the source
    // window really shrinks to 60x20 and the surviving control client receives,
    // in this order:
    //     %client-session-changed /dev/ttys007 $1 target
    //     %layout-change @0 a1dd,60x20,0,0,0 a1dd,60x20,0,0,0 *
    let handler = RequestHandler::new();
    let source = session_name("attach-switch-notify-source");
    let target = session_name("attach-switch-notify-target");
    create_session(&handler, source.clone(), INITIAL_SIZE).await;
    create_session(&handler, target.clone(), TARGET_SIZE).await;
    set_window_size_policy(&handler, &source, "largest").await;
    set_window_size_policy(&handler, &target, "largest").await;

    let switching_pid = std::process::id();
    let surviving_pid = switching_pid.saturating_add(1);
    let switching_size = TerminalSize {
        cols: 101,
        rows: 41,
    };
    let surviving_size = TerminalSize { cols: 60, rows: 20 };
    let (_attach_id, _attach_events) =
        register_attached_client(&handler, switching_pid, &source, switching_size).await;
    let (_surviving_id, mut surviving_events) =
        register_control_client_with_id(&handler, surviving_pid, &source).await;
    let response = handler
        .handle(Request::RefreshClient(Box::new(
            refresh_client_size_request(surviving_pid, surviving_size),
        )))
        .await;
    assert!(
        matches!(response, Response::RefreshClient(_)),
        "{response:?}"
    );
    assert_eq!(
        session_size(&handler, &source).await,
        attached_content_size(switching_size)
    );
    let source_window_id = active_window_id(&handler, &source).await;
    let source_layout_prefix = format!("%layout-change @{source_window_id} ");
    settle_control_notifications(&mut surviving_events).await;

    let response = handler
        .handle(Request::SwitchClient(SwitchClientRequest {
            target: target.clone(),
        }))
        .await;

    assert!(
        matches!(response, Response::SwitchClient(_)),
        "{response:?}"
    );
    assert_eq!(
        session_size(&handler, &source).await,
        surviving_size,
        "the source session must fall back to its surviving control client's geometry"
    );

    let lines =
        collect_control_notifications_through(&mut surviving_events, &source_layout_prefix).await;
    let layout_index = lines
        .iter()
        .position(|line| line.starts_with(&source_layout_prefix))
        .expect("the surviving control client must be told the source window shrank");
    assert_eq!(
        layout_change_geometry(&lines[layout_index]).as_deref(),
        Some("60x20"),
        "{:?}",
        lines[layout_index]
    );
    let session_changed_index = lines
        .iter()
        .position(|line| line.starts_with("%client-session-changed "))
        .expect("the surviving control client must be told the other client moved away");
    assert!(
        session_changed_index < layout_index,
        "tmux 3.7b reports the client move before the layout it causes: {lines:?}"
    );
}

/// Runs the destination half of an attached `switch-client`: the switching
/// client is the only one that changes session, and the control client that was
/// already sitting on the destination watches its window grow.
///
/// Frozen tmux 3.7b oracle, measured 2026-07-25
/// (`.rmux-audit/oracle/scenario_switch_destination.py` plus the status matrix):
/// with a 101x41 PTY client on `source`, a 60x20 control client on `target`,
/// default one-line status and `window-size largest`, after
/// `switch-client -c <tty> -t target` the destination window grows
/// 60x20 -> 101x40 and the destination control client receives
///     %client-session-changed /dev/ttys011 $1 target
///     %layout-change @1 aefe,101x40,0,0,1 aefe,101x40,0,0,1 *
/// in that order.
async fn assert_switch_notifies_the_destination_layout_change(
    handler: &RequestHandler,
    source: &SessionName,
    target: &SessionName,
    switch: impl AsyncFnOnce(&RequestHandler) -> Response,
) {
    set_window_size_policy(handler, source, "largest").await;
    set_window_size_policy(handler, target, "largest").await;

    let switching_pid = std::process::id();
    let destination_pid = switching_pid.saturating_add(3);
    let switching_size = TerminalSize {
        cols: 101,
        rows: 41,
    };
    let destination_size = TerminalSize { cols: 60, rows: 20 };
    let (_attach_id, _attach_events) =
        register_attached_client(handler, switching_pid, source, switching_size).await;
    let (_destination_id, mut destination_events) =
        register_control_client_with_id(handler, destination_pid, target).await;
    let response = handler
        .handle(Request::RefreshClient(Box::new(
            refresh_client_size_request(destination_pid, destination_size),
        )))
        .await;
    assert!(
        matches!(response, Response::RefreshClient(_)),
        "{response:?}"
    );
    assert_eq!(session_size(handler, target).await, destination_size);
    let target_window_id = active_window_id(handler, target).await;
    let target_layout_prefix = format!("%layout-change @{target_window_id} ");
    settle_control_notifications(&mut destination_events).await;

    let response = switch(handler).await;
    assert!(
        !matches!(response, Response::Error(_)),
        "the switch must succeed: {response:?}"
    );
    assert_eq!(
        session_size(handler, target).await,
        attached_content_size(switching_size),
        "the destination window must grow to the arriving client's geometry"
    );

    let lines =
        collect_control_notifications_through(&mut destination_events, &target_layout_prefix).await;
    let layout_index = lines
        .iter()
        .position(|line| line.starts_with(&target_layout_prefix))
        .expect("the destination control client must be told its window grew");
    assert_eq!(
        layout_change_geometry(&lines[layout_index]).as_deref(),
        Some("101x40"),
        "{:?}",
        lines[layout_index]
    );
    let session_changed_index = lines
        .iter()
        .position(|line| line.starts_with("%client-session-changed "))
        .expect("the destination control client must be told the client arrived");
    assert_eq!(
        lines
            .iter()
            .filter(|line| line.starts_with("%client-session-changed "))
            .count(),
        1,
        "the shared attach-session/switch-client commit must publish once: {lines:?}"
    );
    assert!(
        session_changed_index < layout_index,
        "tmux 3.7b reports the client move before the layout it causes: {lines:?}"
    );
}

#[tokio::test]
async fn switching_attached_client_notifies_the_destination_session_layout_change_like_tmux37() {
    let handler = RequestHandler::new();
    let source = session_name("attach-switch-dest-source");
    let target = session_name("attach-switch-dest-target");
    create_session(&handler, source.clone(), INITIAL_SIZE).await;
    create_session(&handler, target.clone(), TARGET_SIZE).await;
    let switch_target = target.clone();
    assert_switch_notifies_the_destination_layout_change(
        &handler,
        &source,
        &target,
        async |handler| {
            handler
                .handle(Request::SwitchClient(SwitchClientRequest {
                    target: switch_target,
                }))
                .await
        },
    )
    .await;
}

#[tokio::test]
async fn attach_session_from_an_attached_client_notifies_the_destination_layout_change_like_tmux37()
{
    // `attach-session` issued by an already-attached client re-enters the same
    // attached switch arm, so it owes the destination the same notification.
    let handler = RequestHandler::new();
    let source = session_name("attach-reattach-dest-source");
    let target = session_name("attach-reattach-dest-target");
    create_session(&handler, source.clone(), INITIAL_SIZE).await;
    create_session(&handler, target.clone(), TARGET_SIZE).await;
    let attach_target = target.clone();
    assert_switch_notifies_the_destination_layout_change(
        &handler,
        &source,
        &target,
        async |handler| {
            handler
                .handle(Request::AttachSession(rmux_proto::AttachSessionRequest {
                    target: attach_target,
                }))
                .await
        },
    )
    .await;
}

#[tokio::test]
async fn attaching_client_notifies_the_destination_session_layout_change_like_tmux37() {
    // Frozen tmux 3.7b oracle, measured 2026-07-25
    // (`.rmux-audit/oracle/scenario_attach_destination.py` plus the status
    // matrix): a 60x20 control client already on `target`, default one-line
    // status and `window-size largest`, watches a brand-new 101x41 PTY client
    // attach. The window grows 60x20 -> 101x40 and the control client receives
    // `%client-session-changed /dev/pts/19 $0 target` immediately before
    // `%layout-change @0 aefd,101x40,0,0,0 ...`.
    let handler = RequestHandler::new();
    let target = session_name("attach-arrival-dest");
    create_session(&handler, target.clone(), TARGET_SIZE).await;
    set_window_size_policy(&handler, &target, "largest").await;

    let control_pid = std::process::id().saturating_add(5);
    let control_size = TerminalSize { cols: 60, rows: 20 };
    let arriving_size = TerminalSize {
        cols: 101,
        rows: 41,
    };
    let (_control_id, mut control_events) =
        register_control_client_with_id(&handler, control_pid, &target).await;
    let response = handler
        .handle(Request::RefreshClient(Box::new(
            refresh_client_size_request(control_pid, control_size),
        )))
        .await;
    assert!(
        matches!(response, Response::RefreshClient(_)),
        "{response:?}"
    );
    assert_eq!(session_size(&handler, &target).await, control_size);
    let target_window_id = active_window_id(&handler, &target).await;
    let target_layout_prefix = format!("%layout-change @{target_window_id} ");
    settle_control_notifications(&mut control_events).await;

    let response = handler
        .handle(Request::AttachSessionExt2(Box::new(
            rmux_proto::request::AttachSessionExt2Request {
                target: Some(target.clone()),
                target_spec: None,
                detach_other_clients: false,
                kill_other_clients: false,
                read_only: false,
                skip_environment_update: true,
                flags: None,
                working_directory: None,
                client_terminal: rmux_proto::ClientTerminalContext::default(),
                client_size: Some(arriving_size),
            },
        )))
        .await;
    assert!(
        matches!(response, Response::AttachSession(_)),
        "{response:?}"
    );
    assert_eq!(
        session_size(&handler, &target).await,
        attached_content_size(arriving_size),
        "the attached window must grow to the arriving client's geometry"
    );

    let lines =
        collect_control_notifications_through(&mut control_events, &target_layout_prefix).await;
    let layout_index = lines
        .iter()
        .position(|line| line.starts_with(&target_layout_prefix))
        .expect("the control client must be told the attached window grew");
    assert_eq!(
        layout_change_geometry(&lines[layout_index]).as_deref(),
        Some("101x40"),
        "{:?}",
        lines[layout_index]
    );
    let session_changed_index = lines
        .iter()
        .position(|line| line.starts_with("%client-session-changed "))
        .expect("the control client must be told the PTY attached");
    assert_eq!(
        lines
            .iter()
            .filter(|line| line.starts_with("%client-session-changed "))
            .count(),
        1,
        "the initial attach commit must publish once: {lines:?}"
    );
    assert!(
        session_changed_index < layout_index,
        "tmux 3.7b reports the PTY attach before the layout it causes: {lines:?}"
    );
}

#[tokio::test]
async fn attached_client_departure_notifies_the_surviving_control_layout_change_like_tmux37() {
    // Frozen tmux 3.7b oracle, measured 2026-07-25 on a session holding a
    // 101x41 PTY-attached client and a 60x20 control client, `window-size
    // largest`. When the PTY client's process dies, the control client
    // receives
    //     %client-detached /dev/ttys007
    //     %layout-change @0 a1dd,60x20,0,0,0 a1dd,60x20,0,0,0 *
    // in that order: tmux reports the loss immediately and the resize it
    // causes on the next server loop.
    let handler = RequestHandler::new();
    let session = session_name("attach-departure-notify");
    create_session(&handler, session.clone(), INITIAL_SIZE).await;
    set_window_size_policy(&handler, &session, "largest").await;

    let departing_pid = std::process::id();
    let surviving_pid = departing_pid.saturating_add(1);
    let departing_size = TerminalSize {
        cols: 101,
        rows: 41,
    };
    let surviving_size = TerminalSize { cols: 60, rows: 20 };
    let (attach_id, _attach_events) =
        register_attached_client(&handler, departing_pid, &session, departing_size).await;
    let (_control_id, mut control_events) =
        register_control_client_with_id(&handler, surviving_pid, &session).await;
    let response = handler
        .handle(Request::RefreshClient(Box::new(
            refresh_client_size_request(surviving_pid, surviving_size),
        )))
        .await;
    assert!(
        matches!(response, Response::RefreshClient(_)),
        "{response:?}"
    );
    assert_eq!(
        session_size(&handler, &session).await,
        attached_content_size(departing_size)
    );
    let layout_prefix = format!(
        "%layout-change @{} ",
        active_window_id(&handler, &session).await
    );
    settle_control_notifications(&mut control_events).await;

    handler.finish_attach(departing_pid, attach_id).await;

    assert_eq!(
        session_size(&handler, &session).await,
        surviving_size,
        "the session must fall back to its surviving control client's geometry"
    );
    let lines = collect_control_notifications_through(&mut control_events, &layout_prefix).await;
    let layout_index = lines
        .iter()
        .position(|line| line.starts_with(&layout_prefix))
        .expect("the surviving control client must be told the window shrank");
    assert_eq!(
        layout_change_geometry(&lines[layout_index]).as_deref(),
        Some("60x20"),
        "{:?}",
        lines[layout_index]
    );
    let detached_index = lines
        .iter()
        .position(|line| line.starts_with("%client-detached "))
        .expect("the surviving control client must be told the other client left");
    assert!(
        detached_index < layout_index,
        "tmux 3.7b reports a lost client before the resize it causes: {lines:?}"
    );
}

#[tokio::test]
async fn detach_client_notifies_the_surviving_control_layout_change_like_tmux37() {
    // Same oracle session as the departure test, but the 101x41 client leaves
    // through `detach-client`. tmux 3.7b, measured 2026-07-25, then sends
    //     %layout-change @0 a1dd,60x20,0,0,0 a1dd,60x20,0,0,0 *
    //     %client-detached /dev/ttys007
    // - the opposite order, because the command queue applies the resize before
    // the client is actually lost.
    let handler = RequestHandler::new();
    let session = session_name("detach-client-notify");
    create_session(&handler, session.clone(), INITIAL_SIZE).await;
    set_window_size_policy(&handler, &session, "largest").await;

    let detaching_pid = std::process::id();
    let surviving_pid = detaching_pid.saturating_add(1);
    let detaching_size = TerminalSize {
        cols: 101,
        rows: 41,
    };
    let surviving_size = TerminalSize { cols: 60, rows: 20 };
    let (_attach_id, _attach_events) =
        register_attached_client(&handler, detaching_pid, &session, detaching_size).await;
    let (_control_id, mut control_events) =
        register_control_client_with_id(&handler, surviving_pid, &session).await;
    let response = handler
        .handle(Request::RefreshClient(Box::new(
            refresh_client_size_request(surviving_pid, surviving_size),
        )))
        .await;
    assert!(
        matches!(response, Response::RefreshClient(_)),
        "{response:?}"
    );
    assert_eq!(
        session_size(&handler, &session).await,
        attached_content_size(detaching_size)
    );
    let layout_prefix = format!(
        "%layout-change @{} ",
        active_window_id(&handler, &session).await
    );
    settle_control_notifications(&mut control_events).await;

    // `detach-client` sends the terminal control message and then reconciles;
    // the client is only unregistered when its connection finishes, so the
    // reconcile has to see the departure itself.
    let response = handler
        .handle(Request::DetachClient(DetachClientRequest))
        .await;
    assert!(
        matches!(response, Response::DetachClient(_)),
        "{response:?}"
    );

    assert_eq!(
        session_size(&handler, &session).await,
        surviving_size,
        "the session must fall back to its surviving control client's geometry"
    );
    let lines = collect_control_notifications_through(&mut control_events, &layout_prefix).await;
    let layout_index = lines
        .iter()
        .position(|line| line.starts_with(&layout_prefix))
        .expect("the surviving control client must be told the window shrank");
    assert_eq!(
        layout_change_geometry(&lines[layout_index]).as_deref(),
        Some("60x20"),
        "{:?}",
        lines[layout_index]
    );
}

#[tokio::test]
async fn window_keyed_reconcile_notifies_control_clients_like_tmux37() {
    // The window-keyed reconcile is the one kill-window, kill-session,
    // link/move/swap/unlink-window and pane kill-by-id use for the windows that
    // survive them. tmux 3.7b's `resize_window()` notifies
    // `window-layout-changed` and then `window-resized` for every applied
    // resize, so a control client on that window always receives
    //     %layout-change @0 a1dd,60x20,0,0,0 a1dd,60x20,0,0,0 *
    // (measured 2026-07-25; identical line to the departure oracle, which
    // reaches the same 60x20 geometry).
    let handler = RequestHandler::new();
    let session = session_name("window-reconcile-notify");
    create_session(&handler, session.clone(), INITIAL_SIZE).await;
    set_window_size_policy(&handler, &session, "largest").await;

    let control_pid = std::process::id();
    let control_size = TerminalSize { cols: 60, rows: 20 };
    let (_control_id, mut control_events) =
        register_control_client_with_id(&handler, control_pid, &session).await;
    let response = handler
        .handle(Request::RefreshClient(Box::new(
            refresh_client_size_request(control_pid, control_size),
        )))
        .await;
    assert!(
        matches!(response, Response::RefreshClient(_)),
        "{response:?}"
    );
    assert_eq!(session_size(&handler, &session).await, control_size);
    let layout_prefix = format!(
        "%layout-change @{} ",
        active_window_id(&handler, &session).await
    );

    // Stand in for the departed client whose geometry the window still carries.
    force_window_size(
        &handler,
        &session,
        0,
        TerminalSize {
            cols: 101,
            rows: 41,
        },
    )
    .await;
    settle_control_notifications(&mut control_events).await;

    handler
        .reconcile_attached_window_size_and_emit(&WindowTarget::with_window(session.clone(), 0))
        .await
        .expect("the window reconcile succeeds");

    assert_eq!(session_size(&handler, &session).await, control_size);
    let lines = collect_control_notifications_through(&mut control_events, &layout_prefix).await;
    let layout = lines
        .iter()
        .find(|line| line.starts_with(&layout_prefix))
        .expect("the control client must be told the window was resized");
    assert_eq!(
        layout_change_geometry(layout).as_deref(),
        Some("60x20"),
        "{layout}"
    );
}

#[tokio::test]
async fn destroyed_control_session_rehome_reconciles_target_geometry_like_tmux37() {
    let handler = RequestHandler::new();
    let target = session_name("control-destroy-rehome-target");
    let source = session_name("control-destroy-rehome-source");
    create_session(
        &handler,
        target.clone(),
        TerminalSize { cols: 60, rows: 20 },
    )
    .await;
    create_session(&handler, source.clone(), INITIAL_SIZE).await;
    set_window_size_policy(&handler, &target, "latest").await;
    set_detach_on_destroy(&handler, &source, "off").await;

    let requester_pid = std::process::id();
    let (_control_id, _control_events) =
        register_control_client_with_id(&handler, requester_pid, &source).await;
    let control_size = TerminalSize {
        cols: 101,
        rows: 41,
    };
    let refreshed = handler
        .handle(Request::RefreshClient(Box::new(
            refresh_client_size_request(requester_pid, control_size),
        )))
        .await;
    assert!(
        matches!(refreshed, Response::RefreshClient(_)),
        "{refreshed:?}"
    );

    let killed = handler
        .handle(Request::KillSession(KillSessionRequest {
            target: source,
            kill_all_except_target: false,
            clear_alerts: false,
            kill_group: false,
        }))
        .await;

    assert!(matches!(killed, Response::KillSession(_)), "{killed:?}");
    assert_eq!(session_size(&handler, &target).await, control_size);
    let active_control = handler.active_control.lock().await;
    assert_eq!(
        active_control
            .by_pid
            .get(&requester_pid)
            .and_then(|active| active.session_name.as_ref()),
        Some(&target)
    );
}

#[tokio::test]
async fn destroyed_session_rehome_notifies_the_attached_destination_layout_change_like_tmux37() {
    // Frozen tmux 3.7b oracle, measured 2026-07-25
    // (`.rmux-audit/oracle/scenario_destroy_rehome_destination.py`): `doomed`
    // holds a 101x41 PTY client with `detach-on-destroy off`, `keep` holds a
    // 60x20 control client, `window-size largest`. Killing `doomed` rehomes the
    // PTY client onto `keep`, whose default-status window grows
    // 60x20 -> 101x40, and the
    // destination control client receives
    //     %client-session-changed /dev/ttys010 $0 keep
    //     ...
    //     %layout-change @0 aefd,101x40,0,0,0 aefd,101x40,0,0,0 *
    let handler = RequestHandler::new();
    let keep = session_name("rehome-dest-keep");
    let doomed = session_name("rehome-dest-doomed");
    create_session(&handler, keep.clone(), TARGET_SIZE).await;
    create_session(&handler, doomed.clone(), INITIAL_SIZE).await;
    set_window_size_policy(&handler, &keep, "largest").await;
    set_window_size_policy(&handler, &doomed, "largest").await;
    set_detach_on_destroy(&handler, &doomed, "off").await;

    let attach_pid = std::process::id().saturating_add(7);
    let control_pid = attach_pid.saturating_add(1);
    let rehomed_size = TerminalSize {
        cols: 101,
        rows: 41,
    };
    let destination_size = TerminalSize { cols: 60, rows: 20 };
    let (_attach_id, _attach_events) =
        register_attached_client(&handler, attach_pid, &doomed, rehomed_size).await;
    let (_control_id, mut control_events) =
        register_control_client_with_id(&handler, control_pid, &keep).await;
    let response = handler
        .handle(Request::RefreshClient(Box::new(
            refresh_client_size_request(control_pid, destination_size),
        )))
        .await;
    assert!(
        matches!(response, Response::RefreshClient(_)),
        "{response:?}"
    );
    assert_eq!(session_size(&handler, &keep).await, destination_size);
    let keep_window_id = active_window_id(&handler, &keep).await;
    let keep_layout_prefix = format!("%layout-change @{keep_window_id} ");
    settle_control_notifications(&mut control_events).await;

    let killed = handler
        .handle(Request::KillSession(KillSessionRequest {
            target: doomed,
            kill_all_except_target: false,
            clear_alerts: false,
            kill_group: false,
        }))
        .await;
    assert!(matches!(killed, Response::KillSession(_)), "{killed:?}");
    assert_eq!(
        session_size(&handler, &keep).await,
        attached_content_size(rehomed_size),
        "the rehome destination must grow to the arriving client's geometry"
    );

    let lines =
        collect_control_notifications_through(&mut control_events, &keep_layout_prefix).await;
    let layout_index = lines
        .iter()
        .position(|line| line.starts_with(&keep_layout_prefix))
        .expect("the destination control client must be told the rehome grew its window");
    assert_eq!(
        layout_change_geometry(&lines[layout_index]).as_deref(),
        Some("101x40"),
        "{:?}",
        lines[layout_index]
    );
    let session_changed_index = lines
        .iter()
        .position(|line| line.starts_with("%client-session-changed "))
        .expect("the destination control client must be told the client arrived");
    assert!(
        session_changed_index < layout_index,
        "tmux 3.7b reports the client move before the layout it causes: {lines:?}"
    );
}

#[tokio::test]
async fn attached_arrival_and_departure_keep_control_geometry_in_every_automatic_policy() {
    // Frozen tmux 3.7b oracle, 2026-07-25: a control client remains a
    // window-size candidate while an ordinary attach arrives and after it
    // departs. Latest follows arrival order; largest/smallest aggregate both.
    for (index, (policy, control_size, attach_size, attached_size)) in [
        (
            "latest",
            CONTROL_SIZE,
            TARGET_SIZE,
            attached_content_size(TARGET_SIZE),
        ),
        ("largest", CONTROL_SIZE, TARGET_SIZE, CONTROL_SIZE),
        ("smallest", TARGET_SIZE, CONTROL_SIZE, TARGET_SIZE),
    ]
    .into_iter()
    .enumerate()
    {
        let handler = RequestHandler::new();
        let session = session_name(&format!("control-attach-{policy}"));
        create_session(&handler, session.clone(), INITIAL_SIZE).await;
        set_window_size_policy(&handler, &session, policy).await;
        let control_pid = 92_500 + index as u32 * 2;
        let attach_pid = control_pid + 1;
        let (_control_id, _control_events) =
            register_control_client_with_id(&handler, control_pid, &session).await;
        let refreshed = handler
            .handle(Request::RefreshClient(Box::new(
                refresh_client_size_request(control_pid, control_size),
            )))
            .await;
        assert!(
            matches!(refreshed, Response::RefreshClient(_)),
            "{refreshed:?}"
        );

        let (attach_id, _attach_events) =
            register_attached_client(&handler, attach_pid, &session, attach_size).await;
        handler
            .reconcile_attached_session_size_and_emit(&session)
            .await
            .expect("ordinary attach arrival reconciles mixed client geometry");
        assert_eq!(
            session_size(&handler, &session).await,
            attached_size,
            "{policy} after ordinary attach"
        );

        handler.finish_attach(attach_pid, attach_id).await;
        assert_eq!(
            session_size(&handler, &session).await,
            control_size,
            "{policy} after ordinary detach"
        );
    }
}

#[tokio::test]
async fn control_departure_reconciles_surviving_control_geometry() {
    // Frozen tmux 3.7b oracle, 2026-07-25: removing the winning control
    // candidate restores the surviving control for latest/largest/smallest.
    for (index, (policy, first_size, second_size, removed_first, expected_size)) in [
        ("latest", CONTROL_SIZE, TARGET_SIZE, false, CONTROL_SIZE),
        ("largest", CONTROL_SIZE, TARGET_SIZE, true, TARGET_SIZE),
        ("smallest", TARGET_SIZE, CONTROL_SIZE, true, CONTROL_SIZE),
    ]
    .into_iter()
    .enumerate()
    {
        let handler = RequestHandler::new();
        let session = session_name(&format!("control-depart-{policy}"));
        create_session(&handler, session.clone(), INITIAL_SIZE).await;
        set_window_size_policy(&handler, &session, policy).await;
        let first_pid = 92_600 + index as u32 * 2;
        let second_pid = first_pid + 1;
        let (first_id, _first_events) =
            register_control_client_with_id(&handler, first_pid, &session).await;
        let (second_id, _second_events) =
            register_control_client_with_id(&handler, second_pid, &session).await;
        for (pid, size) in [(first_pid, first_size), (second_pid, second_size)] {
            let response = handler
                .handle(Request::RefreshClient(Box::new(
                    refresh_client_size_request(pid, size),
                )))
                .await;
            assert!(
                matches!(response, Response::RefreshClient(_)),
                "{response:?}"
            );
        }

        let (removed_pid, removed_id) = if removed_first {
            (first_pid, first_id)
        } else {
            (second_pid, second_id)
        };
        handler.finish_control(removed_pid, removed_id).await;
        assert_eq!(
            session_size(&handler, &session).await,
            expected_size,
            "{policy} after control departure"
        );
    }
}

#[tokio::test]
async fn window_size_option_reconciliation_includes_control_candidates() {
    let handler = RequestHandler::new();
    let session = session_name("control-option-reconcile");
    create_session(&handler, session.clone(), INITIAL_SIZE).await;
    let control_pid = 92_650;
    let (_control_id, _control_events) =
        register_control_client_with_id(&handler, control_pid, &session).await;
    let refreshed = handler
        .handle(Request::RefreshClient(Box::new(
            refresh_client_size_request(control_pid, CONTROL_SIZE),
        )))
        .await;
    assert!(
        matches!(refreshed, Response::RefreshClient(_)),
        "{refreshed:?}"
    );
    let (_attach_id, _attach_events) =
        register_attached_client(&handler, 92_651, &session, TARGET_SIZE).await;

    for (policy, expected_size) in [
        ("largest", CONTROL_SIZE),
        ("smallest", attached_content_size(TARGET_SIZE)),
        ("latest", attached_content_size(TARGET_SIZE)),
    ] {
        set_window_size_policy(&handler, &session, policy).await;
        assert_eq!(
            session_size(&handler, &session).await,
            expected_size,
            "{policy} option reconciliation"
        );
    }
}

#[tokio::test]
async fn control_resize_racing_reconcile_cannot_apply_a_stale_geometry() {
    let handler = RequestHandler::new();
    let session = session_name("control-resize-selection-race");
    create_session(&handler, session.clone(), INITIAL_SIZE).await;
    set_window_size_policy(&handler, &session, "largest").await;
    let (_attach_id, _attach_events) =
        register_attached_client(&handler, 92_700, &session, INITIAL_SIZE).await;
    let control_pid = 92_701;
    let (_control_id, _control_events) =
        register_control_client_with_id(&handler, control_pid, &session).await;
    let refreshed = handler
        .handle(Request::RefreshClient(Box::new(
            refresh_client_size_request(control_pid, CONTROL_SIZE),
        )))
        .await;
    assert!(
        matches!(refreshed, Response::RefreshClient(_)),
        "{refreshed:?}"
    );

    let pause = handler.install_attached_size_selection_pause();
    let reconcile_handler = handler.clone();
    let reconcile_session = session.clone();
    let reconcile = tokio::spawn(async move {
        reconcile_handler
            .reconcile_attached_session_size(&reconcile_session)
            .await
    });
    pause.reached.notified().await;

    let newest_size = TerminalSize {
        cols: 120,
        rows: 45,
    };
    let refreshed = handler
        .handle(Request::RefreshClient(Box::new(
            refresh_client_size_request(control_pid, newest_size),
        )))
        .await;
    assert!(
        matches!(refreshed, Response::RefreshClient(_)),
        "{refreshed:?}"
    );
    pause.release.notify_one();

    reconcile
        .await
        .expect("reconcile task joins")
        .expect("reconcile succeeds");
    assert_eq!(
        session_size(&handler, &session).await,
        newest_size,
        "a selection predating the control resize must be retried"
    );
}

/// Frozen tmux 3.7b oracle, 2026-07-25, `tmux -C attach-session` fed one
/// command per flush:
///
/// ```text
/// %begin 1785012377 305 1
/// %end 1785012377 305 1
/// %layout-change @0 c33d,130x46,0,0,0 c33d,130x46,0,0,0 *
/// ```
///
/// tmux flushes the notification for a resize its command applied before it
/// reads the next command, so a control frontend never has to send an
/// unrelated command to learn the new geometry. RMUX keeps that guarantee with
/// the applied-window-resize backstop, which used to run only for requests
/// arriving on a plain socket connection — a control client's own command
/// stream, a multi-command CLI invocation, a hook, a key binding and the
/// identity-checked choose-tree / web-share dispatch all bypass
/// `dispatch_for_connection`.
async fn assert_queued_command_publishes_a_pending_window_resize(
    session_suffix: &str,
    control_pid: u32,
    run_queue: impl AsyncFnOnce(&RequestHandler, u32, SessionName),
) {
    let handler = RequestHandler::new();
    let session = session_name(&format!("queued-resize-backstop-{session_suffix}"));
    create_session(&handler, session.clone(), INITIAL_SIZE).await;
    let (_control_id, mut events) =
        register_control_client_with_id(&handler, control_pid, &session).await;
    let _ = settle_control_notifications(&mut events).await;

    // A geometry write that reached the chokepoint without publishing at its
    // own ordering point: exactly what the backstop exists to catch.
    force_window_size(&handler, &session, 0, TARGET_SIZE).await;

    run_queue(&handler, control_pid, session.clone()).await;

    let lines = settle_control_notifications(&mut events).await;
    let geometry = lines
        .iter()
        .filter(|line| line.starts_with("%layout-change"))
        .filter_map(|line| layout_change_geometry(line))
        .collect::<Vec<_>>();
    assert_eq!(
        geometry,
        vec![format!("{}x{}", TARGET_SIZE.cols, TARGET_SIZE.rows)],
        "the queued command must publish the pending resize exactly once; got {lines:?}"
    );
    assert!(
        handler
            .state
            .lock()
            .await
            .take_applied_window_resizes()
            .is_empty(),
        "the queued command must leave the geometry queue empty"
    );
}

#[tokio::test]
async fn a_control_queue_command_publishes_a_pending_applied_window_resize() {
    assert_queued_command_publishes_a_pending_window_resize(
        "control",
        92_800,
        async |handler: &RequestHandler, control_pid: u32, _session: SessionName| {
            let parsed = handler
                .parse_control_commands("list-sessions")
                .await
                .expect("list-sessions parses");
            let result = handler.execute_control_commands(control_pid, parsed).await;
            assert!(result.error.is_none(), "{:?}", result.error);
        },
    )
    .await;
}

#[tokio::test]
async fn a_detached_queue_command_publishes_a_pending_applied_window_resize() {
    // The detached queue is what runs a multi-command CLI invocation, a hook
    // body and a key binding, none of which reach `dispatch_for_connection`.
    assert_queued_command_publishes_a_pending_window_resize(
        "detached",
        92_810,
        async |handler: &RequestHandler, _control_pid: u32, _session: SessionName| {
            let parsed = handler
                .parse_control_commands("list-sessions")
                .await
                .expect("list-sessions parses");
            handler
                .execute_parsed_commands_for_test(92_811, parsed)
                .await
                .expect("list-sessions succeeds");
        },
    )
    .await;
}

#[tokio::test]
async fn an_identity_checked_dispatch_publishes_a_pending_applied_window_resize() {
    // choose-tree's kill actions (handler_mode_tree/tree_kill.rs) and the
    // web-share request path run their hooks through `finish_identity_dispatch`
    // instead of `dispatch_for_connection`.
    assert_queued_command_publishes_a_pending_window_resize(
        "identity",
        92_820,
        async |handler: &RequestHandler, control_pid: u32, session: SessionName| {
            let session_id = handler
                .state
                .lock()
                .await
                .sessions
                .session(&session)
                .expect("session remains present")
                .id();
            let response = crate::handler::dispatch_with_expected_session_identity(
                handler,
                control_pid,
                session.clone(),
                session_id,
                Request::HasSession(rmux_proto::HasSessionRequest { target: session }),
            )
            .await;
            assert!(matches!(response, Response::HasSession(_)), "{response:?}");
        },
    )
    .await;
}

fn session_name(value: &str) -> SessionName {
    SessionName::new(value).expect("valid session name")
}

async fn create_session(handler: &RequestHandler, session: SessionName, size: TerminalSize) {
    let response = handler
        .handle(Request::NewSession(NewSessionRequest {
            session_name: session,
            detached: true,
            size: Some(size),
            environment: None,
        }))
        .await;
    assert!(matches!(response, Response::NewSession(_)), "{response:?}");
}

async fn set_window_size_policy(handler: &RequestHandler, session: &SessionName, policy: &str) {
    set_window_size_policy_for_window(handler, session, 0, policy).await;
}

async fn set_window_size_policy_for_window(
    handler: &RequestHandler,
    session: &SessionName,
    window_index: u32,
    policy: &str,
) {
    let response = handler
        .handle(Request::SetOption(SetOptionRequest {
            scope: ScopeSelector::Window(WindowTarget::with_window(session.clone(), window_index)),
            option: OptionName::WindowSize,
            value: policy.to_owned(),
            mode: SetOptionMode::Replace,
        }))
        .await;
    assert!(matches!(response, Response::SetOption(_)), "{response:?}");
}

async fn set_detach_on_destroy(handler: &RequestHandler, session: &SessionName, value: &str) {
    let response = handler
        .handle(Request::SetOption(SetOptionRequest {
            scope: ScopeSelector::Session(session.clone()),
            option: OptionName::DetachOnDestroy,
            value: value.to_owned(),
            mode: SetOptionMode::Replace,
        }))
        .await;
    assert!(matches!(response, Response::SetOption(_)), "{response:?}");
}

async fn register_control_client_with_id(
    handler: &RequestHandler,
    requester_pid: u32,
    session: &SessionName,
) -> (u64, mpsc::Receiver<ControlServerEvent>) {
    let (event_tx, event_rx) = mpsc::channel(CONTROL_SERVER_EVENT_CAPACITY);
    let control_id = handler
        .register_control_with_closing(
            requester_pid,
            ControlModeUpgrade {
                initial_command_count: 0,
                mode: ControlMode::Plain,
                terminal_context: crate::outer_terminal::OuterTerminalContext::default(),
            },
            event_tx,
            Arc::new(AtomicBool::new(false)),
        )
        .await;
    handler
        .set_control_session(requester_pid, Some(session.clone()))
        .await
        .expect("set control session");
    (control_id, event_rx)
}

async fn register_attached_client(
    handler: &RequestHandler,
    requester_pid: u32,
    session: &SessionName,
    size: TerminalSize,
) -> (u64, mpsc::UnboundedReceiver<crate::pane_io::AttachControl>) {
    let (control_tx, control_rx) = mpsc::unbounded_channel();
    let attach_id = handler
        .register_attach(requester_pid, session.clone(), control_tx)
        .await;
    let mut active_attach = handler.active_attach.lock().await;
    let size_sequence = handler.next_client_size_sequence();
    let active = active_attach
        .by_pid
        .get_mut(&requester_pid)
        .expect("attached client remains registered");
    active.set_declared_client_size(size);
    active.size_sequence = size_sequence;
    drop(active_attach);
    handler.bump_active_attach_epoch();
    (attach_id, control_rx)
}

fn refresh_client_size_request(
    requester_pid: u32,
    size: TerminalSize,
) -> rmux_proto::request::RefreshClientRequest {
    rmux_proto::request::RefreshClientRequest {
        target_client: Some(requester_pid.to_string()),
        adjustment: None,
        clear_pan: false,
        pan_left: false,
        pan_right: false,
        pan_up: false,
        pan_down: false,
        status_only: false,
        clipboard_query: false,
        flags: None,
        flags_alias: None,
        subscriptions: Vec::new(),
        subscriptions_format: Vec::new(),
        control_size: Some(format!("{}x{}", size.cols, size.rows)),
        colour_report: None,
    }
}

async fn control_client_size(handler: &RequestHandler, requester_pid: u32) -> TerminalSize {
    let active_control = handler.active_control.lock().await;
    let active = active_control
        .by_pid
        .get(&requester_pid)
        .expect("control client remains registered");
    TerminalSize {
        cols: active.client_width,
        rows: active.client_height,
    }
}

/// Puts a window back at a geometry no live client asks for, standing in for
/// the client whose departure the reconcile has to notice.
async fn force_window_size(
    handler: &RequestHandler,
    session: &SessionName,
    window_index: u32,
    size: TerminalSize,
) {
    let mut state = handler.state.lock().await;
    state
        .mutate_session_and_resize_window_terminal(session, window_index, |session| {
            session.resize_window(window_index, size)
        })
        .expect("test window resize succeeds");
}

async fn session_size(handler: &RequestHandler, session: &SessionName) -> TerminalSize {
    handler
        .state
        .lock()
        .await
        .sessions
        .session(session)
        .expect("session remains present")
        .window()
        .size()
}

async fn active_window_id(handler: &RequestHandler, session: &SessionName) -> u32 {
    handler
        .state
        .lock()
        .await
        .sessions
        .session(session)
        .expect("session remains present")
        .window()
        .id()
        .as_u32()
}

async fn window_ids(handler: &RequestHandler, session: &SessionName) -> Vec<u32> {
    handler
        .state
        .lock()
        .await
        .sessions
        .session(session)
        .expect("session remains present")
        .windows()
        .values()
        .map(|window| window.id().as_u32())
        .collect()
}

async fn session_window_sizes(
    handler: &RequestHandler,
    session: &SessionName,
) -> Vec<TerminalSize> {
    handler
        .state
        .lock()
        .await
        .sessions
        .session(session)
        .expect("session remains present")
        .windows()
        .values()
        .map(|window| window.size())
        .collect()
}

fn layout_change_window_id(line: &str) -> Option<u32> {
    line.strip_prefix("%layout-change @")?
        .split_once(' ')
        .and_then(|(window_id, _)| window_id.parse().ok())
}

/// `%layout-change @<id> <layout> <visible layout> <flags>` carries the window
/// geometry in the second comma-separated field of the layout cell.
fn layout_change_geometry(line: &str) -> Option<String> {
    line.split_whitespace()
        .nth(2)
        .and_then(|layout| layout.split(',').nth(1))
        .map(ToOwned::to_owned)
}

/// Collects the notifications in delivery order up to and including the first
/// line starting with `prefix`, so a test can assert on their relative order.
async fn collect_control_notifications_through(
    events: &mut mpsc::Receiver<ControlServerEvent>,
    prefix: &str,
) -> Vec<String> {
    let deadline = tokio::time::Instant::now() + CONTROL_NOTIFICATION_TIMEOUT;
    let mut lines = Vec::new();
    while tokio::time::Instant::now() < deadline {
        match tokio::time::timeout(CONTROL_NOTIFICATION_POLL, events.recv()).await {
            Ok(Some(ControlServerEvent::Notification(line))) => {
                let matched = line.starts_with(prefix);
                lines.push(line);
                if matched {
                    return lines;
                }
            }
            Ok(Some(_)) | Err(_) => continue,
            Ok(None) => break,
        }
    }
    lines
}

/// Collects everything the client receives until its stream stays quiet for
/// [`CONTROL_NOTIFICATION_SETTLE`].
async fn settle_control_notifications(
    events: &mut mpsc::Receiver<ControlServerEvent>,
) -> Vec<String> {
    let mut deadline = tokio::time::Instant::now() + CONTROL_NOTIFICATION_SETTLE;
    let mut lines = Vec::new();
    while tokio::time::Instant::now() < deadline {
        match tokio::time::timeout(CONTROL_NOTIFICATION_POLL, events.recv()).await {
            Ok(Some(event)) => {
                deadline = tokio::time::Instant::now() + CONTROL_NOTIFICATION_SETTLE;
                if let ControlServerEvent::Notification(line) = event {
                    lines.push(line);
                }
            }
            Ok(None) => break,
            Err(_) => continue,
        }
    }
    lines
}