libtmux 0.1.0-alpha.13

Async typed tmux client and object model (alpha)
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
//! Public Server, capability, command-result, and lifecycle contracts.

// Helpers outside a test function are not covered by clippy.toml's
// in-test exemptions, and these files have them.
#![allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)]

use std::collections::hash_map::DefaultHasher;
use std::error::Error as StdError;
use std::ffi::{OsStr, OsString};
use std::fs;
use std::hash::{Hash, Hasher};
use std::io::Write as _;
use std::os::unix::ffi::OsStringExt;
use std::os::unix::fs::{PermissionsExt, symlink};
use std::path::{Path, PathBuf};
use std::process;
use std::time::{Duration, Instant};

#[cfg(feature = "test-support")]
use libtmux::ChannelWait;
#[cfg(feature = "test-support")]
use libtmux::test::scaled;
use libtmux::{
    Command, CommandResult, EngineCapabilities, Error, Server, ServerBuilder,
    ServerConfigurationErrorKind, ServerIdentity,
};
use rustix::io::Errno;
use rustix::process::{Pid, test_kill_process};
use static_assertions::{assert_impl_all, assert_not_impl_any};

assert_impl_all!(Server: Clone, std::fmt::Debug, Eq, Hash, Send, Sync);
assert_impl_all!(ServerBuilder: Send, Sync);
assert_impl_all!(ServerIdentity: Send, Sync);
assert_impl_all!(Command: Send, Sync);
assert_impl_all!(CommandResult: std::fmt::Debug, Send, Sync);
assert_not_impl_any!(CommandResult: std::fmt::Display);
assert_impl_all!(EngineCapabilities: Send, Sync);
assert_impl_all!(ServerConfigurationErrorKind: Clone, Copy, std::fmt::Debug, Eq, Send, Sync);

fn hash(value: &Server) -> u64 {
    let mut hasher = DefaultHasher::new();
    value.hash(&mut hasher);
    hasher.finish()
}

fn write_script(directory: &Path, name: &str, body: &str) -> PathBuf {
    let path = directory.join(name);
    let staging = directory.join(format!(".{name}.{}.tmp", process::id()));
    let mut file = fs::File::create(&staging).expect("staged script is creatable");
    file.write_all(
        format!(
            "#!/bin/sh\nif [ \"${{1-}}\" = __libtmux_fixture_ready__ ]; then\n    exit 0\nfi\nset -eu\n{body}\n"
        )
        .as_bytes(),
    )
    .expect("script is writable");
    file.sync_all().expect("script contents are durable");
    drop(file);
    let mut permissions = fs::metadata(&staging)
        .expect("script metadata is readable")
        .permissions();
    permissions.set_mode(0o700);
    fs::set_permissions(&staging, permissions).expect("staged script is executable");
    fs::rename(&staging, &path).expect("staged script is installed atomically");

    let deadline = Instant::now() + Duration::from_secs(5);
    loop {
        match process::Command::new(&path)
            .arg("__libtmux_fixture_ready__")
            .status()
        {
            Ok(status) => {
                assert!(
                    status.success(),
                    "script readiness probe exited with {status}"
                );
                break;
            }
            Err(source) => {
                assert_eq!(
                    source.raw_os_error(),
                    Some(Errno::TXTBSY.raw_os_error()),
                    "script readiness probe failed"
                );
                assert!(
                    Instant::now() < deadline,
                    "script remained busy past the readiness deadline"
                );
                std::thread::yield_now();
            }
        }
    }
    path
}

fn shell_quote(path: &Path) -> String {
    let value = path.to_string_lossy();
    format!("'{}'", value.replace('\'', "'\"'\"'"))
}

fn fake_server(executable: &Path, socket: &Path) -> Server {
    Server::builder()
        .tmux_executable(executable)
        .socket_path(socket)
        .build()
        .expect("fake server configuration is valid")
}

fn pid(value: u32) -> Pid {
    Pid::from_raw(i32::try_from(value).expect("test PID fits i32")).expect("test PID is nonzero")
}

async fn read_pids(
    path: &Path,
    count: usize,
    dispatch: &mut tokio::task::JoinHandle<Result<CommandResult, Error>>,
) -> Vec<u32> {
    let outcome = tokio::time::timeout(Duration::from_secs(5), async {
        loop {
            if let Ok(value) = fs::read_to_string(path) {
                let pids = value
                    .lines()
                    .filter_map(|line| line.parse::<u32>().ok())
                    .collect::<Vec<_>>();
                if pids.len() == count {
                    return Ok(pids);
                }
            }
            tokio::select! {
                result = &mut *dispatch => return Err(result),
                () = tokio::task::yield_now() => {}
            }
        }
    })
    .await
    .expect("child publishes its PIDs before the readiness deadline");
    outcome.expect("dispatch remains active until its child publishes readiness")
}

async fn read_pid(
    path: &Path,
    dispatch: &mut tokio::task::JoinHandle<Result<CommandResult, Error>>,
) -> u32 {
    read_pids(path, 1, dispatch).await[0]
}

async fn assert_process_gone(value: u32) {
    tokio::time::timeout(Duration::from_secs(5), async {
        loop {
            if matches!(test_kill_process(pid(value)), Err(Errno::SRCH)) {
                return;
            }
            tokio::task::yield_now().await;
        }
    })
    .await
    .expect("child is gone after terminal cleanup");
}

fn assert_configuration_error(
    error: &Error,
    expected: ServerConfigurationErrorKind,
    secrets: &[&str],
) {
    assert!(matches!(
        error,
        Error::InvalidServerConfiguration { kind, .. } if *kind == expected
    ));
    assert!(StdError::source(error).is_none());
    for diagnostic in [error.to_string(), format!("{error:?}")] {
        for secret in secrets {
            assert!(
                !diagnostic.contains(secret),
                "leaked {secret:?} in {diagnostic:?}"
            );
        }
    }
}

fn assert_error_path_safe(error: &Error, secret: &str) {
    let mut source: Option<&dyn StdError> = Some(error);
    while let Some(current) = source {
        assert!(!current.to_string().contains(secret));
        assert!(!format!("{current:?}").contains(secret));
        source = current.source();
    }
}

struct RealTmuxGuard {
    socket: PathBuf,
}

impl Drop for RealTmuxGuard {
    fn drop(&mut self) {
        drop(
            process::Command::new("tmux")
                .arg("-S")
                .arg(&self.socket)
                .arg("kill-server")
                .stdout(process::Stdio::null())
                .stderr(process::Stdio::null())
                .status(),
        );
    }
}

