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

async fn assert_send_keys_succeeds(handler: &RequestHandler, target: PaneTarget) {
    let response = handler
        .handle(Request::SendKeys(rmux_proto::SendKeysRequest {
            target,
            keys: vec!["x".to_owned()],
        }))
        .await;
    assert!(matches!(response, Response::SendKeys(_)), "{response:?}");
}

async fn assert_pane_output_observes(
    receiver: &mut crate::pane_io::PaneOutputReceiver,
    expected: &[u8],
) {
    timeout(Duration::from_secs(2), async {
        loop {
            match receiver.recv().await {
                rmux_core::events::OutputCursorItem::Event(event) if event.bytes() == expected => {
                    return;
                }
                rmux_core::events::OutputCursorItem::Event(_) => {}
                rmux_core::events::OutputCursorItem::Gap(gap) => {
                    panic!("pane output cursor fell behind before the expected event: {gap:?}");
                }
            }
        }
    })
    .await
    .expect("expected pane output was not observed");
}

#[tokio::test]
async fn grouped_unlink_k_preserves_each_session_local_fallback_identity() {
    for target_index in [2, 3] {
        for renumber in [false, true] {
            for peer_target_active in [false, true] {
                let handler = RequestHandler::new();
                let owner = session_name(&format!(
                    "unlink-local-owner-{target_index}-{renumber}-{peer_target_active}"
                ));
                let peer = session_name(&format!(
                    "unlink-local-peer-{target_index}-{renumber}-{peer_target_active}"
                ));
                let base_index = handler
                    .handle(Request::SetOption(SetOptionRequest {
                        scope: ScopeSelector::Global,
                        option: OptionName::BaseIndex,
                        value: target_index.to_string(),
                        mode: SetOptionMode::Replace,
                    }))
                    .await;
                assert!(
                    matches!(base_index, Response::SetOption(_)),
                    "{base_index:?}"
                );
                create_session(&handler, owner.as_str()).await;
                for window_index in 0..target_index {
                    create_window_at(&handler, &owner, window_index).await;
                }
                create_grouped_session(&handler, peer.as_str(), &owner).await;
                if peer_target_active {
                    // tmux starts the peer on index 0, so this single command
                    // records 0 as its local last window. On the regression
                    // base RMUX has already copied the owner's target, making
                    // the same command a no-op with no fallback history.
                    let selected = handler
                        .handle(Request::SelectWindow(SelectWindowRequest {
                            target: WindowTarget::with_window(peer.clone(), target_index),
                        }))
                        .await;
                    assert!(
                        matches!(selected, Response::SelectWindow(_)),
                        "{selected:?}"
                    );
                }

                for session_name in [&owner, &peer] {
                    let response = handler
                        .handle(Request::SetOption(SetOptionRequest {
                            scope: ScopeSelector::Session(session_name.clone()),
                            option: OptionName::RenumberWindows,
                            value: if renumber { "on" } else { "off" }.to_owned(),
                            mode: SetOptionMode::Replace,
                        }))
                        .await;
                    assert!(matches!(response, Response::SetOption(_)), "{response:?}");
                }

                let (owner_expected, peer_expected) = {
                    let state = handler.state.lock().await;
                    let owner_session = state.sessions.session(&owner).expect("owner exists");
                    let owner_expected = owner_session
                        .window_at(target_index - 1)
                        .expect("owner cyclic predecessor exists")
                        .id();
                    let peer_expected = state
                        .sessions
                        .session(&peer)
                        .and_then(|session| session.window_at(0))
                        .expect("peer local fallback exists")
                        .id();
                    (owner_expected, peer_expected)
                };

                let response = handler
                    .handle(Request::UnlinkWindow(UnlinkWindowRequest {
                        target: WindowTarget::with_window(owner.clone(), target_index),
                        kill_if_last: true,
                    }))
                    .await;
                assert!(
                    matches!(response, Response::UnlinkWindow(_)),
                    "{response:?}"
                );

                let state = handler.state.lock().await;
                assert_eq!(
                    state
                        .sessions
                        .session(&owner)
                        .expect("owner survives")
                        .window()
                        .id(),
                    owner_expected,
                    "owner target={target_index}, renumber={renumber}, peer active={peer_target_active}"
                );
                assert_eq!(
                    state
                        .sessions
                        .session(&peer)
                        .expect("peer survives")
                        .window()
                        .id(),
                    peer_expected,
                    "peer target={target_index}, renumber={renumber}, active={peer_target_active}"
                );
            }
        }
    }
}

#[tokio::test]
async fn link_window_refreshes_attached_non_syntactic_group_peer_output_receiver() {
    let handler = RequestHandler::new();
    let owner = session_name("linked-refresh-owner");
    let peer = session_name("linked-refresh-peer");
    let source = session_name("linked-refresh-source");
    create_session(&handler, owner.as_str()).await;
    create_grouped_session(&handler, peer.as_str(), &owner).await;
    create_session(&handler, source.as_str()).await;

    let source_pane_id = {
        let state = handler.state.lock().await;
        state
            .sessions
            .session(&source)
            .expect("source session exists")
            .window_at(0)
            .expect("source window exists")
            .active_pane()
            .expect("source active pane exists")
            .id()
    };

    let (control_tx, mut control_rx) = mpsc::unbounded_channel();
    handler.register_attach(42, peer.clone(), control_tx).await;
    drain_attach_controls(&mut control_rx).await;

    let response = handler
        .handle(Request::LinkWindow(LinkWindowRequest {
            source: WindowTarget::with_window(source.clone(), 0),
            target: WindowTarget::with_window(owner, 0),
            after: false,
            before: false,
            kill_destination: true,
            detached: true,
        }))
        .await;
    assert!(matches!(response, Response::LinkWindow(_)), "{response:?}");

    let control = timeout(Duration::from_secs(2), control_rx.recv())
        .await
        .expect("attached group peer must be refreshed after link-window")
        .expect("attached group peer control channel remains open");
    let AttachControl::Switch(target) = control else {
        panic!("expected attached group peer switch, got {control:?}");
    };
    let mut target = target.into_target();
    assert_eq!(target.session_name, peer);

    let output = {
        let state = handler.state.lock().await;
        let peer_pane_id = state
            .sessions
            .session(&peer)
            .expect("peer session exists")
            .window_at(0)
            .expect("peer window exists")
            .active_pane()
            .expect("peer active pane exists")
            .id();
        assert_eq!(peer_pane_id, source_pane_id);
        state
            .pane_output_for_target(&peer, 0, 0)
            .expect("linked peer output exists")
            .clone()
    };
    let expected = b"linked-peer-live-output".to_vec();
    output.send(expected.clone());
    assert_pane_output_observes(&mut target.pane_output, &expected).await;
}

#[tokio::test]
async fn scrollbar_options_resize_shared_runtime_and_refresh_linked_alias() {
    for kind in ["typed", "named", "sdk"] {
        let handler = RequestHandler::new();
        let suffix = kind;
        let owner = session_name(&format!("scrollbar-option-owner-{suffix}"));
        let alias = session_name(&format!("scrollbar-option-alias-{suffix}"));
        create_session(&handler, owner.as_str()).await;
        create_session(&handler, alias.as_str()).await;

        let linked = handler
            .handle(Request::LinkWindow(LinkWindowRequest {
                source: WindowTarget::with_window(owner.clone(), 0),
                target: WindowTarget::with_window(alias.clone(), 0),
                after: false,
                before: false,
                kill_destination: true,
                detached: true,
            }))
            .await;
        assert!(matches!(linked, Response::LinkWindow(_)), "{linked:?}");
        handler.wait_for_initial_panes_for_test().await;
        if kind == "sdk" {
            assert!(matches!(
                handler
                    .handle(Request::SetOption(SetOptionRequest {
                        scope: ScopeSelector::Window(WindowTarget::with_window(owner.clone(), 0)),
                        option: OptionName::PaneScrollbars,
                        value: "on".to_owned(),
                        mode: SetOptionMode::Replace,
                    }))
                    .await,
                Response::SetOption(_)
            ));
        }

        let (control_tx, mut control_rx) = mpsc::unbounded_channel();
        handler
            .register_attach(
                match kind {
                    "typed" => 44,
                    "named" => 45,
                    "sdk" => 46,
                    _ => unreachable!(),
                },
                alias.clone(),
                control_tx,
            )
            .await;
        drain_attach_controls(&mut control_rx).await;

        let request = match kind {
            "named" => Request::SetOptionByName(Box::new(rmux_proto::SetOptionByNameRequest {
                scope: rmux_proto::OptionScopeSelector::Window(WindowTarget::with_window(
                    owner.clone(),
                    0,
                )),
                name: "pane-scrollbars".to_owned(),
                value: Some("on".to_owned()),
                mode: SetOptionMode::Replace,
                only_if_unset: false,
                unset: false,
                unset_pane_overrides: false,
                format: false,
                format_target: None,
            })),
            "sdk" => Request::PaneOptionSet(rmux_proto::PaneOptionSetRequest {
                target: PaneTargetRef::slot(PaneTarget::with_window(owner.clone(), 0, 0)),
                name: "pane-scrollbars-style".to_owned(),
                value: Some("width=2,pad=1".to_owned()),
                mode: SetOptionMode::Replace,
                unset: false,
            }),
            "typed" => Request::SetOption(SetOptionRequest {
                scope: ScopeSelector::Window(WindowTarget::with_window(owner.clone(), 0)),
                option: OptionName::PaneScrollbars,
                value: "on".to_owned(),
                mode: SetOptionMode::Replace,
            }),
            _ => unreachable!(),
        };
        let response = handler.handle(request).await;

        assert!(
            matches!(
                response,
                Response::SetOption(_) | Response::SetOptionByName(_) | Response::PaneOptionSet(_)
            ),
            "{suffix}: {response:?}"
        );
        let control = timeout(Duration::from_secs(2), control_rx.recv())
            .await
            .expect("linked alias must be refreshed after scrollbar geometry changes")
            .expect("linked alias control channel remains open");
        assert!(
            matches!(control, AttachControl::Refresh | AttachControl::Switch(_)),
            "{suffix}: unexpected linked alias control: {control:?}"
        );
        let mut state = handler.state.lock().await;
        let resolved = if kind == "sdk" {
            state
                .options
                .resolve_for_pane(&alias, 0, 0, OptionName::PaneScrollbarsStyle)
        } else {
            state
                .options
                .resolve_for_window(&alias, 0, OptionName::PaneScrollbars)
        };
        assert_eq!(
            resolved,
            Some(if kind == "sdk" { "width=2,pad=1" } else { "on" }),
            "{suffix}"
        );
        let owner_size = state
            .clone_pane_master_if_alive(&owner, 0, 0)
            .expect("owner pane runtime")
            .size()
            .expect("owner pane size");
        let alias_size = state
            .clone_pane_master_if_alive(&alias, 0, 0)
            .expect("alias pane runtime")
            .size()
            .expect("alias pane size");
        assert_eq!(
            (owner_size.cols, alias_size.cols),
            if kind == "sdk" {
                (117, 117)
            } else {
                (119, 119)
            },
            "{suffix}: both aliases expose the resized shared PTY"
        );
    }
}

#[tokio::test]
async fn link_window_k_rejects_same_window_identity_through_group_peer_atomically() {
    let handler = RequestHandler::new();
    let owner = session_name("link-self-owner");
    let peer = session_name("link-self-peer");
    let external = session_name("link-self-external");
    create_session(&handler, owner.as_str()).await;
    create_grouped_session(&handler, peer.as_str(), &owner).await;
    create_session(&handler, external.as_str()).await;

    let linked = handler
        .handle(Request::LinkWindow(LinkWindowRequest {
            source: WindowTarget::with_window(owner.clone(), 0),
            target: WindowTarget::with_window(external.clone(), 1),
            after: false,
            before: false,
            kill_destination: false,
            detached: true,
        }))
        .await;
    assert!(matches!(linked, Response::LinkWindow(_)), "{linked:?}");

    let (before_sessions, before_targets, stable_window_id) = {
        let state = handler.state.lock().await;
        let before_sessions = [&owner, &peer, &external]
            .into_iter()
            .map(|session_name| {
                state
                    .sessions
                    .session(session_name)
                    .expect("session exists before rejected replacement")
                    .clone()
            })
            .collect::<Vec<_>>();
        let before_targets = state.window_linked_window_targets(&owner, 0);
        let stable_window_id = state
            .sessions
            .session(&owner)
            .and_then(|session| session.window_at(0))
            .expect("runtime owner window exists")
            .id();
        assert_eq!(
            state
                .sessions
                .session(&peer)
                .and_then(|session| session.window_at(0))
                .expect("group peer window exists")
                .id(),
            stable_window_id
        );
        assert_eq!(
            state
                .sessions
                .session(&external)
                .and_then(|session| session.window_at(1))
                .expect("external linked window exists")
                .id(),
            stable_window_id
        );
        (before_sessions, before_targets, stable_window_id)
    };

    for target in [
        PaneTarget::with_window(owner.clone(), 0, 0),
        PaneTarget::with_window(peer.clone(), 0, 0),
        PaneTarget::with_window(external.clone(), 1, 0),
    ] {
        assert_send_keys_succeeds(&handler, target).await;
    }

    for source in [
        WindowTarget::with_window(peer.clone(), 0),
        WindowTarget::with_window(external.clone(), 1),
    ] {
        let response = handler
            .handle(Request::LinkWindow(LinkWindowRequest {
                source: source.clone(),
                target: WindowTarget::with_window(owner.clone(), 0),
                after: false,
                before: false,
                kill_destination: true,
                detached: true,
            }))
            .await;
        assert!(
            matches!(response, Response::Error(_)),
            "same-WindowId replacement from {source} must fail atomically, got {response:?}"
        );
    }

    {
        let state = handler.state.lock().await;
        let after_sessions = [&owner, &peer, &external]
            .into_iter()
            .map(|session_name| {
                state
                    .sessions
                    .session(session_name)
                    .expect("session survives rejected replacement")
                    .clone()
            })
            .collect::<Vec<_>>();
        assert_eq!(after_sessions, before_sessions);
        assert_eq!(
            state.window_linked_window_targets(&owner, 0),
            before_targets
        );
        assert_eq!(state.window_link_count(&owner, 0), 2);
        for target in [
            WindowTarget::with_window(owner.clone(), 0),
            WindowTarget::with_window(peer.clone(), 0),
            WindowTarget::with_window(external.clone(), 1),
        ] {
            assert_eq!(
                state
                    .sessions
                    .session(target.session_name())
                    .and_then(|session| session.window_at(target.window_index()))
                    .expect("all aliases survive rejected replacement")
                    .id(),
                stable_window_id
            );
        }
    }

    for target in [
        PaneTarget::with_window(owner, 0, 0),
        PaneTarget::with_window(peer, 0, 0),
        PaneTarget::with_window(external, 1, 0),
    ] {
        assert_send_keys_succeeds(&handler, target).await;
    }
}