#[test]
fn construction_exposes_immutable_configuration_and_structural_identity() {
    let directory = tempfile::tempdir().expect("temporary directory");
    let socket = directory.path().join("server.sock");
    let config = directory.path().join("tmux.conf");
    let timeout = Duration::from_secs(7);

    let left = Server::builder()
        .socket_path(&socket)
        .config_file(&config)
        .colors(256)
        .tmux_executable("tmux")
        .default_timeout(timeout)
        .build()
        .expect("valid server configuration");
    let right = Server::builder()
        .socket_path(&socket)
        .default_timeout(Duration::from_secs(1))
        .build()
        .expect("same endpoint is valid");

    assert_eq!(left, right);
    assert_eq!(hash(&left), hash(&right));
    assert_eq!(left.identity(), right.identity());
    assert_eq!(left.socket_path(), socket);
    assert_eq!(left.socket_name(), None);
    assert_eq!(left.config_file(), Some(config.as_path()));
    assert_eq!(left.colors(), Some(256));
    assert_eq!(left.tmux_executable(), OsStr::new("tmux"));
    assert_eq!(left.default_timeout(), timeout);
}

#[test]
fn builder_rejects_conflicting_selectors_and_invalid_colors_before_execution() {
    let conflict = Server::builder()
        .socket_name("sentinel-name")
        .socket_path("/tmp/sentinel-explicit")
        .build()
        .expect_err("selectors conflict");
    assert_configuration_error(
        &conflict,
        ServerConfigurationErrorKind::ConflictingSocketSelectors,
        &["sentinel-name", "sentinel-explicit"],
    );

    let invalid_name = Server::builder()
        .socket_name("../sentinel-name")
        .build()
        .expect_err("socket name is not one component");
    assert_configuration_error(
        &invalid_name,
        ServerConfigurationErrorKind::InvalidSocketName,
        &["sentinel-name"],
    );

    let invalid_path = Server::builder()
        .socket_path(PathBuf::from(OsString::from_vec(
            b"/tmp/sentinel-path\0tail".to_vec(),
        )))
        .build()
        .expect_err("socket path contains NUL");
    assert_configuration_error(
        &invalid_path,
        ServerConfigurationErrorKind::InvalidSocketPath,
        &["sentinel-path"],
    );

    let invalid_config = Server::builder()
        .config_file(PathBuf::from(OsString::from_vec(
            b"/tmp/sentinel-config\0tail".to_vec(),
        )))
        .build()
        .expect_err("config path contains NUL");
    assert_configuration_error(
        &invalid_config,
        ServerConfigurationErrorKind::InvalidConfigPath,
        &["sentinel-config"],
    );

    for colors in [16, 88] {
        let invalid_colors = Server::builder()
            .colors(colors)
            .tmux_executable("/nonexistent/tmux")
            .build()
            .expect_err("only supported tmux color modes are accepted");
        assert_configuration_error(
            &invalid_colors,
            ServerConfigurationErrorKind::InvalidColorMode,
            &[],
        );
    }
}

#[test]
fn default_named_and_explicit_socket_selection_are_distinct() {
    let default = Server::new().expect("default server configuration");
    let named = Server::builder()
        .socket_name("libtmux-task-seven")
        .build()
        .expect("named server configuration");
    let explicit = Server::builder()
        .socket_path("relative.sock")
        .build()
        .expect("relative explicit path is captured");

    assert_eq!(default.socket_name(), None);
    assert!(default.socket_path().is_absolute());
    assert_eq!(named.socket_name(), Some(OsStr::new("libtmux-task-seven")));
    assert!(explicit.socket_path().is_absolute());
    assert_ne!(named, explicit);
}

#[test]
fn server_debug_redacts_socket_config_and_executable_paths() {
    let server = Server::builder()
        .socket_path("/tmp/sentinel-socket/server")
        .config_file("/tmp/sentinel-config/tmux.conf")
        .tmux_executable("/tmp/sentinel-executable/tmux")
        .build()
        .expect("configuration paths need not exist at construction");
    let diagnostic = format!("{server:?}");

    for secret in ["sentinel-socket", "sentinel-config", "sentinel-executable"] {
        assert!(!diagnostic.contains(secret));
    }
}