#[tokio::test]
async fn link_window_k_between_distinct_grouped_window_ids_remains_supported() {
    let handler = RequestHandler::new();
    let owner = session_name("link-distinct-owner");
    let peer = session_name("link-distinct-peer");
    create_session(&handler, owner.as_str()).await;
    create_grouped_session(&handler, peer.as_str(), &owner).await;
    let created = handler
        .handle(Request::NewWindow(Box::new(NewWindowRequest {
            target: owner.clone(),
            name: None,
            detached: true,
            start_directory: None,
            environment: None,
            command: Some(quiet_window_test_command()),
            process_command: None,
            target_window_index: Some(1),
            insert_at_target: false,
        })))
        .await;
    assert!(matches!(created, Response::NewWindow(_)), "{created:?}");

    let source_window_id = {
        let state = handler.state.lock().await;
        let destination_window_id = state
            .sessions
            .session(&owner)
            .and_then(|session| session.window_at(0))
            .expect("destination window exists")
            .id();
        let source_window_id = state
            .sessions
            .session(&peer)
            .and_then(|session| session.window_at(1))
            .expect("grouped source window exists")
            .id();
        assert_ne!(source_window_id, destination_window_id);
        source_window_id
    };

    let response = handler
        .handle(Request::LinkWindow(LinkWindowRequest {
            source: WindowTarget::with_window(peer.clone(), 1),
            target: WindowTarget::with_window(owner.clone(), 0),
            after: false,
            before: false,
            kill_destination: true,
            detached: true,
        }))
        .await;
    assert!(
        matches!(response, Response::LinkWindow(_)),
        "distinct grouped WindowIds must remain replaceable, got {response:?}"
    );

    {
        let state = handler.state.lock().await;
        for target in [
            WindowTarget::with_window(owner.clone(), 0),
            WindowTarget::with_window(peer.clone(), 0),
            WindowTarget::with_window(owner.clone(), 1),
            WindowTarget::with_window(peer.clone(), 1),
        ] {
            assert_eq!(
                state
                    .sessions
                    .session(target.session_name())
                    .and_then(|session| session.window_at(target.window_index()))
                    .expect("linked grouped alias exists")
                    .id(),
                source_window_id
            );
            state
                .pane_profile_in_window(target.session_name(), target.window_index(), 0)
                .expect("linked grouped alias keeps runtime access");
        }
    }
    for target in [
        PaneTarget::with_window(owner.clone(), 0, 0),
        PaneTarget::with_window(peer.clone(), 0, 0),
        PaneTarget::with_window(owner, 1, 0),
        PaneTarget::with_window(peer, 1, 0),
    ] {
        assert_send_keys_succeeds(&handler, target).await;
    }
}

#[tokio::test]
async fn unlink_window_via_group_peer_refreshes_exact_family_and_removes_exact_timers() {
    let handler = RequestHandler::new();
    let monitor = handler
        .handle(Request::SetOption(SetOptionRequest {
            scope: ScopeSelector::Global,
            option: OptionName::MonitorSilence,
            value: "60".to_owned(),
            mode: SetOptionMode::Replace,
        }))
        .await;
    assert!(matches!(monitor, Response::SetOption(_)), "{monitor:?}");

    let owner = session_name("unlink-refresh-owner");
    let peer = session_name("unlink-refresh-peer");
    let external = session_name("unlink-refresh-external");
    create_session(&handler, owner.as_str()).await;
    create_grouped_session(&handler, peer.as_str(), &owner).await;
    create_session(&handler, external.as_str()).await;
    let created = handler
        .handle(Request::NewWindow(Box::new(NewWindowRequest {
            target: owner.clone(),
            name: None,
            detached: true,
            start_directory: None,
            environment: None,
            command: Some(quiet_window_test_command()),
            process_command: None,
            target_window_index: Some(1),
            insert_at_target: false,
        })))
        .await;
    assert!(matches!(created, Response::NewWindow(_)), "{created:?}");
    let linked = handler
        .handle(Request::LinkWindow(LinkWindowRequest {
            source: WindowTarget::with_window(owner.clone(), 0),
            target: WindowTarget::with_window(external.clone(), 1),
            after: false,
            before: false,
            kill_destination: false,
            detached: true,
        }))
        .await;
    assert!(matches!(linked, Response::LinkWindow(_)), "{linked:?}");

    let (control_tx, mut control_rx) = mpsc::unbounded_channel();
    handler.register_attach(43, owner.clone(), control_tx).await;
    drain_attach_controls(&mut control_rx).await;

    let removed_targets = [
        WindowTarget::with_window(owner.clone(), 0),
        WindowTarget::with_window(peer.clone(), 0),
    ];
    let preserved_targets = [
        WindowTarget::with_window(owner.clone(), 1),
        WindowTarget::with_window(peer.clone(), 1),
        WindowTarget::with_window(external.clone(), 0),
        WindowTarget::with_window(external.clone(), 1),
    ];
    for target in &removed_targets {
        assert!(
            handler.silence_timer_snapshot_for_test(target).is_some(),
            "removed alias starts with a silence timer: {target}"
        );
    }
    let preserved_timer_snapshots = preserved_targets
        .iter()
        .map(|target| handler.silence_timer_snapshot_for_test(target))
        .collect::<Vec<_>>();

    let response = handler
        .handle(Request::UnlinkWindow(UnlinkWindowRequest {
            target: WindowTarget::with_window(peer.clone(), 0),
            kill_if_last: false,
        }))
        .await;
    assert!(
        matches!(&response, Response::UnlinkWindow(result) if result.target == WindowTarget::with_window(peer.clone(), 1)),
        "expected grouped peer unlink success, got {response:?}"
    );

    let control = timeout(Duration::from_secs(2), control_rx.recv())
        .await
        .expect("non-syntactic owner attach must be refreshed after unlink-window")
        .expect("owner attach control channel remains open");
    let AttachControl::Switch(target) = control else {
        panic!("expected refreshed owner switch, got {control:?}");
    };
    let mut target = target.into_target();
    assert_eq!(target.session_name, owner);

    let output = {
        let state = handler.state.lock().await;
        assert!(state
            .sessions
            .session(&owner)
            .and_then(|session| session.window_at(0))
            .is_none());
        assert!(state
            .sessions
            .session(&peer)
            .and_then(|session| session.window_at(0))
            .is_none());
        assert!(
            state
                .sessions
                .session(&external)
                .and_then(|session| session.window_at(1))
                .is_some(),
            "external linked alias survives grouped peer unlink"
        );
        state
            .pane_output_for_target(&owner, 1, 0)
            .expect("owner survivor output exists")
            .clone()
    };
    let expected = b"unlink-peer-live-output".to_vec();
    output.send(expected.clone());
    assert_pane_output_observes(&mut target.pane_output, &expected).await;

    for target in &removed_targets {
        assert_eq!(
            handler.silence_timer_snapshot_for_test(target),
            None,
            "unlink-window removes the vanished alias timer: {target}"
        );
    }
    for (target, snapshot) in preserved_targets.iter().zip(preserved_timer_snapshots) {
        assert_eq!(
            handler.silence_timer_snapshot_for_test(target),
            snapshot,
            "unlink-window must not postpone surviving or unrelated timer {target}"
        );
    }
}

#[tokio::test]
async fn link_window_shares_runtime_tracks_linked_sessions_and_unlinks_cleanly() {
    let handler = RequestHandler::new();
    let alpha = session_name("alpha");
    let beta = session_name("beta");
    create_session(&handler, "alpha").await;
    create_session(&handler, "beta").await;

    let response = handler
        .handle(Request::LinkWindow(LinkWindowRequest {
            source: WindowTarget::with_window(alpha.clone(), 0),
            target: WindowTarget::with_window(beta.clone(), 1),
            after: false,
            before: false,
            kill_destination: false,
            detached: false,
        }))
        .await;

    assert!(
        matches!(&response, Response::LinkWindow(r) if r.target == WindowTarget::with_window(beta.clone(), 1)),
        "expected link-window success, got {response:?}"
    );

    {
        let state = handler.state.lock().await;
        let alpha_window = state
            .sessions
            .session(&alpha)
            .and_then(|session| session.window_at(0))
            .expect("alpha window 0 should exist");
        let beta_window = state
            .sessions
            .session(&beta)
            .and_then(|session| session.window_at(1))
            .expect("beta window 1 should exist");

        assert_eq!(alpha_window.id(), beta_window.id());
        assert_eq!(state.window_link_count(&alpha, 0), 2);
        assert_eq!(state.window_linked_session_count(&alpha, 0), 2);
        assert_eq!(
            state.window_linked_sessions_list(&alpha, 0),
            vec![alpha.clone(), beta.clone()]
        );
        assert!(
            state.pane_profile_in_window(&beta, 1, 0).is_ok(),
            "linked target should resolve pane runtime through the shared terminal owner"
        );
    }

    let linked_formats = handler
        .handle(Request::DisplayMessage(DisplayMessageRequest {
            target: Some(Target::Window(WindowTarget::with_window(alpha.clone(), 0))),
            print: true,
            message: Some(
                "#{window_linked}:#{window_linked_sessions}:#{window_linked_sessions_list}"
                    .to_owned(),
            ),
            empty_target_context: false,
        }))
        .await
        .command_output()
        .expect("window linked format output")
        .stdout()
        .to_vec();
    assert_eq!(String::from_utf8_lossy(&linked_formats), "1:2:alpha,beta\n");

    let rename = handler
        .handle(Request::RenameWindow(RenameWindowRequest {
            target: WindowTarget::with_window(beta.clone(), 1),
            name: "logs".to_owned(),
        }))
        .await;
    assert!(
        matches!(&rename, Response::RenameWindow(r) if r.target == WindowTarget::with_window(beta.clone(), 1)),
        "expected rename-window success, got {rename:?}"
    );

    {
        let state = handler.state.lock().await;
        let alpha_window = state
            .sessions
            .session(&alpha)
            .and_then(|session| session.window_at(0))
            .expect("alpha window 0 should exist after rename");
        let beta_window = state
            .sessions
            .session(&beta)
            .and_then(|session| session.window_at(1))
            .expect("beta window 1 should exist after rename");

        assert_eq!(alpha_window.name(), Some("logs"));
        assert_eq!(beta_window.name(), Some("logs"));
    }

    let unlink = handler
        .handle(Request::UnlinkWindow(UnlinkWindowRequest {
            target: WindowTarget::with_window(beta.clone(), 1),
            kill_if_last: false,
        }))
        .await;
    assert!(
        matches!(&unlink, Response::UnlinkWindow(r) if r.target == WindowTarget::with_window(beta.clone(), 0)),
        "expected unlink-window success, got {unlink:?}"
    );

    let state = handler.state.lock().await;
    assert_eq!(state.window_link_count(&alpha, 0), 1);
    assert_eq!(state.window_linked_session_count(&alpha, 0), 1);
    assert_eq!(
        state.window_linked_sessions_list(&alpha, 0),
        vec![alpha.clone()]
    );
    assert!(
        state
            .sessions
            .session(&beta)
            .and_then(|session| session.window_at(1))
            .is_none(),
        "unlink-window should remove the target slot from beta"
    );
    assert!(
        state.pane_profile_in_window(&beta, 1, 0).is_err(),
        "unlinked target slot should no longer resolve pane runtime"
    );
}