#[tokio::test]
async fn public_capability_raw_command_and_shutdown_boundary_is_usable() {
    let directory = tempfile::tempdir().expect("temporary directory");
    let server = Server::builder()
        .socket_path(directory.path().join("absent.sock"))
        .build()
        .expect("an absent explicit socket is valid setup");

    let capabilities = server
        .capabilities()
        .await
        .expect("installed tmux is supported");
    assert!(!capabilities.tmux_version().raw().is_empty());

    let result = server
        .cmd(Command::new("list-sessions"))
        .await
        .expect("ordinary nonzero tmux status remains result data");
    assert_ne!(result.exit_code(), Some(0));
    assert_eq!(result.command().to_string(), r#""list-sessions""#);
    assert!(result.request_id() > 0);

    server.shutdown().await.expect("shutdown succeeds");
    server.shutdown().await.expect("shutdown is idempotent");
}

/// tmux creates the parent directory of `-L`/the default socket itself, but
/// never one a `-S` path names, and it answers three different ways:
/// 3.2a exits **0** saying nothing at all, 3.3a through 3.7c exit **0** after
/// printing `error creating <path> (No such file or directory)` on stderr, and
/// next-3.9 prints that and exits **1**. Nothing is created in any of them, so
/// none may read as a partial effect, and tmux's own reason -- when it gave one
/// -- must not be replaced by a generic message or a `Debug`-formatted exit
/// code.
#[tokio::test]
async fn a_missing_socket_directory_is_a_plain_refusal_not_a_partial_effect() {
    let directory = tempfile::tempdir().expect("temporary directory");
    let server = Server::builder()
        .socket_path(directory.path().join("missing-parent").join("sock"))
        .build()
        .expect("a socket under a missing directory is valid setup");

    let error = server
        .new_session("wont-exist")
        .await
        .expect_err("tmux creates nothing under a missing parent directory");

    assert_ne!(
        error.kind(),
        libtmux::ErrorKind::PartialEffect,
        "nothing was created, so this is not a partial effect: {error:?}",
    );
    let message = error.to_string();
    assert!(
        message.contains("error creating") || message.contains("gave no reason"),
        "tmux's own reason survives, or the message says there was none: {message}",
    );
    assert!(
        !message.contains("Some(0)"),
        "a Debug-formatted exit code does not leak into the message: {message}",
    );

    server.shutdown().await.expect("shutdown succeeds");
}

#[tokio::test]
async fn capability_probe_is_exact_shared_lazy_and_preserves_versions() {
    let directory = tempfile::tempdir().expect("temporary directory");
    let log = directory.path().join("probe.log");
    let script = write_script(
        directory.path(),
        "fake-tmux",
        &format!(
            r#"
if [ "$#" -eq 1 ] && [ "$1" = "-V" ]; then
    printf '<%s>\n' "$1" >> {}
    printf 'renamed-tmux 3.2a\n'
    exit 0
fi
printf 'unexpected command\n' >&2
exit 91
"#,
            shell_quote(&log),
        ),
    );
    let socket = directory.path().join("socket");
    let config = directory.path().join("config");
    let server = Server::builder()
        .tmux_executable(&script)
        .socket_path(&socket)
        .config_file(&config)
        .colors(256)
        .build()
        .expect("server configuration is valid");

    assert!(!log.exists(), "construction is inert");
    let cloned = server.clone();
    let (first, second, third) = tokio::join!(
        server.capabilities(),
        server.capabilities(),
        cloned.capabilities(),
    );
    let first = first.expect("version probe succeeds");
    let second = second.expect("shared probe succeeds");
    let third = third.expect("cloned server shares probe");

    assert_eq!(first.tmux_version().raw(), "3.2a");
    assert!(std::ptr::eq(first, second));
    assert!(std::ptr::eq(first, third));
    assert_eq!(
        fs::read_to_string(&log).expect("probe was recorded"),
        "<-V>\n"
    );
    server.shutdown().await.expect("shutdown succeeds");

    let development = write_script(
        directory.path(),
        "development-tmux",
        "[ \"$#\" -eq 1 ] && [ \"$1\" = \"-V\" ]\nprintf 'tmux master\\n'",
    );
    let development = fake_server(&development, &directory.path().join("development.sock"));
    let capabilities = development
        .capabilities()
        .await
        .expect("master meets the minimum capability floor");
    assert_eq!(capabilities.tmux_version().raw(), "master");
    assert!(capabilities.tmux_version().is_development());
    development.shutdown().await.expect("shutdown succeeds");
}

#[tokio::test]
async fn failed_and_nonzero_capability_probes_are_not_cached() {
    let directory = tempfile::tempdir().expect("temporary directory");
    let attempts = directory.path().join("attempts");
    let script = write_script(
        directory.path(),
        "retry-tmux",
        &format!(
            r#"
if [ "$#" -ne 1 ] || [ "$1" != "-V" ]; then
    exit 92
fi
printf x >> {}
if [ "$(wc -c < {})" -le 2 ]; then
    printf 'tmux 3.7b\n'
    printf 'sentinel-probe-stderr\n' >&2
    exit 9
fi
printf 'tmux 3.7b\n'
"#,
            shell_quote(&attempts),
            shell_quote(&attempts),
        ),
    );
    let server = fake_server(&script, &directory.path().join("retry.sock"));

    let first = server
        .capabilities()
        .await
        .expect_err("parseable stdout with nonzero status is rejected");
    let first_request_id = match &first {
        Error::VersionProbeFailed {
            request_id,
            command,
            exit_code,
            signal,
            ..
        } => {
            assert!(*request_id > 0);
            assert_eq!(command.to_string(), r#""-V""#);
            assert_eq!(*exit_code, Some(9));
            assert_eq!(*signal, None);
            Some(*request_id)
        }
        _ => None,
    }
    .expect("first error is a failed version probe");
    assert!(
        !first.is_transient(),
        "a nonzero probe gives no reason that replaying unchanged will help",
    );
    assert!(StdError::source(&first).is_none());
    assert!(!first.to_string().contains("sentinel-probe-stderr"));
    assert!(!format!("{first:?}").contains("sentinel-probe-stderr"));

    let second = server
        .capabilities()
        .await
        .expect_err("a second failed initialization is retried");
    let second_request_id = match &second {
        Error::VersionProbeFailed { request_id, .. } => Some(*request_id),
        _ => None,
    }
    .expect("second error is a failed version probe");
    assert!(
        !second.is_transient(),
        "a later artificial recovery does not make nonzero probes retryable",
    );
    assert!(second_request_id > 0);
    assert_ne!(first_request_id, second_request_id);
    assert!(StdError::source(&second).is_none());
    assert!(!second.to_string().contains("sentinel-probe-stderr"));
    assert!(!format!("{second:?}").contains("sentinel-probe-stderr"));

    let third = server
        .capabilities()
        .await
        .expect("failed initializations are retried");
    assert_eq!(third.tmux_version().raw(), "3.7b");
    assert_eq!(fs::read(&attempts).expect("attempts are recorded"), b"xxx");
    server.shutdown().await.expect("shutdown succeeds");
}

#[tokio::test]
async fn minimum_version_rejection_does_not_disable_the_raw_escape_hatch() {
    let directory = tempfile::tempdir().expect("temporary directory");
    let marker = directory.path().join("command-ran");
    let script = write_script(
        directory.path(),
        "old-tmux",
        &format!(
            r#"
if [ "$#" -eq 1 ] && [ "$1" = "-V" ]; then
    printf 'tmux 3.2\n'
    exit 0
fi
: > {}
"#,
            shell_quote(&marker),
        ),
    );
    let server = fake_server(&script, &directory.path().join("old.sock"));

    let error = server
        .capabilities()
        .await
        .expect_err("tmux below 3.2a is rejected");
    assert!(matches!(error, Error::UnsupportedTmuxVersion { .. }));
    assert!(
        !marker.exists(),
        "capability probing has no command side effect"
    );

    let result = server
        .cmd(Command::new("display-message"))
        .await
        .expect("raw execution remains available without capability escalation");
    assert!(result.success());
    assert!(
        marker.exists(),
        "raw command reached the configured executable"
    );
    server.shutdown().await.expect("shutdown succeeds");
}

#[tokio::test]
async fn raw_dispatch_preserves_global_argv_and_logical_summary() {
    let directory = tempfile::tempdir().expect("temporary directory");
    let socket = directory.path().join("sentinel-socket;");
    let config = directory.path().join("sentinel-config;");
    let script = write_script(
        directory.path(),
        "argv-tmux",
        r#"
if [ "$#" -eq 1 ] && [ "$1" = "-V" ]; then
    printf 'tmux 3.7b\n'
    exit 0
fi
for argument do
    printf '<%s>\n' "$argument"
done
printf '<TMUX=%s>\n' "${TMUX-unset}"
printf '<TMUX_PANE=%s>\n' "${TMUX_PANE-unset}"
"#,
    );
    let server = Server::builder()
        .tmux_executable(&script)
        .socket_path(&socket)
        .config_file(&config)
        .colors(256)
        .build()
        .expect("server configuration is valid");
    let command = Command::new("display-message").arg("value;");
    let result = server.cmd(command).await.expect("fake command succeeds");
    let stdout = result.stdout_utf8().expect("fixture output is UTF-8");

    assert_eq!(
        stdout,
        format!(
            "<-S>\n<{}>\n<-f>\n<{}>\n<-2>\n<-u>\n<display-message>\n<value\\;>\n<TMUX=unset>\n<TMUX_PANE=unset>\n",
            socket.display(),
            config.display(),
        )
    );
    assert_eq!(
        result.command().to_string(),
        r#""display-message" "value;""#
    );
    assert!(!format!("{result:?}").contains("sentinel-socket"));
    assert!(!format!("{result:?}").contains("sentinel-config"));
    server.shutdown().await.expect("shutdown succeeds");
}

#[tokio::test]
async fn logical_nul_inputs_are_classified_without_spawning_the_executable() {
    let directory = tempfile::tempdir().expect("temporary directory");
    let marker = directory.path().join("spawned");
    let script = write_script(
        directory.path(),
        "nul-tmux",
        &format!(": > {}", shell_quote(&marker)),
    );
    let server = fake_server(&script, &directory.path().join("nul.sock"));
    let cases = [
        (
            Command::new(OsString::from_vec(b"sentinel-subcommand\0tail".to_vec())),
            "tmux subcommand",
            "sentinel-subcommand",
        ),
        (
            Command::new("display-message")
                .arg(OsString::from_vec(b"sentinel-argument\0tail".to_vec())),
            "tmux argument",
            "sentinel-argument",
        ),
    ];

    let mut request_ids = Vec::new();
    for (command, expected_input, sentinel) in cases {
        let error = server
            .cmd(command)
            .await
            .expect_err("NUL input is rejected before spawn");
        let request_id = match &error {
            Error::InvalidCommandInput {
                request_id, input, ..
            } => {
                assert_eq!(*input, expected_input);
                Some(*request_id)
            }
            _ => None,
        }
        .expect("NUL input produces an invalid-command error");
        assert!(request_id > 0);
        request_ids.push(request_id);
        let mut source: Option<&dyn StdError> = Some(&error);
        while let Some(current) = source {
            assert!(!current.to_string().contains(sentinel));
            assert!(!format!("{current:?}").contains(sentinel));
            source = current.source();
        }
    }
    assert_ne!(request_ids[0], request_ids[1]);
    assert!(!marker.exists(), "invalid logical input never spawns");
    server.shutdown().await.expect("shutdown succeeds");
}

#[tokio::test]
async fn command_results_expose_exact_status_bytes_and_distinct_request_ids() {
    let directory = tempfile::tempdir().expect("temporary directory");
    let script = write_script(
        directory.path(),
        "result-tmux",
        r#"
if [ "$#" -eq 1 ] && [ "$1" = "-V" ]; then
    printf 'tmux 3.7b\n'
    exit 0
fi
last=''
for argument do last=$argument; done
case "$last" in
    raw)
        printf 'stdout\n\n\377'
        printf 'stderr\n\n\376' >&2
        exit 7
        ;;
    signal)
        kill -TERM $$
        ;;
    secret)
        printf 'sentinel-result-output'
        printf 'sentinel-result-error' >&2
        ;;
    *)
        printf 'ok\n'
        ;;
esac
"#,
    );
    let server = fake_server(&script, &directory.path().join("result.sock"));

    let result = server
        .cmd(Command::new("raw"))
        .await
        .expect("nonzero status remains result data");
    assert!(!result.success());
    assert_eq!(result.exit_code(), Some(7));
    assert_eq!(result.signal(), None);
    assert_eq!(result.stdout(), b"stdout\n\n\xff");
    assert_eq!(result.stderr(), b"stderr\n\n\xfe");
    assert!(result.stdout_utf8().is_err());
    assert!(result.stderr_utf8().is_err());
    assert!(result.stdout_lossy().contains("stdout\n\n"));
    assert!(result.stderr_lossy().contains("stderr\n\n"));

    let signal = server
        .cmd(Command::new("signal"))
        .await
        .expect("signal status remains result data");
    assert!(!signal.success());
    assert_eq!(signal.exit_code(), None);
    assert_eq!(signal.signal(), Some(15));

    let secret = server
        .cmd(Command::new("secret"))
        .await
        .expect("secret fixture succeeds");
    let diagnostic = format!("{secret:?}");
    assert!(!diagnostic.contains("sentinel-result-output"));
    assert!(!diagnostic.contains("sentinel-result-error"));

    let logical = Command::new("ok");
    let sequential = server
        .cmd(logical.clone())
        .await
        .expect("sequential command succeeds");
    let cloned_server = server.clone();
    let (first, second) = tokio::join!(
        server.cmd(logical.clone()),
        cloned_server.cmd(logical.clone()),
    );
    let first = first.expect("first concurrent command succeeds");
    let second = second.expect("second concurrent command succeeds");
    let ids = [
        result.request_id(),
        signal.request_id(),
        sequential.request_id(),
        first.request_id(),
        second.request_id(),
    ];
    for (index, id) in ids.iter().enumerate() {
        assert!(!ids[..index].contains(id), "request IDs are distinct");
    }

    let streams = server
        .cmd(Command::new("raw"))
        .await
        .expect("second raw command succeeds")
        .into_streams();
    assert_eq!(streams.0, b"stdout\n\n\xff");
    assert_eq!(streams.1, b"stderr\n\n\xfe");
    server.shutdown().await.expect("shutdown succeeds");
}

#[tokio::test]
async fn shared_shutdown_cancels_active_work_and_closes_every_clone() {
    let directory = tempfile::tempdir().expect("temporary directory");
    let script = write_script(
        directory.path(),
        "blocking-tmux",
        r#"
if [ "$#" -eq 1 ] && [ "$1" = "-V" ]; then
    printf 'tmux 3.7b\n'
    exit 0
fi
previous=''
for argument do
    if [ "$previous" = block ]; then
        sleep 60 &
        descendant=$!
        printf '%s\n%s\n' "$$" "$descendant" > "$argument"
        wait "$descendant"
    fi
    if [ "$previous" = rejected ]; then
        : > "$argument"
        exit 0
    fi
    previous=$argument
done
exit 93
"#,
    );
    let pid_path = directory.path().join("active.pid");
    let rejected_marker = directory.path().join("rejected");
    let server = fake_server(&script, &directory.path().join("shutdown.sock"));
    let dispatch_server = server.clone();
    let dispatch_pid_path = pid_path.clone();
    let mut dispatch = tokio::spawn(async move {
        dispatch_server
            .cmd(Command::new("block").arg(dispatch_pid_path.into_os_string()))
            .await
    });
    let child_pids = read_pids(&pid_path, 2, &mut dispatch).await;

    let first = server.clone();
    let second = server.clone();
    let (first_shutdown, second_shutdown) = tokio::join!(first.shutdown(), second.shutdown());
    first_shutdown.expect("first shutdown succeeds");
    second_shutdown.expect("concurrent shutdown succeeds");
    server.shutdown().await.expect("repeated shutdown succeeds");

    assert!(matches!(
        dispatch.await.expect("dispatch task remains healthy"),
        Err(Error::ExecutorShutdown { .. })
    ));
    for child_pid in child_pids {
        assert_process_gone(child_pid).await;
    }
    let rejected = server
        .clone()
        .cmd(Command::new("rejected").arg(rejected_marker.clone().into_os_string()))
        .await
        .expect_err("the shut down executor refuses every later call");
    assert!(matches!(rejected, Error::ExecutorShutdown { .. }));
    assert!(
        !rejected.is_transient(),
        "waiting cannot reopen this Core's executor",
    );
    assert!(
        !rejected_marker.exists(),
        "closed executor never spawns again"
    );
}