#[tokio::test]
async fn linked_session_formats_include_session_group_peers() {
    let handler = RequestHandler::new();
    let alpha = session_name("alpha");
    let gamma = session_name("gamma");
    create_session(&handler, "alpha").await;
    create_grouped_session(&handler, "beta", &alpha).await;
    create_session(&handler, "gamma").await;
    create_grouped_session(&handler, "delta", &gamma).await;

    let response = handler
        .handle(Request::LinkWindow(LinkWindowRequest {
            source: WindowTarget::with_window(alpha.clone(), 0),
            target: WindowTarget::with_window(gamma.clone(), 1),
            after: false,
            before: false,
            kill_destination: false,
            detached: false,
        }))
        .await;
    assert!(
        matches!(&response, Response::LinkWindow(r) if r.target == WindowTarget::with_window(gamma.clone(), 1)),
        "expected link-window success, got {response:?}"
    );

    let linked_formats = handler
        .handle(Request::DisplayMessage(DisplayMessageRequest {
            target: Some(Target::Window(WindowTarget::with_window(alpha.clone(), 0))),
            print: true,
            message: Some(
                "#{window_linked}:#{window_linked_sessions}:#{window_linked_sessions_list}"
                    .to_owned(),
            ),
            empty_target_context: false,
        }))
        .await
        .command_output()
        .expect("window linked format output")
        .stdout()
        .to_vec();

    assert_eq!(
        String::from_utf8_lossy(&linked_formats),
        "1:4:alpha,beta,gamma,delta\n"
    );
}

#[tokio::test]
async fn linked_windows_survive_runtime_owner_session_rename() {
    let handler = RequestHandler::new();
    let alpha = session_name("alpha");
    let beta = session_name("beta");
    let gamma = session_name("gamma");
    create_session(&handler, "alpha").await;
    create_session(&handler, "beta").await;

    assert!(matches!(
        handler
            .handle(Request::LinkWindow(LinkWindowRequest {
                source: WindowTarget::with_window(alpha.clone(), 0),
                target: WindowTarget::with_window(beta.clone(), 1),
                after: false,
                before: false,
                kill_destination: false,
                detached: false,
            }))
            .await,
        Response::LinkWindow(_)
    ));

    assert!(matches!(
        handler
            .handle(Request::RenameSession(RenameSessionRequest {
                target: alpha,
                new_name: gamma.clone(),
            }))
            .await,
        Response::RenameSession(_)
    ));

    {
        let state = handler.state.lock().await;
        assert_eq!(state.window_link_count(&gamma, 0), 2);
        assert_eq!(state.window_link_count(&beta, 1), 2);
        assert_eq!(
            state.window_linked_sessions_list(&beta, 1),
            vec![gamma.clone(), beta.clone()]
        );
        assert!(
            state.pane_profile_in_window(&beta, 1, 0).is_ok(),
            "linked target should still resolve through renamed runtime owner"
        );
    }

    let list = handler
        .handle(Request::ListPanes(Box::new(ListPanesRequest {
            target: beta,
            target_window_index: Some(1),
            format: Some("#{session_name}:#{window_index}:#{pane_index}".to_owned()),
            filter: None,
            sort_order: None,
            reversed: false,
        })))
        .await;
    let Response::ListPanes(list) = list else {
        panic!("linked list-panes should survive owner rename, got {list:?}");
    };
    assert_eq!(String::from_utf8_lossy(list.output.stdout()), "beta:1:0\n");
}

#[tokio::test]
async fn link_window_relative_same_destination_slot_makes_room_like_tmux() {
    let handler = RequestHandler::new();
    let alpha = session_name("alpha");
    create_session(&handler, "alpha").await;
    insert_window(&handler, &alpha, 1).await;
    insert_window(&handler, &alpha, 2).await;

    let source_pane_id = {
        let state = handler.state.lock().await;
        state
            .sessions
            .session(&alpha)
            .expect("alpha should exist")
            .pane_id_in_window(1, 0)
            .expect("source pane should exist")
    };

    let response = handler
        .handle(Request::LinkWindow(LinkWindowRequest {
            source: WindowTarget::with_window(alpha.clone(), 1),
            target: WindowTarget::with_window(alpha.clone(), 0),
            after: true,
            before: false,
            kill_destination: false,
            detached: false,
        }))
        .await;

    assert_eq!(
        response,
        Response::LinkWindow(rmux_proto::LinkWindowResponse {
            target: WindowTarget::with_window(alpha.clone(), 1),
        })
    );

    let state = handler.state.lock().await;
    let session = state.sessions.session(&alpha).expect("alpha should exist");
    assert_eq!(
        session.windows().keys().copied().collect::<Vec<_>>(),
        vec![0, 1, 2, 3]
    );
    assert_eq!(session.pane_id_in_window(1, 0), Some(source_pane_id));
    assert_eq!(session.pane_id_in_window(2, 0), Some(source_pane_id));
    assert_eq!(state.window_link_count(&alpha, 1), 2);
    assert_eq!(state.window_link_count(&alpha, 2), 2);
}

#[tokio::test]
async fn linked_windows_survive_runtime_owner_session_removal_after_rename() {
    let handler = RequestHandler::new();
    let alpha = session_name("alpha");
    let beta = session_name("beta");
    let gamma = session_name("gamma");
    create_session(&handler, "alpha").await;
    create_session(&handler, "beta").await;

    assert!(matches!(
        handler
            .handle(Request::LinkWindow(LinkWindowRequest {
                source: WindowTarget::with_window(alpha.clone(), 0),
                target: WindowTarget::with_window(beta.clone(), 1),
                after: false,
                before: false,
                kill_destination: false,
                detached: false,
            }))
            .await,
        Response::LinkWindow(_)
    ));
    assert!(matches!(
        handler
            .handle(Request::RenameSession(RenameSessionRequest {
                target: alpha,
                new_name: gamma.clone(),
            }))
            .await,
        Response::RenameSession(_)
    ));

    let kill = handler
        .handle(Request::KillSession(KillSessionRequest {
            target: gamma.clone(),
            kill_all_except_target: false,
            clear_alerts: false,
            kill_group: false,
        }))
        .await;
    assert!(
        matches!(kill, Response::KillSession(_)),
        "expected kill-session success, got {kill:?}"
    );

    {
        let state = handler.state.lock().await;
        assert!(
            state.sessions.session(&gamma).is_none(),
            "runtime owner session should be removed"
        );
        assert_eq!(state.window_link_count(&beta, 1), 1);
        assert_eq!(
            state.window_linked_sessions_list(&beta, 1),
            vec![beta.clone()]
        );
        assert!(
            state.pane_profile_in_window(&beta, 1, 0).is_ok(),
            "surviving linked target should adopt the removed owner's pane runtime"
        );
    }

    let list = handler
        .handle(Request::ListPanes(Box::new(ListPanesRequest {
            target: beta,
            target_window_index: Some(1),
            format: Some("#{session_name}:#{window_index}:#{pane_index}".to_owned()),
            filter: None,
            sort_order: None,
            reversed: false,
        })))
        .await;
    let Response::ListPanes(list) = list else {
        panic!("linked list-panes should survive owner removal, got {list:?}");
    };
    assert_eq!(String::from_utf8_lossy(list.output.stdout()), "beta:1:0\n");
}