#[tokio::test]
async fn configured_default_timeout_is_applied_and_reaps_the_child() {
    let directory = tempfile::tempdir().expect("temporary directory");
    let script = write_script(
        directory.path(),
        "timeout-tmux",
        r#"
if [ "$#" -eq 1 ] && [ "$1" = "-V" ]; then
    printf 'tmux 3.7b\n'
    exit 0
fi
for argument do
    if [ "$argument" = probe ]; then
        printf 'executor-alive\n'
        exit 0
    fi
done
previous=''
for argument do
    if [ "$previous" = block ]; then
        printf '%s\n' "$$" > "$argument"
        while :; do sleep 60; done
    fi
    previous=$argument
done
exit 94
"#,
    );
    let pid_path = directory.path().join("timeout.pid");
    let server = Server::builder()
        .tmux_executable(&script)
        .socket_path(directory.path().join("timeout.sock"))
        .default_timeout(Duration::from_secs(2))
        .build()
        .expect("server configuration is valid");
    let dispatch_server = server.clone();
    let dispatch_pid_path = pid_path.clone();
    let mut dispatch = tokio::spawn(async move {
        dispatch_server
            .cmd(Command::new("block").arg(dispatch_pid_path.into_os_string()))
            .await
    });
    let child_pid = read_pid(&pid_path, &mut dispatch).await;
    let error = dispatch
        .await
        .expect("dispatch task remains healthy")
        .expect_err("blocking command reaches configured timeout");

    assert!(matches!(error, Error::Timeout { .. }));
    assert!(
        !error.is_transient(),
        "the child ran before timing out, so replay could duplicate its effect",
    );
    assert!(pid_path.exists(), "the command crossed the spawn boundary");
    assert_process_gone(child_pid).await;
    let probe = server
        .cmd(Command::new("probe"))
        .await
        .expect("a different call can use the same live server handle");
    assert!(probe.success());
    assert_eq!(probe.stdout(), b"executor-alive\n");
    server.shutdown().await.expect("shutdown remains clean");
}

#[tokio::test]
async fn missing_executable_is_inert_until_use_and_errors_are_path_safe() {
    let directory = tempfile::tempdir().expect("temporary directory");
    let available = write_script(
        directory.path(),
        "available-tmux",
        "[ \"$#\" -eq 1 ] && [ \"$1\" = \"-V\" ]\nprintf 'tmux 3.7b\\n'",
    );
    let executable = directory.path().join("sentinel-missing-tmux");
    let server = Server::builder()
        .tmux_executable(&executable)
        .socket_path(directory.path().join("missing.sock"))
        .build()
        .expect("a missing configured executable is valid inert setup");

    let command_error = server
        .cmd(Command::new("display-message"))
        .await
        .expect_err("first command reports the missing executable");
    let capability_error = server
        .capabilities()
        .await
        .expect_err("capability probing reports the missing executable");
    assert!(matches!(&command_error, Error::ExecutableNotFound { .. }));
    assert!(matches!(
        &capability_error,
        Error::ExecutableNotFound { .. }
    ));
    assert!(
        !command_error.is_transient(),
        "the unchanged call cannot start a missing executable",
    );
    assert!(
        !capability_error.is_transient(),
        "the unchanged probe cannot start a missing executable",
    );
    assert_error_path_safe(&command_error, "sentinel-missing-tmux");
    assert_error_path_safe(&capability_error, "sentinel-missing-tmux");
    symlink(&available, &executable).expect("missing executable path becomes available atomically");
    assert_eq!(
        server
            .capabilities()
            .await
            .expect("failed missing-executable probe is retried")
            .tmux_version()
            .raw(),
        "3.7b"
    );
    server.shutdown().await.expect("shutdown succeeds");
}

#[tokio::test]
async fn a_spawn_failure_needs_more_than_replaying_unchanged() {
    let directory = tempfile::tempdir().expect("temporary directory");
    let script = write_script(
        directory.path(),
        "temporarily-unexecutable-tmux",
        "printf 'transport recovered\n'",
    );
    let mut permissions = fs::metadata(&script)
        .expect("script metadata is readable")
        .permissions();
    permissions.set_mode(0o600);
    fs::set_permissions(&script, permissions.clone()).expect("execution is refused");
    let server = fake_server(&script, &directory.path().join("spawn.sock"));

    let error = server
        .cmd(Command::new("display-message"))
        .await
        .expect_err("the executable cannot be started");
    assert!(matches!(error, Error::Spawn { .. }));
    assert!(
        !error.is_transient(),
        "permission failure needs repair rather than unchanged replay",
    );

    permissions.set_mode(0o700);
    fs::set_permissions(&script, permissions).expect("execution is restored");
    let retried = server
        .cmd(Command::new("display-message"))
        .await
        .expect("the unchanged call runs on the same server handle");
    assert!(retried.success());
    assert_eq!(retried.stdout(), b"transport recovered\n");

    server.shutdown().await.expect("shutdown succeeds");
}

#[test]
fn server_operations_run_on_a_current_thread_runtime_created_after_construction() {
    let directory = tempfile::tempdir().expect("temporary directory");
    let script = write_script(
        directory.path(),
        "current-thread-tmux",
        r#"
if [ "$#" -eq 1 ] && [ "$1" = "-V" ]; then
    printf 'tmux 3.7b\n'
    exit 0
fi
printf 'current-thread\n'
"#,
    );
    let server = fake_server(&script, &directory.path().join("current-thread.sock"));
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .expect("current-thread runtime builds");

    runtime.block_on(async {
        assert_eq!(
            server
                .capabilities()
                .await
                .expect("capabilities succeed")
                .tmux_version()
                .raw(),
            "3.7b"
        );
        let result = server
            .cmd(Command::new("display-message"))
            .await
            .expect("raw command succeeds");
        assert_eq!(result.stdout(), b"current-thread\n");
        server.shutdown().await.expect("shutdown succeeds");
    });
}