#[tokio::test]
async fn unlink_window_runtime_owner_transfers_runtime_to_surviving_alias() {
    let handler = RequestHandler::new();
    let owner = session_name("unlink-runtime-owner");
    let external = session_name("unlink-runtime-external");
    create_session(&handler, owner.as_str()).await;
    insert_window(&handler, &owner, 1).await;
    create_session(&handler, external.as_str()).await;

    let linked = handler
        .handle(Request::LinkWindow(LinkWindowRequest {
            source: WindowTarget::with_window(owner.clone(), 0),
            target: WindowTarget::with_window(external.clone(), 1),
            after: false,
            before: false,
            kill_destination: false,
            detached: true,
        }))
        .await;
    assert!(matches!(linked, Response::LinkWindow(_)), "{linked:?}");

    let unlinked = handler
        .handle(Request::UnlinkWindow(UnlinkWindowRequest {
            target: WindowTarget::with_window(owner.clone(), 0),
            kill_if_last: false,
        }))
        .await;
    assert!(
        matches!(unlinked, Response::UnlinkWindow(_)),
        "{unlinked:?}"
    );

    {
        let state = handler.state.lock().await;
        assert_eq!(state.window_link_count(&external, 1), 1);
        state
            .pane_profile_in_window(&external, 1, 0)
            .expect("surviving external alias adopts the detached owner's runtime");
        state
            .pane_profile_in_window(&owner, 1, 0)
            .expect("the owner's unrelated window keeps its runtime");
    }
    assert_send_keys_succeeds(&handler, PaneTarget::with_window(external, 1, 0)).await;
}

#[tokio::test]
async fn link_window_k_runtime_owner_transfers_replaced_runtime_to_surviving_alias() {
    let handler = RequestHandler::new();
    let owner = session_name("link-k-runtime-owner");
    let external = session_name("link-k-runtime-external");
    let replacement = session_name("link-k-runtime-replacement");
    create_session(&handler, owner.as_str()).await;
    insert_window(&handler, &owner, 1).await;
    create_session(&handler, external.as_str()).await;
    create_session(&handler, replacement.as_str()).await;

    let linked = handler
        .handle(Request::LinkWindow(LinkWindowRequest {
            source: WindowTarget::with_window(owner.clone(), 0),
            target: WindowTarget::with_window(external.clone(), 1),
            after: false,
            before: false,
            kill_destination: false,
            detached: true,
        }))
        .await;
    assert!(matches!(linked, Response::LinkWindow(_)), "{linked:?}");

    let replaced = handler
        .handle(Request::LinkWindow(LinkWindowRequest {
            source: WindowTarget::with_window(replacement.clone(), 0),
            target: WindowTarget::with_window(owner.clone(), 0),
            after: false,
            before: false,
            kill_destination: true,
            detached: true,
        }))
        .await;
    assert!(matches!(replaced, Response::LinkWindow(_)), "{replaced:?}");

    {
        let state = handler.state.lock().await;
        assert_eq!(state.window_link_count(&external, 1), 1);
        state
            .pane_profile_in_window(&external, 1, 0)
            .expect("surviving alias adopts the replaced runtime");
        state
            .pane_profile_in_window(&owner, 0, 0)
            .expect("replacement target resolves its new linked runtime");
    }
    assert_send_keys_succeeds(&handler, PaneTarget::with_window(external, 1, 0)).await;
    assert_send_keys_succeeds(&handler, PaneTarget::with_window(owner, 0, 0)).await;
}

#[tokio::test]
async fn killing_grouped_runtime_owner_preserves_external_linked_alias() {
    let handler = RequestHandler::new();
    let owner = session_name("group-kill-runtime-owner");
    let peer = session_name("group-kill-runtime-peer");
    let external = session_name("group-kill-runtime-external");
    create_session(&handler, owner.as_str()).await;
    create_grouped_session(&handler, peer.as_str(), &owner).await;
    create_session(&handler, external.as_str()).await;

    let linked = handler
        .handle(Request::LinkWindow(LinkWindowRequest {
            source: WindowTarget::with_window(owner.clone(), 0),
            target: WindowTarget::with_window(external.clone(), 1),
            after: false,
            before: false,
            kill_destination: false,
            detached: true,
        }))
        .await;
    assert!(matches!(linked, Response::LinkWindow(_)), "{linked:?}");

    let killed = handler
        .handle(Request::KillSession(KillSessionRequest {
            target: owner.clone(),
            kill_all_except_target: false,
            clear_alerts: false,
            kill_group: false,
        }))
        .await;
    assert!(matches!(killed, Response::KillSession(_)), "{killed:?}");

    {
        let state = handler.state.lock().await;
        assert!(state.sessions.session(&owner).is_none());
        assert_eq!(state.window_link_count(&peer, 0), 2);
        assert_eq!(state.window_link_count(&external, 1), 2);
        assert_eq!(
            state.window_linked_sessions_list(&external, 1),
            vec![peer.clone(), external.clone()],
            "external alias metadata must be rekeyed from the removed owner to its peer"
        );
        state
            .pane_profile_in_window(&peer, 0, 0)
            .expect("group peer keeps the transferred runtime");
        state
            .pane_profile_in_window(&external, 1, 0)
            .expect("external alias follows the transferred group runtime");
    }
    assert_send_keys_succeeds(&handler, PaneTarget::with_window(peer, 0, 0)).await;
    assert_send_keys_succeeds(&handler, PaneTarget::with_window(external, 1, 0)).await;
}

#[tokio::test]
async fn link_window_shares_pane_base_index_with_linked_slots() {
    let handler = RequestHandler::new();
    let alpha = session_name("alpha");
    let beta = session_name("beta");
    create_session(&handler, "alpha").await;
    create_session(&handler, "beta").await;

    assert!(matches!(
        handler
            .handle(Request::SplitWindow(SplitWindowRequest {
                target: SplitWindowTarget::Session(alpha.clone()),
                direction: SplitDirection::Vertical,
                before: false,
                environment: None,
            }))
            .await,
        Response::SplitWindow(_)
    ));
    assert!(matches!(
        handler
            .handle(Request::SetOption(SetOptionRequest {
                scope: ScopeSelector::Window(WindowTarget::with_window(alpha.clone(), 0)),
                option: OptionName::PaneBaseIndex,
                value: "1".to_owned(),
                mode: SetOptionMode::Replace,
            }))
            .await,
        Response::SetOption(_)
    ));
    assert!(matches!(
        handler
            .handle(Request::LinkWindow(LinkWindowRequest {
                source: WindowTarget::with_window(alpha.clone(), 0),
                target: WindowTarget::with_window(beta.clone(), 1),
                after: false,
                before: false,
                kill_destination: false,
                detached: false,
            }))
            .await,
        Response::LinkWindow(_)
    ));

    let list = handler
        .handle(Request::ListPanes(Box::new(ListPanesRequest {
            target: beta.clone(),
            target_window_index: Some(1),
            format: Some("#{pane_index}".to_owned()),
            filter: None,
            sort_order: None,
            reversed: false,
        })))
        .await;
    let Response::ListPanes(list) = list else {
        panic!("linked list-panes should succeed, got {list:?}");
    };
    assert_eq!(
        String::from_utf8_lossy(list.output.stdout()),
        "1\n2\n",
        "linked windows should render the source pane-base-index"
    );

    let resolved = handler
        .handle(Request::ResolveTarget(ResolveTargetRequest {
            target: Some("beta:1.1".to_owned()),
            target_type: ResolveTargetType::Pane,
            window_index: false,
            prefer_unattached: false,
        }))
        .await;
    let Response::ResolveTarget(resolved) = resolved else {
        panic!("linked visible pane target should resolve, got {resolved:?}");
    };
    assert_eq!(
        resolved.target,
        Target::Pane(PaneTarget::with_window(beta, 1, 0))
    );
}

#[tokio::test]
async fn linked_window_id_resolution_prefers_current_session_slot() {
    let handler = RequestHandler::new();
    let alpha = session_name("alpha");
    let beta = session_name("beta");
    create_session(&handler, "alpha").await;
    create_session(&handler, "beta").await;

    assert!(matches!(
        handler
            .handle(Request::LinkWindow(LinkWindowRequest {
                source: WindowTarget::with_window(alpha.clone(), 0),
                target: WindowTarget::with_window(beta.clone(), 1),
                after: false,
                before: false,
                kill_destination: false,
                detached: true,
            }))
            .await,
        Response::LinkWindow(_)
    ));

    let window_id = {
        let state = handler.state.lock().await;
        state
            .sessions
            .session(&alpha)
            .and_then(|session| session.window_at(0))
            .expect("linked source window exists")
            .id()
            .to_string()
    };

    let resolved = handler
        .handle(Request::ResolveTarget(ResolveTargetRequest {
            target: Some(window_id),
            target_type: ResolveTargetType::Window,
            window_index: false,
            prefer_unattached: false,
        }))
        .await;
    let Response::ResolveTarget(resolved) = resolved else {
        panic!("linked window id should resolve through preferred session, got {resolved:?}");
    };
    assert_eq!(
        resolved.target,
        Target::Window(WindowTarget::with_window(beta, 1))
    );
}

#[tokio::test]
async fn unlink_window_kill_if_last_deletes_an_unshared_window_slot() {
    let handler = RequestHandler::new();
    let alpha = session_name("alpha");
    create_session(&handler, "alpha").await;
    insert_window(&handler, &alpha, 1).await;

    let response = handler
        .handle(Request::UnlinkWindow(UnlinkWindowRequest {
            target: WindowTarget::with_window(alpha.clone(), 1),
            kill_if_last: true,
        }))
        .await;

    assert!(
        matches!(&response, Response::UnlinkWindow(r) if r.target == WindowTarget::with_window(alpha.clone(), 0)),
        "expected unlink-window -k to remove the unshared slot, got {response:?}"
    );

    let state = handler.state.lock().await;
    let session = state.sessions.session(&alpha).expect("alpha should exist");
    assert!(
        session.window_at(1).is_none(),
        "unlink-window -k should delete the unshared destination window"
    );
    assert_eq!(session.active_window_index(), 0);
}

#[tokio::test]
async fn unlink_only_linked_window_destroys_the_empty_session() {
    // Frozen tmux 3.7b, measured on 2026-07-26: unlinking a session's only
    // window removes that session when the window survives through another
    // link.
    let handler = RequestHandler::new();
    let owner = session_name("unlink-only-window-owner");
    let alias = session_name("unlink-only-window-alias");
    create_session(&handler, owner.as_str()).await;
    create_session(&handler, alias.as_str()).await;

    assert!(matches!(
        handler
            .handle(Request::LinkWindow(LinkWindowRequest {
                source: WindowTarget::with_window(owner.clone(), 0),
                target: WindowTarget::with_window(alias.clone(), 9),
                after: false,
                before: false,
                kill_destination: false,
                detached: true,
            }))
            .await,
        Response::LinkWindow(_)
    ));
    assert!(matches!(
        handler
            .handle(Request::KillWindow(KillWindowRequest {
                target: WindowTarget::with_window(alias.clone(), 0),
                kill_all_others: false,
            }))
            .await,
        Response::KillWindow(_)
    ));

    let response = handler
        .handle(Request::UnlinkWindow(UnlinkWindowRequest {
            target: WindowTarget::with_window(alias.clone(), 9),
            kill_if_last: false,
        }))
        .await;
    assert!(
        matches!(response, Response::UnlinkWindow(_)),
        "{response:?}"
    );

    let state = handler.state.lock().await;
    assert!(
        state.sessions.session(&alias).is_none(),
        "the empty alias session must be destroyed"
    );
    assert!(
        state
            .sessions
            .session(&owner)
            .and_then(|session| session.window_at(0))
            .is_some(),
        "the linked owner window must survive"
    );
}

#[tokio::test]
async fn unlink_only_linked_window_preserves_a_concurrently_added_window() {
    let handler = std::sync::Arc::new(RequestHandler::new());
    let owner = session_name("unlink-race-owner");
    let alias = session_name("unlink-race-alias");
    create_session(&handler, owner.as_str()).await;
    create_session(&handler, alias.as_str()).await;

    let linked = handler
        .handle(Request::LinkWindow(LinkWindowRequest {
            source: WindowTarget::with_window(owner.clone(), 0),
            target: WindowTarget::with_window(alias.clone(), 9),
            after: false,
            before: false,
            kill_destination: false,
            detached: true,
        }))
        .await;
    assert!(matches!(linked, Response::LinkWindow(_)), "{linked:?}");
    let killed = handler
        .handle(Request::KillWindow(KillWindowRequest {
            target: WindowTarget::with_window(alias.clone(), 0),
            kill_all_others: false,
        }))
        .await;
    assert!(matches!(killed, Response::KillWindow(_)), "{killed:?}");

    let pause = handler.install_kill_session_selection_identity_pause(alias.clone());
    let unlink_handler = std::sync::Arc::clone(&handler);
    let unlink_alias = alias.clone();
    let unlinking = tokio::spawn(async move {
        unlink_handler
            .handle(Request::UnlinkWindow(UnlinkWindowRequest {
                target: WindowTarget::with_window(unlink_alias, 9),
                kill_if_last: false,
            }))
            .await
    });
    timeout(Duration::from_secs(1), pause.reached.notified())
        .await
        .expect("conditional session removal reaches the identity pause");

    let created = handler
        .handle(Request::NewWindow(Box::new(NewWindowRequest {
            target: alias.clone(),
            name: None,
            detached: true,
            start_directory: None,
            environment: None,
            command: Some(quiet_window_test_command()),
            process_command: None,
            target_window_index: Some(10),
            insert_at_target: false,
        })))
        .await;
    assert!(matches!(created, Response::NewWindow(_)), "{created:?}");
    pause.release.notify_one();

    let unlinked = timeout(Duration::from_secs(2), unlinking)
        .await
        .expect("unlink-window must finish")
        .expect("unlink-window task joins");
    assert!(
        matches!(unlinked, Response::UnlinkWindow(_)),
        "{unlinked:?}"
    );

    let state = handler.state.lock().await;
    let alias_session = state
        .sessions
        .session(&alias)
        .expect("the concurrently extended session survives");
    assert!(alias_session.window_at(9).is_none());
    assert!(alias_session.window_at(10).is_some());
    assert!(
        state
            .sessions
            .session(&owner)
            .and_then(|session| session.window_at(0))
            .is_some(),
        "the linked owner window survives"
    );
}