#[test]
fn extreme_default_timeouts_do_not_overflow_current_thread_dispatch() {
    let directory = tempfile::tempdir().expect("temporary directory");
    let script = write_script(
        directory.path(),
        "extreme-timeout-tmux",
        "printf 'extreme-timeout-command\\n'",
    );
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .expect("current-thread runtime builds");

    for (name, timeout) in [
        ("huge-finite", Duration::from_secs(u64::MAX / 2)),
        ("maximum", Duration::MAX),
    ] {
        let server = Server::builder()
            .tmux_executable(&script)
            .socket_path(directory.path().join(format!("{name}.sock")))
            .default_timeout(timeout)
            .build()
            .expect("extreme timeout is valid configuration");

        runtime.block_on(async {
            let result = server
                .cmd(Command::new("display-message"))
                .await
                .expect("extreme timeout command succeeds");
            assert!(result.success());
            assert_eq!(result.stdout(), b"extreme-timeout-command\n");
            server.shutdown().await.expect("shutdown succeeds");
        });
    }
}

#[tokio::test]
async fn real_tmux_preserves_literal_semicolon_effects_on_an_isolated_socket() {
    let directory = tempfile::tempdir().expect("temporary directory");
    let socket = directory.path().join("socket;");
    let config = directory.path().join("config;");
    fs::write(&config, "set -g status off\n").expect("config is writable");
    let _guard = RealTmuxGuard {
        socket: socket.clone(),
    };
    let server = Server::builder()
        .socket_path(&socket)
        .config_file(&config)
        .colors(256)
        .build()
        .expect("isolated real-tmux server configuration");

    let started = server
        .cmd(
            Command::new("new-session")
                .arg("-d")
                .arg("-s")
                .arg("libtmux-foundation"),
        )
        .await
        .expect("tmux starts on the isolated socket");
    assert!(
        started.success(),
        "tmux stderr: {:?}",
        started.stderr_lossy()
    );
    let configured = server
        .cmd(Command::new("show-options").arg("-gv").arg("status"))
        .await
        .expect("show-options executes");
    assert_eq!(configured.stdout(), b"off\n");

    let cases = [
        ("LIBTMUX_SEMICOLON", ";"),
        ("LIBTMUX_TRAILING", "value;"),
        ("LIBTMUX_INTERIOR", "a;b"),
        ("LIBTMUX_BACKSLASH", "\\;"),
    ];
    for (name, value) in cases {
        let set = server
            .cmd(
                Command::new("set-environment")
                    .arg("-g")
                    .arg(name)
                    .arg(value),
            )
            .await
            .expect("set-environment executes");
        assert!(set.success(), "tmux stderr: {:?}", set.stderr_lossy());

        let shown = server
            .cmd(Command::new("show-environment").arg("-g").arg(name))
            .await
            .expect("show-environment executes");
        assert!(shown.success(), "tmux stderr: {:?}", shown.stderr_lossy());
        assert_eq!(
            shown.stdout(),
            format!("{name}={value}\n").as_bytes(),
            "logical value {value:?} changed after tmux parsing",
        );
    }

    server.shutdown().await.expect("executor shutdown succeeds");
    drop(server);
    let daemon_status = process::Command::new("tmux")
        .arg("-S")
        .arg(&socket)
        .arg("has-session")
        .arg("-t")
        .arg("libtmux-foundation")
        .status()
        .expect("external tmux client starts");
    assert!(
        daemon_status.success(),
        "client shutdown leaves the isolated tmux daemon running"
    );
}

#[test]
fn an_absent_tmux_variable_is_told_apart_from_a_malformed_one() {
    // No variable at all: the ordinary state of a process nobody started
    // inside tmux, which a caller may reasonably branch on.
    let outside = Server::from_env_value(None::<OsString>).expect_err("not inside tmux");
    assert_configuration_error(&outside, ServerConfigurationErrorKind::NotInsideTmux, &[]);

    // Present but not tmux's triple: something rewrote it, which is a broken
    // environment rather than a state to branch on. Collapsing the two into
    // one variant loses exactly that distinction.
    for broken in ["", ",7,$0"] {
        let error = Server::from_env_value(Some(broken)).expect_err("malformed value");
        assert_configuration_error(
            &error,
            ServerConfigurationErrorKind::MalformedTmuxVariable,
            &[],
        );
    }

    // And a well-formed value still resolves.
    Server::from_env_value(Some("/tmp/libtmux-rs-dev/from-env.sock,7,$0"))
        .expect("a triple names a socket");
}

#[cfg(feature = "test-support")]
#[tokio::test]
async fn a_channel_lock_is_released_when_the_body_fails() {
    let guard = libtmux::test::TestServer::builder()
        .start()
        .await
        .expect("tmux starts");
    let server = guard.server();

    let outcome: Result<(), _> = server
        .with_channel_lock("deploy", async |_| Err::<(), _>("the body failed"))
        .await;
    assert!(matches!(
        outcome,
        Err(libtmux::ScopeError::Operation("the body failed"))
    ));

    // A wedged channel would block this forever, so the fixture deadline is
    // what would report it; taking the lock is the assertion.
    server
        .lock_channel("deploy")
        .await
        .expect("the channel was released");
    server
        .unlock_channel("deploy")
        .await
        .expect("the channel unlocks");

    guard.shutdown().await.expect("tmux fixture shuts down");
}

/// A handle that gives up sooner than the fixture's, on the same socket.
#[cfg(feature = "test-support")]
fn impatient_handle(guard: &libtmux::test::TestServer, within: Duration) -> Server {
    Server::builder()
        .socket_path(guard.socket_path())
        .default_timeout(within)
        .build()
        .expect("a second handle on the fixture's socket")
}

/// Every process on this machine whose command line names `channel`.
#[cfg(feature = "test-support")]
fn processes_naming(channel: &str) -> Vec<String> {
    let listing = process::Command::new("ps")
        .arg("-eo")
        .arg("args=")
        .output()
        .expect("ps lists processes");
    // `ps` itself is never a match: its own arguments do not name the channel.
    String::from_utf8_lossy(&listing.stdout)
        .lines()
        .filter(|line| line.contains(channel))
        .map(ToOwned::to_owned)
        .collect()
}