#[tokio::test]
async fn unlink_window_kill_if_last_rekeys_renumbered_silence_timers_without_delay() {
    let handler = RequestHandler::new();
    let alpha = session_name("unlink-renumber-timers");
    let unrelated = session_name("unlink-renumber-unrelated");
    create_session(&handler, alpha.as_str()).await;
    insert_window(&handler, &alpha, 1).await;
    insert_window(&handler, &alpha, 2).await;
    create_session(&handler, unrelated.as_str()).await;

    let response = handler
        .handle(Request::SetOption(SetOptionRequest {
            scope: ScopeSelector::Session(alpha.clone()),
            option: OptionName::RenumberWindows,
            value: "on".to_owned(),
            mode: SetOptionMode::Replace,
        }))
        .await;
    assert!(matches!(response, Response::SetOption(_)), "{response:?}");
    let response = handler
        .handle(Request::SetOption(SetOptionRequest {
            scope: ScopeSelector::Global,
            option: OptionName::MonitorSilence,
            value: "60".to_owned(),
            mode: SetOptionMode::Replace,
        }))
        .await;
    assert!(matches!(response, Response::SetOption(_)), "{response:?}");

    let targets = [
        WindowTarget::with_window(alpha.clone(), 0),
        WindowTarget::with_window(alpha.clone(), 1),
        WindowTarget::with_window(alpha.clone(), 2),
    ];
    let snapshots = targets.clone().map(|target| {
        handler
            .silence_timer_snapshot_for_test(&target)
            .expect("each window starts with an armed silence timer")
    });
    let unrelated_target = WindowTarget::with_window(unrelated, 0);
    let unrelated_snapshot = handler
        .silence_timer_snapshot_for_test(&unrelated_target)
        .expect("unrelated session timer starts armed");
    let surviving_window_ids = {
        let state = handler.state.lock().await;
        let session = state.sessions.session(&alpha).expect("alpha exists");
        [
            session.window_at(1).expect("window one exists").id(),
            session.window_at(2).expect("window two exists").id(),
        ]
    };

    let response = handler
        .handle(Request::UnlinkWindow(UnlinkWindowRequest {
            target: targets[0].clone(),
            kill_if_last: true,
        }))
        .await;
    assert!(
        matches!(&response, Response::UnlinkWindow(result) if result.target == WindowTarget::with_window(alpha.clone(), 1)),
        "expected unlink-window -k success with renumbering, got {response:?}"
    );

    {
        let state = handler.state.lock().await;
        let session = state.sessions.session(&alpha).expect("alpha survives");
        assert_eq!(
            session.window_at(0).expect("old window one moved").id(),
            surviving_window_ids[0]
        );
        assert_eq!(
            session.window_at(1).expect("old window two moved").id(),
            surviving_window_ids[1]
        );
        assert!(session.window_at(2).is_none());
    }
    assert_eq!(
        handler
            .silence_timer_snapshot_for_test(&targets[0])
            .expect("old window one timer moved to zero")
            .1,
        snapshots[1].1,
        "renumbering must preserve old window one's absolute silence deadline"
    );
    assert_eq!(
        handler
            .silence_timer_snapshot_for_test(&targets[1])
            .expect("old window two timer moved to one")
            .1,
        snapshots[2].1,
        "renumbering must preserve old window two's absolute silence deadline"
    );
    assert_eq!(
        handler.silence_timer_snapshot_for_test(&targets[2]),
        None,
        "the stale pre-renumber timer key must be removed"
    );
    assert_eq!(
        handler.silence_timer_snapshot_for_test(&unrelated_target),
        Some(unrelated_snapshot),
        "unrelated session timer must remain untouched"
    );
}

#[tokio::test]
async fn unlink_window_restores_previous_last_window_flag_after_active_link_removal() {
    let handler = RequestHandler::new();
    let alpha = session_name("alpha");
    create_session(&handler, "alpha").await;
    insert_window(&handler, &alpha, 1).await;
    insert_window(&handler, &alpha, 2).await;

    assert!(matches!(
        handler
            .handle(Request::SelectWindow(SelectWindowRequest {
                target: WindowTarget::with_window(alpha.clone(), 1),
            }))
            .await,
        Response::SelectWindow(_)
    ));
    assert!(matches!(
        handler
            .handle(Request::SelectWindow(SelectWindowRequest {
                target: WindowTarget::with_window(alpha.clone(), 0),
            }))
            .await,
        Response::SelectWindow(_)
    ));

    assert!(matches!(
        handler
            .handle(Request::LinkWindow(LinkWindowRequest {
                source: WindowTarget::with_window(alpha.clone(), 0),
                target: WindowTarget::with_window(alpha.clone(), 9),
                after: false,
                before: false,
                kill_destination: false,
                detached: false,
            }))
            .await,
        Response::LinkWindow(_)
    ));
    {
        let state = handler.state.lock().await;
        assert_eq!(state.window_link_count(&alpha, 0), 2);
        assert_eq!(state.window_linked_session_count(&alpha, 0), 1);
        assert_eq!(
            state.window_linked_sessions_list(&alpha, 0),
            vec![alpha.clone()]
        );
    }
    assert!(matches!(
        handler
            .handle(Request::UnlinkWindow(UnlinkWindowRequest {
                target: WindowTarget::with_window(alpha.clone(), 9),
                kill_if_last: true,
            }))
            .await,
        Response::UnlinkWindow(_)
    ));

    let state = handler.state.lock().await;
    let session = state.sessions.session(&alpha).expect("alpha should exist");
    assert_eq!(session.active_window_index(), 0);
    assert_eq!(session.last_window_index(), Some(1));
}