/// tmux releases a signal to whatever is waiting and keeps it only when
/// nothing is, so a wait that gave up must not be counted as waiting.
#[cfg(feature = "test-support")]
#[tokio::test]
async fn a_signal_after_a_wait_ran_out_of_time_reaches_the_next_wait() {
    let guard = libtmux::test::TestServer::builder()
        .start()
        .await
        .expect("tmux starts");
    let server = guard.server();
    let channel = libtmux::test::unique_name("timed-out");

    assert_eq!(
        server
            .wait_for_channel(&channel, scaled(Duration::from_millis(200)))
            .await
            .expect("the wait runs"),
        ChannelWait::TimedOut,
        "nothing signalled the channel",
    );

    server
        .signal_channel(&channel)
        .await
        .expect("the channel is signalled");

    assert_eq!(
        server
            .wait_for_channel(&channel, scaled(Duration::from_secs(5)))
            .await
            .expect("the wait runs"),
        ChannelWait::Signalled,
        "the signal arrived before this wait started, so the wait returns at once",
    );

    guard.shutdown().await.expect("tmux fixture shuts down");
}

/// A dropped wait is a wait that gave up, and gives up the same way.
#[cfg(feature = "test-support")]
#[tokio::test]
async fn a_signal_after_a_dropped_wait_reaches_the_next_wait() {
    let guard = libtmux::test::TestServer::builder()
        .start()
        .await
        .expect("tmux starts");
    let server = guard.server();
    let channel = libtmux::test::unique_name("dropped");

    let dropped = server.wait_for_channel(&channel, scaled(Duration::from_secs(30)));
    assert!(
        tokio::time::timeout(scaled(Duration::from_millis(200)), dropped)
            .await
            .is_err(),
        "nothing signalled the channel",
    );

    server
        .signal_channel(&channel)
        .await
        .expect("the channel is signalled");

    assert_eq!(
        server
            .wait_for_channel(&channel, scaled(Duration::from_secs(5)))
            .await
            .expect("the wait runs"),
        ChannelWait::Signalled,
    );

    guard.shutdown().await.expect("tmux fixture shuts down");
}

/// One signal releases every waiter, so one client can carry every wait this
/// process has on the channel -- and must, or the second would keep a signal
/// the first already answered.
#[cfg(feature = "test-support")]
#[tokio::test]
async fn waits_on_one_channel_share_one_client() {
    let guard = libtmux::test::TestServer::builder()
        .start()
        .await
        .expect("tmux starts");
    let server = guard.server();
    let channel = libtmux::test::unique_name("shared");

    for _ in 0..2 {
        assert_eq!(
            server
                .wait_for_channel(&channel, scaled(Duration::from_millis(200)))
                .await
                .expect("the wait runs"),
            ChannelWait::TimedOut,
        );
        let clients = processes_naming(&channel);
        assert_eq!(clients.len(), 1, "clients on the channel: {clients:?}");
    }

    server
        .signal_channel(&channel)
        .await
        .expect("the channel is signalled");
    assert_eq!(
        server
            .wait_for_channel(&channel, scaled(Duration::from_secs(5)))
            .await
            .expect("the wait runs"),
        ChannelWait::Signalled,
    );

    guard.shutdown().await.expect("tmux fixture shuts down");
}

/// Signalling a channel is what releases the client parked on it, so a parked
/// client must not be able to hold the dispatch that would do the releasing.
#[cfg(feature = "test-support")]
#[tokio::test]
async fn a_parked_wait_does_not_hold_the_server_s_one_dispatch_slot() {
    let guard = libtmux::test::TestServer::builder()
        .dispatch_limits(
            libtmux::DispatchLimits::default()
                .max_in_flight(1)
                .acquire_timeout(Some(scaled(Duration::from_secs(2)))),
        )
        .start()
        .await
        .expect("tmux starts");
    let server = guard.server();
    let channel = libtmux::test::unique_name("crowded");

    assert_eq!(
        server
            .wait_for_channel(&channel, scaled(Duration::from_millis(200)))
            .await
            .expect("the wait runs"),
        ChannelWait::TimedOut,
    );

    // The only slot is free, so the signal gets through and the wait it
    // releases reads it.
    server
        .signal_channel(&channel)
        .await
        .expect("the channel is signalled");
    assert_eq!(
        server
            .wait_for_channel(&channel, scaled(Duration::from_secs(5)))
            .await
            .expect("the wait runs"),
        ChannelWait::Signalled,
    );

    guard.shutdown().await.expect("tmux fixture shuts down");
}

/// The wait's client is this process's to account for: after shutdown none of
/// it is left running.
#[cfg(feature = "test-support")]
#[tokio::test]
async fn a_wait_that_ran_out_of_time_leaves_no_client_behind_after_shutdown() {
    let guard = libtmux::test::TestServer::builder()
        .start()
        .await
        .expect("tmux starts");
    let channel = libtmux::test::unique_name("parked");

    assert_eq!(
        guard
            .server()
            .wait_for_channel(&channel, scaled(Duration::from_millis(200)))
            .await
            .expect("the wait runs"),
        ChannelWait::TimedOut,
    );

    guard.shutdown().await.expect("tmux fixture shuts down");

    let left = processes_naming(&channel);
    assert!(left.is_empty(), "processes left running: {left:?}");
}

/// tmux hands a released lock to the first queued locker, dead or alive, so a
/// locker that gave up must not still be queued.
#[cfg(feature = "test-support")]
#[tokio::test]
async fn a_lock_that_ran_out_of_time_while_queued_leaves_the_channel_lockable() {
    let guard = libtmux::test::TestServer::builder()
        .start()
        .await
        .expect("tmux starts");
    let server = guard.server();
    let impatient = impatient_handle(&guard, scaled(Duration::from_millis(400)));
    let channel = libtmux::test::unique_name("queued");

    server
        .lock_channel(&channel)
        .await
        .expect("the channel locks");

    let queued = impatient
        .lock_channel(&channel)
        .await
        .expect_err("the second lock runs out of time while queued");
    assert_eq!(queued.kind(), libtmux::ErrorKind::Timeout);

    server
        .unlock_channel(&channel)
        .await
        .expect("the holder releases the channel");

    tokio::time::timeout(
        scaled(Duration::from_secs(5)),
        server.lock_channel(&channel),
    )
    .await
    .expect("the channel is not wedged")
    .expect("the channel locks again");
    server
        .unlock_channel(&channel)
        .await
        .expect("the channel unlocks");

    guard.shutdown().await.expect("tmux fixture shuts down");
}

/// `with_channel_lock` takes the same lock, so it inherits the same hazard.
#[cfg(feature = "test-support")]
#[tokio::test]
async fn a_lock_scope_that_ran_out_of_time_while_queued_leaves_the_channel_lockable() {
    let guard = libtmux::test::TestServer::builder()
        .start()
        .await
        .expect("tmux starts");
    let server = guard.server();
    let impatient = impatient_handle(&guard, scaled(Duration::from_millis(400)));
    let channel = libtmux::test::unique_name("queued-scope");

    server
        .lock_channel(&channel)
        .await
        .expect("the channel locks");

    let outcome: Result<(), _> = impatient
        .with_channel_lock(&channel, async |_| Ok::<(), Error>(()))
        .await;
    assert!(
        matches!(
            &outcome,
            Err(libtmux::ScopeError::Creation(error)) if error.kind() == libtmux::ErrorKind::Timeout
        ),
        "the scope never starts: {outcome:?}",
    );

    server
        .unlock_channel(&channel)
        .await
        .expect("the holder releases the channel");

    tokio::time::timeout(
        scaled(Duration::from_secs(5)),
        server.lock_channel(&channel),
    )
    .await
    .expect("the channel is not wedged")
    .expect("the channel locks again");
    server
        .unlock_channel(&channel)
        .await
        .expect("the channel unlocks");

    guard.shutdown().await.expect("tmux fixture shuts down");
}

/// A lock dropped while still queued is granted in turn and released, rather
/// than held by a caller that is no longer there.
#[cfg(feature = "test-support")]
#[tokio::test]
async fn a_lock_dropped_while_queued_leaves_the_channel_lockable() {
    let guard = libtmux::test::TestServer::builder()
        .start()
        .await
        .expect("tmux starts");
    let server = guard.server();
    let channel = libtmux::test::unique_name("dropped-lock");

    server
        .lock_channel(&channel)
        .await
        .expect("the channel locks");

    assert!(
        tokio::time::timeout(
            scaled(Duration::from_millis(400)),
            server.lock_channel(&channel),
        )
        .await
        .is_err(),
        "the second lock is still queued behind the holder",
    );

    server
        .unlock_channel(&channel)
        .await
        .expect("the holder releases the channel");

    tokio::time::timeout(
        scaled(Duration::from_secs(5)),
        server.lock_channel(&channel),
    )
    .await
    .expect("the channel is not wedged")
    .expect("the channel locks again");
    server
        .unlock_channel(&channel)
        .await
        .expect("the channel unlocks");

    guard.shutdown().await.expect("tmux fixture shuts down");
}

/// A lock scope dropped while its lock is still queued: the lock runs in a
/// task of its own, so the drop cannot strand it.
#[cfg(feature = "test-support")]
#[tokio::test]
async fn a_lock_scope_dropped_while_queued_leaves_the_channel_lockable() {
    let guard = libtmux::test::TestServer::builder()
        .start()
        .await
        .expect("tmux starts");
    let server = guard.server();
    let channel = libtmux::test::unique_name("dropped-scope");

    server
        .lock_channel(&channel)
        .await
        .expect("the channel locks");

    let scope = server.with_channel_lock(&channel, async |_| Ok::<(), Error>(()));
    assert!(
        tokio::time::timeout(scaled(Duration::from_millis(400)), scope)
            .await
            .is_err(),
        "the scope is still queued behind the holder",
    );

    server
        .unlock_channel(&channel)
        .await
        .expect("the holder releases the channel");

    tokio::time::timeout(
        scaled(Duration::from_secs(5)),
        server.lock_channel(&channel),
    )
    .await
    .expect("the channel is not wedged")
    .expect("the channel locks again");
    server
        .unlock_channel(&channel)
        .await
        .expect("the channel unlocks");

    guard.shutdown().await.expect("tmux fixture shuts down");
}

#[cfg(feature = "test-support")]
#[tokio::test]
async fn a_buffer_larger_than_an_argument_round_trips_through_files() {
    let guard = libtmux::test::TestServer::builder()
        .start()
        .await
        .expect("tmux starts");
    let server = guard.server();
    let scratch = tempfile::tempdir().expect("a scratch directory");
    let source = scratch.path().join("in");
    let written = scratch.path().join("out");

    // Past `MAX_ARG_STRLEN`, so `set_buffer` cannot carry it: the kernel
    // refuses the argument before tmux sees it.
    let payload = vec![b'x'; 200_000];
    fs::write(&source, &payload).expect("the source is written");

    assert!(
        server
            .set_buffer(Some("big"), os_string_from_bytes(&payload))
            .await
            .is_err(),
        "a 200 KiB argument does not fit on a command line",
    );

    server
        .load_buffer(Some("big"), &source)
        .await
        .expect("tmux reads the file");
    // Compared by shape rather than by value: a failed `assert_eq!` on the
    // whole payload prints 200 KB of `120,` and buries the reason.
    let loaded = server.buffer("big").await.expect("the buffer reads");
    assert_eq!(loaded.as_ref().map(Vec::len), Some(payload.len()));
    assert_eq!(
        loaded.as_deref(),
        Some(payload.as_slice()),
        "the bytes differ"
    );

    server
        .save_buffer(Some("big"), &written)
        .await
        .expect("tmux writes the file");
    let read_back = fs::read(&written).expect("the output is readable");
    assert_eq!(read_back.len(), payload.len());
    assert!(read_back == payload, "the bytes differ");

    guard.shutdown().await.expect("tmux fixture shuts down");
}

#[cfg(feature = "test-support")]
fn os_string_from_bytes(bytes: &[u8]) -> OsString {
    use std::os::unix::ffi::OsStringExt as _;
    OsString::from_vec(bytes.to_vec())
}

/// A caller who wants a deadline shorter than the server's default does not
/// need an API for it: dropping the command future signals the process group
/// and reaps it, so `tokio::time::timeout` is a per-call deadline with the
/// cleanup already attached.
#[cfg(feature = "test-support")]
#[tokio::test]
async fn a_caller_can_bound_one_command_with_tokio_timeout() {
    let guard = libtmux::test::TestServer::builder()
        .start()
        .await
        .expect("tmux starts");
    let server = guard.server();

    // `run-shell` blocks in tmux for as long as the command does, and the
    // server's own default timeout is 30 seconds, so reaching this deadline
    // is the caller's bound rather than the crate's. Dispatched with `cmd`
    // rather than `Server::run_shell`, which refuses outright on 3.3 through
    // 3.4 -- a version gate on captured output this test does not read.
    let started = Instant::now();
    let outcome = tokio::time::timeout(
        Duration::from_millis(400),
        server.cmd(Command::new("run-shell").arg("sleep 3")),
    )
    .await;

    assert!(outcome.is_err(), "the caller's deadline ended the wait");
    assert!(
        started.elapsed() < Duration::from_secs(5),
        "it ended at the caller's deadline, not the server's: {:?}",
        started.elapsed(),
    );

    // The server is still usable afterwards: a bounded call is not a broken
    // connection.
    server.sessions().await.expect("the server still answers");

    guard.shutdown().await.expect("tmux fixture shuts down");
}